qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
9,656,867
I was trying to create a linked list with structs. The idea is to use 2 different stucts, one which is a node, and another which is a pointer to the nodes (so, I can link the nodes together). But I wanted to initialize the pointer to the first node as NULL, and create subsequent nodes later: I am having an error in the 2 constructor methods (List and Polynomial), I can't use the operator = like the way I am. But I can't understand why. ``` struct List { //Data members to hold an array of pointers, pointing to a specific node Node *list[100]; //Default constructor List(); }; List::List() { *list[0] = NULL; } class Polynomial { public: [...] private: List *poly; //Store the pointer links in an array Node first_node; int val; }; Polynomial::Polynomial() { poly = new List(); } /*******************************************************************************************************************************/ // Method : initialize() // Description : This function creates the linked nodes /*******************************************************************************************************************************/ Polynomial::void initialize(ifstream &file) { int y[20]; double x[20]; int i = 0, j = 0; //Read from the file file >> x[j]; file >> y[j]; first_node(x[j], y[j++]); //Create the first node with coef, and pwr *poly->list[i] = &first_node; //Link to the fist node //Creat a linked list while(y[j] != 0) { file >> x[j]; file >> y[j]; *poly->list[++i] = new Node(x[j], y[j++]); } val = i+1; //Keeps track of the number of nodes } ``` I have been getting errors in the Polynomial constructor and the List constructor.
2012/03/11
[ "https://Stackoverflow.com/questions/9656867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989359/" ]
@Rikonator is on the right track there with Soundpool. It's much more suited to the kind of functionality you are after. If you decide to go with the mediaplayer anyway, though, don't forget the prepareAsync () method to prevent it from hanging the UI thread. You can read more about playing media [here](http://developer.android.com/guide/topics/media/mediaplayer.html).
``` MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); } mp.start(); } catch (Exception e) { e.printStackTrace(); } ```
51,054
Is there a quick way to show where a paragraph is sitting in the document structure hierarchy? ``` * Chapter 1 ... * Chapter 5 ** Section 4 ... paragraph X ``` I would like to tell that `paragraph X` is sitting under `Chapter 5, Section 4` without having to navigate the cursor away from the text.
2019/06/15
[ "https://emacs.stackexchange.com/questions/51054", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/23726/" ]
Your function is not defined correctly. You don't need the code inside the interactive line, and you don't need the hook function. This should work fine I think: ``` (defun org-show-position-in-text () ;; display outline path of hierarchical headings (interactive) (message (mapconcat #'identity (org-get-outline-path t) "/"))) ```
My half-successful attempt: =========================== ``` (defun org-show-position-in-text () ;; display outline path of hierarchical headings (interactive (mapconcat #'identity (org-get-outline-path t) "/"))) (add-hook 'org-mode-hook 'org-show-position-in-text) ``` The above function just about does the job. Only that it throws the error `Wrong type argument: listp` before showing the full path to the heading. Please refer to @John Kitchin's answer for the correct code.
74,293,324
I'm a new C# programmer here in the early stages of creating a project in Unity where you play as a microbe that needs to eat blue food pellets to grow and survive. I've got the blue food pellets to spawn randomly across the map but I want to add a delay because too much is spawning at once. This is what I've attempted to do so far. Any help would be appreciated! ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading.Tasks; public class Spawner : MonoBehaviour { public GameObject food; public async void Wait(float duration) { Vector3 randomSpawnPosition = new Vector3(Random.Range(-50, 50), 1, Random.Range(-50, 50)); Instantiate(food, randomSpawnPosition, Quaternion.identity); await Task.Delay((int)duration * 1000); } // Update is called once per frame void Update() { async void Wait(float duration); } } ``` What I've tried: Putting the delay function in the update function. The program just gets confused and thinks I'm trying to call the function. Calling the function after combining all my code into the one function, the program rejects this.
2022/11/02
[ "https://Stackoverflow.com/questions/74293324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19153501/" ]
Like the default code snippet says, Update runs every frame. Using Task.Delay to delay events would still spawn objects with the same frequency, they would only start spawning delayed. The typical way to do this in Unity is to use a [coroutine](https://docs.unity3d.com/Manual/Coroutines.html). ```cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { [SerializeField] GameObject food; protected void OnEnable() { StartCoroutine(SpawnFoodRoutine()); } IEnumerator SpawnFoodRoutine() { while(enabled) { SpawnFood(); var waitTime = Random.Range(1f, 5f); yield return new WaitForSeconds(waitTime); } } void SpawnFood() { Vector3 randomSpawnPosition = new Vector3( Random.Range(-50f, 50f), 1f, Random.Range(-50f, 50f)); Instantiate(food, randomSpawnPosition, Quaternion.identity); } } ```
I have made this prefab called “pellet”, then I have created a new gameObject called “SpawnManager” and, finally, added this script to SpawnManager: ``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnPellet : MonoBehaviour { public GameObject prefab; public bool canSpawnNewPellet = true; public float delay; void Update(){ if(canSpawnNewPellet){ Invoke("SpawnNewPellet", delay); canSpawnNewPellet = false; } } void SpawnNewPellet() { GameObject instance = Instantiate(prefab); instance.transform.position = new Vector3(Random.Range(0,10), Random.Range(0,10), 0); canSpawnNewPellet = true; } } ``` The I have dragged and dropped/edited values on the fields in the inspector (Prefab, canSpawnNewPellet and Delay). Those are public fields inside the script, so you can populate them drag and dropping directly from your assets folder. [![Assets, Hierarchy & Inspector](https://i.stack.imgur.com/vNM3j.png)](https://i.stack.imgur.com/vNM3j.png) Hit play and you have a new spawn every X seconds where X is the value of delay in seconds. Screenshot of the game executing after 21 seconds. [![Screenshot](https://i.stack.imgur.com/TUvYV.png)](https://i.stack.imgur.com/TUvYV.png) What does it do? Every frame it evaluates if can spawn a new pellet (bool canSpawnNewPellet). If it can, then it starts an invocation of another method with X seconds (and mark the bool as false since we don’t want to call more invocations during de instantiation of our first sample). For more references: <https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html> Edited: typo.
28,882,520
I'm writing a json-file inside a generated folder. After an hour I want to delete the folder with its content automatically. I tried: ``` $dir = "../tmpDir"; $cdir = scandir($dir); foreach ($cdir as $key => $value) { if (!in_array($value,array(".",".."))) { if (is_dir($dir.'/'.$value)) { if(filectime($dir.'/'.$value)< (time()-3600)) { // after 1 hour $files = glob($dir.'/'.$value); // get all file names foreach($files as $file) { // iterate files if(is_file($file)) { unlink($file); // delete file } } rmdir($dir.'/'.$value); /*destroy the session if the folder is deleted*/ if(isset($_SESSION["dirname"]) && $_SESSION["dirname"] == $value) { session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage } } } } } ``` I get: rmdir(../tmpDir/1488268867): Directory not empty in **/Applications/MAMP/htdocs/....** on line **46** if I remove the ``` if(is_file($file)) { } ``` I get a permission error Maybe someone knows why I get this error
2015/03/05
[ "https://Stackoverflow.com/questions/28882520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2839873/" ]
The method sizeToFit calls sizeThatFits: which returns the ‘best’ size to fit the **current** bounds and then resize label. So at first you constrain the label and it has to fit the given width. You can see description of [NSLineBreakByWordWrapping](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html#//apple_ref/c/tdef/NSLineBreakMode) - Wrapping occurs at word boundaries, unless the word itself doesn’t fit on a single line. For your purposes you should allow label to fit the knowingly more wider width than it requires. But it is difficult because the task is to find the best font size and we cannot predict the width. And the best way is to find font size based on the longest word in the text. So the algorithm: 1. Detect the longest word, by separating by spaces. 2. Iteratively, decrease the font size and calculate the size of the longest word while the word is bigger than required width. 3. Set calculated font to full text and call sizeThatFits. Please, find the sample code below ("Verdana" font was used for testing) ``` - (void) setText { NSString * text = @"Incidental, indirect, secondary, side rival - Побочный, косвенный, второстепенный, боковой соперник"; CGFloat maxWidth = 300.; [self setText:text toLabel:self.label maxWidth:maxWidth]; } - (void) setText:(NSString *)text toLabel:(UILabel*)label maxWidth:(CGFloat)maxWidth { CGFloat fontSize = [self fontSizeOfWord:[self theLongestWord:text] initialFontSize:40. constrainedByWidth:maxWidth]; NSMutableAttributedString * attributedString = [self attributedStringForText:text]; [self setupAttributedStirng:attributedString withFontWithSize:fontSize]; label.attributedText = attributedString; CGRect labelFrame = label.frame; labelFrame.size = [label sizeThatFits:[attributedString sizeAdaptedForWidth:maxWidth]]; label.frame = labelFrame; } - (NSString*) theLongestWord:(NSString*)text { NSArray * words = [text componentsSeparatedByString:@" "]; NSUInteger longestLength = 0; NSUInteger index = NSNotFound; for(int i = 0; i < words.count; i++) { NSString * word = words[i]; CGFloat length = word.length; if(length > longestLength) { longestLength = length; index = i; } } return (index != NSNotFound ? words[index] : nil); } - (CGFloat)fontSizeOfWord:(NSString *)word initialFontSize:(CGFloat)initialFontSize constrainedByWidth:(CGFloat)maxWidth { NSMutableAttributedString * wordString = [self attributedStringForText:word]; CGFloat fontSize = initialFontSize; for (; fontSize >= 5.; --fontSize) { [self setupAttributedStirng:wordString withFontWithSize:fontSize]; CGSize wordSize = [wordString sizeAdaptedForWidth:CGFLOAT_MAX]; if(wordSize.width <= maxWidth){ break; } } return fontSize; } - (NSMutableAttributedString*) attributedStringForText:(NSString*)text { return (text&&text.length ? [[NSMutableAttributedString alloc] initWithString:text]:nil); } - (void)setupAttributedStirng:(NSMutableAttributedString *)attributedString withFontWithSize:(CGFloat)fontSize { NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; [paragraphStyle setAlignment:NSTextAlignmentCenter]; UIFont * font = [UIFont fontWithName:@"Verdana" size:fontSize]; [paragraphStyle setLineSpacing:fontSize*0.3f]; NSDictionary * attributes = @{NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font}; [attributedString addAttributes:attributes range:NSMakeRange(0, [attributedString length])]; } ``` Category for `NSAttributedString`: ``` @implementation NSAttributedString (AdaptedSize) - (CGSize) sizeAdaptedForWidth:(CGFloat)width { CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self); CGSize targetSize = CGSizeMake(width, CGFLOAT_MAX); CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [self length]), NULL, targetSize, NULL); CFRelease(framesetter); return fitSize; } @end ```
Have you tried the [`UILabel.adjustsFontSizeToWidth`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth) property?
25,580,404
I'm new to Web development and have been messing around with `BootStrap`. I've been trying to make a Web form on my new website, but I can't seem to access the username variable. Here's my form code: ``` <form class="navbar-form navbar-left" role="search" action="username"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` And here's my `index.php` in the username folder: ``` <?php echo $_POST['username']; echo 'fail'; echo 'username'; if(isset($_POST['username'])) { $name = $_POST['username']; echo 'success'; } ?> ``` With my debugging, I get the message fail to show up, but not the username, so I assume I am doing something wrong either with setting the username, or accessing it.
2014/08/30
[ "https://Stackoverflow.com/questions/25580404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You have the following mistakes 1. You didn't set the `method` attribute in your form.So when the form is submitted the data will be posted via get method.And you need to access `$_GET` variable for getting the form data. So here when you submit the form the data will be in `$_GET` variable.But you are trying to access `$_POST` variable in your code.So you can try like setting the method attribute to `method="post` in your form and continue with the same code in index.php or try changing `$_POST` to $\_GET` in your index.php and making no changes in your form 2. You are definging the code in index.php when the form is submitted.So you need to set the `action="index.php"` in your form So it will be like this finally ``` <form class="navbar-form navbar-left" role="search" action="username/index.php" method="post"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` index.php ``` <?php echo $_POST['username']; echo 'fail'; echo 'username'; if(isset($_POST['username'])) { $name = $_POST['username']; echo 'success'; } ?> ``` OR ``` <form class="navbar-form navbar-left" role="search" action="username/index.php"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` index.php ``` <?php echo $_GET['username']; echo 'fail'; echo 'username'; if(isset($_GET['username'])) { $name = $_GET['username']; echo 'success'; } ?> ```
Set your `action` attribute to `index.php` and set your `method="post"` if you access the username with `$_POST['username']`.
25,580,404
I'm new to Web development and have been messing around with `BootStrap`. I've been trying to make a Web form on my new website, but I can't seem to access the username variable. Here's my form code: ``` <form class="navbar-form navbar-left" role="search" action="username"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` And here's my `index.php` in the username folder: ``` <?php echo $_POST['username']; echo 'fail'; echo 'username'; if(isset($_POST['username'])) { $name = $_POST['username']; echo 'success'; } ?> ``` With my debugging, I get the message fail to show up, but not the username, so I assume I am doing something wrong either with setting the username, or accessing it.
2014/08/30
[ "https://Stackoverflow.com/questions/25580404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
According to your description, your HTML code should look something like this: ``` <form method="post" class="navbar-form navbar-left" role="search" action="username/index.php"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` You could also use `<input class="btn btn-default" type="submit" value="Search"/>` instead of `<button type="submit"></button>`.
You have the following mistakes 1. You didn't set the `method` attribute in your form.So when the form is submitted the data will be posted via get method.And you need to access `$_GET` variable for getting the form data. So here when you submit the form the data will be in `$_GET` variable.But you are trying to access `$_POST` variable in your code.So you can try like setting the method attribute to `method="post` in your form and continue with the same code in index.php or try changing `$_POST` to $\_GET` in your index.php and making no changes in your form 2. You are definging the code in index.php when the form is submitted.So you need to set the `action="index.php"` in your form So it will be like this finally ``` <form class="navbar-form navbar-left" role="search" action="username/index.php" method="post"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` index.php ``` <?php echo $_POST['username']; echo 'fail'; echo 'username'; if(isset($_POST['username'])) { $name = $_POST['username']; echo 'success'; } ?> ``` OR ``` <form class="navbar-form navbar-left" role="search" action="username/index.php"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` index.php ``` <?php echo $_GET['username']; echo 'fail'; echo 'username'; if(isset($_GET['username'])) { $name = $_GET['username']; echo 'success'; } ?> ```
25,580,404
I'm new to Web development and have been messing around with `BootStrap`. I've been trying to make a Web form on my new website, but I can't seem to access the username variable. Here's my form code: ``` <form class="navbar-form navbar-left" role="search" action="username"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` And here's my `index.php` in the username folder: ``` <?php echo $_POST['username']; echo 'fail'; echo 'username'; if(isset($_POST['username'])) { $name = $_POST['username']; echo 'success'; } ?> ``` With my debugging, I get the message fail to show up, but not the username, so I assume I am doing something wrong either with setting the username, or accessing it.
2014/08/30
[ "https://Stackoverflow.com/questions/25580404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
According to your description, your HTML code should look something like this: ``` <form method="post" class="navbar-form navbar-left" role="search" action="username/index.php"> <div class="form-group"> <input name="username" type="text" class="form-control" placeholder="Username"> </div> <button type="submit" class="btn btn-default">Search</button> </form> ``` You could also use `<input class="btn btn-default" type="submit" value="Search"/>` instead of `<button type="submit"></button>`.
Set your `action` attribute to `index.php` and set your `method="post"` if you access the username with `$_POST['username']`.
6,554,484
can anyone please tell me what is the error on this code? I am trying to set a cookie for the fancybox popup but it is showing on every refresh. All .js are included. ``` <script> $(document).ready(function(){ if(!$.cookie('the_cookie1')){ $.cookie('the_cookie1', 'true', { expires: 3}); $.fancybox( '<h2>Hi!</h2><p>Lorem ipsum dolor</p>', { 'autoDimensions' : false, 'width' : 350, 'height' : 'auto', 'transitionIn' : 'none', 'transitionOut' : 'none' } ); } }); </script> ```
2011/07/02
[ "https://Stackoverflow.com/questions/6554484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/807325/" ]
I modified the code block to the following and it's functioning as expected both in Chrome 13 and FF5. ``` <script> $(document).ready(function () { var cookieName = 'the_cookie1'; var cookie = $.cookie(cookieName); if(cookie === null) { var cookieOptions = { expires: 3, path: '/' /*domain:, secure: false */ }; $.cookie(cookieName, 'true', cookieOptions); $.fancybox( '<h2>Hi!</h2><p>Lorem ipsum dolor</p>', { 'autoDimensions': false, 'width': 350, 'height': 'auto', 'transitionIn': 'none', 'transitionOut': 'none' } ); } }); </script> ``` FireFox 5 ![enter image description here](https://i.stack.imgur.com/x6nX6.png) Chrome 13 ![enter image description here](https://i.stack.imgur.com/lkM4W.png) First run, I receive the box and the cookie is set. Thereafter, no box. I did notice some strangeness with Chrome where the cookie would not appear in the console occasionally but debugging the script in fact revealed the cookie was set and functioning.
try changing your condition to this: ``` if(! ($.cookie('the_cookie1')){... ``` this both covers null and 'undefined'.
21,041
I have an RN-41 bluetooth module connected to an MSP430. I want to connect the RN-41 to an Android cellphone. Just by having power to the Bluetooth module, the cellphone finds the device. However, it is not able to make pairing the only documentation that I find about pairing on the RN-41 says that the default key for pairing should be 1234. In any case the cellphone doesn't even ask for the pass key but shows an error saying that is not able to pair. Can anyone provide some guidance?
2011/10/19
[ "https://electronics.stackexchange.com/questions/21041", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/5712/" ]
The problem I was actually having with the module, was a hardware problem. I tried to connect the Bluetooth module power to the VCC pin of the target board of the MSP. It is a 3.3v source, which is appears to be compatible. But the maximum current that could pass through that pin was 15mA, which is enough to set the device discoverable but it stays short when trying to establish a connection (needs around 35mA). Hence, I was able to see it, but got an error upon establishing a connection. Hope this helps somebody else in the future.
It has been a while since I messed with my RN41 connecting to an android phone, but I will try to provide some advice for you. The bluetooth module uses [SPP (Serial Port Profile)](http://en.wikipedia.org/wiki/Bluetooth_profile#Serial_Port_Profile_.28SPP.29) as its default profile. Essentially the way that it works is it opens up a serial port tunnel that can be used just as if you were using a RS232 connection on a computer. The problem with this profile is that it isn't always fully support because it isn't commonly used in consumer products. Here is a [StackOverflow post](https://stackoverflow.com/questions/4031434/activate-bluetooth-spp-in-android) that talks about it a bit. You can verify that it isn't a hardware issue by connecting it to a computer that supports SPP. Depending on your goals, it may be better for you to use a different bluetooth profile which is described in the [datasheet](http://www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-bluetooth-um.pdf) starting on page 18.
46,292,300
I have a linux server OEL 5.8 in which 8 oracle DB instances are running. 4 Db instances are running on Oracle 10.2.0.4 and other 4 on 11.2.0.3. Initially, all the DB instances were running on 10.2.0.4. I upgraded 4 of them to 11.2.0.3. Now the existing linux server is going to be migrated on new location. Server was cloned to the new server location and I got the exact replica of my old server at new location. I was able to start the Oracle 10g DB instances perfectly fine just changing the hostname in tnsnames.ora and listener.ora. However I am unable to start ORacle 11g instances. sqlplus is unable to find the Db instance. $ORACLE\_SID, $ORACLE\_HOME and $PATH are set to oracle 11g location in environment variables. Pfile exists in $ORACLE\_HOME/dbs. But when I try to connect like 'sqlplus / as sysdba' I am unable to find any idle instnace to start. ``` flow81 > echo $ORACLE_HOME /dboracle/orabase/product/11.2.0.3 flow81 > echo $PATH /dboracle/orabase/product/11.2.0.3/bin flow81 > echo $ORACLE_SID flow81 flow81 > sqlplus / as sysdba SQL*Plus: Release 11.2.0.3.0 Production on Tue Sep 19 05:58:01 2017 Copyright (c) 1982, 2011, Oracle. All rights reserved. Connected. SQL> ``` For DB instances in 10g, ``` fltr81 > sqlplus / as sysdba SQL*Plus: Release 10.2.0.4.0 - Production on Tue Sep 19 06:00:10 2017 Copyright (c) 1982, 2007, Oracle. All Rights Reserved. Connected to an idle instance. SQL> STARTUP ORACLE instance started. Total System Global Area 159383552 bytes Fixed Size 2082464 bytes Variable Size 113248608 bytes Database Buffers 37748736 bytes Redo Buffers 6303744 bytes Database mounted. Database Opened. ``` My question is why sqlplus is unable to find idle instance in oracle 11g to start them?
2017/09/19
[ "https://Stackoverflow.com/questions/46292300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7430328/" ]
There was some configuration issue in /etc/hosts. IP was mapped against some different hostname, hence the issue. After mapping IP to correct Hostname issue got resolved.
Its very simply if your Database is already started up, sqlplus will connect to the instance. If instance is not started up, sqlplus will connect to an idle instance by default. Moreover if you want to connect with a specific instance you have to specify @SID\_NAME as follows in the sqlplus command sqlplus / as sysdba@SID
3,896,524
Question: Prove that if $f, g: [a, b] → \mathbb{R}$ are continuous and $f (x) <g (x) $ for every $x \in [a, b]$, then there exists $δ> 0$ such that $f + δ ≤ g$. I have tried to take the $f-g$ function and apply something like intermediate value theorem, but couldn't conclude anything. I've seen a [solution](https://math.stackexchange.com/questions/379843/prove-for-continuous-f-and-g-fxgx-there-exists-k-such-that-fxk) that uses covers, but we haven't seen that yet and would like to know if there is an easier way to fix it.
2020/11/06
[ "https://math.stackexchange.com/questions/3896524", "https://math.stackexchange.com", "https://math.stackexchange.com/users/700522/" ]
let $h=g-f>0$ on $[a,b]$. Since $h$ is continuous on a closed interval, it has a global minimum (extreme value theorem). then let $\delta=\min\_{x\in[a,b]}{h(x)}$ Then, by definition $\delta>0$ and $\forall x\in[a,b], f(x)+\delta\leq g(x) $
Suppose not. Then for every $\delta>0$ there is a point $x\in[a,b]$ where $g(x)-f(x)<\delta$. In particular, there is a sequence $x\_n\in[a,b]$ with $g(x\_n)-f(x\_n)<1/n$. The sequence $x\_n$ doesn't necessarily have a limit, but by Bolzano-Weierstrass there is a convergent subsequence $x\_{n\_i}\to x\in[a,b]$. Now $g(x\_{n\_i})-f(x\_{n\_i})\to 0$, so $g(x)=f(x)$.
3,896,524
Question: Prove that if $f, g: [a, b] → \mathbb{R}$ are continuous and $f (x) <g (x) $ for every $x \in [a, b]$, then there exists $δ> 0$ such that $f + δ ≤ g$. I have tried to take the $f-g$ function and apply something like intermediate value theorem, but couldn't conclude anything. I've seen a [solution](https://math.stackexchange.com/questions/379843/prove-for-continuous-f-and-g-fxgx-there-exists-k-such-that-fxk) that uses covers, but we haven't seen that yet and would like to know if there is an easier way to fix it.
2020/11/06
[ "https://math.stackexchange.com/questions/3896524", "https://math.stackexchange.com", "https://math.stackexchange.com/users/700522/" ]
The idea is that you want to prove that there exists some constant $\delta$ such that $g(x)-f(x) \geqslant \delta >0$ for all $x \in [a,b]$. Your only hypothesis are the continuity of $f$ and $g$, with $g >f$, over the set $[a,b]$. But there is a well-known property of continuous functions over closed bounded interval : if $h : [a,b] \to \mathbb{R}$ is continuous, then $h$ is bounded and its infimum and supremum are maximum and minimum. Thus, if $h = g-f$, then $h$ is continuous over $[a,b]$ and has a minimum : \begin{align} \exists c \in [a,b],~ \forall x \in [a,b],~ h(x) \geqslant h(c) \end{align} Consequently, \begin{align} \exists c \in [a,b],~ \forall x \in [a,b],~ g(x) \geqslant h(c) + f(x) \end{align} By assumption, $h(c) = g(c)-f(c) >0$, and so the result follows by defining $\delta = h(c)$.
Suppose not. Then for every $\delta>0$ there is a point $x\in[a,b]$ where $g(x)-f(x)<\delta$. In particular, there is a sequence $x\_n\in[a,b]$ with $g(x\_n)-f(x\_n)<1/n$. The sequence $x\_n$ doesn't necessarily have a limit, but by Bolzano-Weierstrass there is a convergent subsequence $x\_{n\_i}\to x\in[a,b]$. Now $g(x\_{n\_i})-f(x\_{n\_i})\to 0$, so $g(x)=f(x)$.
12,687,239
When scripts are loaded via [Head JS](http://headjs.com/) I am unable to force the content to refresh using the Ctrl+F5 (or equivalent) keyboard shortcut. The scripts cache correctly and the browser obeys the cache directives sent from the server (I'm using IIS 7.5). But unlike scripts tags included directly in the markup, I can't override the cache and force a refresh of the scripts loaded via Head JS. I'm assuming this is a consequence of the way the scripts are loaded dynamically. I can live with this behaviour because forcing the refresh is only convenient during development, and I know of other ways I can force the content to be retrieved from the server. I just wondered if anyone could explain why this is the case... ### Update This was never a problem for us in Live, because the cache directives for our static content were set appropriately. It was only ever a problem in Development and QA, The options left available to me were... * Configure all Dev and QA browsers to never cache content. * Configure the static content cache directives differently for Dev and QA environments - essentially setting MaxAge to something so small the content would always be expired. Only setting the correct MaxAge value in Live. I went with the second option.
2012/10/02
[ "https://Stackoverflow.com/questions/12687239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
Dynamic script loading is not a part of the page loading proper. When you force refresh, the browser reloads the page and all resources referenced in its HTML and in referenced CSS files, but the scripts you load with `head.js` are not referenced in the page content and the browser has no way to figure out that `head.js` is going to create references to additional resources. At the point where these references are created, the browser is no longer refreshing the page and thus normal cache rules apply. You can force reload of your scripts by appending unique query strings to their URLs (e.g. `jquery.js?random=437593486394`), but this will disable caching for all loads of your page, not just when you force refresh.
This is also a problem with require.js. Hopefully one of these work arounds will also apply to Head.Js * If using Chrome, open the developer tools panel on the Network tab, right click and choose 'Clear Browser Cache' * Do a bit of 'Cache-busting' by appending a datetime stamp to the query string for js resources * If your using IIS (which it looks like you are). Go to the HTTP Response Headers panel of your website, click Set Common Headers and set Expire Web content to immediately. The latter is my preferred option for my development machine ![IIS HTTP Response Headers Panel](https://i.stack.imgur.com/DsFfq.png)
12,687,239
When scripts are loaded via [Head JS](http://headjs.com/) I am unable to force the content to refresh using the Ctrl+F5 (or equivalent) keyboard shortcut. The scripts cache correctly and the browser obeys the cache directives sent from the server (I'm using IIS 7.5). But unlike scripts tags included directly in the markup, I can't override the cache and force a refresh of the scripts loaded via Head JS. I'm assuming this is a consequence of the way the scripts are loaded dynamically. I can live with this behaviour because forcing the refresh is only convenient during development, and I know of other ways I can force the content to be retrieved from the server. I just wondered if anyone could explain why this is the case... ### Update This was never a problem for us in Live, because the cache directives for our static content were set appropriately. It was only ever a problem in Development and QA, The options left available to me were... * Configure all Dev and QA browsers to never cache content. * Configure the static content cache directives differently for Dev and QA environments - essentially setting MaxAge to something so small the content would always be expired. Only setting the correct MaxAge value in Live. I went with the second option.
2012/10/02
[ "https://Stackoverflow.com/questions/12687239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
Dynamic script loading is not a part of the page loading proper. When you force refresh, the browser reloads the page and all resources referenced in its HTML and in referenced CSS files, but the scripts you load with `head.js` are not referenced in the page content and the browser has no way to figure out that `head.js` is going to create references to additional resources. At the point where these references are created, the browser is no longer refreshing the page and thus normal cache rules apply. You can force reload of your scripts by appending unique query strings to their URLs (e.g. `jquery.js?random=437593486394`), but this will disable caching for all loads of your page, not just when you force refresh.
I wouldn't say its a question of dynamic or not dynamic, when you inject a script it still causes the browser to make a HTTP request and apply whatever caching logic it applies. Like mentioned above if you don't want scripts to be cached ..dynamic or static, it doesn't matter, you will usually have to append a timestamp in the form of a query string to it. If you just want to see if you changes are working, do a force refresh in your browser ...usually CTRL+F5
12,687,239
When scripts are loaded via [Head JS](http://headjs.com/) I am unable to force the content to refresh using the Ctrl+F5 (or equivalent) keyboard shortcut. The scripts cache correctly and the browser obeys the cache directives sent from the server (I'm using IIS 7.5). But unlike scripts tags included directly in the markup, I can't override the cache and force a refresh of the scripts loaded via Head JS. I'm assuming this is a consequence of the way the scripts are loaded dynamically. I can live with this behaviour because forcing the refresh is only convenient during development, and I know of other ways I can force the content to be retrieved from the server. I just wondered if anyone could explain why this is the case... ### Update This was never a problem for us in Live, because the cache directives for our static content were set appropriately. It was only ever a problem in Development and QA, The options left available to me were... * Configure all Dev and QA browsers to never cache content. * Configure the static content cache directives differently for Dev and QA environments - essentially setting MaxAge to something so small the content would always be expired. Only setting the correct MaxAge value in Live. I went with the second option.
2012/10/02
[ "https://Stackoverflow.com/questions/12687239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
This is also a problem with require.js. Hopefully one of these work arounds will also apply to Head.Js * If using Chrome, open the developer tools panel on the Network tab, right click and choose 'Clear Browser Cache' * Do a bit of 'Cache-busting' by appending a datetime stamp to the query string for js resources * If your using IIS (which it looks like you are). Go to the HTTP Response Headers panel of your website, click Set Common Headers and set Expire Web content to immediately. The latter is my preferred option for my development machine ![IIS HTTP Response Headers Panel](https://i.stack.imgur.com/DsFfq.png)
I wouldn't say its a question of dynamic or not dynamic, when you inject a script it still causes the browser to make a HTTP request and apply whatever caching logic it applies. Like mentioned above if you don't want scripts to be cached ..dynamic or static, it doesn't matter, you will usually have to append a timestamp in the form of a query string to it. If you just want to see if you changes are working, do a force refresh in your browser ...usually CTRL+F5
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
The only way to see the Blender console and thus the script output is to launch Blender from a terminal using the full path to the executable: `"/Applications/Blender/blender.app/Contents/MacOS/blender"` All script output will appear in the terminal only. Following @DickMeehan's comment and since I hate to install yet another App, here is the AppleScript to automatically start a Blender with its Terminal window. Note: tested on `MacOS High Sierra 10.13.3` only: ``` set blenderAppPath to "/Applications/Blender/blender.app/Contents/MacOS/blender" (* This command will open a Terminal app that should be closed with CMD-Q otherwise it will persist after Blender and the terminal window are closed with CMD-W *) set openCmd to "open -n -W -a /Applications/Utilities/Terminal.app/Contents/MacOS/Terminal --args " do shell script openCmd & blenderAppPath ``` Refer to the following to make an actual clickable App using the Automator. This app can then be simply dragged to the launch bar for convenience. <https://apple.stackexchange.com/questions/84348/how-can-i-create-a-stand-alone-app-to-run-a-terminal-command> [![enter image description here](https://i.stack.imgur.com/T5KT6.gif)](https://i.stack.imgur.com/T5KT6.gif) [![enter image description here](https://i.stack.imgur.com/qR5lX.gif)](https://i.stack.imgur.com/qR5lX.gif)
Without creating a new application with Applescript and all, you can just create a shell script with the '.command' extension. The extension makes it clickable, which opens a console and executes the file. 1. Open a terminal 2. `cd /Applications` 3. `nano Blender.command` paste this and save the file ``` #!/bin/sh cd `dirname $0`; ./Blender.app/Contents/MacOS/Blender ``` 4. `chmod u+x Blender.command` Now click on the 'Blender.command' icon next to your Blender application.
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
If you want to be able to launch it like any other application, the simplest way is to do this: 1. Launch **Automator** (it is in your Mac's Applications folder) and launch **Terminal** (it is in Applications/Utilities). 2. Create a new Application in Automator. ![](https://i.stack.imgur.com/mfQed.png) 3. Type "run" in the variables search field, and drag **Run Shell Script** to the right part of the workspace. ![](https://i.stack.imgur.com/6BPta.png) 4. In **Finder**, locate **Blender.app** (it is probably in your Applications folder). Right click on the app and choose **Show Package Contents**. Inside the Contents, navigate to `/Contents/MacOS/Blender` 5. Drag this **Blender** file onto your Terminal window and Terminal will show you the file path. For me it is `/Applications/Blender\ 2.9.app/Contents/MacOS/Blender`, for example. 6. Copy that file path. Inside Automator, in the Run Shell Script text field, type `open` then space, then paste in the file path. Example: `open /Applications/Blender\ 2.9.app/Contents/MacOS/Blender` [![Launching Blender with the Terminal console, using a shell script in Automator](https://i.stack.imgur.com/35GQU.png)](https://i.stack.imgur.com/35GQU.png) * **Note:** If you have multiple versions of Blender in your Applications folder (Blender 2.79b.app, Blender 2.9.app, Blender 2.92.app ...) and update regularly (as you should), then it might make more sense to create an **alias** in your Applications folder of ...`/Contents/MacOS/Blender` called something like "Blender - Console" and use that for your shell script path instead: `open /Applications/Blender\ -\ Console`. Then you don't need to mess with Automator each time you get a new version of Blender - simply make a new alias with the name "Blender - Console". This way launching "Blender (Console).app" (or whatever you name it) will always point to the latest. 7. Name and save your launcher app in your Applications folder. Then in Finder you can drag it to your Dock. ![](https://i.stack.imgur.com/u5f8t.png) 8 (Optional). If you don't like the default robot icon, you can give your app a custom icon using Finder's Info window. In your Applications folder, select both Blender.app and your new custom app, then press `Cmd``I` to **Get Info**. Click on Blender.app's icon to highlight it, then `Cmd``C` to copy it. Then click to highlight your app's icon and press `Cmd``V` to paste the blender icon in. ![](https://i.stack.imgur.com/fdhbO.gif) You can create a custom icon too if you like, open it in Preview and copy it. But icon design is beyond the scope of this topic. Enjoy your custom launcher app. --- **Edit:** One final thing to mention is that *the first time* you launch a newly installed version of Blender you should launch the Blender app normally instead of through your custom launcher. This gives macOS a chance to verify it so that you don't run into any errors when launching. In other words, let your Mac do this once: ![](https://i.stack.imgur.com/odv76.png)
It seem's I cannot comment. Small note, blender 3.x is located at: `/Applications/Blender.app/Contents/MacOS/Blender`
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
Right click on the Blender icon in the Applications folder and select "Show Package contents". Make an alias of `Contents/MacOS/Blender` by right clicking and selecting "Make Alias". Rename it and move it somewhere you like. This opens the console in the background, next to the Blender application. source: <https://www.lynda.com/Blender-tutorials/Set-up-Blender-console-window/486043/533594-4.html>
The only way to see the Blender console and thus the script output is to launch Blender from a terminal using the full path to the executable: `"/Applications/Blender/blender.app/Contents/MacOS/blender"` All script output will appear in the terminal only. Following @DickMeehan's comment and since I hate to install yet another App, here is the AppleScript to automatically start a Blender with its Terminal window. Note: tested on `MacOS High Sierra 10.13.3` only: ``` set blenderAppPath to "/Applications/Blender/blender.app/Contents/MacOS/blender" (* This command will open a Terminal app that should be closed with CMD-Q otherwise it will persist after Blender and the terminal window are closed with CMD-W *) set openCmd to "open -n -W -a /Applications/Utilities/Terminal.app/Contents/MacOS/Terminal --args " do shell script openCmd & blenderAppPath ``` Refer to the following to make an actual clickable App using the Automator. This app can then be simply dragged to the launch bar for convenience. <https://apple.stackexchange.com/questions/84348/how-can-i-create-a-stand-alone-app-to-run-a-terminal-command> [![enter image description here](https://i.stack.imgur.com/T5KT6.gif)](https://i.stack.imgur.com/T5KT6.gif) [![enter image description here](https://i.stack.imgur.com/qR5lX.gif)](https://i.stack.imgur.com/qR5lX.gif)
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
A really quick way for mac users to do this is to create an alias using the Terminal (It's not as scary as it looks) open Terminal type `nano ~/.bash_profile` on the first line paste this `alias blender='/Applications/blender-2.80.0/blender.app/Contents/MacOS/blender'` Exit nano by `ctrl + x` and press `y` to save changes type `source ~/.bash_profile` You only need to do this once. Now every time you need to open Blender from the command line, open terminal and type `blender` Blender will launch from the terminal and you can see the output.
If you want to be able to launch it like any other application, the simplest way is to do this: 1. Launch **Automator** (it is in your Mac's Applications folder) and launch **Terminal** (it is in Applications/Utilities). 2. Create a new Application in Automator. ![](https://i.stack.imgur.com/mfQed.png) 3. Type "run" in the variables search field, and drag **Run Shell Script** to the right part of the workspace. ![](https://i.stack.imgur.com/6BPta.png) 4. In **Finder**, locate **Blender.app** (it is probably in your Applications folder). Right click on the app and choose **Show Package Contents**. Inside the Contents, navigate to `/Contents/MacOS/Blender` 5. Drag this **Blender** file onto your Terminal window and Terminal will show you the file path. For me it is `/Applications/Blender\ 2.9.app/Contents/MacOS/Blender`, for example. 6. Copy that file path. Inside Automator, in the Run Shell Script text field, type `open` then space, then paste in the file path. Example: `open /Applications/Blender\ 2.9.app/Contents/MacOS/Blender` [![Launching Blender with the Terminal console, using a shell script in Automator](https://i.stack.imgur.com/35GQU.png)](https://i.stack.imgur.com/35GQU.png) * **Note:** If you have multiple versions of Blender in your Applications folder (Blender 2.79b.app, Blender 2.9.app, Blender 2.92.app ...) and update regularly (as you should), then it might make more sense to create an **alias** in your Applications folder of ...`/Contents/MacOS/Blender` called something like "Blender - Console" and use that for your shell script path instead: `open /Applications/Blender\ -\ Console`. Then you don't need to mess with Automator each time you get a new version of Blender - simply make a new alias with the name "Blender - Console". This way launching "Blender (Console).app" (or whatever you name it) will always point to the latest. 7. Name and save your launcher app in your Applications folder. Then in Finder you can drag it to your Dock. ![](https://i.stack.imgur.com/u5f8t.png) 8 (Optional). If you don't like the default robot icon, you can give your app a custom icon using Finder's Info window. In your Applications folder, select both Blender.app and your new custom app, then press `Cmd``I` to **Get Info**. Click on Blender.app's icon to highlight it, then `Cmd``C` to copy it. Then click to highlight your app's icon and press `Cmd``V` to paste the blender icon in. ![](https://i.stack.imgur.com/fdhbO.gif) You can create a custom icon too if you like, open it in Preview and copy it. But icon design is beyond the scope of this topic. Enjoy your custom launcher app. --- **Edit:** One final thing to mention is that *the first time* you launch a newly installed version of Blender you should launch the Blender app normally instead of through your custom launcher. This gives macOS a chance to verify it so that you don't run into any errors when launching. In other words, let your Mac do this once: ![](https://i.stack.imgur.com/odv76.png)
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
Without creating a new application with Applescript and all, you can just create a shell script with the '.command' extension. The extension makes it clickable, which opens a console and executes the file. 1. Open a terminal 2. `cd /Applications` 3. `nano Blender.command` paste this and save the file ``` #!/bin/sh cd `dirname $0`; ./Blender.app/Contents/MacOS/Blender ``` 4. `chmod u+x Blender.command` Now click on the 'Blender.command' icon next to your Blender application.
It seem's I cannot comment. Small note, blender 3.x is located at: `/Applications/Blender.app/Contents/MacOS/Blender`
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
Right click on the Blender icon in the Applications folder and select "Show Package contents". Make an alias of `Contents/MacOS/Blender` by right clicking and selecting "Make Alias". Rename it and move it somewhere you like. This opens the console in the background, next to the Blender application. source: <https://www.lynda.com/Blender-tutorials/Set-up-Blender-console-window/486043/533594-4.html>
A really quick way for mac users to do this is to create an alias using the Terminal (It's not as scary as it looks) open Terminal type `nano ~/.bash_profile` on the first line paste this `alias blender='/Applications/blender-2.80.0/blender.app/Contents/MacOS/blender'` Exit nano by `ctrl + x` and press `y` to save changes type `source ~/.bash_profile` You only need to do this once. Now every time you need to open Blender from the command line, open terminal and type `blender` Blender will launch from the terminal and you can see the output.
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
A really quick way for mac users to do this is to create an alias using the Terminal (It's not as scary as it looks) open Terminal type `nano ~/.bash_profile` on the first line paste this `alias blender='/Applications/blender-2.80.0/blender.app/Contents/MacOS/blender'` Exit nano by `ctrl + x` and press `y` to save changes type `source ~/.bash_profile` You only need to do this once. Now every time you need to open Blender from the command line, open terminal and type `blender` Blender will launch from the terminal and you can see the output.
Without creating a new application with Applescript and all, you can just create a shell script with the '.command' extension. The extension makes it clickable, which opens a console and executes the file. 1. Open a terminal 2. `cd /Applications` 3. `nano Blender.command` paste this and save the file ``` #!/bin/sh cd `dirname $0`; ./Blender.app/Contents/MacOS/Blender ``` 4. `chmod u+x Blender.command` Now click on the 'Blender.command' icon next to your Blender application.
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
The only way to see the Blender console and thus the script output is to launch Blender from a terminal using the full path to the executable: `"/Applications/Blender/blender.app/Contents/MacOS/blender"` All script output will appear in the terminal only. Following @DickMeehan's comment and since I hate to install yet another App, here is the AppleScript to automatically start a Blender with its Terminal window. Note: tested on `MacOS High Sierra 10.13.3` only: ``` set blenderAppPath to "/Applications/Blender/blender.app/Contents/MacOS/blender" (* This command will open a Terminal app that should be closed with CMD-Q otherwise it will persist after Blender and the terminal window are closed with CMD-W *) set openCmd to "open -n -W -a /Applications/Utilities/Terminal.app/Contents/MacOS/Terminal --args " do shell script openCmd & blenderAppPath ``` Refer to the following to make an actual clickable App using the Automator. This app can then be simply dragged to the launch bar for convenience. <https://apple.stackexchange.com/questions/84348/how-can-i-create-a-stand-alone-app-to-run-a-terminal-command> [![enter image description here](https://i.stack.imgur.com/T5KT6.gif)](https://i.stack.imgur.com/T5KT6.gif) [![enter image description here](https://i.stack.imgur.com/qR5lX.gif)](https://i.stack.imgur.com/qR5lX.gif)
It seem's I cannot comment. Small note, blender 3.x is located at: `/Applications/Blender.app/Contents/MacOS/Blender`
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
The only way to see the Blender console and thus the script output is to launch Blender from a terminal using the full path to the executable: `"/Applications/Blender/blender.app/Contents/MacOS/blender"` All script output will appear in the terminal only. Following @DickMeehan's comment and since I hate to install yet another App, here is the AppleScript to automatically start a Blender with its Terminal window. Note: tested on `MacOS High Sierra 10.13.3` only: ``` set blenderAppPath to "/Applications/Blender/blender.app/Contents/MacOS/blender" (* This command will open a Terminal app that should be closed with CMD-Q otherwise it will persist after Blender and the terminal window are closed with CMD-W *) set openCmd to "open -n -W -a /Applications/Utilities/Terminal.app/Contents/MacOS/Terminal --args " do shell script openCmd & blenderAppPath ``` Refer to the following to make an actual clickable App using the Automator. This app can then be simply dragged to the launch bar for convenience. <https://apple.stackexchange.com/questions/84348/how-can-i-create-a-stand-alone-app-to-run-a-terminal-command> [![enter image description here](https://i.stack.imgur.com/T5KT6.gif)](https://i.stack.imgur.com/T5KT6.gif) [![enter image description here](https://i.stack.imgur.com/qR5lX.gif)](https://i.stack.imgur.com/qR5lX.gif)
If you want to be able to launch it like any other application, the simplest way is to do this: 1. Launch **Automator** (it is in your Mac's Applications folder) and launch **Terminal** (it is in Applications/Utilities). 2. Create a new Application in Automator. ![](https://i.stack.imgur.com/mfQed.png) 3. Type "run" in the variables search field, and drag **Run Shell Script** to the right part of the workspace. ![](https://i.stack.imgur.com/6BPta.png) 4. In **Finder**, locate **Blender.app** (it is probably in your Applications folder). Right click on the app and choose **Show Package Contents**. Inside the Contents, navigate to `/Contents/MacOS/Blender` 5. Drag this **Blender** file onto your Terminal window and Terminal will show you the file path. For me it is `/Applications/Blender\ 2.9.app/Contents/MacOS/Blender`, for example. 6. Copy that file path. Inside Automator, in the Run Shell Script text field, type `open` then space, then paste in the file path. Example: `open /Applications/Blender\ 2.9.app/Contents/MacOS/Blender` [![Launching Blender with the Terminal console, using a shell script in Automator](https://i.stack.imgur.com/35GQU.png)](https://i.stack.imgur.com/35GQU.png) * **Note:** If you have multiple versions of Blender in your Applications folder (Blender 2.79b.app, Blender 2.9.app, Blender 2.92.app ...) and update regularly (as you should), then it might make more sense to create an **alias** in your Applications folder of ...`/Contents/MacOS/Blender` called something like "Blender - Console" and use that for your shell script path instead: `open /Applications/Blender\ -\ Console`. Then you don't need to mess with Automator each time you get a new version of Blender - simply make a new alias with the name "Blender - Console". This way launching "Blender (Console).app" (or whatever you name it) will always point to the latest. 7. Name and save your launcher app in your Applications folder. Then in Finder you can drag it to your Dock. ![](https://i.stack.imgur.com/u5f8t.png) 8 (Optional). If you don't like the default robot icon, you can give your app a custom icon using Finder's Info window. In your Applications folder, select both Blender.app and your new custom app, then press `Cmd``I` to **Get Info**. Click on Blender.app's icon to highlight it, then `Cmd``C` to copy it. Then click to highlight your app's icon and press `Cmd``V` to paste the blender icon in. ![](https://i.stack.imgur.com/fdhbO.gif) You can create a custom icon too if you like, open it in Preview and copy it. But icon design is beyond the scope of this topic. Enjoy your custom launcher app. --- **Edit:** One final thing to mention is that *the first time* you launch a newly installed version of Blender you should launch the Blender app normally instead of through your custom launcher. This gives macOS a chance to verify it so that you don't run into any errors when launching. In other words, let your Mac do this once: ![](https://i.stack.imgur.com/odv76.png)
102,860
Noobie here. Should I open Mac terminal and cd to /Applications/Blender/ which is where my Blender app is? Doesn't seem to work for me trying to run script from Text screen in Blender. I guess there is no way to see output within Blender itself?
2018/03/11
[ "https://blender.stackexchange.com/questions/102860", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53255/" ]
A really quick way for mac users to do this is to create an alias using the Terminal (It's not as scary as it looks) open Terminal type `nano ~/.bash_profile` on the first line paste this `alias blender='/Applications/blender-2.80.0/blender.app/Contents/MacOS/blender'` Exit nano by `ctrl + x` and press `y` to save changes type `source ~/.bash_profile` You only need to do this once. Now every time you need to open Blender from the command line, open terminal and type `blender` Blender will launch from the terminal and you can see the output.
It seem's I cannot comment. Small note, blender 3.x is located at: `/Applications/Blender.app/Contents/MacOS/Blender`
10,771,653
Why does the textfield doesn't follow the `.span1` rule? What can I do to fix it? <http://jsfiddle.net/aurorius/aNRBn/> ``` <html> <head> <title></title> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> <form class="form-horizontal"> <fieldset> <div class="control-group"> <label class="control-label" for="focusedInput">Focused input</label> <div class="controls"> <input class="focused span1" id="focusedInput" type="text" value="This is focused" /> </div> </div> <div class="control-group"> <label class="control-label">Uneditable input</label> <div class="controls"> <span class="span1 uneditable-input">Some value here</span> </div> </div> </fieldset> </form> </div> </div> </div> </body> </html> ​ ``` A quick way to fix it is by changing `row-fluid` to `row`. But how do I fix it while still using the `row-fluid` tag?
2012/05/27
[ "https://Stackoverflow.com/questions/10771653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113573/" ]
It would be much more convenient to define allowed routes in routes.rb and add exception handling in application controller for routing error: ``` class ApplicationController < ActionController::Base rescue_from ActionController::RoutingError, :with => :render_not_found private def render_not_found render_error_page_for(404) end def render_error_page_for(code) respond_to do |format| format.html { render :file => "#{Rails.root}/public/#{code}.html", :status => code, :layout => false } end end ```
i do catch my exception handling in my application controller but unfortunately for admin\_data, i don't explicitly set it in routes.rb. it gets configured somewhere in the gem with namespace or something (im not really sure) but on a positive note... i finally fixed it! i changed my glob and did... ``` match '*not_found', to: 'errors#error_404', :constraints => {:subdomain => "!(admin_data.)"} ``` to ignore everything which uses admin\_data.
73,537,836
At the moment, I am working on a project that requires me to add three videos to the homepage, but loading them all at once will reduce the load time considerably. Also i want to use `<video/>` tag instead of using `<iframe/>` because i want that autoplay functionality. What's the best way to do this in React? Using NextJS and Chakra UI.
2022/08/30
[ "https://Stackoverflow.com/questions/73537836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033113/" ]
You can use [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) and do it as below. For React all you have to do is to add the below code in an `useEffect` with empty dependency. ```js const video = document.querySelector("video"); function handleIntersection(entries) { entries.map(async (entry) => { if (entry.isIntersecting) { const res = await fetch("/video.mp4"); const data = await res.blob(); video.src = URL.createObjectURL(data); } }); } const observer = new IntersectionObserver(handleIntersection); observer.observe(video); ``` ```html <video autoplay muted loop playsinline></video> ``` Also I used a video with a relative path to avoid possible [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS) issues.
i found a way to do it using '[@react-hook/intersection-observer](https://www.npmjs.com/package/@react-hook/intersection-observer)' ``` import useIntersectionObserver from '@react-hook/intersection-observer' import { useRef } from 'react' const LazyIframe = () => { const containerRef = useRef() const lockRef = useRef(false) const { isIntersecting } = useIntersectionObserver(containerRef) if (isIntersecting) { lockRef.current = true } return ( <div ref={containerRef}> {lockRef.current && ( <video src={"add video source here"} type="video/mp4" ></video> )} </div> ) } ```
51,133,540
Is it possible to track the cost of bigquery queries using the `configuration.labels` attribute on a query request? I have specified some labels and I do find it in the job definition as you can see here: ``` { "configuration": { "labels": { "label1": "tomas", "label2": "yolo" }, "query": { "allowLargeResults": false, "createDisposition": "CREATE_IF_NEEDED", "destinationTable": { "datasetId": "dataset", "projectId": "project name", "tableId": "label " }, "priority": "INTERACTIVE", "query": "a select query", "useLegacySql": false, "writeDisposition": "WRITE_TRUNCATE" ... } ``` I have also enabled billing export under billing, but when I look at the exported data I can’t find my labels. Labeling works fine when applied to dataset and tables, but I can't get it to work with queries. Are these labels for queries something else and doesn't show up in the billing?
2018/07/02
[ "https://Stackoverflow.com/questions/51133540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280693/" ]
I have not been able to query or filter on specific labels, but can at least display them with this... ``` SELECT service.description, cost, labels FROM `PROJECTNAME.billing_report.gcp_billing_export_v1_016D47_E84908_9F5AB5` WHERE cost > 0 LIMIT 1000 ```
If you use `bq` command, you can do it by adding `--label` flag as below ```sh bq query \ --nouse_legacy_sql \ --label foo:bar \ 'SELECT COUNT(*) FROM `bigquery-public-data`.samples.shakespeare' ``` Then, you can issue below filter in Cloud logging ``` resource.type="bigquery_resource" protoPayload.serviceData.jobCompletedEvent.job.jobConfiguration.labels.foo="bar" ``` For API or Client Library, check this [object](https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#jobconfiguration)
236,743
I'm looking into solid state relays for an application where I need to switch between two different transducers to allow two different modes of operation for an echo sounder. Basically a MUX that allows selecting either transducer #1 or transducer #2. Short overview of how an echo sounder works: the echo sounder generates a short pulse (1-10 ms, 60 Vrms) which is emitted through the transducer. Then afterwards the echo sounder goes into listening mode receiving the returned echo which reflects of objects and the bottom as it travels through the water column. Developing a MUX has some challenging requirements for this kind of signal: * transmit requires a relatively high voltage signal to pass through (max 60 Vrms sinusoid of 1-10 ms duration), whereas when the echo sounder is listening it will receive a signal which has a low amplitude (< 10 mV). * The signal should pass through without distortion (close to linear transfer curve). * The received signal should not be colored by noise (high S/N ratio, > ~90 dB). * Signal is bipolar. Is this even possible with SSRs? A better device? With solid state relays I'm wondering if a device capable of relatively high current will not perform well for low signals during receiving (non-linearity or too noisy). Of course a mechanical relay would solve all these but might not last as long if switching frequently and reliability is important (i.e. years). [![Drawing shows TX and RX circuitry switched during transmit and receive (listen) phase. Operator can switch the mux to use transducer 1 or 2 when echo sounder is off.](https://i.stack.imgur.com/39E7e.png)](https://i.stack.imgur.com/39E7e.png) Assumptions: Both transmit and received signals have no DC component. Transmit is a pure tone of e.g. 35 kHz. The received signals will be more wideband, but will be bandpass filtered in the receiver. The switching between transducer 1 and 2 can be restricted to only occur when system is turned off. Transducers are ceramic. Impedance of transducer at transmit frequency is on the order of 1.5 kOhm. Assume max 40 mA inst. current during transmit pulse. Assume there is no ringing in existing circuit as transmit pulse has smooth envelope (ramp up/down). The transmit circuitry is only connected for as long as the pulse is transmitted, afterwards the receiver is connected and listens until the next transmit ping.
2016/05/27
[ "https://electronics.stackexchange.com/questions/236743", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/41060/" ]
The 74HC4051 has level shifters inside that allow you to use a logic supply that is GND to Vcc and another supply voltage Vee that is less than (or equal to) GND. This is a great advantage when you want to use dual supplies such as +/-5V for the analog electronics, and the digital signals are 0 to +5 (or +/-3.3V with digital logic 0/3.3V), and if you don't need the feature you can just ground Vee. I am not sure I believe the operating area shown here: [![enter image description here](https://i.stack.imgur.com/MadfI.png)](https://i.stack.imgur.com/MadfI.png) The early CD4051 clearly required Vee <= GND.
The CD4051 mux can work at +15 volts single-ended supply, or +/- 7.5 volts for bipolar supply handling bipolar signals to +/- 5 volts or so. The IC also needs a ground ref for the 3 to 5 volt logic used to select which of 8 input/outputs is selected to connect to the common I/O pin. So for bipolar operation you need 3 power supply voltages and a gnd connection. The Vee pin is the negative power for the analog section. For bipolar operation it is connected to -7.5 volts. For single supply operation Vee is connected to ground. Even powered by +/- 7.5 volts for the CD4051, it is best to keep an analog signal in the range of +/- 5 volts, at the channel resistance goes way up close to the supply rails. The 74HC4051 is limited to 11 volts single ended supply or +/- 5.5 volts for a bipolar supply. The signals are limited to about +/- 3.5 volts.
74,776
Do we have any standard for using ghost buttons? I know basic details on when to use ghost buttons but more detailed explanation will help Can we use ghost button as well as solid button on same page? If you notice, there is close icon next to close button. Do you think its very smalll and it should also be button? That close is to close page. ![enter image description here](https://i.stack.imgur.com/N2VXL.png)
2015/03/12
[ "https://ux.stackexchange.com/questions/74776", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/52106/" ]
This question is quite broad for a single answer to cover everything, but I'll give it a go! First of all, **motion sickness**. In actual fact it's not even motion sickness, it's the opposite - it's the brain telling you you're moving when other senses tell you you're not. And in any case, it's not the manipulation of scene elements itself that is directly related to the problem of sickness (or v-sickness, simulator sickness, Rift Sickness, or whatever you want to call it). I worked as a developer on VR games and simulation experiences at the beginning of the 1990's - the times of Virtuality and Sega VR. At that time we had a lot of trouble with sickness. In a typical end-user environment, games were kept to about 2 minutes of playtime because after that we found people quickly started feeling unwell. Experiences tended to be slower and less frantic than games so you could get more time, but still the problem persisted. Getting students in to test our equipment (which they happily did!) often turned out to be a err.. messy business because of the longer testing times. The causes of sickness in VR then were mostly down to the lag between motion of the body, especially the head, and the resulting visuals in the headset feeding back to the eyes. The more lag, the sooner you became disoriented and felt ill. The headsets were heavy, the refresh rate on the display was relatively low compared to modern VR equipment, and the trackers themselves had relatively high latency and sample rates. All this has had *a lot* of money thrown at it in recent years in order to reduce the lag. Tracker sample rates are now up to 1kHz and the motion lag is down to just a couple of milliseconds, drastically reducing the risk of graphics entering the 'barfogenic zone'. Displays have changed (from LCD to OLED) in order to reduce smearing and increase sharpness and refresh rates. And the ability to fine-tune or calibrate the headsets for individual users is much better now compared to the 'one ring to rule them all' approach that has been used in the past which essentially meant that no user ever had it right! Overwhelming the senses is another thing that can add to the sickness feeling. The games of the 1990's were played in tremendously loud bustling hot environments like London's Trocadero. Reducing brightness, volume, and environmental effects allows you to take back some control of your senses to 'manage' the situation better without being overwhelmed. So my point this far is that the feeling of sickness comes from the experience as a whole. If you tried to use a mouse as a VR input device that would not in itself be a cause. **The mouse is not an appropriate interaction mechanism** for VR, other than the fact that it has scrolly type wheel which can be useful. The natural input method for VR is your hands (putting accessibility aside - just for the moment), not least because they are always with you, and you can't put them down, but also because you don't have to think about using them. A mouse essentially needs a flat surface which is a mismatch from manipulating a 3D environment. In fact, even talk of using similar hand held controllers to existing games is probably naive. Leaving the hands free to 'do their thing' is I think a critical step in making VR usable for most people. The use of gestures or particular hand or arm positions will have meaning. Sign language might be useful. So **drag and drop games** would need to cater for different orientations of the body, the game, the head and the hands. Luckily we're already quite used to device touchscreens and using them at different angles so touch, drag, swipe, pinch, expand gestures are already quite well known and these would translate quite well to a drag and drop game in a VR environment allowing the user to immerse themselves and orient themselves and the scene and it's elements to a comfortable point. This is in fact the least of the worries. Most VR development probably starts out with exactly some simple drag and drop game, but the problems come when you start dealing with real detailed, meaningful, personal data, and interfacing between the virtual and real worlds, because that's what is going to be needed - in the same way that we talk about cross-channel and multi-channel experiences for desktop, mobile and brick & morter environments. Finally - **I don't think you would ever 'port over'** the UI/UX of a drag and drop game to VR. You would have to completely rethink the interactions from the ground up. You would have to strip back the concept of the game to it's bare bones and then say 'how could we do that in VR'? That's not to say there won't be games of the same name carried over from the PC or consoles, but they'll take as much investment of time and money, if not more, to get perfect for VR as they did originally.
The reason why a mouse is a terrible UI for VR is because when you (inevitably) take your hand off of it (to type or itch or eat etc.), then you have to find the mouse without being able to see it! That can't happen in VR. You have to be able to see the things you're interacting with **or** the things you're interacting with have to be either 2-handed items that you won't put down **or** basically impossible to put down. e.g. gloves, a gun, an xbox controller or your own hands.
38,007,813
Which one should i use in an angular app and why? ``` array.filter(o => o.name === myName); ``` or ``` $filter('filter')(array, {name: myName}, true); ```
2016/06/24
[ "https://Stackoverflow.com/questions/38007813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967289/" ]
The key difference is the **shortcuts or syntactic sugar** provided by the `$filter('filter')`. For example, the following syntax can be used to get the items containing the `keyword` string in any of the item's `string` properties: ``` $filter('filter')(array, 'keyword') ``` Which can not be as simple using the standard ES5 `Array.prototype.filter`. Whereas the general idea is the same for both approaches - to return a subset of a given array as a **NEW** array. **Update**: [Under the hood](https://github.com/angular/angular.js/blob/master/src/ng/filter/filter.js#L3) angular uses the `Array.prototype.filter`: ``` function filterFilter() { // predicateFn is created here... return Array.prototype.filter.call(array, predicateFn); } ``` So, if you don't use the shortcuts - angular simply delegates the call to the standard `filter`. **To answer your question**: use the one that lets you write less code. In your particular case it would be `array.filter(o => o.name === myName);`
You should use `Array.filter` and then assign the result. When you use `$filter`, it is re-applied at the end of every **$digest** cycle for all the bindings and that is performance intensive to watch for the values and update the results after every **$digest** cycle. Instead you should filter your result and assign it to your scope variable explicitly
38,007,813
Which one should i use in an angular app and why? ``` array.filter(o => o.name === myName); ``` or ``` $filter('filter')(array, {name: myName}, true); ```
2016/06/24
[ "https://Stackoverflow.com/questions/38007813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967289/" ]
While using $filter('filter') can be easier and more syntactically attractive, I can think of four good reasons to use Array.filter over $filter('filter') **Efficiency** While it is true that $filter('filter') uses Array.filter under the hood, it also uses other code, including deep comparisons, in addition to Array.filter. In most cases the speed difference is negligible, but in some use cases it can be substantial. When working with large data objects for example, I've found that using Array.filter makes a difference. **Angular 2+ does not support AngularJS-style filter** From the [angular migration guide](https://angular.io/guide/upgrade#no-angular-filter-or-orderby-filters): > > The built-in AngularJS filter and orderBy filters do not exist in > Angular, so you need to do the filtering and sorting yourself. > > > If there is any possibility that you may upgrade to Angular 2 or higher in the future, then using Array.filter will save you some migration migraines. Even if you don't plan on upgrading, clearly the Angular team didn't think the AngularJS filter was worth keeping, which leads me to think it's probably better to avoid it anyway. **Favor native code over library code** Libraries and frameworks like AngularJS are amazing tools; But if you have to choose between using vanilla javascript or using a library, *and there isn't a good reason to use the library*, you should always use the vanilla javascript. It is more universally understood, less dependent on 3rd party code, etc. There are a plethora of online articles arguing this point. **"$filter" inhibits type-checking in Typescript files** This one only applies if you use (or plan to use) Typescript. At the time of writing, the @types library for angularjs defines the return type of all $filter functions as *any*, which can lead to some serious type-checking problems if you aren't careful. By contrast, Array.filter always returns the expected array type.
You should use `Array.filter` and then assign the result. When you use `$filter`, it is re-applied at the end of every **$digest** cycle for all the bindings and that is performance intensive to watch for the values and update the results after every **$digest** cycle. Instead you should filter your result and assign it to your scope variable explicitly
20,329,018
I have used [OverScroller](http://developer.android.com/reference/android/widget/OverScroller.html) for implementing scroll of my view. Here is some code: ``` @Override protected void onDraw(Canvas canvas) { if (scroller.computeScrollOffset()){ int x = scroller.getCurrX(); int y = scroller.getCurrY(); scrollTo(x, y); ViewCompat.postInvalidateOnAnimation(this); } super.onDraw(canvas); } public void open(){ scroller.startScroll(0, 0, 0, -mContent.getMeasuredHeight(), ANIMATION_TIME); invalidate(); } public void close(){ scroller.startScroll(0, getScrollY(), 0, mContent.getMeasuredHeight(), ANIMATION_TIME); invalidate(); } ``` It works fine. But on device with Full HD screen (Sony xperia Z) the method onDraw calls 4 times. On "Samsung Galaxy Note 2" it calls about 10 times. Hence on xperia i see lags. What can i do to improve performance ? **UPD:** Here is full code <http://xsnippet.org/359714>
2013/12/02
[ "https://Stackoverflow.com/questions/20329018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368428/" ]
you should override computeScroll() for things like that and not onDraw()
You can override **onFinishInflate ()** method in your custom View class and you can write OverScroll related code under this method instead of **onDraw()**. For more detail [click here](http://developer.android.com/reference/android/view/View.html#onFinishInflate%28%29).
451,983
> > Let $N>1$ be a positive integer. What will be the Arithmetic mean of positive integers less than $N$ and co-prime with $N$? > > > Getting no idea how to proceed!
2013/07/25
[ "https://math.stackexchange.com/questions/451983", "https://math.stackexchange.com", "https://math.stackexchange.com/users/53265/" ]
(The way the problem reads at this time is "What will be the Arithmetic mean of positive integers less than $N$ and co-prime with $N$?" (I mention this in case there was some other version of the question and it got edited.)) $n$ is coprime to $N$ if and only if $N-n$ is coprime to $N$. The average of $n$ and $N-n$ is $N/2$. The average of the averages of all such cases is the average of a bunch of numbers each equal to $N/2$. The average of all numbers in $\{1,\dots,N\}$ that are coprime to $N$ is therefore $N/2$. **Later edit:** Here's an example. The numbers in $\{1,\dots,20\}$ that are coprime to $20$ are $1,3,7,9,11,13,17,19$. They come in these pairs: \begin{align} 1, & 19 \text{ (The average of these two is $10$.)} \\ 3, & 17 \text{ (The average of these two is $10$.)} \\ 7, & 13 \text{ (The average of these two is $10$.)} \\ 9, & 11 \text{ (The average of these two is $10$.)} \end{align} Now take the average of all those $10$s. The average is $10$.
HINT: As $(a,n)=(n-a,n),$ Let $$S=\sum\_{1\le a\le n,(a,n)=1}a,$$ then $$S=\sum\_{1\le a\le n,(a,n)=1}(n-a)$$ $$\implies2S=\phi(n)(a+n-a)=n\phi(n)$$ where $\phi(n)$ is the Euler [Totient](http://en.wikipedia.org/wiki/Euler%27s_totient_function) function, the number of positive integers $<n$ and co-prime to $n$ The Arithmetic mean will be $\frac S{\phi(n)}$
3,791,345
Let $F([0,1], \mathbb{R})$ the space of functions of [0,1] in $\mathbb{R}$, together with the topology of the point convergence $\tau$. Show that the set of continuous functions of [0,1] in $\mathbb{R}$ is dense in $(F([0,1], \mathbb{R}), \tau)$.
2020/08/15
[ "https://math.stackexchange.com/questions/3791345", "https://math.stackexchange.com", "https://math.stackexchange.com/users/651825/" ]
You can indeed use the Riesz representation theorem to solve the problem. The hypothesis $$ \left| \int f g \right | \leq M \| f\|\_{p}$$ shows in particular that the element $g$ defines a linear continuous functional $T\_g$ on the space $L^{p}$ via the relation $$T\_g(f) = \int f g.$$ Now, Riesz representation theorem tells you that there exists a unique $h \in L^{q}$ that represents the functional $T\_g$ in the sense that $$T\_g(f) = \int hf \hspace{0.9 cm} \text{for any $f \in L^{p}$.}$$ Moreover, the theorem states that $\|T\_g\| = \|h\|\_{q}$. From this you may deduce that $g=h$ and since you already have seen that $\|T\_g\| \leq M$, you inmediately obtain that $\|g \| \leq M.$
I will assume that $g$ is real valued and $p>1$. (The case $p=1$ is similar). I will prove b) directly and a) follows from b). Let $N$ be a positive integer and $f=(sgn \,g)|g|^{q/p}I\_{|g| \leq N}$ where $q$ is the conjugate index. Then $g$ is bounded and the given inequality becomes $\int\_{|g| \leq N} |g|^{q} \leq M (\int\_{|g| \leq N} |g|^{q})^{1/p}$. This implies that $(\int\_{|g| \leq N} |g|^{q})^{1/q} \leq M$. now let $N \to \infty$.
2,202,271
Is there a way to have an app write a into a file and then have another app read from that file? I mean writting into the file system of the iPhone. I want to do this without using an internet connection. So uploading the file and then downloading from the other app is not what i mean. Thanks!
2010/02/04
[ "https://Stackoverflow.com/questions/2202271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217808/" ]
It appears that there are ways you can, but it won't get approved by Apple if you do. See <http://blogs.oreilly.com/iphone/2008/09/sandbox-think-like-apple.html> for more information.
I'm not sure exactly what circumstances you're in here, but you could register app B as a handler for a particular protocol, and have app A try to open such a link (e.g. appB://yourinfohere). It depends on how much data you want to transfer and many other things, but it might work.
2,202,271
Is there a way to have an app write a into a file and then have another app read from that file? I mean writting into the file system of the iPhone. I want to do this without using an internet connection. So uploading the file and then downloading from the other app is not what i mean. Thanks!
2010/02/04
[ "https://Stackoverflow.com/questions/2202271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217808/" ]
The current sand boxing of applications does not allow this, however it appears that this may be available in future iPhone OS versions. [Reference](http://www.techhail.com/gadgets/iphone-os-3-2-for-ipad-with-improved-text-file-document-support-xcode-tools/3088)
I'm not sure exactly what circumstances you're in here, but you could register app B as a handler for a particular protocol, and have app A try to open such a link (e.g. appB://yourinfohere). It depends on how much data you want to transfer and many other things, but it might work.
43,035,000
Can someone explain why the second promise returned by then function is resolved? It looks like Angular JS bug in its Promises implementation. According to the documentation [here](https://docs.angularjs.org/api/ng/service/$q) the second promise should also have been rejected. ```js // Code goes here var myMod = angular.module("myMod", []); myMod.controller('bodyCtrl', function($scope, $timeout, $q) { var deferred = $q.defer(); deferred.promise.then(function(d) { console.log("success called"); return d; }, function(d) { console.log("failure called"); return d; }) .then(function(d) { console.log("success called2"); return d; }, function(d) { console.log("failure called2"); return d; }); $timeout(function() { deferred.reject(); }, 2 * 1000); }); ``` ```html <!DOCTYPE html> <html ng-app="myMod"> <head> <script src="https://code.angularjs.org/1.5.8/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-controller="bodyCtrl"> <h1>Hello Plunker!</h1> </body> </html> ```
2017/03/26
[ "https://Stackoverflow.com/questions/43035000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079362/" ]
So: 1. **One-to-one**: you could use a `Dense` layer as you are not processing sequences: ```py model.add(Dense(output_size, input_shape=input_shape)) ``` 2. **One-to-many**: this option is not supported well as chaining models is not very easy in `Keras`, so the following version is the easiest one: ```py model.add(RepeatVector(number_of_times, input_shape=input_shape)) model.add(LSTM(output_size, return_sequences=True)) ``` 3. **Many-to-one**: actually, your code snippet is (almost) an example of this approach: ```py model = Sequential() model.add(LSTM(1, input_shape=(timesteps, data_dim))) ``` 4. **Many-to-many**: This is the easiest snippet when the length of the input and output matches the number of recurrent steps: ```py model = Sequential() model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True)) ``` 5. **Many-to-many when number of steps differ from input/output length**: this is freaky hard in Keras. There are no easy code snippets to code that. **EDIT: Ad 5** In one of my recent applications, we implemented something which might be similar to *many-to-many* from the 4th image. In case you want to have a network with the following architecture (when an input is longer than the output): ```py O O O | | | O O O O O O | | | | | | O O O O O O ``` You could achieve this in the following manner: ```py model = Sequential() model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True)) model.add(Lambda(lambda x: x[:, -N:, :])) #Select last N from output ``` Where `N` is the number of last steps you want to cover (on image `N = 3`). From this point getting to: ```py O O O | | | O O O O O O | | | O O O ``` is as simple as artificial padding sequence of length `N` using e.g. with `0` vectors, in order to adjust it to an appropriate size.
Great Answer by @Marcin Możejko I would **add the following to NR.5** (many to many with different in/out length): A) as Vanilla LSTM ``` model = Sequential() model.add(LSTM(N_BLOCKS, input_shape=(N_INPUTS, N_FEATURES))) model.add(Dense(N_OUTPUTS)) ``` B) as Encoder-Decoder LSTM ``` model.add(LSTM(N_BLOCKS, input_shape=(N_INPUTS, N_FEATURES)) model.add(RepeatVector(N_OUTPUTS)) model.add(LSTM(N_BLOCKS, return_sequences=True)) model.add(TimeDistributed(Dense(1))) model.add(Activation('linear')) ```
34,572,816
First of all I'm a newbie to Python. I'm trying to combine multiple data into a single CSV. Following is the CSV format, **file1.csv** ``` Country of Residence,2014-04,2015-04 NORTH AMERICA ,"5,514","6,160" Canada ,"2,417","2,864" U.S.A. ,"3,097","3,296" LATIN AMERICA & THE CARIBBEAN ,281,293 WESTERN EUROPE ,"37,369","34,964" Austria ,893,666 Belgium ,867,995 ``` **file2.csv** ``` Country of Residence,2014-11,2015-11 LATIN AMERICA & THE CARIBBEAN ,373,418 Argentina ,47,50 Brazil ,68,122 Chille ,24,30 Colombia ,31,25 Others ,203,191 WESTERN EUROPE-OTHERS ,1330,1367 Croatia ,77,72 Greece ,408,452 Ireland ,428,343 Finland ,149,178 Portugal ,211,261 Others ,57,61 ``` In the final csv, I would like to have a unique header list as, ``` Country of Residence,2014-04,2015-04,2014-05,2015-05,..2014-11,2014-11 NORTH AMERICA ,"5,514","6,160",NaN,Nan,... Portugal, Nan,Nan,Nan,Nan,.....,211,261 ``` Also I would like have the country list to be unique, so I can fill the numbers by reading the csv list. In the following code I get unique column headers but I don't know how to make the Country column unique and add a number based on country and month of the year.. Any help is greatly appreciated. ``` for filename in glob.iglob(os.path.join('/Documents/stats/csv','*.csv')): with open(filename,'rb') as f: csvIn = csv.reader(f) hdr = csvIn.next() hdr[0] = hdr[0].replace('\xef\xbb\xbf','') hdrList.append((len(hdr),hdr)) hdrList.sort() hdrs = [] template = [] for t in hdrList: for f in t[1]: print(f) if if not (f in hdrs): hdrs.append(f) template.append('') ```
2016/01/03
[ "https://Stackoverflow.com/questions/34572816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5739474/" ]
There is a grate library for custom fonts in android: [custom fonts](https://github.com/chrisjenx/Calligraphy) Here is a sample how to use it. In gradle you need to put this line: ``` compile 'uk.co.chrisjenx:calligraphy:2.1.0' ``` Then make a class that extends application and write this code: ``` public class App extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("your font path") .setFontAttrId(R.attr.fontPath) .build() ); } } ``` In the activity class put this method before onCreate: ``` @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } ``` In your manifest file write like this: ``` <application android:name=".App" ``` It will change the whole activity to your font!. I'ts simple solution and clean!
You can achieve this in mainly 3 ways. one way would be to create a custom TextView and refer that everywhere, ie : ``` public class TypefacedTextView extends TextView { public TypefacedTextView(Context context, AttributeSet attrs) { super(context, attrs); Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName); setTypeface(typeface); } } ``` and inside View.xml ``` <packagename.TypefacedTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello"/> ``` Another way, is to use the powerful `Calligraphy` library in github. [see this](https://github.com/chrisjenx/Calligraphy) And finally, you can override the defaults with your own fonts, [see this](https://stackoverflow.com/questions/2711858/is-it-possible-to-set-font-for-entire-application)
13,758,536
This question has been asked several times in various forms but I haven't found a definitive answer. I need to be able to get dimensions and positions of descendant `Views` after the initial layout of a container (a `contentView`). The dimensions required in this case are of a View(Group) that is not predictable - might have multiple lines of text, minimum height to accommodate decoration, etc. I don't want to do it every on every layout pass (`onLayout`). The measurement I need is a from a deeply nested child, so overriding the `onLayout`/`onMeasure` of each container in between seems a poor choice. I'm not going to do anything that'll cause a loop (trigger-event-during-event). Romain Guy hinted once that we could just `.post` a `Runnable` in the constructor of a `View` (which AFAIK would be in the UI thread). This seems to work on most devices (on 3 of the 4 I have personally), but fails on Nexus S. Looks like Nexus S doesn't have dimensions for everything until it's done one pass per child, and does not have the correct dimensions when the `post`ed `Runnable`'s `run` method is invoked. I tried counting layout passes (in `onLayout`) and comparing to `getChildCount`, which again works on 3 out of 4, but a different 3 (fails on Droid Razr, which seems to do just one pass - and get all measurements - regardless of the number of children). I tried various permutations of the above (posting normally; posting to a `Handler`; casting `getContext()` to an `Activity` and calling `runOnUiThread`... same results for all). I ended up using a horrible shameful no-good hack, by checking the height of the target group against its parent's height - if it's different, it means it's been laid out. Obviously, not the best approach - but the only one that seems to work reliably between various devices and implementations. I know there's no built-in event or callback we can use, but is there a better way? TYIA **/EDIT** The bottom line for me I guess is that the Nexus S does not wait until after layout has completed when `.posting()` a `Runnable`, as is the case on all other devices I've tested, and as suggested by Romain Guy and others. I have not found a good workaround. Is there one?
2012/12/07
[ "https://Stackoverflow.com/questions/13758536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429430/" ]
I've been successful using the OnGlobalLayoutListener. It worked great on my Nexus S ``` final LinearLayout marker = (LinearLayout) findViewById(R.id.distance_marker); OnGlobalLayoutListener listener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //some code using marker.getHeight(), etc. markersContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }; marker.getViewTreeObserver().addOnGlobalLayoutListener(listener); ```
My own experience with OnGlobalLayoutListener is that it does not always wait to fire until all of the child views have been laid out. So, if you're looking for the dimensions of a particular child (or child of a child, etc.) view, then if you test them within the onGlobalLayout() method, you may find that they reflect some intermediate state of the layout process, and not the final (quiescent) state that will be displayed to the user. In testing this, I noticed that by performing a postDelayed() with a one second delay (obviously, a race condition, but this was just for testing), I did get a correct value (for a child of a child view), but if I did a simple post() with no delay, I got the wrong value. My solution was to avoid OnGlobalLayoutListener, and instead use a straight override of dispatchDraw() in my top-level view (the one containing the child whose child I needed to measure). The default dispatchDraw() draws all of the child views of the present view, so if you post a call to your code that performs the measurements after calling super.dispatchDraw(canvas) within dispatchDraw(), then you can be sure that all child views will be drawn prior to taking your measurements. Here is what that looks like: ``` @Override protected void dispatchDraw(Canvas canvas) { //Draw the child views super.dispatchDraw(canvas); //All child views should have been drawn now, so we should be able to take measurements // of the global layout here post(new Runnable() { @Override public void run() { testAndRespondToChildViewMeasurements(); } }); } ``` Of course, drawing will occur prior to your taking these measurements, and it will be too late to prevent that. But if that is not a problem, then this approach seems to very reliably provide the final (quiescent) measurements of the descendant views. Once you have the measurements you need, you will want to set a flag at the top of testAndRespondToChildViewMeasurements() so that it will then return without doing anything further (or to make a similar test within the dispatchDraw() override itself), because, unlike an OnGlobalLayoutListener, there is no way to remove this override.
59,398,255
I have an enumerable that goes through several transformation steps and a final filter step E.g ``` [1,2,3,4,5,6,7,8,9].map{|i| i * 2} .map{|i| i * i} .filter{|i| i % 3 ==0 } .each{|i| puts how_do_i_get_initial_value_here } .or_the_initial_value_here ``` How do I get the initial value whose transformations satisfied the filter? Thus in the above example, how do I end up with `[3,6,9]` instead of `[36, 144, 324]`
2019/12/18
[ "https://Stackoverflow.com/questions/59398255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560599/" ]
You need to carry original value to the final step. Object-oriented approach can help by introducing a "filter" type ``` class Filter attr_reader :value def initialize(value) @value = value end def satisfies? (value * 2 * value) % 3 == 0 end end ``` Usage ``` [1,2,3,4,5,6,7,8,9].map { |i| Filter.new(i) }.select(&:satisfies?).map(&:value) ```
You could just undo the things you did. So ``` [1,2,3,4,5,6,7,8,9] .map{ |i| i * 2 } .map{ |i| i * i } .filter{ |i| i % 3 ==0 } .map{ |i| Math.sqrt(i) / 2 } ```
59,398,255
I have an enumerable that goes through several transformation steps and a final filter step E.g ``` [1,2,3,4,5,6,7,8,9].map{|i| i * 2} .map{|i| i * i} .filter{|i| i % 3 ==0 } .each{|i| puts how_do_i_get_initial_value_here } .or_the_initial_value_here ``` How do I get the initial value whose transformations satisfied the filter? Thus in the above example, how do I end up with `[3,6,9]` instead of `[36, 144, 324]`
2019/12/18
[ "https://Stackoverflow.com/questions/59398255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560599/" ]
You need to carry original value to the final step. Object-oriented approach can help by introducing a "filter" type ``` class Filter attr_reader :value def initialize(value) @value = value end def satisfies? (value * 2 * value) % 3 == 0 end end ``` Usage ``` [1,2,3,4,5,6,7,8,9].map { |i| Filter.new(i) }.select(&:satisfies?).map(&:value) ```
You are given a method: ``` def f(n) 4 * n**2 end ``` where `f(n)` is the transformed value of an element `n` from the given array (as `(2 * n)*(2 * n) = 4 * n**2)`). `f` is a 1-1 mapping, so it has an inverse method `g` (i.e., `g(f(n)) #=> n` for all integers `n`): ``` def g(m) Math.sqrt(m).round/2 end ``` (We need `.round` because of round-off errors.) Suppose we have: ``` arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` then ``` z = arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } #=> [36, 144, 324] ``` Then the inverse of these values is given by: ``` z.map { |m| g(m) } #=> [3, 6, 9] ``` Notice that: ``` arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } ``` is the same as: ``` arr.filter { |x| x % 3 == 0 }.map { |n| f(n) } ```
59,398,255
I have an enumerable that goes through several transformation steps and a final filter step E.g ``` [1,2,3,4,5,6,7,8,9].map{|i| i * 2} .map{|i| i * i} .filter{|i| i % 3 ==0 } .each{|i| puts how_do_i_get_initial_value_here } .or_the_initial_value_here ``` How do I get the initial value whose transformations satisfied the filter? Thus in the above example, how do I end up with `[3,6,9]` instead of `[36, 144, 324]`
2019/12/18
[ "https://Stackoverflow.com/questions/59398255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560599/" ]
You could simply apply the transformations that you do in the two `map` calls directly in `filter`: ```rb [1,2,3,4,5,6,7,8,9] .filter { |i| (i * 2)**2 % 3 == 0 } ``` Alternatively, you could keep the original value in a "tuple" as follows: ```rb [1,2,3,4,5,6,7,8,9] .map { |i| [i, i] } .map { |a, b| [a, b * 2] } .map { |a, b| [a, b * b] } .filter { |a, b| b % 3 == 0 } .map { |a, _| a } ```
You could just undo the things you did. So ``` [1,2,3,4,5,6,7,8,9] .map{ |i| i * 2 } .map{ |i| i * i } .filter{ |i| i % 3 ==0 } .map{ |i| Math.sqrt(i) / 2 } ```
59,398,255
I have an enumerable that goes through several transformation steps and a final filter step E.g ``` [1,2,3,4,5,6,7,8,9].map{|i| i * 2} .map{|i| i * i} .filter{|i| i % 3 ==0 } .each{|i| puts how_do_i_get_initial_value_here } .or_the_initial_value_here ``` How do I get the initial value whose transformations satisfied the filter? Thus in the above example, how do I end up with `[3,6,9]` instead of `[36, 144, 324]`
2019/12/18
[ "https://Stackoverflow.com/questions/59398255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560599/" ]
You are given a method: ``` def f(n) 4 * n**2 end ``` where `f(n)` is the transformed value of an element `n` from the given array (as `(2 * n)*(2 * n) = 4 * n**2)`). `f` is a 1-1 mapping, so it has an inverse method `g` (i.e., `g(f(n)) #=> n` for all integers `n`): ``` def g(m) Math.sqrt(m).round/2 end ``` (We need `.round` because of round-off errors.) Suppose we have: ``` arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` then ``` z = arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } #=> [36, 144, 324] ``` Then the inverse of these values is given by: ``` z.map { |m| g(m) } #=> [3, 6, 9] ``` Notice that: ``` arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } ``` is the same as: ``` arr.filter { |x| x % 3 == 0 }.map { |n| f(n) } ```
You could just undo the things you did. So ``` [1,2,3,4,5,6,7,8,9] .map{ |i| i * 2 } .map{ |i| i * i } .filter{ |i| i % 3 ==0 } .map{ |i| Math.sqrt(i) / 2 } ```
59,398,255
I have an enumerable that goes through several transformation steps and a final filter step E.g ``` [1,2,3,4,5,6,7,8,9].map{|i| i * 2} .map{|i| i * i} .filter{|i| i % 3 ==0 } .each{|i| puts how_do_i_get_initial_value_here } .or_the_initial_value_here ``` How do I get the initial value whose transformations satisfied the filter? Thus in the above example, how do I end up with `[3,6,9]` instead of `[36, 144, 324]`
2019/12/18
[ "https://Stackoverflow.com/questions/59398255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560599/" ]
You could simply apply the transformations that you do in the two `map` calls directly in `filter`: ```rb [1,2,3,4,5,6,7,8,9] .filter { |i| (i * 2)**2 % 3 == 0 } ``` Alternatively, you could keep the original value in a "tuple" as follows: ```rb [1,2,3,4,5,6,7,8,9] .map { |i| [i, i] } .map { |a, b| [a, b * 2] } .map { |a, b| [a, b * b] } .filter { |a, b| b % 3 == 0 } .map { |a, _| a } ```
You are given a method: ``` def f(n) 4 * n**2 end ``` where `f(n)` is the transformed value of an element `n` from the given array (as `(2 * n)*(2 * n) = 4 * n**2)`). `f` is a 1-1 mapping, so it has an inverse method `g` (i.e., `g(f(n)) #=> n` for all integers `n`): ``` def g(m) Math.sqrt(m).round/2 end ``` (We need `.round` because of round-off errors.) Suppose we have: ``` arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` then ``` z = arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } #=> [36, 144, 324] ``` Then the inverse of these values is given by: ``` z.map { |m| g(m) } #=> [3, 6, 9] ``` Notice that: ``` arr.map { |n| f(n) }.filter { |x| x % 3 == 0 } ``` is the same as: ``` arr.filter { |x| x % 3 == 0 }.map { |n| f(n) } ```
66,197,834
I am getting a weird segmentation fault when accessing a structure inside of a opaque structure form it's definition file. I have just recently learned about opaque pointers, but my my guess is, I am doing something wrong with the allocation of the internal structure. However, in a first call to the structure it seems to work and the it get unaccessible within the same method. So I define my opaque structure pointer inside of `connection.h`: ```c #ifndef _Connection_h #deifne _Connection_h // Connection opaque pointer typedef struct connection; // API _Bool connection_connect(struct connection *self); #endif // _Connection_h ``` And then inside of `connection.c` I am allocating the internal `serv` structure pointer of type `struct sockaddr_un`. ```c #include "../connection.h" struct connection { _Bool (*connect)(); char *(*get_name)(); char name[MAX_NAMELEN]; char hostname[MAX_NAMELEN]; uint serv_id; struct sockaddr_un *serv; // Server socket structure }; // ** Public Interface ** _Bool connection_connect(struct connection *self) { printf("Generic connection (opaque pointer)..\n"); strcpy(self->name, SERVERNAME); // Socket path char path[108]; strcpy(path, SERVERNAME); strcat(path, "_socket"); printf("self->name = %s\n", self->name); // Allocate the serv socket structure self->serv = malloc(sizeof(*self->serv)); strcpy(self->serv->sun_path, path); self->serv->sun_family = AF_UNIX; printf("self->serv->sun_path = %s\n", self->serv->sun_path); printf("self->serv->sun_family = %hn\n", self->serv->sun_family); // Locate the host char hostname[MAX_NAMELEN]; gethostname(hostname, MAX_NAMELEN); strcpy(self->hostname, hostname); if ((self->serv_id = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) handle_error("Socket"); return 1; } ``` Then allocation of the `connection` interface methods is handled by client. For the minimal reproducible example a `client` type implementation may handle interface methods allocations like so: ```c #include "../connection.h" typedef struct connection { void (*connect)(); } *client; void client_connect(client self) { connection_connect(self); printf("Client connection..\n"); } client make_client(client self) { client tmp = malloc(sizeof(client)); tmp->connect = client_connect; return tmp; } // Main procedure int main(int argc, char **argv) { client c = make_client(c); c->connect(c); return 0; } ``` After execution the allocated structure first seem to be allocated correctly and it's instances are accessible until the last `printf`: ```sh Generic connection (opaque pointer).. self->name = freebay self->serv->sun_path = freebay_socket [1] 210938 segmentation fault (core dumped) ``` ```c (gdb) p self->serv $1 = (struct sockaddr_un *) 0x66203d2068746170 (gdb) x self->serv 0x66203d2068746170: Cannot access memory at address 0x66203d2068746170 ``` My question is, why `self->serv` gets unaccessible after using it inside of the same method?
2021/02/14
[ "https://Stackoverflow.com/questions/66197834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473663/" ]
You're not allocating enough memory: ``` self->serv = malloc(sizeof(struct sockaddr_un *)); ``` You're allocating enough space for a *pointer* to a `struct sockaddr_un`, not an instance of one. The pointer size is smaller than the struct size, so when you attempt to write to the struct you write past the end of allocated memory, triggering [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). The proper way to allocate the space is: ``` self->serv = malloc(sizeof(struct sockaddr_un)); ``` Or even better: ``` self->serv = malloc(sizeof(*self->serv)); ``` As the latter doesn't care what the type is. Also, this is incorrect: ``` printf("self->serv->sun_family = %hn\n", self->serv->sun_family); ``` Because `%hn` is expecting a `short int *`, not a `short int`. Change this to `%hd`. --- With the full example you've given, we can now see that you have two incompatible structs with the same name in each of your .c files. Your main file defines `struct connection` as: ``` typedef struct connection { void (*connect)(); } *client; ``` While connection.c defines it as: ``` struct connection { _Bool (*connect)(); char *(*get_name)(); char name[MAX_NAMELEN]; char hostname[MAX_NAMELEN]; uint serv_id; struct sockaddr_un *serv; // Server socket structure }; ``` Your main file creates an instance of the former in `make_client` with this: ``` client tmp = malloc(sizeof(client)); ``` This is invalid by itself because again you're allocating space for a pointer and not an instance of the struct. It would need to be: ``` client tmp = malloc(sizeof(*tmp)); ``` But even if you fixed that, you then pass this pointer to `connection_connect` which expects a pointer to the latter structure, not the former. All functions that would create an instance of `struct connection` and modify its members should reside in connection.c where the real definition lives. That's how opaque structs are supposed to work.
You do not allocate `self->serv->sun_path` before copying data to it. Something must go wrong after that. Except if `sun_path` is an array of `char`.
66,197,834
I am getting a weird segmentation fault when accessing a structure inside of a opaque structure form it's definition file. I have just recently learned about opaque pointers, but my my guess is, I am doing something wrong with the allocation of the internal structure. However, in a first call to the structure it seems to work and the it get unaccessible within the same method. So I define my opaque structure pointer inside of `connection.h`: ```c #ifndef _Connection_h #deifne _Connection_h // Connection opaque pointer typedef struct connection; // API _Bool connection_connect(struct connection *self); #endif // _Connection_h ``` And then inside of `connection.c` I am allocating the internal `serv` structure pointer of type `struct sockaddr_un`. ```c #include "../connection.h" struct connection { _Bool (*connect)(); char *(*get_name)(); char name[MAX_NAMELEN]; char hostname[MAX_NAMELEN]; uint serv_id; struct sockaddr_un *serv; // Server socket structure }; // ** Public Interface ** _Bool connection_connect(struct connection *self) { printf("Generic connection (opaque pointer)..\n"); strcpy(self->name, SERVERNAME); // Socket path char path[108]; strcpy(path, SERVERNAME); strcat(path, "_socket"); printf("self->name = %s\n", self->name); // Allocate the serv socket structure self->serv = malloc(sizeof(*self->serv)); strcpy(self->serv->sun_path, path); self->serv->sun_family = AF_UNIX; printf("self->serv->sun_path = %s\n", self->serv->sun_path); printf("self->serv->sun_family = %hn\n", self->serv->sun_family); // Locate the host char hostname[MAX_NAMELEN]; gethostname(hostname, MAX_NAMELEN); strcpy(self->hostname, hostname); if ((self->serv_id = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) handle_error("Socket"); return 1; } ``` Then allocation of the `connection` interface methods is handled by client. For the minimal reproducible example a `client` type implementation may handle interface methods allocations like so: ```c #include "../connection.h" typedef struct connection { void (*connect)(); } *client; void client_connect(client self) { connection_connect(self); printf("Client connection..\n"); } client make_client(client self) { client tmp = malloc(sizeof(client)); tmp->connect = client_connect; return tmp; } // Main procedure int main(int argc, char **argv) { client c = make_client(c); c->connect(c); return 0; } ``` After execution the allocated structure first seem to be allocated correctly and it's instances are accessible until the last `printf`: ```sh Generic connection (opaque pointer).. self->name = freebay self->serv->sun_path = freebay_socket [1] 210938 segmentation fault (core dumped) ``` ```c (gdb) p self->serv $1 = (struct sockaddr_un *) 0x66203d2068746170 (gdb) x self->serv 0x66203d2068746170: Cannot access memory at address 0x66203d2068746170 ``` My question is, why `self->serv` gets unaccessible after using it inside of the same method?
2021/02/14
[ "https://Stackoverflow.com/questions/66197834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473663/" ]
You're not allocating enough memory: ``` self->serv = malloc(sizeof(struct sockaddr_un *)); ``` You're allocating enough space for a *pointer* to a `struct sockaddr_un`, not an instance of one. The pointer size is smaller than the struct size, so when you attempt to write to the struct you write past the end of allocated memory, triggering [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). The proper way to allocate the space is: ``` self->serv = malloc(sizeof(struct sockaddr_un)); ``` Or even better: ``` self->serv = malloc(sizeof(*self->serv)); ``` As the latter doesn't care what the type is. Also, this is incorrect: ``` printf("self->serv->sun_family = %hn\n", self->serv->sun_family); ``` Because `%hn` is expecting a `short int *`, not a `short int`. Change this to `%hd`. --- With the full example you've given, we can now see that you have two incompatible structs with the same name in each of your .c files. Your main file defines `struct connection` as: ``` typedef struct connection { void (*connect)(); } *client; ``` While connection.c defines it as: ``` struct connection { _Bool (*connect)(); char *(*get_name)(); char name[MAX_NAMELEN]; char hostname[MAX_NAMELEN]; uint serv_id; struct sockaddr_un *serv; // Server socket structure }; ``` Your main file creates an instance of the former in `make_client` with this: ``` client tmp = malloc(sizeof(client)); ``` This is invalid by itself because again you're allocating space for a pointer and not an instance of the struct. It would need to be: ``` client tmp = malloc(sizeof(*tmp)); ``` But even if you fixed that, you then pass this pointer to `connection_connect` which expects a pointer to the latter structure, not the former. All functions that would create an instance of `struct connection` and modify its members should reside in connection.c where the real definition lives. That's how opaque structs are supposed to work.
Compiling your code I found this: ``` connection.c:37:43: warning: format specifies type 'short *' but the argument has type 'sa_family_t' (aka 'unsigned char') [-Wformat] printf("self->serv->sun_family = %hn\n", self->serv->sun_family); ~~~ ^~~~~~~~~~~~~~~~~~~~~~ 1 warning generated. ``` If you write: ```c printf("self->serv->sun_family = %cn\n", self->serv->sun_family); ``` Program has no error
66,197,834
I am getting a weird segmentation fault when accessing a structure inside of a opaque structure form it's definition file. I have just recently learned about opaque pointers, but my my guess is, I am doing something wrong with the allocation of the internal structure. However, in a first call to the structure it seems to work and the it get unaccessible within the same method. So I define my opaque structure pointer inside of `connection.h`: ```c #ifndef _Connection_h #deifne _Connection_h // Connection opaque pointer typedef struct connection; // API _Bool connection_connect(struct connection *self); #endif // _Connection_h ``` And then inside of `connection.c` I am allocating the internal `serv` structure pointer of type `struct sockaddr_un`. ```c #include "../connection.h" struct connection { _Bool (*connect)(); char *(*get_name)(); char name[MAX_NAMELEN]; char hostname[MAX_NAMELEN]; uint serv_id; struct sockaddr_un *serv; // Server socket structure }; // ** Public Interface ** _Bool connection_connect(struct connection *self) { printf("Generic connection (opaque pointer)..\n"); strcpy(self->name, SERVERNAME); // Socket path char path[108]; strcpy(path, SERVERNAME); strcat(path, "_socket"); printf("self->name = %s\n", self->name); // Allocate the serv socket structure self->serv = malloc(sizeof(*self->serv)); strcpy(self->serv->sun_path, path); self->serv->sun_family = AF_UNIX; printf("self->serv->sun_path = %s\n", self->serv->sun_path); printf("self->serv->sun_family = %hn\n", self->serv->sun_family); // Locate the host char hostname[MAX_NAMELEN]; gethostname(hostname, MAX_NAMELEN); strcpy(self->hostname, hostname); if ((self->serv_id = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) handle_error("Socket"); return 1; } ``` Then allocation of the `connection` interface methods is handled by client. For the minimal reproducible example a `client` type implementation may handle interface methods allocations like so: ```c #include "../connection.h" typedef struct connection { void (*connect)(); } *client; void client_connect(client self) { connection_connect(self); printf("Client connection..\n"); } client make_client(client self) { client tmp = malloc(sizeof(client)); tmp->connect = client_connect; return tmp; } // Main procedure int main(int argc, char **argv) { client c = make_client(c); c->connect(c); return 0; } ``` After execution the allocated structure first seem to be allocated correctly and it's instances are accessible until the last `printf`: ```sh Generic connection (opaque pointer).. self->name = freebay self->serv->sun_path = freebay_socket [1] 210938 segmentation fault (core dumped) ``` ```c (gdb) p self->serv $1 = (struct sockaddr_un *) 0x66203d2068746170 (gdb) x self->serv 0x66203d2068746170: Cannot access memory at address 0x66203d2068746170 ``` My question is, why `self->serv` gets unaccessible after using it inside of the same method?
2021/02/14
[ "https://Stackoverflow.com/questions/66197834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473663/" ]
Compiling your code I found this: ``` connection.c:37:43: warning: format specifies type 'short *' but the argument has type 'sa_family_t' (aka 'unsigned char') [-Wformat] printf("self->serv->sun_family = %hn\n", self->serv->sun_family); ~~~ ^~~~~~~~~~~~~~~~~~~~~~ 1 warning generated. ``` If you write: ```c printf("self->serv->sun_family = %cn\n", self->serv->sun_family); ``` Program has no error
You do not allocate `self->serv->sun_path` before copying data to it. Something must go wrong after that. Except if `sun_path` is an array of `char`.
40,527,745
As User types in the input i am searching the table and displaying results accordingly . But the issue i am facing is that the table header is being hidden after the search . This is my code ``` $(document).ready(function() { $('#searchinputtext').keyup(function() { var tr = $('#videosfromtagstable tbody tr'); //use tr not td if ($(this).val().length >= 2) { var inputdata = $.trim($("#searchinputtext").val()); $('#errmsgnovideos').hide(); var noElemvideo = true; var val = $.trim(this.value).toLowerCase(); el = tr.filter(function() { return $(this).find('td:eq(0)').text().toLowerCase().indexOf(val) >= 0; }); // <==== closest("tr") removed if (el.length >= 1) { noElemvideo = false; } //now you fadeIn/Out every row not every cell tr.not(el).fadeOut(); el.fadeIn(); if (noElemvideo) if (inputdata !== '') { $('#errmsgnovideos').html('No Results Matched').show(); } else { $('#errmsgnovideos').hide(); } } else { tr.fadeIn(); //show all if length does not match the required number of characters $('#errmsgnovideos').hide(); } }) }); ``` <http://jsfiddle.net/cod7ceho/307/> Could you please tell me how to resolve this issue .
2016/11/10
[ "https://Stackoverflow.com/questions/40527745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
Use `<thead>` ``` <input type="text" id="searchinputtext" class="form-control" placeholder="Search"> <span id="errmsgnovideos"></span> <table class="mytable1 table table-bordered table-hover" id="videosfromtagstable"> <thead> <tr class="existingvideos"> <th width="20%">Name</th> <th width="35%">File</th> <th width="30%">Course</th> <th width="15%">SEEPZ</th> </tr> </thead> <tbody class="connectedSortable ui-sortable"> <tr video-id="48" title="" class="newvideos exercises-add-table-content"> <td>Dsada</td> <td><a href="xxx" target="_blank">dftyr.mp4</a></td> <td> <span class="btn btn-sm btn-success btn-circle">Five</span> </td> <td><i class="fa fa-check"></i></td> </tr> <tr video-id="49" title="" class="newvideos exercises-add-table-content"> <td>Fds</td> <td><a href="xxx" target="_blank">dftyr.mp4</a></td> <td> <span class="btn btn-sm btn-success btn-circle">Five</span> </td> <td><i class="fa fa-check"></i></td> </tr> </tbody> </table> ``` demo:<http://jsfiddle.net/cod7ceho/308/> or if your the type "i can't modify my html" ``` $('#videosfromtagstable tbody tr:not(:first)'); ``` <http://jsfiddle.net/cod7ceho/312/>
``` <input type="text" id="searchinputtext" class="form-control" placeholder="Search"> <table class="mytable1 table table-bordered table-hover" id="videosfromtagstable"> <tbody class="connectedSortable ui-sortable"> <tr class="existingvideos"> <th width="20%">Name</th> <th width="35%">File</th> <th width="30%">Course</th> <th width="15%">SEEPZ</th> </tr> <tr video-id="48" title="" class="newvideos exercises-add-table-content"> <td>Dsada</td> <td><a href="xxx" target="_blank">dftyr.mp4</a></td> <td> <span class="btn btn-sm btn-success btn-circle">Five</span> </td> <td><i class="fa fa-check"></i></td> </tr> <tr video-id="49" title="" class="newvideos exercises-add-table-content"> <td>Fds</td> <td><a href="xxx" target="_blank">dftyr.mp4</a></td> <td> <span class="btn btn-sm btn-success btn-circle">Five</span> </td> <td><i class="fa fa-check"></i></td> </tr> </tbody> <tfoot> <tr><td colspan="3" id="errmsgnovideos"></td></tr> </tfoot> </table> $(document).ready(function() { $('#searchinputtext').keyup(function() { var tr = $('#videosfromtagstable tbody tr').not(".existingvideos"); //use tr not td if ($(this).val().length >= 2) { var inputdata = $.trim($("#searchinputtext").val()); $('#errmsgnovideos').hide(); var noElemvideo = true; var val = $.trim(this.value).toLowerCase(); el = tr.filter(function() { return $(this).find('td:eq(0)').text().toLowerCase().indexOf(val) >= 0; }); // <==== closest("tr") removed if (el.length >= 1) { noElemvideo = false; } //now you fadeIn/Out every row not every cell tr.not(el).fadeOut(); el.fadeIn(); if (noElemvideo) if (inputdata !== '') { $('#errmsgnovideos').html('No Results Matched').show(); } else { $('#errmsgnovideos').hide(); } } else { tr.fadeIn(); //show all if length does not match the required number of characters $('#errmsgnovideos').hide(); } }) }); ``` You try this may help you
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It will call the single-argument constructor for `AccountMembershipService`, passing a `null` as the argument, before processing the body of the constructor you list. From [MSDN](http://msdn.microsoft.com/en-us/library/ms173115.aspx): > > A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression. > > > More detail in section 17.10.1 (Constructor initializers) of the [C# spec](http://msdn.microsoft.com/en-us/netframework/aa569283).
It calls another constructor in your class and passes `null` as a parameter. You can also write `: base(...)` to explicitly call a constructor in your base class.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It calls a different constructor with a `null` argument.
It calls another constructor in your class and passes `null` as a parameter. You can also write `: base(...)` to explicitly call a constructor in your base class.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There is most likely another constructor in your class that looks like this: ``` public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` Your code calls this constructor first and passes `null` as the argument for `provider`, then executes the original constructor.
It calls another constructor in your class and passes `null` as a parameter. You can also write `: base(...)` to explicitly call a constructor in your base class.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The above answers are answering the question asked, but to go a bit further: This is one technique we use for inversion of control and making unit testing possible. Here are both constructors ``` public AccountMembershipService() : this(null) { } public AccountMembershipService(MembershipProvider provider) { _provider = provider ?? Membership.Provider; } ``` The first constructor with :this(null) calls your 2nd constructor, passing null to the parameter provider. One reason for doing this is to avoid duplication of logic. Suppose you did: ``` public AccountMembershipService() { _provider = Membership.Provider; } public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` While perfectly reasonable, if you change the name of \_provider, or perhaps add some other initialization code, you'd have to modify it in 2 places. By calling :this(null), now all your work just happens in one place. The reason we have 2 constructors is, by calling the default constructor, the static instance Membership.Provider gets used. Unfortunately it would be very difficult to unit test, because now we have dependencies on the membership providers, on the database, on having valid data, etc. Instead, by creating the 2nd constructor, we can now pass in a mock MembershipProvider. This is an entirely different topic though, so if you're interested in how that works, feel free to ask another question.
It calls another constructor in your class and passes `null` as a parameter. You can also write `: base(...)` to explicitly call a constructor in your base class.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It will call the single-argument constructor for `AccountMembershipService`, passing a `null` as the argument, before processing the body of the constructor you list. From [MSDN](http://msdn.microsoft.com/en-us/library/ms173115.aspx): > > A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression. > > > More detail in section 17.10.1 (Constructor initializers) of the [C# spec](http://msdn.microsoft.com/en-us/netframework/aa569283).
It calls a different constructor with a `null` argument.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It will call the single-argument constructor for `AccountMembershipService`, passing a `null` as the argument, before processing the body of the constructor you list. From [MSDN](http://msdn.microsoft.com/en-us/library/ms173115.aspx): > > A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression. > > > More detail in section 17.10.1 (Constructor initializers) of the [C# spec](http://msdn.microsoft.com/en-us/netframework/aa569283).
The above answers are answering the question asked, but to go a bit further: This is one technique we use for inversion of control and making unit testing possible. Here are both constructors ``` public AccountMembershipService() : this(null) { } public AccountMembershipService(MembershipProvider provider) { _provider = provider ?? Membership.Provider; } ``` The first constructor with :this(null) calls your 2nd constructor, passing null to the parameter provider. One reason for doing this is to avoid duplication of logic. Suppose you did: ``` public AccountMembershipService() { _provider = Membership.Provider; } public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` While perfectly reasonable, if you change the name of \_provider, or perhaps add some other initialization code, you'd have to modify it in 2 places. By calling :this(null), now all your work just happens in one place. The reason we have 2 constructors is, by calling the default constructor, the static instance Membership.Provider gets used. Unfortunately it would be very difficult to unit test, because now we have dependencies on the membership providers, on the database, on having valid data, etc. Instead, by creating the 2nd constructor, we can now pass in a mock MembershipProvider. This is an entirely different topic though, so if you're interested in how that works, feel free to ask another question.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There is most likely another constructor in your class that looks like this: ``` public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` Your code calls this constructor first and passes `null` as the argument for `provider`, then executes the original constructor.
It calls a different constructor with a `null` argument.
5,292,379
``` public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } ``` I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project. Can you explain what the 'this(null)' bit is doing?
2011/03/13
[ "https://Stackoverflow.com/questions/5292379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There is most likely another constructor in your class that looks like this: ``` public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` Your code calls this constructor first and passes `null` as the argument for `provider`, then executes the original constructor.
The above answers are answering the question asked, but to go a bit further: This is one technique we use for inversion of control and making unit testing possible. Here are both constructors ``` public AccountMembershipService() : this(null) { } public AccountMembershipService(MembershipProvider provider) { _provider = provider ?? Membership.Provider; } ``` The first constructor with :this(null) calls your 2nd constructor, passing null to the parameter provider. One reason for doing this is to avoid duplication of logic. Suppose you did: ``` public AccountMembershipService() { _provider = Membership.Provider; } public AccountMembershipService(MembershipProvider provider) { _provider = provider; } ``` While perfectly reasonable, if you change the name of \_provider, or perhaps add some other initialization code, you'd have to modify it in 2 places. By calling :this(null), now all your work just happens in one place. The reason we have 2 constructors is, by calling the default constructor, the static instance Membership.Provider gets used. Unfortunately it would be very difficult to unit test, because now we have dependencies on the membership providers, on the database, on having valid data, etc. Instead, by creating the 2nd constructor, we can now pass in a mock MembershipProvider. This is an entirely different topic though, so if you're interested in how that works, feel free to ask another question.
15,196
I am creating a SaaS that will be delivered through a Vertical Information Portal (VIP). In my research I have found that by developing a custom lean web browser and installing it on the clients platform, I can better restrict access to the portal on the web by only allowing this custom browser to access it. I realize there is a threat of duplicating the the client browser. but I feel it is better option instead of any browser being able to access the portal to receive the payed services, and much easier to flag for piracy. However, in regards to security of a custom browser, I have not been able to find any useful information. I would elaborate on this point, but unless I am missing something (which is probably the case), I have nothing to go on. Can you point me in the right direction to make a thorough threat assessment on a custom browser build for a VIP delivered SaaS? **EDIT** By looking at the possibilities of a customized connection from server to client, I am not trying to re-invent the wheel, but looking at innovative options to make improvements to the wheel. I do not make the assumption that any system is totally secure, and I fully believe the practice of IT Security is a constant work in progress that must be improved on (hence, the purpose of this question).
2012/05/21
[ "https://security.stackexchange.com/questions/15196", "https://security.stackexchange.com", "https://security.stackexchange.com/users/10090/" ]
It sounds to me like you want your Web based SaaS application to be accessed only by browser/client/hosts that have some system integrity properties that are usually lacking in a typical web client host -- e.g. absence of malware, resistance to malware. If that is so, then you should consider developing a client that is a hardened dedicated browser appliance: a) delivered to users as a liveCD image to be booted on typical PC HW from RO media; b) built using SE Linux and bootstrap to restrict the executable application software to consist of a web browser; c) local packet filter configured to permit communication only with the host(s) of the server side of the application; d) browser configured to trust only the server certificate of the server side of your application; e) several other supporting characteristics, but that's the gist. An worked example of hardened dedicated browser appliance is available at: <https://github.com/trustthevote/BrowserAppliance> In addition, you will probably want to build into the client image a key pair and PK certificate that the server requires as a pre-req for service. As you point out, it is certainly possible for the cert and key pair to be extracted and used by a different client host; but it is a strong measure to prevent casual or accidental use of "normal" client hosts such that the server would interact with these risky clients. If your application uses strong user authentication, then you de-scope your risk further by limiting the pool of people who would benefit from something as weird as cracking keys out of a perfectly usable hardened dedicated browser appliance, in order to rig up their existing PC as a client, without having to boot from RO media as a pre-req for using your application. Hope this helps! John Sebes <http://osdv.org>
This is [(in)security though obscurity](http://en.wikipedia.org/wiki/Security_through_obscurity), I don't see how this improves the security of any system. Probably the reason why you can't find any information on this topic is because its not a good idea. I suspect you would also implement your own HTTP protocol, and then forbid clients from sniffing the wire with wireshark/tcpdump. Oah and you will have to forbid the client from opening their own socekts, and access to telnet... But all that aside, I can still find and leverage xss/csrf/sql injection/whatever using just a web browser... What is keeping the attacker from putting sql statements into an html form or the address bar. So by reimplementing the wheal you are already giving the attacker a perfect tool to compromise your system. Whats the point?
33,945
After the one ring was destroyed and Aragorn was crowned King of Gondor and Arnor, he and Arwen were married. Though he looks older than his bride, I'm learning that Arwen is actually older than Aragorn by at least 2,600 years. She's obviously robbing the cradle, but I can't get an exact fix on exactly how old they were when married.
2013/04/07
[ "https://scifi.stackexchange.com/questions/33945", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/13090/" ]
Both Aragorn and Arwen's births, and their marriage, are listed in the Third Age section of The Tale of Years (Appendix B, at the back of *Return of the King*). Arwen was born in the year 241. Aragorn was born on March 1 of 2931. Since they were married at the end of June in 3019, this means Aragorn was 88 years old when they were married, and Arwen was either 2778 or 2777 (depending on whether she was born in the first or second half of the year).
Aragorn was 88 (having aged 45 years) and Arwen 2778 (having aged 33 years) --------------------------------------------------------------------------- As far as I can tell, Tolkien's last known writings about Arwen's growth is the work "Elvish Ages & Númenórean" written in 1965 and published in *The Nature of Middle-earth*. Tolkien begins by describing the nature of elvish growth in Middle-earth in the Third Age, before giving examples of how it applies for different characters. > > Elves' ages must be counted in two different stages: growth-years (GY) and life-years (LY). The GYs were relatively swift and in Middle-earth= 3 Löar. The LYs were very slow and in Middle-earth = 144 löar. ... They reached "full growth" of body in 24 GY. ... They then had 48 LY of youth, and then 48 LY of "full age" or "steadfast body", by which time their knowledge ceased to increase. ... If we neglect the difference of speed and call each unit a "year", we then see that an elf reached maturity at 24, end of "youth" at 72, and "old age" at 120. In mortal equivalents the age in physical and other characteristics indicated can be found approximately by multiplying by ¾. > > *The Nature of Middle-earth* - "Elvish Ages & Númenórean" > > > Basically, for the first 72 years of an elf's life they age one elf year every 3 normal years, until they turn "24" (72). After that they only age one elf year every 144 normal years. However, each of these aforementioned elf years is really the equivalent of what a mortal grows in 3/4 of a year. So to get an understanding of how old an elf is you need to figure out how many total Growth-Years and Life-Years they've lived, and then multiply that number by 3/4. > > *The case of Arwen.* **Taking her birth as T[hird]A[ge] 241**, she will then be "full-grown" in TA 313 (241 + 72). In 2951, when she first meets Aragorn, she will be (in Elven Growth- and Life-years) 24 + 18⅓ (nearly); (2951-313)/144 = 42⅓ = mortal equivalent 31¾. Aragorn was > only 20. > > > **In 3019, when they were married, she would have aged very little > and would be nearly Elvish 43 (24 + (3019-313)/144) = mortal equivalent > 32-3. But Aragorn would have lived 88 years and 4 months. His "age" would however be about "45".** ... > > > The Númenórean scale fixed by the Valar (for other than Elros) was > for a life in full (if not "resigned" earlier) of thrice that of ordinary men. This was reckoned so: A "Númenórean" reached "full-growth" at 24 (as with Elves; but this was for them reckoned in Sun-years); after that, 70 x 3 = 210 years were "permitted" = total 234. But decline set in (at first slow) at the 210th year (from birth); so that a Númenórean had an expectation of 186 fully active years after > reaching physical maturity. > > *The Nature of Middle-earth* - "Elvish Ages & Númenórean" > > >
29,293,426
I want to add version number and build number to my app in Titanium Studio. How to I can add these two to my apps?
2015/03/27
[ "https://Stackoverflow.com/questions/29293426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534812/" ]
I too was struggling with this. Especially after testflightapp merged with iTunesConnect. The latter needs a strict build number system. There's a nifty solution. Let's say your app version is 1.2.3 You will set this in tiapp.xml. Now if you add another number to the end like so 1.2.3.1 then the first three will be used as a version number and the whole 4 numbers will be used as a build number. When you upload next build you just set it to 1.2.3.2 and it'll be a new build.
The version number of your app is set in the project's `tiapp.xml` file. A build number is usually automatically appended when you build/run the project for iOS. You can look at the build number by opening the Xcode project file in the project's `build` directory and going to the build settings.
45,529,342
here I'm trying to make an inscription form an as a form validation i've chosen that the name must contain at least 2 charecters, So i've added an event listner to the input with the `id="nom"` but the problem that occurs here is that the code gets only the initial value which is empty so it doesn't really matter what the user write in the specified input field the event will be launched with the empty value. ``` `<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> </head> <body> <form action="#" method="get"> <fieldset id="fieldset"> <legend>Inscription :</legend> <label for="">Sexe :</label><br> <input type="radio" name="gender" value="male" checked><label for="male">Homme</label> <br><input type="radio" name="gender" value="female"><label for="female">Femme</label> <br><sapn class="tooltip">Vous devez selectionner votre sexe</sapn> <br><br><label>Nom :</label><br> <input type="text" id="nom"> <sapn class="tooltip">Un nom ne peut pas faire moins de 2 caractères</sapn> <br><br><label>Prénom :</label><br> <input type="text" id="prenom"> <sapn class="tooltip">Un prénom ne peut pas faire moins de 2 caractères</sapn> <br><br><label>Age :</label><br> <input type="text" id="age"> <sapn class="tooltip">l'age doit etre compris entre 5 et 140</sapn> <br><br><label>Pseudo :</label><br> <input type="text" id="pseudo"> <sapn class="tooltip">Le pseudo ne peut pas faire moins de 4 caractères</sapn> <br><br><label>Mot de passe :</label><br> <input type="password" id="mdp"> <sapn class="tooltip">Le mot de passe ne peut pas faire moins de 6 caractères</sapn> <br><br><label>Mot de passe (confirmation):</label><br> <input type="password" id="mdpconf"> <sapn class="tooltip">Le mot de passe de confirmation doit etre identique à celui d'origine</sapn> <br><br><label for="country">Pays :</label><br> <select name="country" id="country"> <option value="none" selected >Selectionnez votre pays</option> <option value="Allemagne" >Allemagne</option> <option value="France" >France</option> <option value="Tunisie" >Tunisie</option> </select> <sapn class="tooltip">Vous devez selectionner votre pays de résidence</sapn> <br><br><label for="mail">Recevoir des mails </label> <input type="checkbox" class="answer"> <br><br><input type="submit" value="M'inscrire" id="submit"> <input type="reset" value="Reintitialiser le formulaure" id="reset"> </fieldset> </form> <script> (function (){ var nom = document.getElementById('nom'); var prenom = document.getElementById('prenom'); var sexe = document.querySelectorAll('input[type = checkbox],checked'); var age = document.getElementById('age'); var pseudo = document.getElementById('pseudo'); var mdp = document.getElementById('mdp'); var mdpconf = document.getElementById('mdpconf'); var pays = document.getElementById('country'); var tooltips = document.querySelectorAll(".tooltip"); for(i = 0;i < tooltips.length; i++){ tooltips[i].style.display = 'none'; } function moreThenTwo(text){ if (text.value.length < 2){ text.style.borderColor="red"; tooltips[1].style.display = "inline-block"; age.value = text.value.length; } else text.style.borderColor = "green"; }; nom.addEventListener('change',moreThenTwo(nom)); })(); </script> </body> </html>` ```
2017/08/06
[ "https://Stackoverflow.com/questions/45529342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208122/" ]
In this line: ``` arr = (arr.OrderBy(i => i).ToArray()); ``` you are creating a new array and assigning to to `arr`. The array you passed to the function is no longer accessible by that function. If you want to be able to modify the array `arr` so that other functions can use it, you need to use the [`ref` keyword](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref): ``` public static void ArrayCalledWithOrderBy(ref string[] arr) ```
You can use Object.ReferenceEquals to check arr's reference has been change after call arr.OrderBy(i => i).ToArray(). ``` public static void ArrayCalledWithOrderBy(string[] origin) { var arr = (origin.OrderBy(i => i).ToArray()); //isEqual flag is false var isEqual = Object.ReferenceEquals(arr, origin); DisplayArray(arr, "After orderby inside method"); } ```
45,529,342
here I'm trying to make an inscription form an as a form validation i've chosen that the name must contain at least 2 charecters, So i've added an event listner to the input with the `id="nom"` but the problem that occurs here is that the code gets only the initial value which is empty so it doesn't really matter what the user write in the specified input field the event will be launched with the empty value. ``` `<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> </head> <body> <form action="#" method="get"> <fieldset id="fieldset"> <legend>Inscription :</legend> <label for="">Sexe :</label><br> <input type="radio" name="gender" value="male" checked><label for="male">Homme</label> <br><input type="radio" name="gender" value="female"><label for="female">Femme</label> <br><sapn class="tooltip">Vous devez selectionner votre sexe</sapn> <br><br><label>Nom :</label><br> <input type="text" id="nom"> <sapn class="tooltip">Un nom ne peut pas faire moins de 2 caractères</sapn> <br><br><label>Prénom :</label><br> <input type="text" id="prenom"> <sapn class="tooltip">Un prénom ne peut pas faire moins de 2 caractères</sapn> <br><br><label>Age :</label><br> <input type="text" id="age"> <sapn class="tooltip">l'age doit etre compris entre 5 et 140</sapn> <br><br><label>Pseudo :</label><br> <input type="text" id="pseudo"> <sapn class="tooltip">Le pseudo ne peut pas faire moins de 4 caractères</sapn> <br><br><label>Mot de passe :</label><br> <input type="password" id="mdp"> <sapn class="tooltip">Le mot de passe ne peut pas faire moins de 6 caractères</sapn> <br><br><label>Mot de passe (confirmation):</label><br> <input type="password" id="mdpconf"> <sapn class="tooltip">Le mot de passe de confirmation doit etre identique à celui d'origine</sapn> <br><br><label for="country">Pays :</label><br> <select name="country" id="country"> <option value="none" selected >Selectionnez votre pays</option> <option value="Allemagne" >Allemagne</option> <option value="France" >France</option> <option value="Tunisie" >Tunisie</option> </select> <sapn class="tooltip">Vous devez selectionner votre pays de résidence</sapn> <br><br><label for="mail">Recevoir des mails </label> <input type="checkbox" class="answer"> <br><br><input type="submit" value="M'inscrire" id="submit"> <input type="reset" value="Reintitialiser le formulaure" id="reset"> </fieldset> </form> <script> (function (){ var nom = document.getElementById('nom'); var prenom = document.getElementById('prenom'); var sexe = document.querySelectorAll('input[type = checkbox],checked'); var age = document.getElementById('age'); var pseudo = document.getElementById('pseudo'); var mdp = document.getElementById('mdp'); var mdpconf = document.getElementById('mdpconf'); var pays = document.getElementById('country'); var tooltips = document.querySelectorAll(".tooltip"); for(i = 0;i < tooltips.length; i++){ tooltips[i].style.display = 'none'; } function moreThenTwo(text){ if (text.value.length < 2){ text.style.borderColor="red"; tooltips[1].style.display = "inline-block"; age.value = text.value.length; } else text.style.borderColor = "green"; }; nom.addEventListener('change',moreThenTwo(nom)); })(); </script> </body> </html>` ```
2017/08/06
[ "https://Stackoverflow.com/questions/45529342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208122/" ]
Arrays are reference types, so when you pass an array to a method. Its *reference* is passed by *value*. You should be aware that the `arr` in this method: ``` public static void ArrayCalledWithOrderBy(string[] arr) { arr = (arr.OrderBy(i => i).ToArray()); DisplayArray(arr, "After orderby inside method"); } ``` and the `arr` here: var arr = new string[] { "pink", "blue", "red", "black", "aqua" }; DisplayArray(arr, "Before method calls"); ArrayCalledWithOrderBy(arr); Are two different variables holding references to the same array, until this line: ``` arr = (arr.OrderBy(i => i).ToArray()); ``` In this line you change `arr` to refer to the sorted array, instead of the array passed in. See? `OrderBy` creates a new array that is sorted. The original array is not mutated. `Array.Sort` mutates the array passed in, so it actually changes the `arr` here: ``` var arr = new string[] { "pink", "blue", "red", "black", "aqua" }; ```
You can use Object.ReferenceEquals to check arr's reference has been change after call arr.OrderBy(i => i).ToArray(). ``` public static void ArrayCalledWithOrderBy(string[] origin) { var arr = (origin.OrderBy(i => i).ToArray()); //isEqual flag is false var isEqual = Object.ReferenceEquals(arr, origin); DisplayArray(arr, "After orderby inside method"); } ```
1,099,439
Recently, I find out that somebody uses my network traffic. I found his `MAC` address and now I wanna find full details of his device. I tried: <http://www.macvendors.com/> and such this, but the response was only the name of manufacture. Tnx from anybody who helps me( or says a better solution to find him:) ) EDIT: Anybody who has another way to find him, tells me.
2016/07/11
[ "https://superuser.com/questions/1099439", "https://superuser.com", "https://superuser.com/users/613671/" ]
Just searching on the MAC will only give you the vendor. It will never show you in which hardware the component with the MAC was used. (Think of it as finding the vendor name for a lightbulb, which does not tell you in which device the bulb was used). But given that you have the MAC and almost certainly the IP, you can use tools like nmap to find out more. If you do not like command line tools then try [the zenmap wrapper](https://nmap.org/zenmap/) around nmap. This usually will tell you which OS the device is running. That way you have a good idea if it is a phone (windows CE, android, ios or a PC (linux, BSD, windows). Once you know that you can start to refine. E.g. if it turns out to be a windows device try `\\ip\c$`.
It is not possible to get device details via MAC address as @Hennes already said as the MAC address is only specific to the network card. Another way to obtain more information is to log into your router/firewall and look for known devices with the found MAC. There you have the association MAC <-> IP address. You the can use tools like nmap/zenmap to gather more information. If you are just after locking him/her out of your network it may be possible (depending on your router) to block access for the device with the specific MAC address.
1,099,439
Recently, I find out that somebody uses my network traffic. I found his `MAC` address and now I wanna find full details of his device. I tried: <http://www.macvendors.com/> and such this, but the response was only the name of manufacture. Tnx from anybody who helps me( or says a better solution to find him:) ) EDIT: Anybody who has another way to find him, tells me.
2016/07/11
[ "https://superuser.com/questions/1099439", "https://superuser.com", "https://superuser.com/users/613671/" ]
Just searching on the MAC will only give you the vendor. It will never show you in which hardware the component with the MAC was used. (Think of it as finding the vendor name for a lightbulb, which does not tell you in which device the bulb was used). But given that you have the MAC and almost certainly the IP, you can use tools like nmap to find out more. If you do not like command line tools then try [the zenmap wrapper](https://nmap.org/zenmap/) around nmap. This usually will tell you which OS the device is running. That way you have a good idea if it is a phone (windows CE, android, ios or a PC (linux, BSD, windows). Once you know that you can start to refine. E.g. if it turns out to be a windows device try `\\ip\c$`.
I have another idea for this purpose: what if somebody , on purpose , set own wifi without any password and the thief could connect again! I think in that case we have more chance to discover what device is connected to our router.
1,099,439
Recently, I find out that somebody uses my network traffic. I found his `MAC` address and now I wanna find full details of his device. I tried: <http://www.macvendors.com/> and such this, but the response was only the name of manufacture. Tnx from anybody who helps me( or says a better solution to find him:) ) EDIT: Anybody who has another way to find him, tells me.
2016/07/11
[ "https://superuser.com/questions/1099439", "https://superuser.com", "https://superuser.com/users/613671/" ]
I have another idea for this purpose: what if somebody , on purpose , set own wifi without any password and the thief could connect again! I think in that case we have more chance to discover what device is connected to our router.
It is not possible to get device details via MAC address as @Hennes already said as the MAC address is only specific to the network card. Another way to obtain more information is to log into your router/firewall and look for known devices with the found MAC. There you have the association MAC <-> IP address. You the can use tools like nmap/zenmap to gather more information. If you are just after locking him/her out of your network it may be possible (depending on your router) to block access for the device with the specific MAC address.
37,166,663
So I've got two different classes in C++, ``` #ifndef A_H #define A_H class A { public: ... private: static const int MAX = 52; int a_array[MAX]; }; #endif // A_H ``` And I'd like to use that array into another class... But I was wondering if I can't just return an array, how should I do it? Am I forced to create another array in the class B and copy it? THis would be the second class... ``` #include "A.h" #ifndef B_H #define B_H class B { public: ... void createNewDeck("here would be the array, or the object I'd like to input to use the array inside"); private: static const int min = 5; int a_array[min] }; #endif // B_H ``` EDIT: I want them to be different, I'd like to have a B method that works with the A class array. I would have a B method that takes some values from that array; something like this so you guys can get my idea. ``` void B::createNewDeck(const A &a){ a_array[0] = a.a_array[5]; a_array[3] = a.a_array[48]; } ``` Appreciate your help!
2016/05/11
[ "https://Stackoverflow.com/questions/37166663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5615653/" ]
The array is just a pointer to a piece of data. But you need to be very clear on what you want. Do you want to copy the data and have a separate copy to play with? Or do you want the second class to have full access to the original? You can return the pointer in a function or make the member variable accessible as either public or via a friend.
``` create a method in public int Array(int index) and return the value to your desired like: class B { public: void createNewDeck("here would be the array, or the object I'd like to input to use the array inside"); private: static const int min = 5; int a_array[min] // Method to return value outside public: int Array(int Index) { return Index>min ?-1:a_array[Index-1]; } }; ```
37,166,663
So I've got two different classes in C++, ``` #ifndef A_H #define A_H class A { public: ... private: static const int MAX = 52; int a_array[MAX]; }; #endif // A_H ``` And I'd like to use that array into another class... But I was wondering if I can't just return an array, how should I do it? Am I forced to create another array in the class B and copy it? THis would be the second class... ``` #include "A.h" #ifndef B_H #define B_H class B { public: ... void createNewDeck("here would be the array, or the object I'd like to input to use the array inside"); private: static const int min = 5; int a_array[min] }; #endif // B_H ``` EDIT: I want them to be different, I'd like to have a B method that works with the A class array. I would have a B method that takes some values from that array; something like this so you guys can get my idea. ``` void B::createNewDeck(const A &a){ a_array[0] = a.a_array[5]; a_array[3] = a.a_array[48]; } ``` Appreciate your help!
2016/05/11
[ "https://Stackoverflow.com/questions/37166663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5615653/" ]
The array is just a pointer to a piece of data. But you need to be very clear on what you want. Do you want to copy the data and have a separate copy to play with? Or do you want the second class to have full access to the original? You can return the pointer in a function or make the member variable accessible as either public or via a friend.
Easiest way is to make `B` a friend of `A`. That way `B` will have access to `A`'s `private` member. ``` class B; // forward declare B to make it visible in A's scope. Important class A { private: static const int MAX = 52; int a_array[MAX]; friend class B; // !! //friend B; // if you have C++11 }; ```
15,012,847
I've got a curious bug (bugging me) today. There are three inheritance levels involved: **Grandpa**: ``` abstract class Zend_Db_Table_Row_Abstract implements ArrayAccess, IteratorAggregate { protected $_data = array(); /* snip */ } ``` **Mom**: ``` namespace Survey\Db\Table\Row; class AbstractRow extends \Zend_Db_Table_Row_Abstract { /* snip */ } ``` **Child**: ``` namespace Survey\Db\Table\Row; class SurveyItem extends AbstractRow implements ISkippable { /* snip */ } ``` **Exception**: ``` Type: ErrorException Value: Undefined property: Survey\Db\Table\Row\SurveyItem::$_data Location: [...]/Zend/Db/Table/Row/Abstract.php in handleError , line 177 ``` Line 177 doesn't seem to be relevant, but I'm adding it just so you'd believe me ;) ``` if (!array_key_exists($columnName, $this->_data)) { ``` > > PHP 5.4.11, problem did NOT exist with PHP 5.4.8 > > > When I saw the [fix](https://github.com/smalyshev/php-src/commit/d1da4c6fe71d18966f07f48aaa62c7bc06c2babe) for [Bug #63462 Magic methods called twice for unset protected properties](https://bugs.php.net/bug.php?id=63462), I thought, that wold solve the problem, since this bug leads to exactly the weird unexpected outcome I was seeing. But it turns out, the **problem still exists after updating to PHP 5.4.12**. The likelyhood that there is another similar bug in PHP seems quite high. **Question:** I get the info that a protected field defined in the Grandpa is undefined in the Child. What scenarios can lead to such an outcome?
2013/02/21
[ "https://Stackoverflow.com/questions/15012847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ]
following snippet works flawlessly on PHP 5.4.9: ``` class A { protected $foo = 'hello'; public function bar() { echo $this->foo; } } class B extends A {} class C extends B {} $c = new C(); $c->bar(); ``` Please minimise your code step by step to this to see if/when problem occurs (I wonder why you haven't done it already) If you are sure this worked on PHP 5.4.8 and does not work on PHP 5.4.11 then you found a bug in PHP and should be reporting it on php.net Answer may be different (maybe it simply got 'unset' along the way). Minimise your code and you will know.
If you don't want the parent field to inherit in the child class through object then declar the parent field as "static".
5,751,545
I have a java code that contains a class TRADE\_HISTORY that holds a history of trades. Class TRADE\_HISTORY has a final field named fMapDateOutputPriceRatios that is set in the constructor . fMapDateOutputPriceRatios is a map between dates and a double array (TreeMap). In the constructor, the field is assinged to the argurment using ``` fMapDateOutputPriceRatios = new TreeMap<Date, double[]>(aOutputPriceRatioData); ``` The number of dates is obtained using ``` Set<Date> dates = fMapDateOutputPriceRatios.keySet(); ``` The size of dates is printed out in the constructor. The class has only one constructor. A problem is occurring when a new trade is added. When a new date is added, the double vector is used, and obtained from ``` double[] outputPriceRatios = fMapDateOutputPriceRatios.get( aDate ); ``` The error occurs because the date is not available. While trying to debug the error, the size of dates is being printed. During construction, the size is 1973 elements. When the error occurs, the size is 1964 elements. In particular, the date Apr 11, 2011 is not available at the time of the error. I'm using eclipse and have set a break on the variable fMapDateOutputPriceRatios to break when the field is modified. It only breaks during the constructor. Any suggestion on how to determine why the size of fMapDateOutputPriceRatios changes? The only lines that access fMapDateOutputPriceRatios are ``` TRADE_HISTORY::TRADE_HISTORY(Map<Date, double[]> aOutputPriceRatioData ) fMapDateOutputPriceRatios = new TreeMap<Date, double[]>(aOutputPriceRatioData); Set<Date> dates = fMapDateOutputPriceRatios.keySet(); // Used to debug error TRADE_HISTORY::public void addTradeDistribution_0_to_100(Date aDate, ...) outputPriceRatios = fMapDateOutputPriceRatios.get( aDate ) // Causes error Set<Date> dates = fMapDateOutputPriceRatios.keySet(); // Used to debug error ```
2011/04/22
[ "https://Stackoverflow.com/questions/5751545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/719924/" ]
A final reference to an object instance *does not make that instance immutable!* It only blocks changing the reference to point to a different object instance. The reference is final--not the state of the object instance it references. Note that the set of keys returned by `keySet()` is backed by the map. If you remove keys from it, the corresponding mappings are removed from `fMapDateOutputPriceRatios`. Are you modifying `dates` or using it for anything other than debugging?
First, important question: are you sure Dates used as keys are not modified anywhere? Date is supposed to be an immutable object, but it still contains legacy deprecated methods letting one to change the key content. That would cause unpredictable consequences to TreeMap, including the ones you described. Also, make sure all Dates has hours/minutes/seconds/milliseconds cleaned to 0. Now, suppose the Dates are immutable: You have actually observed the reduction of the key set size, which means the physical modification of the content happens. The only way I know how it can happen is a concurrent access to the map by two or more threads. TreeMap have to rebuild the tree when new key is added. That is, unlink part of the tree, and re-link it somewhere else in the tree. During that time, if another thread accesses the same structure and does the same, that subtree may get lost, causing reduction in number of keys. Therefore, as a first step, try to access this field in a synchronized block: ``` synchronized(fMapDateOutputPriceRatios) { outputPriceRatios = fMapDateOutputPriceRatios.get( aDate ) } ``` P.S. I actually do not see put() in your code anywhere, but it must be there, **there are no miracles**.
5,751,545
I have a java code that contains a class TRADE\_HISTORY that holds a history of trades. Class TRADE\_HISTORY has a final field named fMapDateOutputPriceRatios that is set in the constructor . fMapDateOutputPriceRatios is a map between dates and a double array (TreeMap). In the constructor, the field is assinged to the argurment using ``` fMapDateOutputPriceRatios = new TreeMap<Date, double[]>(aOutputPriceRatioData); ``` The number of dates is obtained using ``` Set<Date> dates = fMapDateOutputPriceRatios.keySet(); ``` The size of dates is printed out in the constructor. The class has only one constructor. A problem is occurring when a new trade is added. When a new date is added, the double vector is used, and obtained from ``` double[] outputPriceRatios = fMapDateOutputPriceRatios.get( aDate ); ``` The error occurs because the date is not available. While trying to debug the error, the size of dates is being printed. During construction, the size is 1973 elements. When the error occurs, the size is 1964 elements. In particular, the date Apr 11, 2011 is not available at the time of the error. I'm using eclipse and have set a break on the variable fMapDateOutputPriceRatios to break when the field is modified. It only breaks during the constructor. Any suggestion on how to determine why the size of fMapDateOutputPriceRatios changes? The only lines that access fMapDateOutputPriceRatios are ``` TRADE_HISTORY::TRADE_HISTORY(Map<Date, double[]> aOutputPriceRatioData ) fMapDateOutputPriceRatios = new TreeMap<Date, double[]>(aOutputPriceRatioData); Set<Date> dates = fMapDateOutputPriceRatios.keySet(); // Used to debug error TRADE_HISTORY::public void addTradeDistribution_0_to_100(Date aDate, ...) outputPriceRatios = fMapDateOutputPriceRatios.get( aDate ) // Causes error Set<Date> dates = fMapDateOutputPriceRatios.keySet(); // Used to debug error ```
2011/04/22
[ "https://Stackoverflow.com/questions/5751545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/719924/" ]
A final reference to an object instance *does not make that instance immutable!* It only blocks changing the reference to point to a different object instance. The reference is final--not the state of the object instance it references. Note that the set of keys returned by `keySet()` is backed by the map. If you remove keys from it, the corresponding mappings are removed from `fMapDateOutputPriceRatios`. Are you modifying `dates` or using it for anything other than debugging?
Thank you for the feedback. Moving the date/output price map to the driving function removes the possibility of a problem with date/output price maps. However, still get unexpected errors. A static counter was added to the constructor of TRADE\_HISTORY to keep track of the number of TRADE\_HISTORY constructed. Also, an integer id was added to the constructor and set equal to the counter, so the id's should be 1, 2, 3.... When the current error occurs, the TRADE\_HISTORY id is printed and is zero, which should not occur. More debugging is needed in the constructor of TRADE\_HISTORY instances. It appears that there is a TRADE\_HISTORY being used that was not constructed properly. If more help is required, a different question will be started.
7,886,575
I have the following array of TrackerReport Object: ``` public class TrackerReport : TrackerMilestone { public long Views { get; set; } public override string ToString() { return "Id=" + MilestoneId + " | Name=" + Name + " | Views = " + Views; } ``` I post also the parent class to better explain: ``` public class TrackerMilestone { public int MilestoneId { get; set; } public int CampaignId { get; set; } public string Name { get; set; } public int? SortIndex { get; set; } public string Url { get; set; } public bool IsGoal { get; set; } public bool IsPartialGoal { get; set; } public int? ParentMilestoneId { get; set; } public int? ViewPercent { get; set; } public override string ToString() { return "Id=" + MilestoneId + " | Name=" + Name + " | Url = " + Url; } } ``` So that it is displayed like this more or less: ``` ID Name Url Counter 1 A ab.com 5 2 N ac.com 2 ``` And I have a List of this object that I fill in this way: ``` var trackerReportList = new List<TrackerReport[]>(); foreach (var trackerItem in trackerChildren) { //currentReport is the array of TrackerReport TrackerReport[] above mentioned var currentReport = GetReportForItem(GetFromDate(), GetToDate(), trackerItem.ID, FindCampaignId(trackerItem)); trackerReportList.Add(currentReport); } ``` All the entries have the same values, but the counter, so, for ex: list1: ``` ID Name Url Counter 1 A ab.com 5 2 N ac.com 2 ``` list2: ``` ID Name Url Counter 1 A ab.com 17 2 N ac.com 28 ``` My goal is to generate a single TrackerReport[], with the sum of the counter values as counter. TrackerReport[]: ``` ID Name Url Counter 1 A ab.com 22 2 N ac.com 30 ``` Is there any Linq query to do this? Or If you come up with a better solution, just post it. Thanks in advance!
2011/10/25
[ "https://Stackoverflow.com/questions/7886575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799758/" ]
This is the `lambda expression` for your query. ``` TrackerReport[] trackerInfoList = trackerReportList .SelectMany(s => s) .GroupBy(g => g.MilestoneId) .Select(s => { var trackerReportCloned = Clone<TrackerReport[]>(s.First()); trackerReportCloned.Views = s.Sum(su => su.Views); return trackerReportCloned; }) .ToArray(); ``` If you have noted, I have used `Clone<T>(T)` method to deep cloning one `object` by the grouped value. I could have done by copying each property, but I found it the easiest. This is the `Clone()` method: ``` public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } ``` Before you continue, you need to set `[Serializable]` attribute on your `DTO` objects. ``` [Serializable] public class TrackerReport : TrackerMilestone { . . . } [Serializable] public class TrackerMilestone { . . . } ``` Hope, this is what you are looking for.
I'd do it in the following way: 1) Let the `TrackerReports[] resultList` is the array of deep copies of the `trackerReportList[0]` items 2) As I understand, the Views property corresponds to the Counter column. If so, then ``` foreach(report in resultList) { report.Views = trackerReportList.Sum(reports => reports.Single(r => r.MilestoneId == report.MilestoneId).Views); } ```
7,886,575
I have the following array of TrackerReport Object: ``` public class TrackerReport : TrackerMilestone { public long Views { get; set; } public override string ToString() { return "Id=" + MilestoneId + " | Name=" + Name + " | Views = " + Views; } ``` I post also the parent class to better explain: ``` public class TrackerMilestone { public int MilestoneId { get; set; } public int CampaignId { get; set; } public string Name { get; set; } public int? SortIndex { get; set; } public string Url { get; set; } public bool IsGoal { get; set; } public bool IsPartialGoal { get; set; } public int? ParentMilestoneId { get; set; } public int? ViewPercent { get; set; } public override string ToString() { return "Id=" + MilestoneId + " | Name=" + Name + " | Url = " + Url; } } ``` So that it is displayed like this more or less: ``` ID Name Url Counter 1 A ab.com 5 2 N ac.com 2 ``` And I have a List of this object that I fill in this way: ``` var trackerReportList = new List<TrackerReport[]>(); foreach (var trackerItem in trackerChildren) { //currentReport is the array of TrackerReport TrackerReport[] above mentioned var currentReport = GetReportForItem(GetFromDate(), GetToDate(), trackerItem.ID, FindCampaignId(trackerItem)); trackerReportList.Add(currentReport); } ``` All the entries have the same values, but the counter, so, for ex: list1: ``` ID Name Url Counter 1 A ab.com 5 2 N ac.com 2 ``` list2: ``` ID Name Url Counter 1 A ab.com 17 2 N ac.com 28 ``` My goal is to generate a single TrackerReport[], with the sum of the counter values as counter. TrackerReport[]: ``` ID Name Url Counter 1 A ab.com 22 2 N ac.com 30 ``` Is there any Linq query to do this? Or If you come up with a better solution, just post it. Thanks in advance!
2011/10/25
[ "https://Stackoverflow.com/questions/7886575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799758/" ]
Here's how to do it using Linq. 1. Firstly, you want to get the data in a single list rather than a `List` of `Arrays`. We can do this with a `SelectMany`. `trackerReportList.SelectMany(c => c)` flattens `List<TrackerReport[]>()` into `IEnumerable<TrackerReport>` 2. Then you group the objects by the relevant column/columns ``` group p by new { ID = p.MilestoneId, Name = p.Name, Url = p.Url} into g ``` 3. Finally, you project the grouping into the format we want. `Counter` is obtained by `Adding` the `Views` for the collection of objects in each grouping. ``` select new { ... }; ``` **Putting it all together:** ``` var report = from p in trackerReportList.SelectMany(c => c) group p by new { ID = p.MilestoneId, Name = p.Name, Url = p.Url} into g select new { ID = g.Key.ID, Name = g.Key.Name, Url = g.Key.Url, Counter = g.Sum(c => c.Views) }; ```
I'd do it in the following way: 1) Let the `TrackerReports[] resultList` is the array of deep copies of the `trackerReportList[0]` items 2) As I understand, the Views property corresponds to the Counter column. If so, then ``` foreach(report in resultList) { report.Views = trackerReportList.Sum(reports => reports.Single(r => r.MilestoneId == report.MilestoneId).Views); } ```
72,325,550
I have a data set which I can represent by this toy example of a list of dictionaries: ``` data = [{ "_id" : "001", "Location" : "NY", "start_date" : "2022-01-01T00:00:00Z", "Foo" : "fruits" }, { "_id" : "002", "Location" : "NY", "start_date" : "2022-01-02T00:00:00Z", "Foo" : "fruits" }, { "_id" : "011", "Location" : "NY", "start_date" : "2022-02-01T00:00:00Z", "Bar" : "vegetables" }, { "_id" : "012", "Location" : "NY", "Start_Date" : "2022-02-02T00:00:00Z", "Bar" : "vegetables" }, { "_id" : "101", "Location" : "NY", "Start_Date" : "2022-03-01T00:00:00Z", "Baz" : "pizza" }, { "_id" : "102", "Location" : "NY", "Start_Date" : "2022-03-2T00:00:00Z", "Baz" : "pizza" }, ] ``` Here is an algorithm in Python which collects each of the keys in each 'collection' and whenever there is a key change, the algorithm adds those keys to output. ``` data_keys = [] for i, lst in enumerate(data): all_keys = [] for k, v in lst.items(): all_keys.append(k) if k.lower() == 'start_date': start_date = v this_coll = {'start_date': start_date, 'all_keys': all_keys} if i == 0: data_keys.append(this_coll) else: last_coll = data_keys[-1] if this_coll['all_keys'] == last_coll['all_keys']: continue else: data_keys.append(this_coll) ``` The correct output given here records each change of field name: `Foo`, `Bar`, `Baz` as well as the change of case in field `start_date` to `Start_Date`: ``` [{'start_date': '2022-01-01T00:00:00Z', 'all_keys': ['_id', 'Location', 'start_date', 'Foo']}, {'start_date': '2022-02-01T00:00:00Z', 'all_keys': ['_id', 'Location', 'start_date', 'Bar']}, {'start_date': '2022-02-02T00:00:00Z', 'all_keys': ['_id', 'Location', 'Start_Date', 'Bar']}, {'start_date': '2022-03-01T00:00:00Z', 'all_keys': ['_id', 'Location', 'Start_Date', 'Baz']}] ``` **Is there a *general algorithm* which covers this pattern comparing current to previous item in a stack?** I need to generalize this algorithm and find a solution to do exactly the same thing with MongoDB documents in a collection. In order for me to discover if Mongo has an Aggregation Pipeline Operator which I could use, I must first understand if this basic algorithm has other common forms so I know what to look for. ***Or someone who knows MongoDB aggregation pipelines really well could suggest operators which would produce the desired result?***
2022/05/20
[ "https://Stackoverflow.com/questions/72325550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343215/" ]
In my organization, this error was solved with this sequence: ``` # apt remove ubuntu-advantage-tools # apt install -f # apt update # apt upgrade ``` A reboot after these steps should complete the updates. The outputs are below: ``` root@host:~# **apt remove ubuntu-advantage-tools** Reading package lists... Done Building dependency tree Reading state information... Done The following package was automatically installed and is no longer required: distro-info Use 'apt autoremove' to remove it. The following packages will be REMOVED: ubuntu-advantage-tools ubuntu-minimal ubuntu-server update-manager-core update-notifier-common 0 upgraded, 0 newly installed, 5 to remove and 9 not upgraded. After this operation, 4812 kB disk space will be freed. Do you want to continue? [Y/n] y (Reading database ... 94121 files and directories currently installed.) Removing ubuntu-server (1.450.2) ... Removing update-notifier-common (3.192.30.10) ... Removing update-manager-core (1:20.04.10.10) ... dpkg: warning: while removing update-manager-core, directory '/var/lib/update-manager' not empty so not removed Removing ubuntu-minimal (1.450.2) ... Removing ubuntu-advantage-tools (27.8~20.04.1) ... Processing triggers for man-db (2.9.1-1) ... root@host:~# **apt install -f** Reading package lists... Done Building dependency tree Reading state information... Done The following package was automatically installed and is no longer required: distro-info Use 'apt autoremove' to remove it. 0 upgraded, 0 newly installed, 0 to remove and 9 not upgraded. root@host:~# **apt update** Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease Hit:2 http://security.ubuntu.com/ubuntu bionic-security InRelease Hit:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease Hit:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease Hit:5 https://download.docker.com/linux/ubuntu focal InRelease Reading package lists... Done Building dependency tree Reading state information... Done 9 packages can be upgraded. Run 'apt list --upgradable' to see them. root@host:~# **apt upgrade** Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done The following package was automatically installed and is no longer required: distro-info Use 'apt autoremove' to remove it. The following packages will be upgraded: ca-certificates cloud-init containerd.io docker-ce docker-ce-cli docker-ce-rootless-extras docker-compose-plugin intel-microcode snapd 9 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. Need to get 145 MB of archives. After this operation, 5364 kB of additional disk space will be used. Do you want to continue? [Y/n] y Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 ca-certificates all 20211016~18.04.1 [144 kB] Get:2 https://download.docker.com/linux/ubuntu focal/stable amd64 containerd.io amd64 1.6.6-1 [28.1 MB] Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 snapd amd64 2.55.5+18.04 [35.6 MB] Get:4 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-cli amd64 5:20.10.17~3-0~ubuntu-focal [40.6 MB] Get:5 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 cloud-init all 22.2-0ubuntu1~18.04.3 [493 kB] Get:6 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 intel-microcode amd64 3.20220510.0ubuntu0.18.04.1 [4063 kB] Get:7 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce amd64 5:20.10.17~3-0~ubuntu-focal [21.0 MB] Get:8 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-rootless-extras amd64 5:20.10.17~3-0~ubuntu-focal [8171 kB] Get:9 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-compose-plugin amd64 2.6.0~ubuntu-focal [6560 kB] Fetched 145 MB in 4s (36.3 MB/s) Preconfiguring packages ... (Reading database ... 93863 files and directories currently installed.) Preparing to unpack .../0-ca-certificates_20211016~18.04.1_all.deb ... Unpacking ca-certificates (20211016~18.04.1) over (20210119~20.04.2) ... Preparing to unpack .../1-containerd.io_1.6.6-1_amd64.deb ... Unpacking containerd.io (1.6.6-1) over (1.6.4-1) ... Preparing to unpack .../2-docker-ce-cli_5%3a20.10.17~3-0~ubuntu-focal_amd64.deb ... Unpacking docker-ce-cli (5:20.10.17~3-0~ubuntu-focal) over (5:20.10.16~3-0~ubuntu-focal) ... Preparing to unpack .../3-docker-ce_5%3a20.10.17~3-0~ubuntu-focal_amd64.deb ... Unpacking docker-ce (5:20.10.17~3-0~ubuntu-focal) over (5:20.10.16~3-0~ubuntu-focal) ... Preparing to unpack .../4-docker-ce-rootless-extras_5%3a20.10.17~3-0~ubuntu-focal_amd64.deb ... Unpacking docker-ce-rootless-extras (5:20.10.17~3-0~ubuntu-focal) over (5:20.10.16~3-0~ubuntu-focal) ... Preparing to unpack .../5-docker-compose-plugin_2.6.0~ubuntu-focal_amd64.deb ... Unpacking docker-compose-plugin (2.6.0~ubuntu-focal) over (2.5.0~ubuntu-focal) ... Preparing to unpack .../6-snapd_2.55.5+18.04_amd64.deb ... Unpacking snapd (2.55.5+18.04) over (2.54.3+20.04.1ubuntu0.3) ... Preparing to unpack .../7-cloud-init_22.2-0ubuntu1~18.04.3_all.deb ... Unpacking cloud-init (22.2-0ubuntu1~18.04.3) over (22.1-14-g2e17a0d6-0ubuntu1~20.04.3) ... Preparing to unpack .../8-intel-microcode_3.20220510.0ubuntu0.18.04.1_amd64.deb ... Unpacking intel-microcode (3.20220510.0ubuntu0.18.04.1) over (3.20210608.0ubuntu0.20.04.1) ... Setting up cloud-init (22.2-0ubuntu1~18.04.3) ... Installing new version of config file /etc/cloud/cloud.cfg ... Setting up intel-microcode (3.20220510.0ubuntu0.18.04.1) ... update-initramfs: deferring update (trigger activated) intel-microcode: microcode will be updated at next boot Setting up ca-certificates (20211016~18.04.1) ... Updating certificates in /etc/ssl/certs... rehash: warning: skipping ca-certificates.crt,it does not contain exactly one certificate or CRL 7 added, 8 removed; done. Setting up containerd.io (1.6.6-1) ... Setting up docker-compose-plugin (2.6.0~ubuntu-focal) ... Setting up docker-ce-cli (5:20.10.17~3-0~ubuntu-focal) ... Setting up docker-ce-rootless-extras (5:20.10.17~3-0~ubuntu-focal) ... Setting up snapd (2.55.5+18.04) ... Installing new version of config file /etc/apparmor.d/usr.lib.snapd.snap-confine.real ... snapd.failure.service is a disabled or a static unit not running, not starting it. snapd.snap-repair.service is a disabled or a static unit not running, not starting it. Setting up docker-ce (5:20.10.17~3-0~ubuntu-focal) ... Processing triggers for mime-support (3.64ubuntu1) ... Processing triggers for rsyslog (8.2001.0-1ubuntu1.3) ... Processing triggers for systemd (245.4-4ubuntu3.17) ... Processing triggers for man-db (2.9.1-1) ... Processing triggers for dbus (1.12.16-2ubuntu2.2) ... Processing triggers for initramfs-tools (0.136ubuntu6.7) ... update-initramfs: Generating /boot/initrd.img-5.4.0-110-generic Processing triggers for ca-certificates (20211016~18.04.1) ... Updating certificates in /etc/ssl/certs... 0 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d... done. ```
When apt says dependencies have conflicting versions, you need to manually specify all dependencies in the command line. This tells apt that you want also to upgrade all dependencies. Apt doesn't by default allow downgrading packages. If any package still conflicts and it is not required by other installed packages, it will be automatically suggested for removal. Version conflicts can be caused by either having two repositories with same package, but different version numbers, or trying to upgrade packages while a repository metadata is still being updated.
63,932,169
Regex program to print words from sentences which contain 2 numbers and they are not next to each other. I made a regex program which prints them but in some cases they print out words with numbers next to each other. ``` import re tekst = str(input("Unesi tekst: ")) pattern = re.findall(r'\b(?=\d*[^\W\d])[^\W\d]*\d[^\W\d]*\d\w*\b',tekst) print(pattern) ``` input: ``` 2test2 te22st 2tes2t t2est2 ``` output: ``` 2test2 2tes2t t2est2 ```
2020/09/17
[ "https://Stackoverflow.com/questions/63932169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14212957/" ]
Use `re.findall`: ``` [i for i in tekst.split() if len(re.findall("\d+", i)) == 2] ``` Output: ``` ['2test2', '2tes2t', 't2est2'] ```
You could update the pattern to repeat the middle negated character class 1+ times to prevent the 2 digits being next to each other. ``` \b(?=\d*[^\W\d])[^\W\d]*\d[^\W\d]+\d[^\W\d]*\b ``` **Explanation** * `\b` Word boundary * `(?=\d*[^\W\d])` Assert as least a single word char that is not a digit * `[^\W\d]*` Match 0+ times a word char without a digit * `\d` Match the first digit * `[^\W\d]1` Match 1+ times a word char without a digit to prevent them begin next to each other * `\d` Match the second digit * `[^\W\d]*` Match 0+ times a word char without a digit * `\b` Word boundary [Regex demo](https://regex101.com/r/hGEpIj/1)
47,439,536
I am able to extract the inner file, but it extracts the entire chain. Suppose the following file structure ``` v a.zip v folder1 v folder2 > inner.txt ``` and suppose I want to extract `inner.txt` to some folder `target`. Currently what happens when I try to do this is that I end up extracting `folder1/folder2/inner.txt` to `target`. Is it possible to extract the single file instead of the entire chain of directories? So that when `target` is opened, the only thing inside is `inner.txt`. EDIT: Using python zip module to unzip files and extract only the inner files to the desired location.
2017/11/22
[ "https://Stackoverflow.com/questions/47439536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7571052/" ]
You should use the **-j** (*junk paths (do not make directories)*) modifier (old *v5.52* has it). Here's the full list: [[DIE.Linux]: unzip(1) - Linux man page](https://linux.die.net/man/1/unzip), or you could simply run *(${PATH\_TO}/)unzip* in the terminal, and it will output the argument list. Considering that you want to extract the file in a folder called *target*, use the command (you may need to specify the path to *unzip*): ``` "unzip" -j "a.zip" -d "target" "folder1/folder2/inner.txt" ``` **Output** (*Win*, but for *Nix* it's the same thing): > > > ``` > (py35x64_test) c:\Work\Dev\StackOverflow\q047439536>"unzip" -j "a.zip" -d "target" "folder1/folder2/inner.txt" > Archive: a.zip > inflating: target/inner.txt > > ``` > > **Output** (without ***-j***): > > > ``` > (py35x64_test) c:\Work\Dev\StackOverflow\q047439536>"unzip" "a.zip" -d "target" "folder1/folder2/inner.txt" > Archive: a.zip > inflating: target/folder1/folder2/inner.txt > > ``` > > Or, since you mentioned *Python*, *code00.py*: ```py import os from zipfile import ZipFile def extract_without_folder(arc_name, full_item_name, folder): with ZipFile(arc_name) as zf: file_data = zf.read(full_item_name) with open(os.path.join(folder, os.path.basename(full_item_name)), "wb") as fout: fout.write(file_data) if __name__ == "__main__": extract_without_folder("a.zip", "folder1/folder2/inner.txt", "target") ```
The zip doesn't have a folder structure in the same way as on the filesystem - each file has a name that is its entire path. You'll want to use a method that allows you to read the file contents (such as zipfile.open or zipfile.read), extract the part of the filename you actually want to use, and save the file contents to that file yourself.
11,768,601
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
2012/08/01
[ "https://Stackoverflow.com/questions/11768601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477097/" ]
In particular with the ability to assign property values with object initializers, multiple overloads for constructors are far less useful than they were. They were mostly useful in the past for setting mutable properties for code compactness. Now one can write ``` MyClass my = new MyClass() { PropA = 1, PropB = 2 }; ``` Almost as compact as ``` MyClass my = new MyClass(1, 2); ``` while being more expressive. However, sometimes the nature of an object dictates that an overload would provide a meaningful contract to the object consumer. For example, providing an overload for a *Rectangle* class that accepts a length and a width is not unreasonable (I would not ding it on a code review). Personally I would still not provide an overload because object initializer syntax is more expressive, avoiding questions like "was that Rectangle(int length, int width) or Rectangle(int width, int length)?" while reading code (I know, intellisense helps while writing code).
I believe this is a fine approach. Typically people use properties for optional parameters; but this makes the object mutable. Using optional constructor arguments/ctor overloads is a good approach to keep the object immutable.
11,768,601
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
2012/08/01
[ "https://Stackoverflow.com/questions/11768601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477097/" ]
I believe this is a fine approach. Typically people use properties for optional parameters; but this makes the object mutable. Using optional constructor arguments/ctor overloads is a good approach to keep the object immutable.
Consider subclassing instead of several constructors. Reason: Often two different different constructors indicate two different behaviors are desired. Different nehaviors should be implemented by different classes. The subclass would then have both a name that indicates how it's a specialized version of the base class, and a constructor that ensures that this kind of object can only be created in a valid state.
11,768,601
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
2012/08/01
[ "https://Stackoverflow.com/questions/11768601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477097/" ]
In particular with the ability to assign property values with object initializers, multiple overloads for constructors are far less useful than they were. They were mostly useful in the past for setting mutable properties for code compactness. Now one can write ``` MyClass my = new MyClass() { PropA = 1, PropB = 2 }; ``` Almost as compact as ``` MyClass my = new MyClass(1, 2); ``` while being more expressive. However, sometimes the nature of an object dictates that an overload would provide a meaningful contract to the object consumer. For example, providing an overload for a *Rectangle* class that accepts a length and a width is not unreasonable (I would not ding it on a code review). Personally I would still not provide an overload because object initializer syntax is more expressive, avoiding questions like "was that Rectangle(int length, int width) or Rectangle(int width, int length)?" while reading code (I know, intellisense helps while writing code).
As a rule of thumb, I add to a constructor only the parameters that are *required* to create a valid, working object. With the advent of object initializer syntax, it is much easier for the client to configure whatever other parameters he wants. However, I think that this rule *should* have many exceptions: many times you might want to provide an overload that makes it easy and clearer to the developer what he can expect to be able to change about an object.
11,768,601
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
2012/08/01
[ "https://Stackoverflow.com/questions/11768601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477097/" ]
In particular with the ability to assign property values with object initializers, multiple overloads for constructors are far less useful than they were. They were mostly useful in the past for setting mutable properties for code compactness. Now one can write ``` MyClass my = new MyClass() { PropA = 1, PropB = 2 }; ``` Almost as compact as ``` MyClass my = new MyClass(1, 2); ``` while being more expressive. However, sometimes the nature of an object dictates that an overload would provide a meaningful contract to the object consumer. For example, providing an overload for a *Rectangle* class that accepts a length and a width is not unreasonable (I would not ding it on a code review). Personally I would still not provide an overload because object initializer syntax is more expressive, avoiding questions like "was that Rectangle(int length, int width) or Rectangle(int width, int length)?" while reading code (I know, intellisense helps while writing code).
Consider subclassing instead of several constructors. Reason: Often two different different constructors indicate two different behaviors are desired. Different nehaviors should be implemented by different classes. The subclass would then have both a name that indicates how it's a specialized version of the base class, and a constructor that ensures that this kind of object can only be created in a valid state.
11,768,601
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
2012/08/01
[ "https://Stackoverflow.com/questions/11768601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477097/" ]
As a rule of thumb, I add to a constructor only the parameters that are *required* to create a valid, working object. With the advent of object initializer syntax, it is much easier for the client to configure whatever other parameters he wants. However, I think that this rule *should* have many exceptions: many times you might want to provide an overload that makes it easy and clearer to the developer what he can expect to be able to change about an object.
Consider subclassing instead of several constructors. Reason: Often two different different constructors indicate two different behaviors are desired. Different nehaviors should be implemented by different classes. The subclass would then have both a name that indicates how it's a specialized version of the base class, and a constructor that ensures that this kind of object can only be created in a valid state.
22,987,874
I want to access a Darwin iCal server which i have implemented using my Rails application. I would like to create events and access the server to get events in specific date range. When I tried to install the [Caldav gem](http://rubygems.org/gems/caldav), I am getting a dependency with the "rexml" gem. > > Could not find gem 'rexml (>= 0) ruby', which is required by gem > 'caldav (>= 0) ruby', in any of the sources. > > > Unfortunately rexml is not there in gemscutter or any other sources. Any idea how I can use the Caldav gem ?
2014/04/10
[ "https://Stackoverflow.com/questions/22987874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907561/" ]
I'm not sure but i've figured out this from what i understand you want like this? ``` $('#NewCustomerDiv input[name=CompanyName]').keyup(function () { if($(this).val().length > 0) { if($(this).val() == "test") $('#CustomerCompanyDiv').slideUp("slow"); else $('#CustomerCompanyDiv').slideDown("slow"); } else { $('#CustomerCompanyDiv').slideUp("slow"); } }); ``` [**Fiddle**](http://jsfiddle.net/7NTEk/2/)
Use the PLACEHOLDER Parameter to inform users of the functionality of a form element: ``` <input type="text" name="CompanyName" placeholder="Type test to slide up"/> ```
22,987,874
I want to access a Darwin iCal server which i have implemented using my Rails application. I would like to create events and access the server to get events in specific date range. When I tried to install the [Caldav gem](http://rubygems.org/gems/caldav), I am getting a dependency with the "rexml" gem. > > Could not find gem 'rexml (>= 0) ruby', which is required by gem > 'caldav (>= 0) ruby', in any of the sources. > > > Unfortunately rexml is not there in gemscutter or any other sources. Any idea how I can use the Caldav gem ?
2014/04/10
[ "https://Stackoverflow.com/questions/22987874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907561/" ]
I'm not sure but i've figured out this from what i understand you want like this? ``` $('#NewCustomerDiv input[name=CompanyName]').keyup(function () { if($(this).val().length > 0) { if($(this).val() == "test") $('#CustomerCompanyDiv').slideUp("slow"); else $('#CustomerCompanyDiv').slideDown("slow"); } else { $('#CustomerCompanyDiv').slideUp("slow"); } }); ``` [**Fiddle**](http://jsfiddle.net/7NTEk/2/)
ok try this [fiddle](http://jsfiddle.net/L7Ebt/3/) Your modified script ``` $(document).ready(function(){ $('#NewCustomerDiv input[name=CompanyName]').keyup(function(){ if($(this).val()==""){ $('#CustomerCompanyDiv').slideUp("slow"); } else{ $('#CustomerCompanyDiv').slideDown("slow"); } }); if($('#NewCustomerDiv input[name=CompanyName]').val()){ $('#CustomerCompanyDiv').slideDown("slow"); } }); ```
28,795,808
Based on recent empirical findings, and based on various posts on the web, it seems that an application running on an iPhone with personal hotspot enabled cannot send broadcasts and/or multicasts out onto the personal hotspot's network. Can anyone shed light on the cause of this problem? **The Application** I have an IOS application, built with cross-platform C++ code, that broadcasts and multicasts its presence onto the network it is running on. The application works flawlessly when the iPhone is connected to a Wi-Fi network. In this case, other devices on the network receive the broadcasts/multicasts, and everything functions correctly. This can be verified easily by connecting a computer running WireShark to the network -- the broadcast/multicast packets can be seen in the packet trace. Needless to say, the application works well on an iPhone connected to a local Wi-Fi. **The Problem** When I run the application on an iPhone that has its personal hotspot enabled, no broadcasts/multicasts are released onto the hotspot network. This can be verified using WireShark, which shows no such packets in its trace. Is there any constraint regarding using a personal hotspot as a network router capable of handling broadcasts and multicasts? When I requested a web page on my "WireSharking" device using a browser, the personal hotspot responds correctly to all packets, returning the web contents. **Collateral Information** I have come across other Stack Overflow posts that report the same, or similar, problems: 1. [TCP connection not working properly when using iPhone as hotspot](https://stackoverflow.com/questions/23535242/tcp-connection-not-working-properly-when-using-iphone-as-hotspot) 2. [Fail to send ssdp broadcast by personal hotspot](https://stackoverflow.com/questions/26559327/fail-to-send-ssdp-broadcast-by-personal-hotspot) A good tutorial for writing such a broadcasting/multicasting application on iPhone is Michael Tyson's "[The Making of Talkie: Multi-interface broadcasting and multicast](http://atastypixel.com/blog/the-making-of-talkie-multi-interface-broadcasting-and-multicast/)". Suffice it to say that my application conforms with all requirements (e.g., setting socket options SO\_BROADCAST, SO\_DONTROUTE, and IP\_MULTICAST\_IF where appropriate). A reply to reference (1) above writes "*Could it be because the personal hotspot introduces Network Address Translation?*". I filtered the WireShark traces to show only packets connected to the hotspot IP, and there is no evidence of the personal hotspot sending anything to a NAT address. **In summary** Can anyone explain why an iPhone running a personal hotspot does not broadcast/multicast packets, and how to solve the problem? Many thanks in advance.
2015/03/01
[ "https://Stackoverflow.com/questions/28795808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/562242/" ]
**I got broadcast working (on iOS 10)** I'm posting a second answer, because I found a way to get broadcast working on iOS 10 in personal hotspot mode. the solution is a bit complex, but here is how I got it to work: 1. use `getifaddrs(if)` to loop through all interfaces (`do {} while (if = if->ifa_next)`) 2. reject loopback interfaces (`if->ifa_flags & IFF_LOOPBACK`) 3. filter only interfaces that support broadcast (`if->ifa_flags & IFF_BROADCAST`) 4. create a socket with `int sock = socket()` 5. enable broadcast: `int yes = 1; setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &yes, sizeof yes)` 6. connect to the broadcast address: `connect(sock, if->ifa_dstaddr, if->ifa_dstaddr->sa_len)` 7. now use `send()` to send your message! I've confirmed that this works both when the iPhone is connected to a WiFi network, and also when it's in personal hotspot mode. **Full Sample Code** ``` #include <ifaddrs.h> #include <arpa/inet.h> #include <net/if.h> -(IBAction)sayHello:(id)sender { // fetch a linked list of all network interfaces struct ifaddrs *interfaces; if (getifaddrs(&interfaces) == -1) { NSLog(@"getifaddrs() failed: %s", strerror(errno)); return; } // loop through the linked list for(struct ifaddrs *interface=interfaces; interface; interface=interface->ifa_next) { // ignore loopback interfaces if (interface->ifa_flags & IFF_LOOPBACK) continue; // ignore interfaces that don't have a broadcast address if (!(interface->ifa_flags & IFF_BROADCAST) || interface->ifa_dstaddr == NULL) continue; // check the type of the address (IPv4, IPv6) int protocol_family; struct sockaddr_in ipv4_addr = {0}; struct sockaddr_in6 ipv6_addr = {0}; struct sockaddr *addr; if (interface->ifa_dstaddr->sa_family == AF_INET) { if (interface->ifa_dstaddr->sa_len > sizeof ipv4_addr) { NSLog(@"Address too big"); continue; } protocol_family = PF_INET; memcpy(&ipv4_addr, interface->ifa_dstaddr, interface->ifa_dstaddr->sa_len); ipv4_addr.sin_port = htons(16000); addr = (struct sockaddr *)&ipv4_addr; char text_addr[255] = {0}; inet_ntop(AF_INET, &ipv4_addr.sin_addr, text_addr, sizeof text_addr); NSLog(@"Sending message to %s:%d", text_addr, ntohs(ipv4_addr.sin_port)); } else if (interface->ifa_dstaddr->sa_family == AF_INET6) { if (interface->ifa_dstaddr->sa_len > sizeof ipv6_addr) { NSLog(@"Address too big"); continue; } protocol_family = PF_INET6; memcpy(&ipv6_addr, interface->ifa_dstaddr, interface->ifa_dstaddr->sa_len); ipv6_addr.sin6_port = htons(16000); addr = (struct sockaddr *)&ipv6_addr; char text_addr[255] = {0}; inet_ntop(AF_INET6, &ipv6_addr.sin6_addr, text_addr, sizeof text_addr); NSLog(@"Sending message to %s:%d", text_addr, ntohs(ipv6_addr.sin6_port)); } else { NSLog(@"Unsupported protocol: %d", interface->ifa_dstaddr->sa_family); continue; } // create a socket int sock = socket(protocol_family, SOCK_DGRAM, IPPROTO_UDP); if (sock == -1) { NSLog(@"socket() failed: %s", strerror(errno)); continue; } // configure the socket for broadcast mode int yes = 1; if (-1 == setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &yes, sizeof yes)) { NSLog(@"setsockopt() failed: %s", strerror(errno)); } // create some bytes to send NSString *message = @"Hello world!\n"; NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; if (-1 == connect(sock, addr, addr->sa_len)) { NSLog(@"connect() failed: %s", strerror(errno)); } // send the message ssize_t sent_bytes = send(sock, data.bytes, data.length, 0); if (sent_bytes == -1) { NSLog(@"send() failed: %s", strerror(errno)); } else if (sent_bytes<data.length) { NSLog(@"send() sent only %d of %d bytes", (int)sent_bytes, (int)data.length); } // close the socket! important! there is only a finite number of file descriptors available! if (-1 == close(sock)) { NSLog(@"close() failed: %s", strerror(errno)); } } freeifaddrs(interfaces); } ``` This sample method broadcasts a UDP message on port 16000. For debugging, you can use the tool `socat`. Just run the following command on your computer (which should be on the same network as the phone): ``` socat UDP-RECV:16000 STDOUT ```
**Quick-and-dirty workaround** I also ran into the same problem when developing an iPhone app that uses a UDP multicast message to discover devices on the network. Apparently the iPhone blocks multicast messages in personal hotspot mode. However, iPhone seems to use the `172.20.10.0/28` subnet for devices on the personal hotspot network. This means that there are just 16 possible addresses. Of these, `172.20.10.0` is apparently not used, `172.20.10.1` is the iPhone itself, and sending messages to `172.20.10.15` fails with a 'not permitted' error. This means that only the following 13 addresses can be used by clients: `172.20.10.2`, `172.20.10.3`, ..., `172.20.10.14`. So my work-around is pretty simple: instead of sending broadcast messages only to to `224.0.0.0`, I also send them to all the other possible addresses in the subnet (`172.20.10.2` - `172.20.10.14`). Of course, to be future-proof in a production app you should probably check the list of network interfaces, check the IP and subnet, etc., but for my personal use this method is sufficient.
13,743,618
I am attempting to get multiple String variables set with one println. Here is what I have: ``` Scanner scanner = new Scanner(System.in); String teacher = ""; String classSelect = ""; String location = ""; System.out.println("Enter a teacher: "); teacher = scanner.next(); System.out.println("Enter a class name: "); classSelect = scanner.next(); System.out.println("Enter a location: "); location = scanner.next(); ``` Here is what I would like to accomplish: ``` String section = ""; String instructor = ""; String location = ""; System.out.printf("Only fill in applicable criteria, leave the rest blank :\n" + "Section://Sets section var// \n" + "Instructor://Sets instructor var// \n" + "Location://Sets location var// \n"); ```
2012/12/06
[ "https://Stackoverflow.com/questions/13743618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414028/" ]
This might not be an ethical way but try it ``` System.out.printf("Only fill in applicable criteria, leave the rest blank and use | after every field:\n" + "Section://Sets section var// \n" + "Instructor://Sets instructor var// \n" + "Location://Sets location var// \n"); ``` if the user enteres ``` abc|xyz|loc ``` accept it in a string ``` String input = scanner.nextLine(); String[] inputs=input.split("|"); inputs[0]//<--section inputs[1]//<--instructor inputs[2]//<--location ```
Are you looking for this: ``` String message = String.format("Only fill in applicable criteria, leave the rest blank :\n" + "Section: %s \n" + "Instructor: %s \n" + "Location:%s \n", section ,instructor,location ); ``` or this? ``` System.out.printf("Only fill in applicable criteria, leave the rest blank :\n" + "Section: %s \n" + "Instructor: %s \n" + "Location:%s \n", section ,instructor,location ); ```
51,222,035
I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons. [Here](https://stackoverflow.com/questions/25028040/jquery-horizontal-scroll-using-buttons) is an identical thread on SO for JQuery. [This demo](http://next.plnkr.co/edit/GxufhJaRJn2SfGb4ilIl?p=preview) is the solution in JQuery. It should illustrate the effect I'm after. **How can I achieve that effect using VueJS?** Some libraries I have already taken a look at include [vue-scroll-to](https://www.npmjs.com/package/vue-scroll-to) and [jump](https://github.com/callmecavs/jump.js). * Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels. * Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window. EDIT: I found a little library that accomplishes this in VanillaJS: <https://github.com/tarun-dugar/easy-scroll>
2018/07/07
[ "https://Stackoverflow.com/questions/51222035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7489488/" ]
> > I made a sandbox for this: [see it here](https://jz38xyr559.codesandbox.io) > > > The logic is this: ``` scroll_left() { let content = document.querySelector(".wrapper-box"); content.scrollLeft -= 50; }, scroll_right() { let content = document.querySelector(".wrapper-box"); content.scrollLeft += 40; } ``` You have a wrapper and you increasing/decreasing the `scrollLeft` property The full code can be found [here](https://codesandbox.io/s/jz38xyr559)
You can use JavaScript only, using the example you gave I converted it to JavaScript only and here's the Codepen for it. <https://codepen.io/immad-hamid/pen/yEmayr> This is the JavaScript that can replace the example that you sent. ``` const rightBtn = document.querySelector('#right-button'); const leftBtn = document.querySelector('#left-button'); const content = document.querySelector('#content'); rightBtn.addEventListener("click", function(event) { content.scrollLeft += 300; event.preventDefault(); }); leftBtn.addEventListener("click", function(event) { content.scrollLeft -= 300; event.preventDefault(); }); ``` For the animation you have to use something... Can you do that?
51,222,035
I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons. [Here](https://stackoverflow.com/questions/25028040/jquery-horizontal-scroll-using-buttons) is an identical thread on SO for JQuery. [This demo](http://next.plnkr.co/edit/GxufhJaRJn2SfGb4ilIl?p=preview) is the solution in JQuery. It should illustrate the effect I'm after. **How can I achieve that effect using VueJS?** Some libraries I have already taken a look at include [vue-scroll-to](https://www.npmjs.com/package/vue-scroll-to) and [jump](https://github.com/callmecavs/jump.js). * Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels. * Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window. EDIT: I found a little library that accomplishes this in VanillaJS: <https://github.com/tarun-dugar/easy-scroll>
2018/07/07
[ "https://Stackoverflow.com/questions/51222035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7489488/" ]
You can use JavaScript only, using the example you gave I converted it to JavaScript only and here's the Codepen for it. <https://codepen.io/immad-hamid/pen/yEmayr> This is the JavaScript that can replace the example that you sent. ``` const rightBtn = document.querySelector('#right-button'); const leftBtn = document.querySelector('#left-button'); const content = document.querySelector('#content'); rightBtn.addEventListener("click", function(event) { content.scrollLeft += 300; event.preventDefault(); }); leftBtn.addEventListener("click", function(event) { content.scrollLeft -= 300; event.preventDefault(); }); ``` For the animation you have to use something... Can you do that?
There's also this example from codepen `$ Here's the link` <https://codepen.io/wa23/pen/pObyrq> here's the important things: HTML (pug) ``` link(href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400" rel="stylesheet") h1 Vue Carousel script#v-carousel(type="x/template") .card-carousel-wrapper .card-carousel--nav__left( @click="moveCarousel(-1)" :disabled="atHeadOfList" ) .card-carousel .card-carousel--overflow-container .card-carousel-cards(:style="{ transform: 'translateX' + '(' + currentOffset + 'px' + ')'}") .card-carousel--card(v-for="item in items") img(src="https://placehold.it/200x200") .card-carousel--card--footer p {{ item.name }} p.tag(v-for="(tag,index) in item.tag" :class="index > 0 ? 'secondary' : ''") {{ tag }} .card-carousel--nav__right( @click="moveCarousel(1)" :disabled="atEndOfList" ) #app carousel ``` Css (Scss) ``` $vue-navy: #2c3e50; $vue-navy-light: #3a5169; $vue-teal: #42b883; $vue-teal-light: #42b983; $gray: #666a73; $light-gray: #f8f8f8; body { background: $light-gray; color: $vue-navy; font-family: 'Source Sans Pro', sans-serif; } .card-carousel-wrapper { display: flex; align-items: center; justify-content: center; margin: 20px 0 40px; color: $gray; } .card-carousel { display: flex; justify-content: center; width: 640px; &--overflow-container { overflow: hidden; } &--nav__left, &--nav__right { display: inline-block; width: 15px; height: 15px; padding: 10px; box-sizing: border-box; border-top: 2px solid $vue-teal; border-right: 2px solid $vue-teal; cursor: pointer; margin: 0 20px; transition: transform 150ms linear; &[disabled] { opacity: 0.2; border-color: black; } } &--nav__left { transform: rotate(-135deg); &:active { transform: rotate(-135deg) scale(0.9); } } &--nav__right { transform: rotate(45deg); &:active { transform: rotate(45deg) scale(0.9); } } } .card-carousel-cards { display: flex; transition: transform 150ms ease-out; transform: translatex(0px); .card-carousel--card { margin: 0 10px; cursor: pointer; box-shadow: 0 4px 15px 0 rgba(40,44,53,.06), 0 2px 2px 0 rgba(40,44,53,.08); background-color: #fff; border-radius: 4px; z-index: 3; margin-bottom: 2px; &:first-child { margin-left: 0; } &:last-child { margin-right: 0; } img { vertical-align: bottom; border-top-left-radius: 4px; border-top-right-radius: 4px; transition: opacity 150ms linear; user-select: none; &:hover { opacity: 0.5; } } &--footer { border-top: 0; padding: 7px 15px; p { padding: 3px 0; margin: 0; margin-bottom: 2px; font-size: 19px; font-weight: 500; color: $vue-navy; user-select: none; &.tag { font-size: 11px; font-weight: 300; padding: 4px; background: rgba(40,44,53,.06); display: inline-block; position: relative; margin-left: 4px; color: $gray; &:before { content:""; float:left; position:absolute; top:0; left: -12px; width:0; height:0; border-color:transparent rgba(40,44,53,.06) transparent transparent; border-style:solid; border-width:8px 12px 12px 0; } &.secondary { margin-left: 0; border-left: 1.45px dashed white; &:before { display: none !important; } } &:after { content:""; position:absolute; top:8px; left:-3px; float:left; width:4px; height:4px; border-radius: 2px; background: white; box-shadow:-0px -0px 0px #004977; } } } } } } h1 { font-size: 3.6em; font-weight: 100; text-align: center; margin-bottom: 0; color: $vue-teal; } ``` JS ``` Vue.component("carousel", { template: "#v-carousel", data() { return { currentOffset: 0, windowSize: 3, paginationFactor: 220, items: [ {name: 'Kin Khao', tag: ["Thai"]}, {name: 'Jū-Ni', tag: ["Sushi", "Japanese", "$$$$"]}, {name: 'Delfina', tag: ["Pizza", "Casual"]}, {name: 'San Tung', tag: ["Chinese", "$$"]}, {name: 'Anchor Oyster Bar', tag: ["Seafood", "Cioppino"]}, {name: 'Locanda', tag: ["Italian"]}, {name: 'Garden Creamery', tag: ["Ice cream"]}, ] } }, computed: { atEndOfList() { return this.currentOffset <= (this.paginationFactor * -1) * (this.items.length - this.windowSize); }, atHeadOfList() { return this.currentOffset === 0; }, }, methods: { moveCarousel(direction) { // Find a more elegant way to express the :style. consider using props to make it truly generic if (direction === 1 && !this.atEndOfList) { this.currentOffset -= this.paginationFactor; } else if (direction === -1 && !this.atHeadOfList) { this.currentOffset += this.paginationFactor; } }, } }); new Vue({ el:"#app" }); ``` edit: Sorry for not answering soon because I was very busy these days
51,222,035
I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons. [Here](https://stackoverflow.com/questions/25028040/jquery-horizontal-scroll-using-buttons) is an identical thread on SO for JQuery. [This demo](http://next.plnkr.co/edit/GxufhJaRJn2SfGb4ilIl?p=preview) is the solution in JQuery. It should illustrate the effect I'm after. **How can I achieve that effect using VueJS?** Some libraries I have already taken a look at include [vue-scroll-to](https://www.npmjs.com/package/vue-scroll-to) and [jump](https://github.com/callmecavs/jump.js). * Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels. * Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window. EDIT: I found a little library that accomplishes this in VanillaJS: <https://github.com/tarun-dugar/easy-scroll>
2018/07/07
[ "https://Stackoverflow.com/questions/51222035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7489488/" ]
> > I made a sandbox for this: [see it here](https://jz38xyr559.codesandbox.io) > > > The logic is this: ``` scroll_left() { let content = document.querySelector(".wrapper-box"); content.scrollLeft -= 50; }, scroll_right() { let content = document.querySelector(".wrapper-box"); content.scrollLeft += 40; } ``` You have a wrapper and you increasing/decreasing the `scrollLeft` property The full code can be found [here](https://codesandbox.io/s/jz38xyr559)
There's also this example from codepen `$ Here's the link` <https://codepen.io/wa23/pen/pObyrq> here's the important things: HTML (pug) ``` link(href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400" rel="stylesheet") h1 Vue Carousel script#v-carousel(type="x/template") .card-carousel-wrapper .card-carousel--nav__left( @click="moveCarousel(-1)" :disabled="atHeadOfList" ) .card-carousel .card-carousel--overflow-container .card-carousel-cards(:style="{ transform: 'translateX' + '(' + currentOffset + 'px' + ')'}") .card-carousel--card(v-for="item in items") img(src="https://placehold.it/200x200") .card-carousel--card--footer p {{ item.name }} p.tag(v-for="(tag,index) in item.tag" :class="index > 0 ? 'secondary' : ''") {{ tag }} .card-carousel--nav__right( @click="moveCarousel(1)" :disabled="atEndOfList" ) #app carousel ``` Css (Scss) ``` $vue-navy: #2c3e50; $vue-navy-light: #3a5169; $vue-teal: #42b883; $vue-teal-light: #42b983; $gray: #666a73; $light-gray: #f8f8f8; body { background: $light-gray; color: $vue-navy; font-family: 'Source Sans Pro', sans-serif; } .card-carousel-wrapper { display: flex; align-items: center; justify-content: center; margin: 20px 0 40px; color: $gray; } .card-carousel { display: flex; justify-content: center; width: 640px; &--overflow-container { overflow: hidden; } &--nav__left, &--nav__right { display: inline-block; width: 15px; height: 15px; padding: 10px; box-sizing: border-box; border-top: 2px solid $vue-teal; border-right: 2px solid $vue-teal; cursor: pointer; margin: 0 20px; transition: transform 150ms linear; &[disabled] { opacity: 0.2; border-color: black; } } &--nav__left { transform: rotate(-135deg); &:active { transform: rotate(-135deg) scale(0.9); } } &--nav__right { transform: rotate(45deg); &:active { transform: rotate(45deg) scale(0.9); } } } .card-carousel-cards { display: flex; transition: transform 150ms ease-out; transform: translatex(0px); .card-carousel--card { margin: 0 10px; cursor: pointer; box-shadow: 0 4px 15px 0 rgba(40,44,53,.06), 0 2px 2px 0 rgba(40,44,53,.08); background-color: #fff; border-radius: 4px; z-index: 3; margin-bottom: 2px; &:first-child { margin-left: 0; } &:last-child { margin-right: 0; } img { vertical-align: bottom; border-top-left-radius: 4px; border-top-right-radius: 4px; transition: opacity 150ms linear; user-select: none; &:hover { opacity: 0.5; } } &--footer { border-top: 0; padding: 7px 15px; p { padding: 3px 0; margin: 0; margin-bottom: 2px; font-size: 19px; font-weight: 500; color: $vue-navy; user-select: none; &.tag { font-size: 11px; font-weight: 300; padding: 4px; background: rgba(40,44,53,.06); display: inline-block; position: relative; margin-left: 4px; color: $gray; &:before { content:""; float:left; position:absolute; top:0; left: -12px; width:0; height:0; border-color:transparent rgba(40,44,53,.06) transparent transparent; border-style:solid; border-width:8px 12px 12px 0; } &.secondary { margin-left: 0; border-left: 1.45px dashed white; &:before { display: none !important; } } &:after { content:""; position:absolute; top:8px; left:-3px; float:left; width:4px; height:4px; border-radius: 2px; background: white; box-shadow:-0px -0px 0px #004977; } } } } } } h1 { font-size: 3.6em; font-weight: 100; text-align: center; margin-bottom: 0; color: $vue-teal; } ``` JS ``` Vue.component("carousel", { template: "#v-carousel", data() { return { currentOffset: 0, windowSize: 3, paginationFactor: 220, items: [ {name: 'Kin Khao', tag: ["Thai"]}, {name: 'Jū-Ni', tag: ["Sushi", "Japanese", "$$$$"]}, {name: 'Delfina', tag: ["Pizza", "Casual"]}, {name: 'San Tung', tag: ["Chinese", "$$"]}, {name: 'Anchor Oyster Bar', tag: ["Seafood", "Cioppino"]}, {name: 'Locanda', tag: ["Italian"]}, {name: 'Garden Creamery', tag: ["Ice cream"]}, ] } }, computed: { atEndOfList() { return this.currentOffset <= (this.paginationFactor * -1) * (this.items.length - this.windowSize); }, atHeadOfList() { return this.currentOffset === 0; }, }, methods: { moveCarousel(direction) { // Find a more elegant way to express the :style. consider using props to make it truly generic if (direction === 1 && !this.atEndOfList) { this.currentOffset -= this.paginationFactor; } else if (direction === -1 && !this.atHeadOfList) { this.currentOffset += this.paginationFactor; } }, } }); new Vue({ el:"#app" }); ``` edit: Sorry for not answering soon because I was very busy these days
51,222,035
I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons. [Here](https://stackoverflow.com/questions/25028040/jquery-horizontal-scroll-using-buttons) is an identical thread on SO for JQuery. [This demo](http://next.plnkr.co/edit/GxufhJaRJn2SfGb4ilIl?p=preview) is the solution in JQuery. It should illustrate the effect I'm after. **How can I achieve that effect using VueJS?** Some libraries I have already taken a look at include [vue-scroll-to](https://www.npmjs.com/package/vue-scroll-to) and [jump](https://github.com/callmecavs/jump.js). * Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels. * Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window. EDIT: I found a little library that accomplishes this in VanillaJS: <https://github.com/tarun-dugar/easy-scroll>
2018/07/07
[ "https://Stackoverflow.com/questions/51222035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7489488/" ]
> > I made a sandbox for this: [see it here](https://jz38xyr559.codesandbox.io) > > > The logic is this: ``` scroll_left() { let content = document.querySelector(".wrapper-box"); content.scrollLeft -= 50; }, scroll_right() { let content = document.querySelector(".wrapper-box"); content.scrollLeft += 40; } ``` You have a wrapper and you increasing/decreasing the `scrollLeft` property The full code can be found [here](https://codesandbox.io/s/jz38xyr559)
If you're looking for horizontal smooth scroll animation in javascript itself without using any library. Use `scrollTo` with `behavior: 'smooth'` ```js Vue.config.devtools = false; Vue.config.productionTip = false; new Vue({ el: '#app', data: { scrollAmount: 0, }, methods: { scrollLeft: function () { const menu = this.$refs.menu menu.scrollTo({ left: this.scrollAmount += 200, behavior: 'smooth', }) }, scrollRight: function () { const menu = this.$refs.menu menu.scrollTo({ left: this.scrollAmount -= 200, behavior: 'smooth', }) } }, mounted() {} }) ``` ```css body { margin: 3em; } * { padding: 0; margin: 0; } .menu-wrapper { position: relative; max-width: 310px; height: 100px; margin: 1em auto; border: 1px solid black; overflow-x: hidden; overflow-y: hidden; } .menu { height: 120px; background: #f3f3f3; box-sizing: border-box; white-space: nowrap; overflow-x: auto; overflow-y: hidden; } .item { display: inline-block; width: 100px; height: 100%; outline: 1px dotted gray; padding: 1em; box-sizing: border-box; } .paddle { position: absolute; top: 0; bottom: 0; width: 3em; } .left-paddle { left: 0; } .right-paddle { right: 0; } .hidden { display: none; } .print { margin: auto; max-width: 500px; } span { display: inline-block; width: 100px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app" class="menu-wrapper"> <ul class="menu" ref="menu"> <li class="item">1</li> <li class="item">2</li> <li class="item">3</li> <li class="item">4</li> <li class="item">5</li> <li class="item">6</li> <li class="item">7</li> <li class="item">8</li> <li class="item">9</li> <li class="item">10</li> <li class="item">11</li> <li class="item">12</li> <li class="item">13</li> </ul> <div class="paddles"> <button class="left-paddle paddle" @click="scrollRight"> - </button> <button class="right-paddle paddle" @click="scrollLeft"> > </button> </div> </div> ```
51,222,035
I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons. [Here](https://stackoverflow.com/questions/25028040/jquery-horizontal-scroll-using-buttons) is an identical thread on SO for JQuery. [This demo](http://next.plnkr.co/edit/GxufhJaRJn2SfGb4ilIl?p=preview) is the solution in JQuery. It should illustrate the effect I'm after. **How can I achieve that effect using VueJS?** Some libraries I have already taken a look at include [vue-scroll-to](https://www.npmjs.com/package/vue-scroll-to) and [jump](https://github.com/callmecavs/jump.js). * Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels. * Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window. EDIT: I found a little library that accomplishes this in VanillaJS: <https://github.com/tarun-dugar/easy-scroll>
2018/07/07
[ "https://Stackoverflow.com/questions/51222035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7489488/" ]
If you're looking for horizontal smooth scroll animation in javascript itself without using any library. Use `scrollTo` with `behavior: 'smooth'` ```js Vue.config.devtools = false; Vue.config.productionTip = false; new Vue({ el: '#app', data: { scrollAmount: 0, }, methods: { scrollLeft: function () { const menu = this.$refs.menu menu.scrollTo({ left: this.scrollAmount += 200, behavior: 'smooth', }) }, scrollRight: function () { const menu = this.$refs.menu menu.scrollTo({ left: this.scrollAmount -= 200, behavior: 'smooth', }) } }, mounted() {} }) ``` ```css body { margin: 3em; } * { padding: 0; margin: 0; } .menu-wrapper { position: relative; max-width: 310px; height: 100px; margin: 1em auto; border: 1px solid black; overflow-x: hidden; overflow-y: hidden; } .menu { height: 120px; background: #f3f3f3; box-sizing: border-box; white-space: nowrap; overflow-x: auto; overflow-y: hidden; } .item { display: inline-block; width: 100px; height: 100%; outline: 1px dotted gray; padding: 1em; box-sizing: border-box; } .paddle { position: absolute; top: 0; bottom: 0; width: 3em; } .left-paddle { left: 0; } .right-paddle { right: 0; } .hidden { display: none; } .print { margin: auto; max-width: 500px; } span { display: inline-block; width: 100px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app" class="menu-wrapper"> <ul class="menu" ref="menu"> <li class="item">1</li> <li class="item">2</li> <li class="item">3</li> <li class="item">4</li> <li class="item">5</li> <li class="item">6</li> <li class="item">7</li> <li class="item">8</li> <li class="item">9</li> <li class="item">10</li> <li class="item">11</li> <li class="item">12</li> <li class="item">13</li> </ul> <div class="paddles"> <button class="left-paddle paddle" @click="scrollRight"> - </button> <button class="right-paddle paddle" @click="scrollLeft"> > </button> </div> </div> ```
There's also this example from codepen `$ Here's the link` <https://codepen.io/wa23/pen/pObyrq> here's the important things: HTML (pug) ``` link(href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400" rel="stylesheet") h1 Vue Carousel script#v-carousel(type="x/template") .card-carousel-wrapper .card-carousel--nav__left( @click="moveCarousel(-1)" :disabled="atHeadOfList" ) .card-carousel .card-carousel--overflow-container .card-carousel-cards(:style="{ transform: 'translateX' + '(' + currentOffset + 'px' + ')'}") .card-carousel--card(v-for="item in items") img(src="https://placehold.it/200x200") .card-carousel--card--footer p {{ item.name }} p.tag(v-for="(tag,index) in item.tag" :class="index > 0 ? 'secondary' : ''") {{ tag }} .card-carousel--nav__right( @click="moveCarousel(1)" :disabled="atEndOfList" ) #app carousel ``` Css (Scss) ``` $vue-navy: #2c3e50; $vue-navy-light: #3a5169; $vue-teal: #42b883; $vue-teal-light: #42b983; $gray: #666a73; $light-gray: #f8f8f8; body { background: $light-gray; color: $vue-navy; font-family: 'Source Sans Pro', sans-serif; } .card-carousel-wrapper { display: flex; align-items: center; justify-content: center; margin: 20px 0 40px; color: $gray; } .card-carousel { display: flex; justify-content: center; width: 640px; &--overflow-container { overflow: hidden; } &--nav__left, &--nav__right { display: inline-block; width: 15px; height: 15px; padding: 10px; box-sizing: border-box; border-top: 2px solid $vue-teal; border-right: 2px solid $vue-teal; cursor: pointer; margin: 0 20px; transition: transform 150ms linear; &[disabled] { opacity: 0.2; border-color: black; } } &--nav__left { transform: rotate(-135deg); &:active { transform: rotate(-135deg) scale(0.9); } } &--nav__right { transform: rotate(45deg); &:active { transform: rotate(45deg) scale(0.9); } } } .card-carousel-cards { display: flex; transition: transform 150ms ease-out; transform: translatex(0px); .card-carousel--card { margin: 0 10px; cursor: pointer; box-shadow: 0 4px 15px 0 rgba(40,44,53,.06), 0 2px 2px 0 rgba(40,44,53,.08); background-color: #fff; border-radius: 4px; z-index: 3; margin-bottom: 2px; &:first-child { margin-left: 0; } &:last-child { margin-right: 0; } img { vertical-align: bottom; border-top-left-radius: 4px; border-top-right-radius: 4px; transition: opacity 150ms linear; user-select: none; &:hover { opacity: 0.5; } } &--footer { border-top: 0; padding: 7px 15px; p { padding: 3px 0; margin: 0; margin-bottom: 2px; font-size: 19px; font-weight: 500; color: $vue-navy; user-select: none; &.tag { font-size: 11px; font-weight: 300; padding: 4px; background: rgba(40,44,53,.06); display: inline-block; position: relative; margin-left: 4px; color: $gray; &:before { content:""; float:left; position:absolute; top:0; left: -12px; width:0; height:0; border-color:transparent rgba(40,44,53,.06) transparent transparent; border-style:solid; border-width:8px 12px 12px 0; } &.secondary { margin-left: 0; border-left: 1.45px dashed white; &:before { display: none !important; } } &:after { content:""; position:absolute; top:8px; left:-3px; float:left; width:4px; height:4px; border-radius: 2px; background: white; box-shadow:-0px -0px 0px #004977; } } } } } } h1 { font-size: 3.6em; font-weight: 100; text-align: center; margin-bottom: 0; color: $vue-teal; } ``` JS ``` Vue.component("carousel", { template: "#v-carousel", data() { return { currentOffset: 0, windowSize: 3, paginationFactor: 220, items: [ {name: 'Kin Khao', tag: ["Thai"]}, {name: 'Jū-Ni', tag: ["Sushi", "Japanese", "$$$$"]}, {name: 'Delfina', tag: ["Pizza", "Casual"]}, {name: 'San Tung', tag: ["Chinese", "$$"]}, {name: 'Anchor Oyster Bar', tag: ["Seafood", "Cioppino"]}, {name: 'Locanda', tag: ["Italian"]}, {name: 'Garden Creamery', tag: ["Ice cream"]}, ] } }, computed: { atEndOfList() { return this.currentOffset <= (this.paginationFactor * -1) * (this.items.length - this.windowSize); }, atHeadOfList() { return this.currentOffset === 0; }, }, methods: { moveCarousel(direction) { // Find a more elegant way to express the :style. consider using props to make it truly generic if (direction === 1 && !this.atEndOfList) { this.currentOffset -= this.paginationFactor; } else if (direction === -1 && !this.atHeadOfList) { this.currentOffset += this.paginationFactor; } }, } }); new Vue({ el:"#app" }); ``` edit: Sorry for not answering soon because I was very busy these days
7,345,786
This code is not working and i do not understand the mistake. Please help. ``` -(UIImage *)addText:(UIImage *)img text:(NSString *)text1 { int w = img.size.width; int h = img.size.height; //lon = h - lon; char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding]; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); /*UIGraphicsBeginImageContext(self.view.bounds.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; CGContextShowTextAtPoint(UIGraphicsGetCurrentContext(), 50, 100, text, strlen(text)); UIImage *viewImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSLog(@"View Image : %@",viewImage);*/ CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage); CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1); //char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];// "05/05/09"; CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman); CGContextSetTextDrawingMode(context, kCGTextFill); CGContextSetRGBFillColor(context, 255, 255, 255, 1); //rotate text CGContextShowTextAtPoint(context, 0, 50, text, strlen(text)); CGContextSetTextMatrix(context, CGAffineTransformMakeRotation( -M_PI/4 )); CGContextShowTextAtPoint(context, 50, 100, text, strlen(text)); //UIImage *compositeImage = UIGraphicsGetImageFromCurrentImageContext(); CGImageRef imageMasked = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); NSLog(@"Image : %@",[UIImage imageWithCGImage:imageMasked]); return [UIImage imageWithCGImage:imageMasked]; //return viewImage; } ```
2011/09/08
[ "https://Stackoverflow.com/questions/7345786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889867/" ]
Unless you have a reason to avoid NSString UIKit additions, this will suffice: ``` +(UIImage*) drawText:(NSString*) text inImage:(UIImage*) image atPoint:(CGPoint) point font:(UIFont*) font color:(UIColor*) color { UIGraphicsBeginImageContextWithOptions(image.size, FALSE, 0.0); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [color set]; [text drawInRect:CGRectIntegral(rect) withFont:font]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } ```
Your code does work. Make sure the string you are passing into it is not empty.
226,503
I am trying to delete first and the last vertex of each line. I created code to delete first and last vertex but it shows me error on line 18: > > > > > > Traceback (most recent call last): File "D:\UKPN\ukpn\_CAD\tet\Delete\_first\_last.py", line 18, in > > insert = arcpy.da.InsertCursor(outFC, "SHAPE@") RuntimeError: cannot open > > 'D:\UKPN\ukpn\_CAD\ukpn\_CAD.gdb\right\_no\_diss\_sample\_diss\_Sp4' Failed > > to execute (Deletefirstlast). > > > > > > > > > My code: ``` import arcpy arcpy.env.overwriteOutput = True # set input/output parameters inFC = arcpy.GetParameterAsText(0) outFC = arcpy.GetParameterAsText(1) #output path fcPath = outFC.rpartition("\\")[0] fcName = outFC.rpartition("\\")[2] if arcpy.Exists(outFC): arcpy.Delete_management(outFC) search = arcpy.da.SearchCursor(inFC, "SHAPE@") insert = arcpy.da.InsertCursor(outFC, "SHAPE@") for row in search: points = [arcpy.Point(point.X, point.Y) for shape in row[0] for point in shape] del points[0] del points[-1] points.append(points[0]) array = arcpy.Array(points) polyline = arcpy.Polyline(array) insert.insertRow([polyline]) ``` I am using ArcGIS Pro Basic license 1.3. Can anyone tell me what am I doing wrong?
2017/01/31
[ "https://gis.stackexchange.com/questions/226503", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/62486/" ]
I think the problem lies in your attempt to "explode" your geometry into a list of point objects. I personally find list comprehension extremely confusing and generally unreadable. The following code does the same and is much easier to read. ```py # Code assumes the following: all polylines are single part & that a minimum number of vertices is 4 import arcpy flayer = "fcLines" # Layer in TOC with arcpy.da.UpdateCursor(flayer,["shape@","OID@"]) as cursor: for row in cursor: geom = row[0] oid = row[1] if geom.length > 0: # Create an array of point arr = geom.getPart(0) print "Processing OID: " + str(oid) print "before: " + str(arr.count) # remove first arr.remove(0) # remove end arr.remove(arr.count - 1) print "after: " + str(arr.count) # Create new polyline and update row newLine = arcpy.Polyline(arr) row[0] = newLine cursor.updateRow(row) ``` Looking at your initial attempt there is no error trapping, what about lines that are composed of only two vertices, what about null geometries, what about stacked points? You need to deal with all those situations, you cannot assume your dataset is perfect.
You are asking your model's user to enter an output feature class location/name as a parameter and deleting it if it exists. The problem is arcpy.da.InsertCursor works only with existing feature classes, so you need to create one (since you want to make sure it is an empty feature class). Try adding [Create Feature Class tool](http://pro.arcgis.com/en/pro-app/tool-reference/data-management/create-feature-class.htm) just before your insert cursor with relevant out path, name and geometry arguments. Also the rest of your code may not work as expected if you have multipartite polylines!
226,503
I am trying to delete first and the last vertex of each line. I created code to delete first and last vertex but it shows me error on line 18: > > > > > > Traceback (most recent call last): File "D:\UKPN\ukpn\_CAD\tet\Delete\_first\_last.py", line 18, in > > insert = arcpy.da.InsertCursor(outFC, "SHAPE@") RuntimeError: cannot open > > 'D:\UKPN\ukpn\_CAD\ukpn\_CAD.gdb\right\_no\_diss\_sample\_diss\_Sp4' Failed > > to execute (Deletefirstlast). > > > > > > > > > My code: ``` import arcpy arcpy.env.overwriteOutput = True # set input/output parameters inFC = arcpy.GetParameterAsText(0) outFC = arcpy.GetParameterAsText(1) #output path fcPath = outFC.rpartition("\\")[0] fcName = outFC.rpartition("\\")[2] if arcpy.Exists(outFC): arcpy.Delete_management(outFC) search = arcpy.da.SearchCursor(inFC, "SHAPE@") insert = arcpy.da.InsertCursor(outFC, "SHAPE@") for row in search: points = [arcpy.Point(point.X, point.Y) for shape in row[0] for point in shape] del points[0] del points[-1] points.append(points[0]) array = arcpy.Array(points) polyline = arcpy.Polyline(array) insert.insertRow([polyline]) ``` I am using ArcGIS Pro Basic license 1.3. Can anyone tell me what am I doing wrong?
2017/01/31
[ "https://gis.stackexchange.com/questions/226503", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/62486/" ]
I have had similar problems with data where we had multiple vertices "stacked" at close to the same x,y pt in polylines and polygons. If you are using ArcGIS Arcmap (32 bit) ESRI products with python 2.7, I wrote a script to identify and clean those issues. In my script, I'm always saving the beginning and ending vertex of a polyline. ``` import arcpy import math #path fc = arcpy.mapping.Layer('D:/Folder/Errors/HIGHWAYS.shp') #UpdateCursor up, then down with arcpy.da.UpdateCursor(fc,["shape@", "OID@"]) as cursor: for row in cursor: # loop through parts for part in row[0]: counter = 0 compX = 000000.1 compY = 000000.1 #print "Beginning OID = " + str(row[1]) for pnt in part: #--NOTE--if you want 2 places with ceil, multi and divide by 100 if (math.ceil(pnt.X*10)/10 < compX + 0.2 and math.ceil(pnt.X*10)/10 > compX - 0.2) and (math.ceil(pnt.Y*10)/10 < compY + 0.2 and math.ceil(pnt.Y*10)/10 > compY - 0.2): print "##########################################################" #print str(compX) + "," + str(compY) print "OID = " + str(row[1]) arr = row[0].getPart(0) if arr.count == 3: print "arr.count = 3" arr.remove(1) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing Malcolm in the Middle vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) cursor.updateRow(row) print "-----------------------------------------" elif arr.count <= 2: print "no beuno---very small line---probably a sliver" else: print "arrcount = " + str(arr.count) print "counter = " + str(counter) if arr.count == (counter + 1): arr.remove(arr.count - 2) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) print "Saved Original Endpoint" cursor.updateRow(row) print "----------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" else: arr.remove(counter - 1) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) cursor.updateRow(row) print "-----------------------------------------" else: compX = math.ceil(pnt.X*10)/10 compY = math.ceil(pnt.Y*10)/10 counter = counter + 1 print ("Done") ``` If you are using something like Oracle Spatial..... ``` select * from ( SELECT id_number, id_2, SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(c.geometry, 0.2) val FROM highway c ) where val <> 'TRUE'; ``` Fixed the data using: ``` update highway set geometry = sdo_util.rectify_geometry(GEOMETRY,0.2) where id_number = 'somenumber1' ; ```
You are asking your model's user to enter an output feature class location/name as a parameter and deleting it if it exists. The problem is arcpy.da.InsertCursor works only with existing feature classes, so you need to create one (since you want to make sure it is an empty feature class). Try adding [Create Feature Class tool](http://pro.arcgis.com/en/pro-app/tool-reference/data-management/create-feature-class.htm) just before your insert cursor with relevant out path, name and geometry arguments. Also the rest of your code may not work as expected if you have multipartite polylines!
226,503
I am trying to delete first and the last vertex of each line. I created code to delete first and last vertex but it shows me error on line 18: > > > > > > Traceback (most recent call last): File "D:\UKPN\ukpn\_CAD\tet\Delete\_first\_last.py", line 18, in > > insert = arcpy.da.InsertCursor(outFC, "SHAPE@") RuntimeError: cannot open > > 'D:\UKPN\ukpn\_CAD\ukpn\_CAD.gdb\right\_no\_diss\_sample\_diss\_Sp4' Failed > > to execute (Deletefirstlast). > > > > > > > > > My code: ``` import arcpy arcpy.env.overwriteOutput = True # set input/output parameters inFC = arcpy.GetParameterAsText(0) outFC = arcpy.GetParameterAsText(1) #output path fcPath = outFC.rpartition("\\")[0] fcName = outFC.rpartition("\\")[2] if arcpy.Exists(outFC): arcpy.Delete_management(outFC) search = arcpy.da.SearchCursor(inFC, "SHAPE@") insert = arcpy.da.InsertCursor(outFC, "SHAPE@") for row in search: points = [arcpy.Point(point.X, point.Y) for shape in row[0] for point in shape] del points[0] del points[-1] points.append(points[0]) array = arcpy.Array(points) polyline = arcpy.Polyline(array) insert.insertRow([polyline]) ``` I am using ArcGIS Pro Basic license 1.3. Can anyone tell me what am I doing wrong?
2017/01/31
[ "https://gis.stackexchange.com/questions/226503", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/62486/" ]
I think the problem lies in your attempt to "explode" your geometry into a list of point objects. I personally find list comprehension extremely confusing and generally unreadable. The following code does the same and is much easier to read. ```py # Code assumes the following: all polylines are single part & that a minimum number of vertices is 4 import arcpy flayer = "fcLines" # Layer in TOC with arcpy.da.UpdateCursor(flayer,["shape@","OID@"]) as cursor: for row in cursor: geom = row[0] oid = row[1] if geom.length > 0: # Create an array of point arr = geom.getPart(0) print "Processing OID: " + str(oid) print "before: " + str(arr.count) # remove first arr.remove(0) # remove end arr.remove(arr.count - 1) print "after: " + str(arr.count) # Create new polyline and update row newLine = arcpy.Polyline(arr) row[0] = newLine cursor.updateRow(row) ``` Looking at your initial attempt there is no error trapping, what about lines that are composed of only two vertices, what about null geometries, what about stacked points? You need to deal with all those situations, you cannot assume your dataset is perfect.
I have had similar problems with data where we had multiple vertices "stacked" at close to the same x,y pt in polylines and polygons. If you are using ArcGIS Arcmap (32 bit) ESRI products with python 2.7, I wrote a script to identify and clean those issues. In my script, I'm always saving the beginning and ending vertex of a polyline. ``` import arcpy import math #path fc = arcpy.mapping.Layer('D:/Folder/Errors/HIGHWAYS.shp') #UpdateCursor up, then down with arcpy.da.UpdateCursor(fc,["shape@", "OID@"]) as cursor: for row in cursor: # loop through parts for part in row[0]: counter = 0 compX = 000000.1 compY = 000000.1 #print "Beginning OID = " + str(row[1]) for pnt in part: #--NOTE--if you want 2 places with ceil, multi and divide by 100 if (math.ceil(pnt.X*10)/10 < compX + 0.2 and math.ceil(pnt.X*10)/10 > compX - 0.2) and (math.ceil(pnt.Y*10)/10 < compY + 0.2 and math.ceil(pnt.Y*10)/10 > compY - 0.2): print "##########################################################" #print str(compX) + "," + str(compY) print "OID = " + str(row[1]) arr = row[0].getPart(0) if arr.count == 3: print "arr.count = 3" arr.remove(1) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing Malcolm in the Middle vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) cursor.updateRow(row) print "-----------------------------------------" elif arr.count <= 2: print "no beuno---very small line---probably a sliver" else: print "arrcount = " + str(arr.count) print "counter = " + str(counter) if arr.count == (counter + 1): arr.remove(arr.count - 2) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) print "Saved Original Endpoint" cursor.updateRow(row) print "----------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" else: arr.remove(counter - 1) newLine = arcpy.Polyline(arr) row[0] = newLine print("Removing vertex " + "{0}, {1}".format(pnt.X, pnt.Y)) cursor.updateRow(row) print "-----------------------------------------" else: compX = math.ceil(pnt.X*10)/10 compY = math.ceil(pnt.Y*10)/10 counter = counter + 1 print ("Done") ``` If you are using something like Oracle Spatial..... ``` select * from ( SELECT id_number, id_2, SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(c.geometry, 0.2) val FROM highway c ) where val <> 'TRUE'; ``` Fixed the data using: ``` update highway set geometry = sdo_util.rectify_geometry(GEOMETRY,0.2) where id_number = 'somenumber1' ; ```
44,671,730
I did not want to do it using "shell, exec, etc"... Only with loop in php! My understanding is in this case: 1. I have a form in page, on form submit, i will call on a PHP script which will run in Background. 2. Background process started and running ....running ....running .....running...... 3. I want to got back process id with which Process id Background process started and previous background process running ....running ....running .....running .......... **I need to do this, and if possible a file where it executes a single code with loop until finish some line** ***Idea to project structure:*** [click here](https://i.stack.imgur.com/5SJKP.jpg)
2017/06/21
[ "https://Stackoverflow.com/questions/44671730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8193147/" ]
Because non-empty strings evaluate to `True` in Python. Solution for you problem could be one of the following ``` if i=="b" or i == "k" or i == "c": ``` or ``` if i in ["b", "k", "c"]: ``` Apart from that you are iterating over a wrong set of values. Replace your `for` with ``` for i in alpha: ```
Your condition `i=="b" or "k" or "c"` probably isn't what you wanted. It always returns true, because `"k"` (and `"c"` as well) is true. What you want is: ``` if i=="b" or i=="k" or i=="c": ``` or, better: ``` if i in {"b", "c", "k"}: ```
44,671,730
I did not want to do it using "shell, exec, etc"... Only with loop in php! My understanding is in this case: 1. I have a form in page, on form submit, i will call on a PHP script which will run in Background. 2. Background process started and running ....running ....running .....running...... 3. I want to got back process id with which Process id Background process started and previous background process running ....running ....running .....running .......... **I need to do this, and if possible a file where it executes a single code with loop until finish some line** ***Idea to project structure:*** [click here](https://i.stack.imgur.com/5SJKP.jpg)
2017/06/21
[ "https://Stackoverflow.com/questions/44671730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8193147/" ]
Because non-empty strings evaluate to `True` in Python. Solution for you problem could be one of the following ``` if i=="b" or i == "k" or i == "c": ``` or ``` if i in ["b", "k", "c"]: ``` Apart from that you are iterating over a wrong set of values. Replace your `for` with ``` for i in alpha: ```
You have missed the check ``` def alphaToPhone(alpha): for i in alpha: if i == "b" or i == "k" or i == "c": phone="yes" else: phone="no" return phone print(alphaToPhone("23ht")) ```
44,671,730
I did not want to do it using "shell, exec, etc"... Only with loop in php! My understanding is in this case: 1. I have a form in page, on form submit, i will call on a PHP script which will run in Background. 2. Background process started and running ....running ....running .....running...... 3. I want to got back process id with which Process id Background process started and previous background process running ....running ....running .....running .......... **I need to do this, and if possible a file where it executes a single code with loop until finish some line** ***Idea to project structure:*** [click here](https://i.stack.imgur.com/5SJKP.jpg)
2017/06/21
[ "https://Stackoverflow.com/questions/44671730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8193147/" ]
Because non-empty strings evaluate to `True` in Python. Solution for you problem could be one of the following ``` if i=="b" or i == "k" or i == "c": ``` or ``` if i in ["b", "k", "c"]: ``` Apart from that you are iterating over a wrong set of values. Replace your `for` with ``` for i in alpha: ```
You code should be like this: ``` def alphaToPhone(alpha): for ch in alpha: if ch == "b" or ch=="k" or ch=="c": phone="yes" else: phone="no" return phone print(alphaToPhone("23ht")) ```
44,671,730
I did not want to do it using "shell, exec, etc"... Only with loop in php! My understanding is in this case: 1. I have a form in page, on form submit, i will call on a PHP script which will run in Background. 2. Background process started and running ....running ....running .....running...... 3. I want to got back process id with which Process id Background process started and previous background process running ....running ....running .....running .......... **I need to do this, and if possible a file where it executes a single code with loop until finish some line** ***Idea to project structure:*** [click here](https://i.stack.imgur.com/5SJKP.jpg)
2017/06/21
[ "https://Stackoverflow.com/questions/44671730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8193147/" ]
Your condition `i=="b" or "k" or "c"` probably isn't what you wanted. It always returns true, because `"k"` (and `"c"` as well) is true. What you want is: ``` if i=="b" or i=="k" or i=="c": ``` or, better: ``` if i in {"b", "c", "k"}: ```
You code should be like this: ``` def alphaToPhone(alpha): for ch in alpha: if ch == "b" or ch=="k" or ch=="c": phone="yes" else: phone="no" return phone print(alphaToPhone("23ht")) ```
44,671,730
I did not want to do it using "shell, exec, etc"... Only with loop in php! My understanding is in this case: 1. I have a form in page, on form submit, i will call on a PHP script which will run in Background. 2. Background process started and running ....running ....running .....running...... 3. I want to got back process id with which Process id Background process started and previous background process running ....running ....running .....running .......... **I need to do this, and if possible a file where it executes a single code with loop until finish some line** ***Idea to project structure:*** [click here](https://i.stack.imgur.com/5SJKP.jpg)
2017/06/21
[ "https://Stackoverflow.com/questions/44671730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8193147/" ]
You have missed the check ``` def alphaToPhone(alpha): for i in alpha: if i == "b" or i == "k" or i == "c": phone="yes" else: phone="no" return phone print(alphaToPhone("23ht")) ```
You code should be like this: ``` def alphaToPhone(alpha): for ch in alpha: if ch == "b" or ch=="k" or ch=="c": phone="yes" else: phone="no" return phone print(alphaToPhone("23ht")) ```
12,242,879
In my project I have to select multiple values and pass it to a query. i.e page1 contains checkboxes. I am storing the selected checkbox id's into an array. I am shuffling that array and getting the values randomly. Now I need to pass these random values to a query. Using IN operator in database I can pass the values statically but how can I pass the values dynamcially to the query. For ex:(Passing values statically) ``` SELECT * FROM Persons WHERE person_id IN ('21','22') ``` In the above query the id's 21 and 22 are know previously and so we are passing statically but I want to send the values to query dynamically. ``` Page1: public static ArrayList<String> chksublist = new ArrayList<String>(); Page2: Collections.shuffle(chksublist ); SELECT * FROM Persons WHERE person_id IN ('21','22') In the above line I want to send the random values which are in chksublist array. ```
2012/09/03
[ "https://Stackoverflow.com/questions/12242879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455252/" ]
see how values are dynamicaly passed ``` // Getting single contact public Contact getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PH_NO }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); // here new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function if (cursor != null) cursor.moveToFirst(); Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)); // return contact return contact; } ```
Try it ``` cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null); ``` using raw query ``` String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")"; db.rawQuery(query); ```
12,242,879
In my project I have to select multiple values and pass it to a query. i.e page1 contains checkboxes. I am storing the selected checkbox id's into an array. I am shuffling that array and getting the values randomly. Now I need to pass these random values to a query. Using IN operator in database I can pass the values statically but how can I pass the values dynamcially to the query. For ex:(Passing values statically) ``` SELECT * FROM Persons WHERE person_id IN ('21','22') ``` In the above query the id's 21 and 22 are know previously and so we are passing statically but I want to send the values to query dynamically. ``` Page1: public static ArrayList<String> chksublist = new ArrayList<String>(); Page2: Collections.shuffle(chksublist ); SELECT * FROM Persons WHERE person_id IN ('21','22') In the above line I want to send the random values which are in chksublist array. ```
2012/09/03
[ "https://Stackoverflow.com/questions/12242879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455252/" ]
`String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";` But shuffling the `chksublist` before sending it to your SQL query has no impact on the result set you get from SQL. It will not randomly permute your results. Remove `Collections.shuffle(chksublist);` and use `String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";`
see how values are dynamicaly passed ``` // Getting single contact public Contact getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PH_NO }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); // here new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function if (cursor != null) cursor.moveToFirst(); Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)); // return contact return contact; } ```