qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
1,001,784
In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods. Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection. What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not. I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations. First, I have the central cache access object, which I call MathContext: ``` class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] ``` The fn argument is the filename the context is created in relation to, from where data can be read to be calculated. Then we have the Calculation class: ``` class CalcBase(object): def exec(self, math_context): raise NotImplementedError ``` And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations: ``` class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n < 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b ``` What I want Fibonacci to be instead, is just a decorated method: ``` @cache def fib(n): if n<2: return 1 return fib(n-1)+fib(n-2) ``` With the math\_context example, when math\_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.
2009/06/16
[ "https://Stackoverflow.com/questions/1001784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I went ahead and made something that might just do what you want. It can be used as both a decorator and a context manager: ``` from __future__ import with_statement try: import cPickle as pickle except ImportError: import pickle class cached(object): """Decorator/context manager for caching function call results. All results are cached in one dictionary that is shared by all cached functions. To use this as a decorator: @cached def function(...): ... The results returned by a decorated function are not cleared from the cache until decorated_function.clear_my_cache() or cached.clear_cache() is called To use this as a context manager: with cached(function) as function: ... function(...) ... The function's return values will be cleared from the cache when the with block ends To clear all cached results, call the cached.clear_cache() class method """ _CACHE = {} def __init__(self, fn): self._fn = fn def __call__(self, *args, **kwds): key = self._cache_key(*args, **kwds) function_cache = self._CACHE.setdefault(self._fn, {}) try: return function_cache[key] except KeyError: function_cache[key] = result = self._fn(*args, **kwds) return result def clear_my_cache(self): """Clear the cache for a decorated function """ try: del self._CACHE[self._fn] except KeyError: pass # no cached results def __enter__(self): return self def __exit__(self, type, value, traceback): self.clear_my_cache() def _cache_key(self, *args, **kwds): """Create a cache key for the given positional and keyword arguments. pickle.dumps() is used because there could be unhashable objects in the arguments, but passing them to pickle.dumps() will result in a string, which is always hashable. I used this to make the cached class as generic as possible. Depending on your requirements, other key generating techniques may be more efficient """ return pickle.dumps((args, sorted(kwds.items())), pickle.HIGHEST_PROTOCOL) @classmethod def clear_cache(cls): """Clear everything from all functions from the cache """ cls._CACHE = {} if __name__ == '__main__': # used as decorator @cached def fibonacci(n): print "calculating fibonacci(%d)" % n if n == 0: return 0 if n == 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2) for n in xrange(10): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) def lucas(n): print "calculating lucas(%d)" % n if n == 0: return 2 if n == 1: return 1 return lucas(n - 1) + lucas(n - 2) # used as context manager with cached(lucas) as lucas: for i in xrange(10): print 'lucas(%d) = %d' % (i, lucas(i)) for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) cached.clear_cache() for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) ```
You could use a global variable wrapped in a getter function: ``` def getConnection(): global connection if connection: return connection connection=createConnection() return connection ```
34,183,343
Tensorflow has a function called [batch\_matmul](https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#batch_matmul) which multiplies higher dimensional tensors. But I'm having a hard time understanding how it works, perhaps partially because I'm having a hard time visualizing it. [![enter image description here](https://i.stack.imgur.com/xoiGQ.png)](https://i.stack.imgur.com/xoiGQ.png) What I want to do is multiply a matrix by each slice of a 3D tensor, but I don't quite understand what the shape of tensor a is. Is z the innermost dimension? Which of the following is correct? [![enter image description here](https://i.stack.imgur.com/sm1bZ.jpg)](https://i.stack.imgur.com/sm1bZ.jpg) I would most prefer the first to be correct -- it's most intuitive to me and easy to see in the .eval() output. But I suspect the second is correct. Tensorflow says that batch\_matmul performs: ``` out[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) ``` What does that mean? What does that mean in the context of my example? What is being multiplied with with what? And why aren't I getting a 3D tensor the way I expected?
2015/12/09
[ "https://Stackoverflow.com/questions/34183343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2584721/" ]
You can imagine it as doing a matmul over each training example in the batch. For example, if you have two tensors with the following dimensions: ``` a.shape = [100, 2, 5] b.shape = [100, 5, 2] ``` and you do a batch `tf.matmul(a, b)`, your output will have the shape `[100, 2, 2]`. 100 is your batch size, the other two dimensions are the dimensions of your data.
You can now do it using tf.einsum, starting from Tensorflow **0.11.0rc0**. For example, ``` M1 = tf.Variable(tf.random_normal([2,3,4])) M2 = tf.Variable(tf.random_normal([5,4])) N = tf.einsum('ijk,lk->ijl',M1,M2) ``` It multiplies the matrix M2 with every frame (3 frames) in every batch (2 batches) in M1. The output is: ``` [array([[[ 0.80474716, -1.38590837, -0.3379252 , -1.24965811], [ 2.57852983, 0.05492432, 0.23039417, -0.74263287], [-2.42627382, 1.70774114, 1.19503212, 0.43006262]], [[-1.04652011, -0.32753903, -1.26430523, 0.8810069 ], [-0.48935518, 0.12831448, -1.30816901, -0.01271309], [ 2.33260512, -1.22395933, -0.92082584, 0.48991606]]], dtype=float32), array([[ 1.71076882, 0.79229093, -0.58058828, -0.23246667], [ 0.20446332, 1.30742455, -0.07969904, 0.9247328 ], [-0.32047141, 0.66072595, -1.12330854, 0.80426538], [-0.02781649, -0.29672042, 2.17819595, -0.73862702], [-0.99663496, 1.3840003 , -1.39621222, 0.77119476]], dtype=float32), array([[[ 0.76539308, 2.77609682, -1.79906654, 0.57580602, -3.21205115], [ 4.49365759, -0.10607499, -1.64613271, 0.96234947, -3.38823152], [-3.59156275, 2.03910899, 0.90939498, 1.84612727, 3.44476724]], [[-1.52062428, 0.27325237, 2.24773455, -3.27834225, 3.03435063], [ 0.02695178, 0.16020992, 1.70085776, -2.8645196 , 2.48197317], [ 3.44154787, -0.59687197, -0.12784094, -2.06931567, -2.35522676]]], dtype=float32)] ``` I have verified, the arithmetic is correct.
37,043
We've got a problem with our network here but first I'll give a bit of background info: DHCP running on a windows server 2000 box is configured to hand out 2 IP Ranges 10.25.104.xxx and 10.25.106.xxx The network infrastructure runs on a Cisco Catalyst 4506 of which are linked via fibre. The network team has configured 1 of the 4506's to only allow 10.25.104.xxx traffic and the other 4506 to only allow 10.25.106.xxx traffic. Everything works fine apart from when you wish to move a PC/laptop from one end of the building to the other. Then the IP isn't released or renewed as DHCP constantly trys to give it the same IP again that won't work on the other VLAN (lease times have been set to minimums but still no use). What we really want to allow is for users that move around and presentation laptops to be able to obtain an IP that works with both IP ranges on either of the 4506's. Does anyone know why this happens? is it the way DHCP is configured? or is it the 4506 and the way it has been configured? Is it to do with VLANs? Can more than 1 vlan be setup(or have access) on 1 port? Sorry for all the questions, dont know that much about VLANs and the like - any help much appreciated! Thanks, John
2009/07/07
[ "https://serverfault.com/questions/37043", "https://serverfault.com", "https://serverfault.com/users/10413/" ]
It sounds like you don't have two separate layer 2 broadcast domains when you say "IP isn't released and renewed as DHCP constantly trys to give it the same IP again that won't work on the oppsite network". It's difficult to know what you mean when you say "The network team has configured 1 of the 4506's to only allow 10.25.104.xxx traffic and the other 4506 to only allow 10.25.106.xxx traffic." The phrase "configured to allow" could mean access-control-lists, or it could mean a VLAN configuration. My guess is that you're running both DHCP servers in a single layer 2 broadcast domain. Talk to your "network team" about putting in an "ip-helper" statement into the layer 3 entity that routes between the 10.24.104.xxx and 10.24.106.xxx subnets, pointing DHCP traffic to the Windows 2000 DHCP server, and ask them to be sure that there's no layer 2 broadcast permitted between the subnets. Edit: Since it appears that you are using a DHCP superscope, I'll go ahead and edit my answer a bit. My guess is that your "network team" has already configured the layer-3 entity routing between the subnets with an "ip-helper" setting for your DHCP server. You can confirm that with them to be sure. Assuming the "ip-helper" is in place all you need to do is delete that superscope (which will break the child scopes back apart into two separate DHCP scopes) and you'll have the functionality you're looking for. The DHCP server, by way of the "ip-helper" will hand out subnet-appropriate addresses for clients.
They might have bind the ip address with mac address in dhcp configuration. when it connected and tries to renew from another pool when it will not work. Remove the mac address binding from dhcp configuration & make it dynamic. Create 2 pools one for desktop machines and another for laptops. I these tips might work.
2,613,781
I am looking for an **efficient** way of finding the intersection of a line with a cylinder. Several answers are suggested on this site and other places, however I found [this answer](https://math.stackexchange.com/questions/2126565/intersection-between-a-cylinder-and-a-given-line) the most efficient one. The only challenge I am facing is that the given question and its answer only apply to a case where the line originates from the cylinder axis. Is there any similar approach that can be generalized to lines starting and ending at any arbitrary position? To be specific, I am looking for finding intersection of any arbitrary line with a cylinder where the cylinder axis is assumed to lie on one the axes (say Z-axis). The given cylinder doesn't have caps and therefore, the line may or may not intersect with the cylinder. If it does intersect, it may have one or two intersection(s) of course.
2018/01/20
[ "https://math.stackexchange.com/questions/2613781", "https://math.stackexchange.com", "https://math.stackexchange.com/users/523293/" ]
If your cylinder is set along an an axis, one way you could think of this is the following: You "watch" your cylinder with your vision axis colinear with the cylinder axis, you can transform your parameterized line in the same referential as the cylinder then solve for a simple circle-line intersection in 2D. [![enter image description here](https://i.stack.imgur.com/mpWFv.png)](https://i.stack.imgur.com/mpWFv.png) I'd recommend working with a paremeterized line too, then finding: * 0 intersection, you're done. * 1 intersection, keep the parameter $t$ you solved for and compute the value in the referential you wish for ( given your line parameterized equation ) * 2 intersections, keep the 2 parameters $t1$, $t2$ you solved for and compute the values in the referential you wish for for ( given your line parameterized equation ) * $\infty$ intersections ( the line is contained within the 2d circle ) for that you can check for 2 points really far appart on the line and check if they are both inside the circle. You are not forced to solve quadratics in order to find this intersection, but you can't avoid some trigonometry, here is an example: [![enter image description here](https://i.stack.imgur.com/Tv6ZR.png)](https://i.stack.imgur.com/Tv6ZR.png) [![enter image description here](https://i.stack.imgur.com/Kly9t.png)](https://i.stack.imgur.com/Kly9t.png)
The best way is to parametrize your line and plug into the equation of the cylinder. For example if you have a line starting at $P(1,2,3)$ and the direction vector is $ V=<2,3,5>$. Then the parametrization is $$x=1+2t, y=2+3t,z=3+5t$$ Now suppose your cylinder is $$ x^2 + y^2 =25$$ Plugging your $ x,y,z $of your line line in the equation of the cylinder implies $$ (1+2t)^2 + (2+3t)^2 =25$$ Solve for t and if you have any answer you have our points of intersection by plugging the values for t in the parametric equations of your line.
437,146
I'm planning to deploy an internal app that has sensitive data. I suggested that we put it on a machine that isn't exposed to the general internet, just our internal network. The I.T. department rejected this suggestion, saying it's not worth it to set aside a whole machine for one application. (The app has its own domain in case that's relevant, but I was told they can't block requests based on the URL.) Inside the app I programmed it to only respect requests if they come from an internal I.P. address, otherwise it just shows a page saying "you can't look at this." Our internal addresses all have a distinct pattern, so I'm checking the request I.P. against a regex. But I'm nervous about this strategy. It feels kind of janky to me. Is this reasonably secure?
2009/01/12
[ "https://Stackoverflow.com/questions/437146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42595/" ]
I would rather go with SSL and some certificates, or a simple username / password protection instead of IP filtering.
It depends exactly HOW secure you really need it to be. I am assuming your server is externally hosted and not connected via a VPN. Therefore, you are checking that the requesting addresses for your HTTPS (you are using HTTPS, aren't you??) site are within your own organisation's networks. Using a regex to match IP addresses sounds iffy, can't you just use a network/netmask like everyone else? How secure does it really need to be? IP address spoofing is not easy, spoofed packets cannot be used to establish a HTTPS connection, unless they also manipulate upstream routers to enable the return packets to be redirected to the attacker. If you need it to be really secure, just get your IT department to install a VPN and route over private IP address space. Set up your IP address restrictions for those private addresses. IP address restrictions where the routing is via a host-based VPN are still secure even if someone compromises an upstream default gateway.
42,987
I would like to know when is a good time to start teaching your baby sign language. I heard they won't start signing back to you before 6-7 months so starting before 3 months might be pointless. Any thoughts on when you think would be a good time to start for your sake as well as your baby's?
2022/10/27
[ "https://parenting.stackexchange.com/questions/42987", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/43628/" ]
Just do it as normal all the time. They pick up everything all the time. That is how children learn by seeing, hearing and experiencing things.
We incorporated basic signs with our children pretty much right after they started opening their eyes (i.e. around 1 month) and coupled it with words. We are not proficient in sign language, we limited ourselves to 'eat', 'drink', and 'more' and was done with a deliberate goal towards the long game and had demonstrable benefits for us. Our kids are now 3 & 5 and are 3 year old will sometimes fall back on his sign language when he's extremely upset and that's where the benefits really show. Temper tantrums can make forming his thoughts into words all the more difficult, so having a few signs to help him say what he wants can be very helpful for him to convey his desires without words. He even uses it at bedtime as his way to say, "I love you," and it is the cutest thing ever. So to summarize, anytime is fine, but I will say there are benefits to be had. It probably won't prevent temper tantrums from occurring, but it will make them a little easier to handle.
1,896,527
Can sommebody please tell me what is not right about this code? It compiles and everything great but the output is solid zero's all the way down. So it is not counting the letters. ``` #include <iostream> #include <fstream> #include <string> using namespace std; const char FileName[] = "c:/test.txt"; int main () { string lineBuffer; ifstream inMyStream (FileName); //open my file stream if (inMyStream.is_open()) { //create an array to hold the letter counts int upperCaseCount[26] = {0}; int lowerCaseCount[26] = {0}; //read the text file while (!inMyStream.eof() ) { //get a line of text getline (inMyStream, lineBuffer); //read through each letter in the lineBuffer char oneLetter; for( int n=0; n < (int)lineBuffer.length(); ++n ) { oneLetter = char( lineBuffer[n] ); //get a letter if (oneLetter >= 'A' && oneLetter <='Z') { //decide if it is a capital letter upperCaseCount[int(oneLetter)- 65]++; //make the index match the count array if (oneLetter >= 'a' && oneLetter <='z') { //decide if it is a lower letter lowerCaseCount[int(oneLetter)- 65]++; //make the index match the count array }//end }//end } }//end of while inMyStream.close(); //close the file stream //display the counts for (int i= 0; i < 26; i++) cout << char(i + 65) << "\t\t" << lowerCaseCount[i] << char(i + 95) << "\t\t" << lowerCaseCount[i] << endl; }//end of if else cout << "File Error: Open Failed"; return 0; } ```
2009/12/13
[ "https://Stackoverflow.com/questions/1896527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230547/" ]
Your `if` concerning upper and lower case letters are incorrectly nested. You don't even look at lowercase letters if `oneLetter` is not uppercase. Those two `if`s should be at the same level. That's the only error I can see. I'd recommend either debugging, as gf suggests, or throwing in some print statements to verify your assumptions about what's happening (or not).
How about the printout at the end, where lower case letter counts are printed twice? This explains why it's "zeroes all the way down", because the original code *was* counting the upper case letters correctly wasn't it?
9,712,162
I have a group of 3 `JRadioButtonMenuItem` in a menu, and 3 `JToggleButton` in a toolbar. Each of them is bound to 3 `Action`, so that when I disable one action, both the corresponding item and button will be disabled. When I click a menu item, I would expect also the corresponding toolbar button to get selected, but it seems that the "unclicked" group has its own strange way to react to these events (with a pattern that I didn't try to identify). Here's the menu group code (simplified): ``` ButtonGroup menuGrp = new ButtonGroup(); JRadioButtonMenuItem itemA = new JRadioButtonMenuItem(actionA); JRadioButtonMenuItem itemB = new JRadioButtonMenuItem(actionB); JRadioButtonMenuItem itemC = new JRadioButtonMenuItem(actionC); menuGrp.add(itemA); menuGrp.add(itemB); menuGrp.add(itemC); itemA.setSelected(true); ``` and here toolbar group code: ``` ButtonGroup toolbarGrp = new ButtonGroup(); JToggleButton buttonA = new JToggleButton(actionA); JToggleButton buttonB = new JToggleButton(actionB); JToggleButton buttonC = new JToggleButton(actionC); toolbarGrp.add(buttonA); toolbarGrp.add(buttonB); toolbarGrp.add(buttonB); buttonA.setSelected(true); ```
2012/03/15
[ "https://Stackoverflow.com/questions/9712162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503900/" ]
I don't know how exactly are you doing it, but this code is working for me: ``` import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JToggleButton; public class Button { public static void main(String[] args){ JFrame frame = new JFrame(); JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu("Foo"); ButtonGroup menuGrp = new ButtonGroup(); JRadioButtonMenuItem itemA = new JRadioButtonMenuItem(); JRadioButtonMenuItem itemB = new JRadioButtonMenuItem(); JRadioButtonMenuItem itemC = new JRadioButtonMenuItem(); menuGrp.add(itemA); menuGrp.add(itemB); menuGrp.add(itemC); menu.add(itemA); menu.add(itemB); menu.add(itemC); itemA.setSelected(true); bar.add(menu); frame.setJMenuBar(bar); JPanel content = new JPanel(); ButtonGroup toolbarGrp = new ButtonGroup(); JToggleButton buttonA = new JToggleButton(); JToggleButton buttonB = new JToggleButton(); JToggleButton buttonC = new JToggleButton(); toolbarGrp.add(buttonA); toolbarGrp.add(buttonB); toolbarGrp.add(buttonC); buttonA.setSelected(true); content.add(buttonA); content.add(buttonB); content.add(buttonC); itemA.setAction(new MyAction(buttonA)); itemB.setAction(new MyAction(buttonB)); itemC.setAction(new MyAction(buttonC)); buttonA.setAction(new MyAction(itemA)); buttonB.setAction(new MyAction(itemB)); buttonC.setAction(new MyAction(itemC)); frame.setContentPane(content); frame.setSize(300, 300); frame.setVisible(true); } static class MyAction extends AbstractAction { AbstractButton button; public MyAction(AbstractButton button){ this.button = button; } @Override public void actionPerformed(ActionEvent e){ button.setSelected(true); } } } ```
You can link the state of any two (or more) buttons by sharing the button model among them, in this case: ``` itemA.setModel(buttonA.getModel()); itemB.setModel(buttonB.getModel()); itemC.setModel(buttonC.getModel()); ``` That way you can avoid calling the `putValue(Action.SELECTED_KEY, true)`. Not sure whether that is actually an improvement, but I do like it more.
21,379,093
I have this CLICK function that works for one specific HTML button. I'd like to use it on multiple buttons, but each button needs to pass different variables to the same page. **BUTTON** ``` <input type="button" id="scs" value="TEST" /> ``` **JQUERY** ``` $("#scs").click(function() { $("#status").html("<p>Please Wait! TESTING</p>"); $.ajax({ url: 'go.php?ab=1', success: function(data, textStatus, xhr) { alert (data); } }); }); ``` How can I adapt this so if I have 4 more buttons each button uses the function, calls the same page but uses unique values ? EG : ``` <input type="button" id="update" value="update" /> Calls go.php?up=1 <input type="button" id="new" value="new" /> Calls go.php?new=1 ``` etc... Thanks
2014/01/27
[ "https://Stackoverflow.com/questions/21379093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1932360/" ]
Give your buttons the same class and call the code using the class name, and add a data attribute to each button to retrieve the seperate values. Give this a try: ``` <input type="button" class="clickButton" data-value="go.php?up=1" value="Update" /> <input type="button" class="clickButton" data-value="go.php?new=1" value="New" /> $(".clickButton").click(function() { $("#status").html("<p>Please Wait! TESTING</p>"); $.ajax({ url: $(this).attr("data-value"), success: function(data, textStatus, xhr) { alert (data); $(this).prop('value', 'New Text'); } }); }); ```
You can check by the value of the clicked button and use a 'url' variable for the ajax request: ``` $("button").click(function() { $("#status").html("<p>Please Wait! TESTING</p>"); var url=''; var value = $(this).val(); if(value == 'update'){ url='go.php?up=1'; } else if(value=='new') { url='go.php?new=1'; } else if(value=='scs') { url='go.php?ab=1'; } $.ajax({ url: url, success: function(data, textStatus, xhr) { alert (data); } }); }); ```
2,865,651
In Visual Studio 2008, the target framework settings for a project are * .NET Framework 2.0 * .NET Framework 3.0 * .NET Framework 3.5 However, in Visual Studio 2010 they are * .NET Framework 2.0 * .NET Framework 3.0 * .NET Framework 3.5 * .NET Framework 3.5 Client Profile * .NET Framework 4 * .NET Framework 4 Client Profile What do the *Client Profile* settings mean? Edit ---- A little more experimentation shows that with MVC, WebForms and WCF projects you don't get the Client Profile options. When creating WinForms and Console applications, the default target framework is .NET 4 Client Profile. Which makes sense.
2010/05/19
[ "https://Stackoverflow.com/questions/2865651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39709/" ]
The client profile is a smaller version of the full .NET framework that contains only the more commonly used content. Scott [wrote](http://www.hanselman.com/blog/TowardsASmallerNET4DetailsOnTheClientProfileAndDownloadingNET.aspx) a nice post about this. [Here](http://msdn.microsoft.com/en-us/library/cc656912.aspx) and [here](http://blogs.msdn.com/jgoldb/archive/2009/05/27/net-framework-4-client-profile-introduction.aspx) is an official introduction. The client profile was added recently, so VS 2008 does not know about it yet. The client profile is one of the major features that come with .NET 4 and VS 2010. Since the Client Profile is a subset of the full .NET 4 framework, you don't need to install it if you already got the full .NET 4. It can be an advantage to develop against the Client Profile since it exists on more machines than the full framework (and it is **smaller in download size** for your customers). The disadvantage that comes along naturally - **it does not include everything**. If you are developing a server application or a program that uses uncommon parts of the framework, you'll need the full framework in any case. Typical client programs, however, are likely satisfied with the Client Profile.
It is a subset of the .NET framework for CLIENT applications (i.e. applications installed on the client computer). As such, they do not incorporate server technologies. THis allows the client download to only install a smaller part. Server technologies are for example ASP.NET. Using ".net client profile" as search on Google, first link leads to <http://msdn.microsoft.com/en-us/library/cc656912.aspx> which has a detailed explanation. Also the local .NET documentation (F1 - I hope you are aware this exists) has the same content.
497,210
**Important: This question isn't actually really an ASP.NET question.** Anyone who knows anything about URLS can answer it. I just happen to be using ASP.NET routing so included that detail. In a nutshell my question is : "What URL format should I design that i can give to external parties to get to a specific place on my site that will be future proof. [I'm new to creating these 'REST' URLs]." --- I need an ASP.NET routing URL that will be given to a third party for tracking marketing campaigns. It is essentially a 'gateway' URL that redirects the user to a specific page on our site which may be the homepage, a special contest or a particular product. In addition to [trying to capture](https://stackoverflow.com/questions/257609/which-browsers-plugins-block-httpreferer-from-being-sent) the [referrer](http://mail-archives.apache.org/mod_mbox/roller-dev/200511.mbox/<4377751C.8040507@busybuddha.org) I will need to receive a partnerId, a campaign number and possibly other parameters. I want to provide a route to do this BUT I want to get it right first time because obviously I cant easily change it once its being used externally. How does something like this look? ``` routes.MapRoute( "3rd-party-campaign-route", "campaign/{destination}/{partnerid}/{campaignid}/{custom}", new { controller = "Campaign", action = "Redirect", custom = (string)null // optional so we need to set it null } ); ``` **campaign** : possibly don't want the word 'campaign' in the actual link -- since users will see it in the URL bar. i might change this to just something cryptic like 'c'. **destination** : dictates which page on our site the link will take the user to. For instance PR to direct the user to products page. **partnerid** : the ID for the company that we've assigned - such as SO for Stack overflow. **campaignid** : campaign id such as 123 - unique to each partner. I have realized that I think I'd prefer for the 3rd party company to be able to manage the campaign ids themselves rather than us providing a website to 'create a campaign'. I'm not completely sure about this yet though. **custom** : custom data (optional). i can add further custom data parameters without breaking existing URLS Note: the reason i have 'destination' is because the campaign ID is decided upon by the client so they need to also tell us where the destination of that campaign is. Alternatively they could 'register' a campaign with us. This may be a better solution to avoid people putting in random campaign IDs but I'm not overly concerned about that and i think this system gives more flexibility. In addition we want to know perhaps which image they used to link to us (so we can track which banner works the best). I THINK this is a candiate for a new campaignid as opposed to a custom data field but i'm not sure. Currently I am using a very primitive URL such as <http://example.com?cid=123>. In this case the campaign ID needs to be issued to the third party and it just isn't a very flexible system. I want to move immediately to a new system for new clients. Any thoughts on future proofing this system? What may I have missed? I know i can always add new formats but I want to use this format as much as possible if that is a good idea.
2009/01/30
[ "https://Stackoverflow.com/questions/497210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
This URL: ``` "campaign/{destination}/{partnerid}/{campaignid}/{custom}", ``` ...doesn't look like a resource to me, it looks like a remote method call. There is a lot of business logic here which is likely to change in the future. Also, it's complicated. My gut instinct when designing URLs is that simpler is generally better. This goes double when you are handing the URL to an external partner. Uniform **Resource** Locators are supposed to specify, well, resources. The destination is certainly a resource (but more on this in a moment), and I think you could consider the campaign a resource. The partner is not a resource you serve. Custom is certainly not a resource, as it's entirely undefined. I hear what you're saying about not wanting to have to tell the partners to "create a campaign," but consider that you're likely to eventually have to go down this road anyway. As soon as the campaign has any properties other than the partner identifier, you pretty much have to do this. So my first to conclusions are that you should probably get rid of the partner ID, and derive it from the campaign. Get rid of custom, too, and use query string parameters instead, should it be necessary. It is appropriate to use query string parameters to specify how to return a resource (as opposed to the identity of the resource). Removing those yields: ``` "campaign/{destination}/{campaignid}", ``` OK, that's simpler, but it still doesn't look right. What's destination doing in between campaign and campaign ID? One approach would be to rearrange things: ``` "campaign/{campaignid}/{destination}", ``` Another would be to use Astoria-style indexing: ``` "campaign({campaignid})/{destination}", ``` For some reason, this looks odd to a lot of people, but it's entirely legal. Feel free to use other legal characters to separate campaign from the ID; the point here is that a / is not the only choice, and may not be the appropriate choice. **However...** One question we haven't covered yet is what should happen if/when the user submits a valid destination, but an invalid campaign or partner ID. If the correct response is that the user should see an error, then all of the above is still valid. If, on the other hand, the correct response is that the user should be silently taken to the destination page anyway, then the campaign ID is really a query string parameter, not a part of the resource. Perhaps some partners wouldn't like being given a URL with a question mark in it, but from a purely REST point of view, I think that's the right approach, if the campaign ID's validity does not determine where the user ends up. In this case, the URL would be: ``` "campaign/{destination}", ``` ...and you would add a query string parameter with the campaign ID. I realize that I haven't given you a definite answer to your question. The trouble is that most of this rests on business considerations which you are probably aware of, but I'm certainly not. So I'm more trying to cover the philosophy of a REST-ful URL, rather than attempting to explain your business to you. :)
Create an URL called <http://mysite.com/gateway> Return an HTML form, tell your partners to fill in the form and POST it. Redirect based on the form values. You could easily provide your partners with the javascript to do the GET and POST. Should be trivial.
9,276,389
Here is my code: ``` template<typename T1, typename T2> class MyClass { public: template<int num> static int DoSomething(); }; template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething() { cout << "This is the common method" << endl; cout << "sizeof(T1) = " << sizeof(T1) << endl; cout << "sizeof(T2) = " << sizeof(T2) << endl; return num; } ``` It works well. But when I try to add this ``` template<typename T1, typename T2> template<> int MyClass<T1, T2>::DoSomething<0>() { cout << "This is ZERO!!!" << endl; cout << "sizeof(T1) = " << sizeof(T1) << endl; cout << "sizeof(T2) = " << sizeof(T2) << endl; return num; } ``` I get compiller errors: invalid explicit specialization before «>» token template-id «DoSomething<0>» for «int MyClass::DoSomething()» does not match any template declaration I use g++ 4.6.1 What should I do?
2012/02/14
[ "https://Stackoverflow.com/questions/9276389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1173593/" ]
Unfortunately, you can't specialise a template that's a member of a class template, without specialising the outer template: > > C++11 14.7.3/16: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, **except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well**. > > > I think your best option is to add the extra parameter to `MyClass`, and then partially specialise that.
Similar to DocValle answer, not to rely on possible compiler optimisation you could use constexpr if to enforce compile time branching ``` template<class T> template<int num> void Classname<T>::methodname() { if constexpr (num == 0) { //implementation for num == 0 } else if constexpr (num == 1) { //implementation for num == 1 } //more cases... } ```
37,461,278
I just started to learn Groovy and wondering if you can set your own property for an integer. For example, ``` def a = 34.5.plus(34.34) def b = 5.64.minus(3.43) def c = 12.64.multiply(33.43) ``` In the above there are certain methods like `plus` `minus` and `multiply` What should I do if I want to define some of my own methods for integers like that. I searched `Google` but couldn't find much about it.
2016/05/26
[ "https://Stackoverflow.com/questions/37461278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4546390/" ]
Sure, you can just add methods to the metaClass of `Integer`. Here's an example: ``` Integer.metaClass.zeds = { -> 'z' * delegate } assert 3.zeds() == 'zzz' ``` You can also add methods to a single instance of integer should you wish to, ie: ``` Integer num = 4 num.metaClass.halved = { -> delegate / 2.0 } assert num.halved() == 2.0 ``` You can also add methods to classes via Extension Methods a good explanation of which [can be found over here](http://mrhaki.blogspot.co.uk/2013/01/groovy-goodness-adding-extra-methods.html) It should be noted (as you originally tagged this question as Java) that obviously, Java code will have no knowledge of these things, as it doesn't know about the metaClass
Use groovy meta programming, this allows you to create dynamic method creation atruntime in the class that you want to place in . bydefault if a method is not found methodmissing exception throws , this is where groovy allows you add method at runtime for more reference use the below comprehensive link <http://groovy-lang.org/metaprogramming.html> If this answer helps , dont forget to click answered.
2,100,184
I am interested in understanding the internals of [JavaScript](http://en.wikipedia.org/wiki/JavaScript). I've tried to read the source for [SpiderMonkey](http://en.wikipedia.org/wiki/SpiderMonkey_%28JavaScript_engine%29) and [Rhino](http://en.wikipedia.org/wiki/Rhino_%28JavaScript_engine%29) but it's quite complex to wrap my head around. The reason I ask is: why does something like * `(![]+[])[+!![]+[]]` produce `"a"` * `(Å=[],[µ=!Å+Å][µ[È=++Å+Å+Å]+({}+Å)[Ç=!!Å+µ,ª=Ç[Å]+Ç[+!Å],Å]+ª])()[µ[Å]+µ[Å+Å]+Ç[È]+ª](Å)` produce `alert(1)`? Source: <http://sla.ckers.org/forum/read.php?24,32930,page=1>. There's many more examples of JavaScript oddities on that forum and I wanted to know how it works from a programming point of view with respect to web application security.
2010/01/20
[ "https://Stackoverflow.com/questions/2100184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204535/" ]
If you want to understand why those wierd expressions work as they do, you can open firebug console and experiment yourself. I did and I got that `![]` is `false`, `!![]` is `true`, adding an array to a boolean value (`false+[]` or `true+[]`) produces a string-version of this value (`false+[]="false"`). That way the expression boils down to: ``` "false"["1"] ``` which is obviously "a"
I recommend you obtain and read: * ECMAScript standard (ECMA 262), 5th edition * Adobe document called "AVM 2 overview" which explains the architecture of the AVM2 virtual machine, on which Adobe Flash and its ActionScript run.
5,301,039
I have a set of JPEG's on my server all the same size. Can I convert this into a PDF file server side?
2011/03/14
[ "https://Stackoverflow.com/questions/5301039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356635/" ]
I am using iText for this requirement ``` Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(yourOutFile)); document.open(); for(int i=0;i<numberOfImages;i++){ Image image1 = Image.getInstance("myImage"+i+".jpg"); image1.scalePercent(23f); document.newPage(); document.add(image1); } document.close(); ```
[DotImage](http://www.atalasoft.com) has built-in classes to do this. If all your jpegs are in one folder, you can do this: ``` FileSystemImageSource source = new FileSystemImageSource(pathToDirectory, "*.jpg", true); PdfEncoder encoder = new PdfEncoder(); using (FileStream outstm = new FileStream(outputPath, FileMode.Create)) { encoder.Save(outstm, source, null); } ``` Which will stream all of the images ending with .jpg into an output PDF file. Each page will be fit to the size of the image (this is settable). As far as I know, there is no practical limit to the number of pages you can encode (I'm pretty sure you will exceed the PDF limit before you exhaust your heap memory). In testing, I've run hundreds of images through it without stressing the machine. Compression can be controlled with an event if you want finer control (ie, JPEG compression level or using Flate or JPEG 2000). Color profiles will be included if present in the JPEG and if you want PDF/A-1b, it will do that too. There is also some basic support for setting up a table of contents, if you want. Disclaimer - I work for Atalasoft and personally wrote the FileSystemImageSource and PdfEncoder classes (as well as nearly all the underlying PDF generation tools).
106,737
I just received a .jpg file that I'm almost positive contains a virus, so I have two questions about what I am able to do with the image. My first question originates from the fact that I opened the file once and the program I used to open it gave the error "invalid or corrupt image". So I want to know whether or not its possible a virus contained inside the image could still have been executed if the software did not 'fully' open the image? My second question is if there is any way to decode/decompile the image data in order to better view its contents. Currently I'm using Notepad++, I just opened the file and am looking at its raw contents, which is one of the reasons why I'm so confident its a virus: [![enter image description here](https://i.stack.imgur.com/MU9B1.png)](https://i.stack.imgur.com/MU9B1.png) So is there a better way to find out what the virus does and how it works? I need to know whether or not my security has been compromised. EDIT: Reasons why I think it contains a virus: 1. It's way bigger than the image I was expecting 2. [Scan](https://www.virustotal.com/en/file/6f9df9afb5f0fbd8e3ac9016121731879b2d3b53f81c0a4efb2d85fda6bbb69e/analysis/1448742319/) 3. Looking at contents in Notepad ([file](https://mega.nz/#!nEdnWJ7a!15RXOhrt8Q2TlupyJ91rpZsdAirkKT4CLdal-1m4q8A)) 4. The way the person who gave me the file acted
2015/11/28
[ "https://security.stackexchange.com/questions/106737", "https://security.stackexchange.com", "https://security.stackexchange.com/users/93150/" ]
Based on the description at Virustotal you've linked to this is in reality not an image, but a real PE32 executable (normal windows executable). So only the file name extension was changed to hide the real purpose of the file. PE32 will not be automatically executed when they have the `.jpg` extension like in this case. Also the image viewer which will be invoked with the file by default will not execute the code but instead exit or complain that this is not a valid image. Thus this file would not work alone. But such files are typically used together with another file which will rename it to `name.exe` and execute it. This can be done by some batch file, with the help of the Windows Scripting Host ActiveX inside a website or mail or similar. This strategy is used to bypass antivirus and firewalls which might skip analyzing the "jpg" file because of the extension and will not find anything suspicious in the accompanying script (which only renames the file and executes it). > > ...if there is any way to decode/decompile the image data > > > Again, this is not an image but an executable so the tool of choice could be some disassembler, debugger, sandboxed execution etc. See also the [analysis from Virustotal](https://www.virustotal.com/en/file/6f9df9afb5f0fbd8e3ac9016121731879b2d3b53f81c0a4efb2d85fda6bbb69e/analysis/1448742319/).
> > "So i want to know whether or not its possible a virus contained > inside the image could still have been executed if the software did > not 'fully' open the image?" > > > Given the other answers say that it is a PE executable, it's very unlikely that you've done anything harmful by opening it in an image editor/viewer. Image viewers generally look at the first few bytes of a file to determine its file type and then bail with an error if it doesn't match known signatures. The introduction of most file formats is what is known as a "magic number" - almost every file format has one. Magic numbers allow readers to perform a sanity check on the file data before attempting to process garbage. If it were a legitimate image file, it is important to note that there have been buffer overflows over the years that exploited the way certain image parsers worked in various software libraries. A few exploits were discovered a few years ago for crafting a special image to exploit various library weaknesses in some of the most popular libraries out there that image editing and viewing software uses. Obviously, as holes are discovered, they are patched but it is up to each software vendor using the library to update their software and then every user of that software has to update the software. That process can take significant time to complete. But in your case, no, it's probably just a badly named EXE and your machine is probably just fine. Which also likely means that everyone they spammed with that message received an equally malformed filename and the recipients also can't open it. Malware delivery fail. Score one for stupid. > > My second question is if there is any way to decode/decompile the > image data in order to better view its contents? > > > There are tools to dissect PE files (high level section breakdown). Looks like .NET might be involved in this case. I've not had to do any disassembling in a while. There are both free and commercial reverse-eningeering tools out there for .NET binaries. Obviously, if you pay money for a tool like that, it will generally be significantly better than the free tools. That all said, if you think your machine has been compromised, disconnect it from all networks and probably turn it off until you can reinstall the OS. The last thing you want/need is Cryptowall and a bonus rootkit to get installed. Reinstalling an OS is the only option these days for a malware infestation. Most of the malware deployed via e-mail today are just small downloaders for going and getting more malware from the Internet. Once there is a small foothold, it is game over for the OS. Finally, don't open strange attachments from weird people.
6,807,507
I would like to write an app to follow the price of lists of stocks. There would be three activities containing lists of stocks : * myStocksActivity containing the stocks I'm interested in * searchedStocksActivity containing a list of stocks I could add in the list contained in myStocksActivity * winnersLoosersStocksActivity containing the list of stocks with the best or worst performance of the day. I would like to persist the list of stocks in myStocksActivity, to be able to remove or add stocks from that list and to add the stocks displayed in searchedStocksActivity or winnersLoosersStocksActivity to myStocksActivity. Another challenge : the price of the stocks should be updated every X minutes depending on the settings of app. The prices should only be updated when the app is running and should only update the prices of the list I'm currently looking at. For the moment, my architecture isn't great : almost all the logic is contained in myStocksActivity and I know it's not a good thing. I was thinking about moving the update of the stock list to a service, but I don't want this service to run when the application is not running. What do you think ? Is my problem clear ? Thank you !
2011/07/24
[ "https://Stackoverflow.com/questions/6807507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/860302/" ]
If I was you I would try and design(and build) a domain model first. This should end up being a set of classes which allows you to do everything you want with your stocks, independently of the a UI. You should also build in data persistence directly into these classes (i suggest using SQLite for this bit). Then once you have a working model, build the UI on top of that. The MVP design pattern works pretty well with android. Implement your activities as Views, these should both present data, and captures UI events and delegate these events to to Presenter instances, which then communicate/manipulate the model, and updates the Views accordingly. For example, MyStocksView could present the user with a list of stocks, and the latest movements of stock price (or whatever). The MyStocksView contains the actual widgets that make up the user interface, and also acts as event listener and handler for various UI events (like when the user click a button). It should also contain a instance of a MyStocksPresenter class. Once the user clicks the button, lets say, "remove stock", the event handler of MyStocksView then fires a method in the presenter instance for example, presenter.removeStock(id) , this method then updates the model (removes it from the in-memory data structures and database) and finally, if everything was successful, updates the View. It basically works as a middle man between the presentation layer, and the data-model. In regards to the automatic updates every X minutes, I would handle this with a AsyncTask, there's not really much point in using a service if you only want this to happen while you app is running.
1. Create a class for a stock, and store the update logic in there 2. I would put the handler - what holds instances of the stock-class and loops over a set to tell them to update - either in its own class purely with static methods and variables, or also in the stock class with static methods/etc. 3. The service then contains timing information, and calls the static update() method 4. The activity that displays stocks starts/stops the service with onCreate/onDestroy or onUpdate/onPause (I think it's update; the on that happens each time the Activity is brought to the forefront) 5. Same activity tells the handler class which ones to load, and uses its list for the display. One other thing: I'd suggest against using a service. Use an AsyncTask. Services actually do run on the UI thread, so if there's a long-running loop during the update, the UI will freeze. AsyncTask starts a thread and will not block the UI.
466,683
SSL certificates by default have line breaks after 67 characters. I'm trying to create SSL certificate files using Chef. Essentially I want to create the entire certificate file from a string variable without any line breaks. I've tried this a few times to no avail (Apache complains about not being able to find certificate). I don't see why line breaks in an SSL cert would be necessary. Any ideas if it's possible to have a cert without any line breaks in the file?
2013/01/13
[ "https://serverfault.com/questions/466683", "https://serverfault.com", "https://serverfault.com/users/75925/" ]
The line length, and so the line breaks, are due to 64-bit encoding used in the certificate files: see this Wikipedia article, for instance, <http://en.wikipedia.org/wiki/Base64> Put newline characters (\n) into your string variable, instead.
If `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines are not required for the CLI tool or API being used to pass the certificate, then just use: ``` awk 'NR>2 { sub(/\r/, ""); printf "%s\\n",last} { last=$0 }' crt.pem ```
1,239,143
i am writing a macro to convert the zeros in the access table to "0000" Zero is text data type so i cast it to int in the if condition to update the records which is only zeros and preventing it in updating records which are non zeros but now all the records are getting updated ..if clause is calling all the time even there is a value 2 in the particular row please help ``` Dim db As Database Dim rst As Recordset Dim strData As String Set db = CurrentDb() Dim qryString As String qryString = "SELECT * FROM tblECodes " Set rst = db.OpenRecordset(qryString) rst.MoveFirst Do While Not rst.EOF Dim testid As String Dim Sch1 As Integer Sch1 = CInt(rst.Fields("Scheduled")) Testid1 = rst.Fields("Testid") If Sch1 = "1" Then strSQLUp = "Update tblECodes set scheduled = '0000' where testid = 148" CurrentDb.Execute strSQLUp End If rst.MoveNext Loop rst.Close db.Close ```
2009/08/06
[ "https://Stackoverflow.com/questions/1239143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your question includes some very confused code. You define this recordset: ``` Set rst = db.OpenRecordset("SELECT * FROM tblECodes") ``` and then walk through it row by row testing whether the row matches certain criteria and then execute a SQL string that updates rows in the very same table. This makes absolutely no sense. This SQL string ought to do the job (assuming I've understood the problem with non-zero fields being updated when they shouldn't be): ``` UPDATE tblECodes SET Scheduled = "0000" WHERE Scheduled = "0" AND Sch1 = "1" AND TestID = 148; ``` So far as I can tell from your code, the SQL statement above is absolutely equivalent to your procedural code, with the added caveat that it will only update records where Scheduled=0. Execute this with CurrentDB.Execute and the dbFailOnError option and you should be successful, at least, insofar as you've clearly described your problem.
The docmd.RunQuery suggestion from Raj should work well. But if you'd like to stay in VBA: ``` Do While Not rst.EOF If rst!Scheduled = "0001" And rst!testid = "148" Then rst.Edit rst!scheduled = "0000" rst.Update End If rst.MoveNext Loop ```
23,302,257
I want to do something as simple as ``` alias set_then_do if ``` because ``` if x=true puts "x is #{x}" end ``` works. But everyone who looks at the code will instinctively want to change the single equals symbol to two ( '=' to '==' ). Just because of the if word. But I want the assignment to be there without confusing the code reader. So I want something like the following: ``` alias set_then_do if set_then_do x=true puts "x is #{x}" end ``` I'm using Ruby 1.9.3 --- To answer the question why; here is my sample case. ``` if http.use_ssl = @use_ssl # ASSIGNMENT! NOT TESTING EQUALITY! http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.verify_depth = 9 end ``` --- This fits my aesthetics: ``` http.use_ssl = @use_ssl; if @use_ssl http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.verify_depth = 9 end ``` I'm still open to an answer to aliasing the if method ^\_^
2014/04/25
[ "https://Stackoverflow.com/questions/23302257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500195/" ]
`if` is not a method; it's a keyword. Ruby doesn't provide any facilities for modifying its syntax, so you can't do this.
I'll start with a disclaimer that I don't recommend doing this. However, as Chuck points you can't do what you want, but you can get "close". Also, I agree `set_then_do` is a poor name and you might want a different one. Maybe `do_if` instead. Having said all that, you can in the global name space make the following function: ``` def do_if(val, &block) yield if val end ``` Then where you want to use it you can do: ``` do_if(http.use_ssl = @use_ssl) do http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.verify_depth = 9 end ``` Again, I wouldn't recommend any of that, but it does come close to what you are looking for.
8,302,293
The following code raises a syntax error: ``` >>> for i in range(10): ... print i ... try: ... pass ... finally: ... continue ... print i ... File "<stdin>", line 6 SyntaxError: 'continue' not supported inside 'finally' clause ``` **Why isn't a `continue` statement allowed inside a `finally` clause?** P.S. This other code on the other hand has no issues: ``` >>> for i in range(10): ... print i ... try: ... pass ... finally: ... break ... 0 ``` If it matters, I'm using Python 2.6.6.
2011/11/28
[ "https://Stackoverflow.com/questions/8302293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/608794/" ]
The use of *continue* in a finally-clause is forbidden because its interpretation would have been problematic. What would you do if the finally-clause were being executed because of an exception? ``` for i in range(10): print i try: raise RuntimeError finally: continue # if the loop continues, what would happen to the exception? print i ``` It is possible for us to make a decision about what this code should do, perhaps swallowing the exception; but good language design suggests otherwise. If the code confuses readers or if there is a clearer way to express the intended logic (perhaps with `try: ... except Exception: pass; continue`), then there is some advantage to leaving this as a *SyntaxError*. Interestingly, you can put a *return* inside a finally-clause and it will swallow all exceptions including *KeyboardInterrupt*, *SystemExit*, and *MemoryError*. That probably isn't a good idea either ;-)
I think the reason for this is actually pretty simple. The continue statement after the finally keyword is executed every time. That is the nature of the finally statement. Whether or not your code throws an exception is irrelevant. Finally will be executed. Therefore, your code... ``` for i in range(10): print i try: pass finally: continue print i # this (and anything else below the continue) won't ever be executed! ``` is equivalent to this code... ``` for i in range(10: print i try: pass finally: pass ``` which is cleaner and terser. Python does not allow continue in a finally block because all code after the continue will never be executed. (Sparse is better than dense.)
18,230,690
I have a list of Question objects and I use a `ForEach` to iterate through the list. For each object I do an `.Add` to add it into my entity framework and then the database. ``` List<Question> add = problem.Questions.ToList(); add.ForEach(_obj => _uow.Questions.Add(_obj)); ``` I need to modify each of the objects in the `ForEach` and set the `AssignedDate` field to `DateTime.Now`. Is there a way I can do this inside of the `ForEach` loop?
2013/08/14
[ "https://Stackoverflow.com/questions/18230690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` foreach(var itemToAdd in add) { Do_first_thing(itemToAdd); Do_Second_Thing(itemToAdd); } ``` or if you will insist on using the `ForEach` method on `List<>` ``` add.ForEach(itemToAdd => { Do_first_thing(itemToAdd); Do_Second_Thing(itemToAdd); }); ``` Personally I'd go with the first, it's clearer.
use a foreach statement ``` foreach (Question q in add) { _uow.Questions.Add(q); q.AssignedDate = DateTime.Now; } ``` or as astander propose do `_obj.AssignedDate = DateTime.Now;` in the `.ForEach(` method
1,091,888
Bluetooth not finding any devices in Ubuntu 18.04. I tried different solutions that were found on the internet but with no success. After Bluetooth is enabled, it keeps searching for devices until it is turned off. All the devices that I am trying to connect with are fully functional, they were paired with other OS and working fine.
2018/11/11
[ "https://askubuntu.com/questions/1091888", "https://askubuntu.com", "https://askubuntu.com/users/635064/" ]
Whilst [Hassan's suggestion](https://askubuntu.com/a/1116767/618353) did not fully solve my issue, it set me on the path that did solve it. I don't have rep to post a comment yet, but just wanted to say thank you SO much to Hassan as part of your solution lead me to find a solution for this issue. It was specifically installing Blueman that helped me solve my issue (whereby my BT headphones stopped connecting after months of working fine). Whilst Blueman did not solve my issue, it did provide the error: ``` Connection Failed: blueman.bluez.errors.DBusFailedError: Protocol not available... ``` On Googling that error, I then did the following and the headphones now connect. 1. I installed `blueman`: ``` sudo apt-get install blueman ``` 2. Then I ran these commands: ``` sudo apt-get install pulseaudio-module-bluetooth killall pulseaudio ``` Then, after restarting Ubuntu, I was able to connect via Blueman.
Answer posted by Yadnesh Salvi pointed me in the right direction to my issue on Ubuntu 18.04. In my case, i was missing `BCM43142A0-0a5c-21d7.hcd` and on restart after copying, i found that i am also missing `BCM43142A0-105b-e065.hcd`. Followed the same steps as suggested for the missing [BCM43142A0-105b-e065.hcd](https://github.com/winterheart/broadcom-bt-firmware/blob/master/brcm/BCM43142A0-105b-e065.hcd) as well and it worked like charm.
24,215,900
What happens: ![enter image description here](https://i.stack.imgur.com/8j0k2.png) What I want to happen: ![enter image description here](https://i.stack.imgur.com/cEsjC.png) HTML: ``` <input type="button" onclick="showSpoiler1(this);" value="Front flip variaion (ramp)" /> <input type="button" onclick="showSpoiler2(this);" value="Front flip variaion (flat)" /> <input type="button" onclick="showSpoiler3(this);" value="Backflip variations" /> <input type="button" onclick="showSpoiler4(this);" value="Sideflip Variations (ramp)" /> <input type="button" onclick="showSpoiler5(this);" value="Twists and other tricks"/> <div1 class="inner" style="display:none;"> <ul> <li><a>Front full</a></a> <li><a>Double Front</a> <li><a>Aerial twist</a> </ul> </div1> <div2 class="inner" style="display:none;"> <ul> <li><a>front 180</a> <li><a class="click" onclick="tr4(this); hide(this)">Webster</a> <li><a class="click" onclick="tr4(this); hide(this)">Loser</a> </ul> </div2> <div3 class="inner" style="display:none;"> <ul> <li><a>Off-axis backtuck</a> <li><a>Back Full</a> </ul> </div3> ``` CSS: ``` div1 { color:blue; } div2 { color:blue; position:relative; left:150px; } div3 { color:blue; position:relative; left: 300px; } ``` JS: ``` function showSpoiler1(obj) { var inner = obj.parentNode.getElementsByTagName("div1")[0]; if (inner.style.display == "none") inner.style.display = ""; else inner.style.display = "none"; } function showSpoiler2(obj) { var inner = obj.parentNode.getElementsByTagName("div2")[0]; if (inner.style.display == "none") inner.style.display = ""; else inner.style.display = "none"; } function showSpoiler3(obj) { var inner = obj.parentNode.getElementsByTagName("div3")[0]; if (inner.style.display == "none") inner.style.display = ""; else inner.style.display = "none"; } ``` I want all the lists to horizontally line up with each other. When i use absolute positioning the text in the next section of my file doesnt move down so my lists collide with it. How could I make them line up and keep them from intersecting with th heading under it?
2014/06/14
[ "https://Stackoverflow.com/questions/24215900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3733200/" ]
Try to add `table` for each div. This should work as you want. ``` <table> <tr> <td> <div1 class="inner" style="display:none;"> ... </div1> </td> <td> <div2 class="inner" style="display:none;"> ... </div2> </td> </tr> </table> ```
Try toggling to display: inline-block or float them to the left;
444,781
In .NET 3.5, I'd like to create a singleton interface: ``` interface ISingleton <T> { public static T Instance {get;} } ``` Of course that doesn't work but is what I'd like. Any suggestions? EDIT: I just want it to be known that all singeltons will have a static property named Instance of the class type. It is always there. An interface would be an explicit way to express this.
2009/01/14
[ "https://Stackoverflow.com/questions/444781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40106/" ]
An Interface can't, to my knowledge, be a Singleton since it doesn't actually exist. An Interface is a Contract that an implementation must follow. As such, the implementation can be a singleton, but the Interface can not.
Ok I made this answer a Wiki, because I am just going to offer an opinion that is at a tangent to your question. I personally think that Singletons are waaay overused, its a use case that IMO is actually reasonably rare, in most cases a static class would suit the use case much better, and in other cases just a factory created imutable object is the best choice, an actual singleton is much rarer than people think. I wouldn't have an interface to describe a common pattern for this, as I would actually want each and every use of a singleton to be thought about very carefully and justified.
20,265,475
I have entered this shell script and its showing errors when compiling ``` echo Enter basic Salary read bs if [ $bs -lt 1500 ] then hra= echo ´$bs \* 10 / 100´|bc fi gs= echo ´$bs + $hra´|bc echo $gs ``` The errors are: ``` (standard_in) 1: illegal character: \302 (standard_in) 1: illegal character: \264 (standard_in) 1: illegal character: \302 (standard_in) 1: illegal character: \264 (standard_in) 1: illegal character: \302 (standard_in) 1: illegal character: \264 (standard_in) 1: illegal character: \302 (standard_in) 1: illegal character: \264 (standard_in) 2: syntax error ```
2013/11/28
[ "https://Stackoverflow.com/questions/20265475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2740691/" ]
One problem is (or, rather, 4 problems are) the use of `´` in place of `'` or `"`. There is another character in there also causing trouble, unless the acute accent is encoded in UTF-8 or UTF-16† Another problem is the use of spaces around assignments; these do not fly in the shell. You must not have spaces on either side of the assignment. ``` echo Enter basic Salary read bs if [ "$bs" -lt 1500 ] then hra=$(echo "$bs * 10 / 100"|bc) fi gs=$(echo "$bs + $hra"|bc) echo $gs ``` You don't really need the variable `gs`; you could write: ``` echo "$bs + $hra" | bc ``` Note that if `bs` is not less than 1500, you get a ill-defined value for `hra` (whatever happens to be left over, or blank if it is unset). † It looks like you have UTF-8 encoded data. ``` $ echo "´" | odx 0x0000: C2 B4 0A ... 0x0003: $ echo "´" | utf8-unicode 0xC2 0xB4 = U+00B4 0x0A = U+000A $ bc | cat ibase=16 obase=8 C2 302 B4 264 quit $ ``` U+00B4 is ACUTE ACCENT in Unicode.
Too many Errors: 1. As stated by Jonathan, is using ´ in place of `. 2. Do not use space while assigning values to variables. 3. Create the data before assigning it to a variable. For e.g. hra=`echo $bs \* 10 / 100|bc` Also, if the input exceeds 1500, then it will give out the error. So you need to do something with it. For e.g. echo "Enter basic Salary" read bs if [ $bs -lt 1500 ] then hra=`echo $bs \* 10 / 100|bc` else hra=`echo $bs \* 5 / 100|bc` fi gs=`echo $bs + $hra|bc` echo $gs
17,033,247
I have a simple string, where I need to insert a few numbers and strings. Say String a = "My name is %s. I am %d years old". I also need to insert same number or string at several of these holes. I need a solution which works for ancient versions of java atleast upto 1.3 I know about String.format (JDK 5+). I read about formatter, my head hurts!! please help.
2013/06/10
[ "https://Stackoverflow.com/questions/17033247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616809/" ]
Your only option is to use [`MessageFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html) here. You'd type: ``` String s = "My name is {0}. I am {1} years old"; ``` and use the appropriate method to render this to a string. For instance: ``` String ret = MessageFormat.format(s, "John", 32); ``` I'd like to put a link to the javadoc, but... I don't know how much has changed since 1.3! (well, link added, it can't hurt) (it should be noted that even in 2013, Java's `ResourceBundle`s *still* use `MessageFormat` and read property files in ISO-8859-1, not UTF-8)
What about this one ``` String text = "The user {0} has email address {1}." String msg = MessageFormat.format(text, params); ``` And this other ``` String text = "The user {name} has email address {email}."; Object[] params = { "nameRobert", "rhume55@gmail.com" }; Map map = new HashMap(); map.put("name", "Robert"); map.put("email", "rhume55@gmail.com"); System.out.println("1st : " + MapFormat.format(text, map)); ```
29,334,843
The situation is following: ```dart abstract class A { void doSomething() => print('Do something..'); } class B implements A { @override void doSomething() => print('Do something already..'); } class C extends A { } ``` I have an abstract class A. Class B implements A. Therefore it overrides doSomething() method. Class C extends A. Everything works fine, until I'm adding factory constructor to class A: ```dart abstract class A { factory A() => new B(); void doSomething() => print('Do something..'); } ``` This leads to an error in my IDE (IntelliJ IDEA): > > The generative constructor expected, but factory found > > > My first idea was to create constructor for class C where I would call factory constructor for A. Is it possible to do? I got the same problem when I try to extend Exception class. It also has a factory constructor: ```dart abstract class Exception { factory Exception([var message]) => new _ExceptionImplementation(message); } ``` Thats why to create my custom exception I have to implement Exception class instead of extending it and it really confuses me. I also would like to clarify one terminology question. Can I say that from point of view of B class, A is an interface, so B is implementing interface A. However, from point of view of C class, A is an abstract class so C is extending abstract class A. Are these statements correct? Thank you. Dmitry.
2015/03/29
[ "https://Stackoverflow.com/questions/29334843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3650018/" ]
If a class has no constructor a generative constructor is implicitly added. If a class has an explicit constructor no generative constructor is added. You have two options. * make the factory constructor a named factory constructor and add a normal constructor ```dart abstract class A { void doSomething() => print('Do something..'); factory A.name() => new B(); A(); } ``` * or make the normal constructor named and call it explicitly from the extending class ```dart abstract class A { void doSomething() => print('Do something..'); factory A() => new B(); A.protected(); } class C extends A { C() : super.protected(); } ``` try at [DartPad](https://dartpad.dartlang.org/28a51cfb570f790146a2) Your statement is right. If you implement a class it acts as an interface and if you extend it it acts as a base class.
I dont know it works but it solves my problem. And I know there are a lot solution for this may be this solution worst. :) but I want to share with you Sometimes backend API returns same model but different by values. like this. ```dart Map<String,dynamic> map1 = { "version": "2.16.0", "language_1":"Dart", "framework_1":"Flutter", }; Map<String,dynamic> map2 = { "version" : "10.0.1", "language_2":"javaScript", "framework_2":"NodeJs", }; ``` I need `D` model so extends other models from `D` ```dart class D{ D({ this.language, this.frameWork, this.version, }); String? language; String? frameWork; String? version; } ``` Extends models from `D` ```dart class A extends D{ A(); factory A.fromJson(Map<String,dynamic> json) => C.fromJsonForA(json); } class B extends D{ B(); factory B.fromJson(Map<String,dynamic> json) => C.fromJsonForB(json); } ``` And write the `factory` constructor in other class `C` ```dart class C extends D implements B,A{ C({ String? language, String? frameWork, String? version, }):super( language:language, frameWork:frameWork, version:version, ); factory C.fromJsonForB(Map<String,dynamic> json){ final c = C.protected(json); c.frameWork = json['framework_2']; c.language = json['language_2']; return c; } factory C.fromJsonForA(Map<String,dynamic> json){ final c = C.protected(json); c.frameWork = json['framework_1']; c.language = json['language_1']; return c; } factory C.protected(Map<String,dynamic> json){ return C( version: json["version"], ); } } ``` And I used :) ```dart A modelA = A.fromJson(map1); B modelB = B.fromJson(map2); ``` ```dart class Example { Example._(); static printModel(D model){ print("${model.language} : ${model.frameWork} version : ${model.version}"); } } ```
28,160,533
My Python code needs to be able to randomly generate a number between 1 and 3 to determine what function to perform (addition, multiplication or subtraction). That works fine. I randomly generate two numbers and need to get this random function. So it would be like a basic maths sum like 3 + 6 = 9. The 3 would be stored as number1 (and randomly generated). The + would be stored as function and would also be randomly generated. The 6 would be stored as number2 and also randomly generated. The problem I am having is combining all the variables together and getting it to work out the maths. So I could do the following: **(the numbers entered would have been randomly generated)** ``` number1 = 3 number2 = 8 function = 3 (for the purposes of this: addition) function then is changed to "+" ``` I am left doing this: ``` answer = number1, function, number2 ``` Which obviously doesn't work.
2015/01/26
[ "https://Stackoverflow.com/questions/28160533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the binary operator functions defined in the `operator` module. The functions `operator.add()`, `operator.sub()` and `operator.mul()` can all be called with two arguments to perform the operation their name suggests. To select one of the three functions at random, you can simply put them in a list and then use `random.choice()`: ``` operators = [operator.add, operator.sub, operator.mul] random_operator = random.choice(operators) ``` The random operator can be applied to your numbers like this: ``` result = random_operator(number1, number2) ```
``` number1 = randint(1,20) number2 = randint(1,20) if function == 1: answer = number1 + number2 elif function == 2: answer = number1 - number2 elif function == 3: answer = number1 * number2 ``` You don't have to over think it.
30,832,215
Pattern matching in Kotlin is nice and the fact it does not execute the next pattern match is good in 90% of use cases. In Android, when database is updated, we use Java switch property to go on next case if we do not put a break to have code looking like that: ``` switch (oldVersion) { case 1: upgradeFromV1(); case 2: upgradeFromV2(); case 3: upgradeFromV3(); } ``` So if someone has an app with version 1 of the DB and missed the app version with DB v2, he will get all the needed upgrade code executed. Converted to Kotlin, we get a mess like: ``` when (oldVersion) { 1 -> { upgradeFromV1() upgradeFromV2() upgradeFromV3() } 2 -> { upgradeFromV2() upgradeFromV3() } 3 -> { upgradeFromV3() } } ``` Here we have only 3 versions, imagine when DB reaches version 19. Anyway to makes when acting in the same way then switch? I tried to continue without luck.
2015/06/14
[ "https://Stackoverflow.com/questions/30832215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/600351/" ]
It is absolutly possible quote from official reference : [Control Flow: if, when, for, while](https://kotlinlang.org/docs/reference/control-flow.html) ``` If many cases should be handled in the same way, the branch conditions may be combined with a comma: when (x) { 0, 1 -> print("x == 0 or x == 1") else -> print("otherwise") } ``` So if same condition list is short, then you can list them separating by coma, or use ranges like condition in 1..10 as stated in other answers
val oldVersion = 6 val newVersion = 10 ``` for (version in oldVersion until newVersion) { when (version) { 1 -> upgradeFromV1() 2 -> upgradeFromV2() 3 -> upgradeFromV3() 4 -> upgradeFromV4() 5 -> upgradeFromV5() 6 -> upgradeFromV6() 7 -> upgradeFromV7() 8 -> upgradeFromV8() 9 -> upgradeFromV9() } println("~~~") } ```
27,248,556
I read the documentation in the MongoDb and I used a simple proves and I only look that: Push is sorting the array but `addtoSet` isn't it. For me visually is the same, I don't know the difference. Could anybody explain me the difference? Another think if it could be in spanish or in a simple english, i'll aprecite it.
2014/12/02
[ "https://Stackoverflow.com/questions/27248556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4312217/" ]
**$push** - adds items in the order in which they were received. Also you can add same items several times. **$addToSet** - adds just unique items, but order of items is not guaranteed. If you need to add unique items in order, you can group and add elements via $addToSet, then $unwind the array with elements, $sort by items, and then do $group again with $push items.
As the name suggest $addToSet (set) wont allow duplicates while $push simply add the element to array
37,241,326
I am working on a project and im learning at the same time and so far everything has been working great! But I want to be able to use the animated css code from Animate.css which should work in concert with the javascript in the wow.js file. Essentially, I need help troubleshooting why the animate.css code (e.g., wow animated bounceIn or wow animated fadeInUp) isn't working. I would provide you with the files but Im not good with JSFiddle but here is the important parts. html ``` <header> <h2 class="wow animated bounceIn" data-wow-duration="700ms" data-wow-delay="100ms">Meet the Authors</h2> </header> ``` CSS ``` @-webkit-keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(.3); transform: scale(.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); transform: scale(1.05); } 70% { -webkit-transform: scale(.9); transform: scale(.9); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(.3); -ms-transform: scale(.3); transform: scale(.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); -ms-transform: scale(1.05); transform: scale(1.05); } 70% { -webkit-transform: scale(.9); -ms-transform: scale(.9); transform: scale(.9); } 100% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } .bounceIn { -webkit-animation-name: bounceIn; animation-name: bounceIn; } ``` I could provide the files if needed
2016/05/15
[ "https://Stackoverflow.com/questions/37241326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6300892/" ]
Exceptions *are* classes, so obviously they each need their own class. It can be a normal class, inner class or a nested class as usual.
1) A custom exception class can be defined either within the class it is intended for or in a separate class. Example of the former - `ThrowingClass.java`: ``` public class ThrowingClass { public static class ThrownInnerException extends Exception { public ThrownInnerException() {}; } public void throwingMethod() throws ThrownInnerException { throw new ThrownInnerException(); } } ``` Example of the latter - `ThrownException.java`: ``` public class ThrownException extends Exception { public ThrownException() {}; } ``` and `ThrowingClass.java`: ``` public class ThrowingClass { public void throwingMethod() throws ThrownException { throw new ThrownException(); } } ``` 2) Multiple custom exception classes can be defined within a single class file. Each custom exception class does not require its own class file. Example - `MultiThrowingClass.java`: ``` public class MultiThrowingClass { public static class ThrownExceptionTypeOne extends Exception { public ThrownExceptionTypeOne() {}; } public static class ThrownExceptionTypeTwo extends Exception { public ThrownExceptionTypeTwo() {}; } public void throwingMethodOne() throws ThrownExceptionTypeOne { throw new ThrownExceptionTypeOne(); } public void throwingMethodTwo() throws ThrownExceptionTypeTwo { throw new ThrownExceptionTypeTwo(); } } ```
19,257
With [Hadoop](http://en.wikipedia.org/wiki/Hadoop) and [CouchDB](http://en.wikipedia.org/wiki/CouchDB) all over in Blogs and related news what's a distributed-fault-tolerant storage (engine) that actually works. * CouchDB doesn't actually have any distribution features built-in, to my knowledge the glue to automagically distribute entries or even whole databases is simply missing. * Hadoop seems to be very widely used - at least it gets good press, but still has a single point of failure: The NameNode. Plus, it's only mountable via FUSE, I understand the HDFS isn't actually the main goal of Hadoop * [GlusterFS](http://en.wikipedia.org/wiki/GlusterFS) does have a shared nothing concept but lately I read several posts that lead me to the opinion it's not quite as stable * [Lustre](http://en.wikipedia.org/wiki/Lustre_(file_system)#ZFS_integration) also has a single point of failure as it uses a dedicated metadata server * [Ceph](https://en.wikipedia.org/wiki/Ceph_%28software%29) seems to be the player of choice but the homepage states it is still in it's alpha stages. So the question is which distributed filesystem has the following feature set (no particular order): * POSIX-compatible * easy addition/removal of nodes * shared-nothing concept * runs on cheap hardware (AMD Geode or VIA Eden class processors) * authentication/authorization built-in * a network file system (I'd like to be able to mount it simultaneously on different hosts) Nice to have: * locally accessible files: I can take a node down mount the partition with a standard local file system (ext3/xfs/whatever...) and still access the files I'm **not** looking for hosted applications, rather something that will allow me to take say 10GB of each of our hardware boxes and have that storage available in our network, easily mountable on a multitude of hosts.
2009/06/03
[ "https://serverfault.com/questions/19257", "https://serverfault.com", "https://serverfault.com/users/7936/" ]
Take a look at chirp <http://www.cse.nd.edu/~ccl/software/chirp/> and parrot <http://www.cse.nd.edu/~ccl/software/parrot/>
> > Lustre also has a single point of failure as it uses a dedicated metadata server > > > Lustre is designed to support failover and a MDS/MDT/OSS can have a number of addresses which it can be contacted at, heartbeat can be used to migrate the service around. Be aware that some recent versions have had issues where the unmount appears to work but there is data still in flight to the disc, However the double mount protection should have helped ( apart from the interesting issues that has had )....
3,017,454
High, I need to do some image manipulations on CT volume images. Mainly segmentations. Which open-source library supports 3D algorithms - Filtering, edge detection, deformable objects and so ? Language is not an issue at the moment. 10x
2010/06/10
[ "https://Stackoverflow.com/questions/3017454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363827/" ]
You can try itk: <http://www.itk.org/>
My company processes CT and MR medical images, to perform segmentation, and related shape measurement for industrial clients. We use (and contribute to) [VXL](http://vxl.sourceforge.net "VXL") as our underlying 2D and 3D image, math and geometry library. [ITK](http://www.itk.org/) is also very good.
2,277,633
I've got a program that runs very happily with `-Xmx2g`. With `-Xmx1g`, it grinds to a halt. It never gets an out of memory exception -- or, at least, I've never had the patience to wait long enough. This suggests that the total footprint does fit into 1g, but that the GC has some anxiety about possibly running out of space. The memory footprint is a combination of some large, stable, items with a good deal of ephemeral traffic. Are any of the more-or-less obscure GC options relevant to this situation?
2010/02/17
[ "https://Stackoverflow.com/questions/2277633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131433/" ]
It sounds like you have not given the JVM enough heap. Sure, the working set may fit in 1Gbytes, but you still need to give it more. To understand why, read on. Let us assume that when a garbage collector runs, it does an amount of work `W1` that is proportional to the amount of non-garbage that it scans in order to identify the garbage and another amount of work `W2` that is proportional to the amount of garbage that it finds. (In fact, it is a bit more complicated than this ... but lets keep the analysis simple.) Suppose that you have a heap 1Gb heap with 0.9Gb occupied by reachable objects. Each time the GC runs, it can reclaim at most 0.1Gb of the heap space, and in doing so it needs to do `W1 * 0.9Gb + W2 * 0.1Gb` of work. The amount of work per byte reclaimed is `(W1 * 0.9Gb + W2 * 0.1Gb) / 0.1Gb`; i.e. `9 * W1 + W2`. Now suppose that you have a 2Gb heap with 0.9Gb occupied by reachable objects. Now the amount of work per byte reclaimed is `(W1 * 0.9Gb + W2 * 1.1Gb) / 1.1Gb` or `W1 * 9/11 + W2`. If you compare these two, you will see that the GC does roughly `W1 * 8` more work per byte reclaimed in the 1Gb heap compared to the 2Gb heap. As a general rule the closer to full you run the heap, the more inefficient the garbage collector is going to be. The lessons are: * configure the JVM to use a generous heap, and * configure the JVM to throw an OOM if there is less than (say) 25% of the heap free after running a full GC.
If you wan't to do some fine tuning you should check the `MinHeapFreeRatio` and `MaxHeapFreeRatio` parameters among others desribed here [Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html) this sould lead to the "tranquillizer effect".
16,214,190
I'm converting an image to **base64** string and sending it from android device to the server. Now, I need to change that string back to an image and save it in the database. Any help?
2013/04/25
[ "https://Stackoverflow.com/questions/16214190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999885/" ]
Convert base64\_string into opencv (RGB): ``` from PIL import Image import cv2 # Take in base64 string and return cv image def stringToRGB(base64_string): imgdata = base64.b64decode(str(base64_string)) img = Image.open(io.BytesIO(imgdata)) opencv_img= cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB) return opencv_img ```
You can try using open-cv to save the file since it helps with image type conversions internally. The sample code: ``` import cv2 import numpy as np def save(encoded_data, filename): nparr = np.fromstring(encoded_data.decode('base64'), np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR) return cv2.imwrite(filename, img) ``` Then somewhere in your code you can use it like this: ``` save(base_64_string, 'testfile.png'); save(base_64_string, 'testfile.jpg'); save(base_64_string, 'testfile.bmp'); ```
31,914,071
I want to create a button group, where button from a group can be selected at once. Let's suppose we have got three buttons, the user should be able to select only one button, so if user selects "Apple" then they shouldn't be able to select the Apple button again. The main purpose will be to stop user selecting the button which is already selected. ``` <div class="btn-group btn-group-lg"> <button type="button" class="btn btn-primary">Apple</button> <button type="button" class="btn btn-primary">Samsung</button> <button type="button" class="btn btn-primary">Sony</button> </div> ``` How can I solve this?
2015/08/10
[ "https://Stackoverflow.com/questions/31914071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4841850/" ]
For Bootstrap 4: ``` <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Active </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Radio </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio </label> </div> ``` [See the docs](https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons)
`Button` are used for buttons ``` <div class="btn-group btn-group-lg"> <input type="radio" class="btn btn-primary" value="Apple" name="radio"> Apple <input type="radio" class="btn btn-primary" value= "Samsung" name="radio"> Samsung <input type="radio" class="btn btn-primary" value "Sony" name="radio"> Sony </div> ``` Radios are `<input type="radio">`. If you want only one radio checked they have to get the same `name`.
16,739,935
You might have noticed in the new Play Music application (from version 5.0.0 onwards) the three dots close to every song, popping up a context menu: ![Play Music app with context menu open in one song](https://i.stack.imgur.com/TZ3fU.png) I prefer the looks of these points when compared to the old triangle, similar to a spinner. I know this shouldn't be that difficult to implement from scratch, my question is: Is there any new standard way of implementing this pattern (much alike the new Navigation Drawer pattern on the top-left side)? Thanks in advance.
2013/05/24
[ "https://Stackoverflow.com/questions/16739935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1062290/" ]
For a showing a popup list from a menu resource, use [PopupMenu](http://developer.android.com/reference/android/widget/PopupMenu.html), (or [PopupMenuCompat](http://developer.android.com/reference/android/support/v4/widget/PopupMenuCompat.html) for API below 11). For a more complex list where you specify the adapter yourself, use [ListPopupWindow](https://developer.android.com/reference/android/widget/ListPopupWindow.html) (or [ListPopupWindowCompat](http://developer.android.com/reference/android/support/v4/widget/ListPopupWindowCompat.html) API below 11).
That is the [ListPopupMenu](https://developer.android.com/reference/android/widget/ListPopupWindow.html) basically all you have to do is create an imageview with that drawable and call the `ListPopupMenu` on the image click
11,451,528
I have a ticket system. Messages are placed in a div and that div has hidden sub messages (the replies of that ticket) [Demo](http://www.gc-cdn.com/snippets/java.php) [jsFiddle Hosted Demo](http://jsfiddle.net/cs87W/) Click an Arrow - shows the thread child. Click it again it hides the thread child and the arrow goes up and down. I want it so that if the current thread is open, the user clicks the other arrow, the open arrow should restore back and vice versa. **jQuery** ``` $(document).ready(function(){ $('h1').click(function(){ if ($(this).next('.parent').hasClass('showMe')){ $('.parent').removeClass('showMe').hide(); $(this).find("#ticket_arrow").removeClass('up'); $(this).find("#ticket_arrow").addClass('down'); } else { $('.parent').removeClass('showMe').hide(); $(this).find("#ticket_arrow").removeClass('down'); $(this).find("#ticket_arrow").addClass('up'); $(this).next('.parent').addClass('showMe').show(); } }); }); /** Hides all sub threads on Load **/ $('.parent').hide(); ``` **HTML** ``` <style type="text/css"> .ticket_thread_h1 span{cursor:pointer} .down{background:url(http://www.gc-cdn.com/personalstylist/down.png) no-repeat;width:15px;height:10px;display:block} .up{background:url(http://www.gc-cdn.com/personalstylist/up.png) no-repeat;width:15px;height:10px;display:block} </style> <h1 id="ticket_thread_1" class="ticket_thread_h1">Thread # 1 <span id="ticket_arrow" class="down">&nbsp;</span></h1> <div class="parent"> <div class="sub_thread"><p>Thread Messages #1 1</p></div> <div class="sub_thread"><p>Thread Messages #1 2</p></div> </div> <h1 id="ticket_thread_2" class="ticket_thread_h1">Thread # 2 <span id="ticket_arrow" class="down">&nbsp;</span></h1> <div class="parent"> <div class="sub_thread"><p>Thread Messages #2 1</p></div> <div class="sub_thread"><p>Thread Messages #2 2</p></div> </div> ```
2012/07/12
[ "https://Stackoverflow.com/questions/11451528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596952/" ]
Add the following code : ``` $("h1").find('.up').each(function(){$(this).removeClass('up').addClass('down');}); ``` after `$(this).find("#ticket_arrow").removeClass('down');` in `else` part, so code must be : ``` $('h1').click(function(){ if ($(this).next('.parent').hasClass('showMe')){ $('.parent').removeClass('showMe').hide(); $(this).find("#ticket_arrow").removeClass('up'); $(this).find("#ticket_arrow").addClass('down'); } else { $('.parent').removeClass('showMe').hide(); $(this).find("#ticket_arrow").removeClass('down'); $("h1").find('.up').each(function(){$(this).removeClass('up').addClass('down');}); $(this).find("#ticket_arrow").addClass('up'); $(this).next('.parent').addClass('showMe').show(); } }); ``` that's work for me. **Edit**: BTW, why you have a multiple elements with same ID ?
``` $('h1').click(function(){ var $t = $(this); $t.siblings('h1').children('span').removeClass('up') .end().next().hide(); $t.children('span').toggleClass('up') .end().next().toggle(); }); ``` I would just style the arrow default as down (most items will have it this way) and toggle "up". [jsfiddle](http://jsfiddle.net/cs87W/11/)
753,436
I'll post my work, but I'm not sure how to calculate variance. The question asks for the expected sum of 3 dice rolls and the variance. I think I got the expected sum. Any help would be awesome :) thanks! ![enter image description here](https://i.stack.imgur.com/jCtYd.jpg)
2014/04/14
[ "https://math.stackexchange.com/questions/753436", "https://math.stackexchange.com", "https://math.stackexchange.com/users/75304/" ]
The variance calculation is incorrect. Let random variables $X\_1,X\_2,X\_3$ denote the results on the first roll, the second, and the third. The $X\_i$ are independent. The variance of a sum of independent random variables is the sum of the variances. Since the variance of each roll is the same, and there are three die rolls, our desired variance is $3\operatorname{Var}(X\_1)$. To calculate the variance of $X\_1$, we calculate $E(X\_1^2)-(E(X\_1))^2$. And $$E(X\_1^2)=\frac{1}{6}\left(1^2+2^2+\cdots+6^2\right).$$
If your dice are "independant" then the variance of the sum is the sum of the variance
239,331
I would like a plausible way to tank the world economy. I am trying to make a political horror world, that would be very different from today. The basis should be a lack of money or decreased value of money. Can the world's money run out and cause economic collapse?
2022/12/13
[ "https://worldbuilding.stackexchange.com/questions/239331", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/100112/" ]
Fill the [floor with hematite](https://www.latimes.com/archives/la-xpm-2000-sep-16-mn-21968-story.html) ======================================================================================================= This is a yellow powder, an oxide of iron. It's extremely common and long lasting. The Egyptians coated their floors with it. It rips apart the lungs and softer tissues. When the darts hit they'll likely move quickly or fall over, stirring up the dust and making their lives much more painful. It doesn't decay since it's stable, so it can last 4000 years easily, just as the Egyptian version did.
As others have said, no organic compound would stay stable trough centuries. So you should go for inorganic ones. **Mercury!** It's not hard to work with. In fact, we have [examples](https://en.wikipedia.org/wiki/Mercury_(element)#Historic_uses) of mercury usage that are millenia old. And it cannot spoil, so it's toxicity won't degrade. And it is extremely toxic, especially if you use some compound forms of it. If you put it into glass containers (for example, in dart tips) you won't even have an issue with mercury evaporation. Or, if you are feeling particulary nasty, go for vapor route. In a sealed tomb that contain a large enough pool of mercury whole atmosphere would be toxic because of mercury vapors. And since tomb was sealed it won't run out.
17,811,991
I want to add custom data attribute to option tag. For example: ``` <select> <option data-image="url 1">Val 1</option> <option data-image="url 2">Val 2</option> <option data-image=" ... "> ... </option> <option data-image="url N">Val N</option> <select> ``` How can I do that?
2013/07/23
[ "https://Stackoverflow.com/questions/17811991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1059419/" ]
That is impossible with the `select` directive (see the [documentation](https://docs.angularjs.org/api/ng/directive/select)). But you can easily make what you want with `ngRepeat` ([see the documentation](https://docs.angularjs.org/api/ng/directive/ngRepeat)): ``` <select ng-model="choice"> <option ng-repeat="item in itemsList" data-image="{{item.url}}">{{item.label}}</option> </select> ``` `[JSFiddle](http://jsfiddle.net/Blackhole/a61pv1jr/)`
have done a little modification to @Blackhole's answer. Try this code pen: [CODEPEN](https://codepen.io/NomeshD/pen/jJoYJd) ``` function loadCountryFlagCtrl($scope) { $scope.countries = [ { country_id: "SL", name:"Sri Lanka", flag:"http://icons.iconarchive.com/icons/gosquared/flag/24/Sri-Lanka-flat-icon.png" },{ country_id: "IND", name:"India", flag:"http://icons.iconarchive.com/icons/gosquared/flag/24/Andorra-flat-icon.png" } ]; } ``` And the **HTML**: ``` <div ng-controller="loadCountryFlagCtrl"> <div class="content"> <div class="header"> <form action=""> <div class="select_list" ng-class='{active:active}' ng-click="active=!active"> <span ng-style="{'background-image':'url('+countries.country_selected.flag+')'}">{{countries.country_selected.name}}</span> <ul class="options"> <li class="select_list_option" ng-repeat="country in countries" ng-click="countries.country_selected=country" ng-style="{'background-image':'url('+country.flag+')'}">{{country.name}}</li> </ul> </div> <br/> <div>selected country:{{countries.country_selected.name}}</div> </form> </div> </div> ``` and the **CSS**: ``` .select_list{ background-color: #fff; border: 1px solid #b3b3b3; cursor: pointer; height: 21px; line-height: 21px; padding: 3px 5px; position: relative; vertical-align: middle; width: 250px; } .select_list:after{ content:"▼"; position:absolute; right:3px; color:#b3b3b3; } .select_list > .options{ display:none; position:absolute; top:100%; left:-1px; width:100%; border:1px solid #666; padding:0; margin:0; } .select_list.active > .options{ display:block; } .select_list > span, .select_list > .options li { background-position: 5px center; background-repeat: no-repeat; padding-left: 30px; list-style:none; } .select_list > .options li:hover { background-color:#eee; } ``` Hope this will be helpful for other programmers :)
81,865
I am looking here for the best simple and intuitive application that is designed to produce neat looking graphs, for example "number of Ubuntu users in the last 10 years" or "average amounts paid by windows, mac and linux users for each Humble Indie Bundle edition". I just want it to be easy to produce (not too many functions), and nice looking (no ugly business charts)! Thanks for your help!
2011/11/22
[ "https://askubuntu.com/questions/81865", "https://askubuntu.com", "https://askubuntu.com/users/29270/" ]
I recommend [RLPlot](http://apt.ubuntu.com/p/rlplot) [![Install rlplot](https://hostmar.co/software-small)](http://apt.ubuntu.com/p/rlplot) From the RLPlot website. > > RLPlot is is a plotting program to create high quality graphs from data. Based on values stored in a spreadsheet several menus help you to create graphs of your choice. The Graphs are displayed as you get them (wysiwyg). Double click any element of the graph (or a single click with the right mouse button) to modify its properties. RLPlot is a cross platform development for Linux and Windows. Mac OsX users can find some useful information how to install RLPlot at <http://naranja.umh.es/~atg/>. > > > ![enter image description here](https://i.stack.imgur.com/JVOYZ.png) ![example image](https://i.stack.imgur.com/iEHA5.jpg)
I personally like `R` (equivalently `octave`) which essentially gives you all you need and awesome plots quality. Also consider `gnuplot`, much easier and faster to use.
39,432,077
I'm trying to pivot multiple columns of the following table: [![enter image description here](https://i.stack.imgur.com/RoPKp.jpg)](https://i.stack.imgur.com/RoPKp.jpg) The result I would like to get is the following: [![enter image description here](https://i.stack.imgur.com/UGcNr.jpg)](https://i.stack.imgur.com/UGcNr.jpg) I'm using PowerQuery in Excel, but I couldn't manage to pivot multiple columns (i.e., I can pivot the column "Number", for example). Anyone has any insight about the correct usage of PowerQuery?
2016/09/11
[ "https://Stackoverflow.com/questions/39432077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068548/" ]
For example, if the country header is in cell `A1` then this formula in `D2`: ``` = "tax rate" & CountIf( $A$2:$A2, $A2 ) ``` then copy the formula cell `D2` and paste it in the cells below it should give you something like: ``` country tax rate Income thresholds count UK 20% 35k tax rate1 UK 30% 50k tax rate2 ..... ``` Now you can pivot by that extra count column with PivotTable or PowerQuery. You can use the same formula for the Income th1, Income th2, etc columns.
Here's a solution using the PQ ribbon, but note the last step (Group By) is not dynamic e.g. you would have to change it if you wanted 4+4 columns per country. ``` let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"country", type text}, {"tax rate", type number}, {"Income thresholds", type text}}), #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1), #"Grouped Rows" = Table.Group(#"Added Index", {"country"}, {{"Min Index", each List.Min([Index]), type number}, {"All Rows", each _, type table}}), #"Expanded All Rows" = Table.ExpandTableColumn(#"Grouped Rows", "All Rows", {"Income thresholds", "Index", "tax rate"}, {"Income thresholds", "Index", "tax rate"}), #"Added Custom" = Table.AddColumn(#"Expanded All Rows", "Column Index", each [Index] - [Min Index] + 1), #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Min Index", "Index"}), #"Duplicated Column" = Table.DuplicateColumn(#"Removed Columns", "Column Index", "Column Index - Copy"), #"Added Prefix" = Table.TransformColumns(#"Duplicated Column", {{"Column Index", each "tax rate" & Text.From(_, "en-AU"), type text}}), #"Pivoted Column" = Table.Pivot(#"Added Prefix", List.Distinct(#"Added Prefix"[#"Column Index"]), "Column Index", "tax rate", List.Max), #"Added Prefix1" = Table.TransformColumns(#"Pivoted Column", {{"Column Index - Copy", each "Income thresholds" & Text.From(_, "en-AU"), type text}}), #"Pivoted Column1" = Table.Pivot(#"Added Prefix1", List.Distinct(#"Added Prefix1"[#"Column Index - Copy"]), "Column Index - Copy", "Income thresholds", List.Max), #"Grouped Rows1" = Table.Group(#"Pivoted Column1", {"country"}, {{"tax rate1", each List.Max([tax rate1]), type number}, {"tax rate2", each List.Max([tax rate2]), type number}, {"tax rate3", each List.Max([tax rate3]), type number}, {"Income th1", each List.Max([Income thresholds1]), type text}, {"Income th2", each List.Max([Income thresholds2]), type text}, {"Income th3", each List.Max([Income thresholds3]), type text}}) in #"Grouped Rows1" ```
2,485,601
c# .Net 3.5 visual studio 2008, windows xp I have a main form in a project, given a specific set of circumstances another form is instantiated and displayed to the user: ``` Form frmT = new frmTargetFolder(expName, this); frmT.Show(); ``` As you can see, I am passing a reference to the new form from the current one. My question is, what do I have to do to a method so that it is exposed to the new form, the same for a variable? I have tried defining the functions as public, but I can't seem to access them, also I have written a Get and Set method for a variable, again how do I expose these functions and methods to other forms? ``` public void hit() { MessageBox.Show("hit it"); } bool setOverRide { get { return OverRide; } set { OverRide = value; } } ``` The main form is called frmDataXfer and the form, form which I am trying to call the functions and methods of frmDataXfer is called frmTargetFolder, an instance of which is created in the frmDataXfer and referenced as frmT. Thanks, R.
2010/03/21
[ "https://Stackoverflow.com/questions/2485601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109614/" ]
it's already discussed something similiar to ur question here.. Anyway to access a variable of a form class, simply make the variable public and you can access it using an object of that class Simple Example: ``` class Test : Form { ___public int variable = 10; // visible! ___public Test() {} } ``` [This](http://itpian.com/Coding/6520-how-to-access-one-variable-present-in-one-form-in-another-form-in-C-sharp-NET-br-.aspx) may help further.
Just remember that forms are first-and-foremost classes like any other, they just inherit from System.Windows.Forms.Form to give it special UI functions. So, that being said, any `public` (or `internal` in the same project) field, property or method is accessible provided you have an instance of the object. You don't need to store a form as a field to be able to reference it. You could just pass it as a parameter to a method call.
21,144,927
I have the following script: ``` function Start() { var TheData = 'tes"sst3\'k'; var TheHTML = '<div class="SomeClass">' + TheData + '</div>'; TheHTML += '<input type="text" id="TheTextBox" value="'; TheHTML += TheData + '" />'; $('#Dynamic').html(TheHTML); } ``` Basically, I'm creating HTML on the fly and embedding some variable text into it. The problem is that the text contains quotes and the value of the textbox doesn't match the value of the label because of the quotes. How can I solve this?? ![enter image description here](https://i.stack.imgur.com/CTWFt.png) The jsFiddle is [**here**](http://jsfiddle.net/6Sj7K/). Thanks
2014/01/15
[ "https://Stackoverflow.com/questions/21144927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/565968/" ]
It's much safer (for this exact reason) to let jQuery worry about all that and generate your `HTML` like this: ``` var $input = $("<input>").attr("id","TheTextBox").val(TheData); var $div = $("<div>").addClass("SomeClass").text(TheData).append($input); var $wrapper = $("<div>").append($div); var TheHTML = $wrapper.html(); ```
Here is your answer ``` $(Start); function Start() { var TheData = 'tes"sst3\'k'; var TheHTML = '<div class="SomeClass">' + TheData + '</div>'; TheHTML += '<input type="text" id="TheTextBox" value='; TheHTML += TheData + ' />'; $('#Dynamic').html(TheHTML); } ```
7,957,952
Is there an event in javascript that I could bind some sort of listener to that will tell me when all javascript/jQuery/Ajax is done executing on the page? The page will not be loading/unloading/reloading, etc between the time the execution begins and the time that I need the listener to "listen", so those events don't work. The page literally is not doing anything. The button is clicked and some javascript functions fire which contain Ajax calls to web services. After all have finished, I want to change window.location. But window.location is changing before the web services have finished in my case. Currently using setTimeout to achieve this, but as sometimes the code needs more time to run than normal, sometimes the window.location is firing before all the other javascript has finished. Simply put ``` <input type = "button"... onclick="doThis();"; function doThis() { try{ //Contains AJAX calls to web services which is mainly what screws up my timing since it may still be trying to execute stuff when the redirect statement happens } catch (e) { } //Currently doing setTimeout(redirect, 10000); //Would like to simply detect when all of the above is done and then redirect. } ``` Edit: Left out a crucial piece of info. The AJAX calls are in a for loop. The use of variables and success callbacks hasn't been working so well for me as by the time my success callback is executing, my variables have taken on new values in the for loop.
2011/10/31
[ "https://Stackoverflow.com/questions/7957952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877442/" ]
What you are trying to achieve is a classical concurrent programming problem. It is solved by the use of a [barrier](http://en.wikipedia.org/wiki/Barrier_%28computer_science%29). To put it simply, you need to: 1. Count how many calls you've done. 2. Set a callback on all AJAX completion events. 3. Make that callback decrement the number of calls. 4. The callback checks whether the number of calls has reached zero or not. If yes, then your final code (here, `redirect`) is called. The actual implementation is left as an exercise to the reader  :) Hint: embed AJAX calls into a function that handles all counter incrementation and callback setting.
What I do: * Create a variable that represents the number of outstanding AJAX calls. * Before making an AJAX call, increment the variable. * At the end of the code that completes an AJAX call, call a function (e.g. ajaxComplete). * ajaxComplete should decrement the count. When it reaches zero, you know all your calls are complete.
33,401,216
i'm quite new to this. I've spent some hours to go through the various questions on this topic but couldn't find an answer that fits to me question. I have an viewcontroller (not a tableviewcontroller) with a tableview as subview. My question is how to reload the table data inside the :viewwillappear method of the view controller. Inside the method i can't "access" the tableview instance. (Also i understand i can't use reloaddata() because im not using a tableviewcontroller). Do you know any simple solution? (i very much assume that a protocol could help here?) this is the code in short: ``` class ViewController3: UIViewController, UITableViewDataSource, UITableViewDelegate { var Person_data = [Person]() override func viewDidLoad() { super.viewDidLoad() let tb: UITableView = UITableView(frame: CGRect(x: 10, y: 50, width: 200, height:600), style: UITableViewStyle.Plain) tb.dataSource = self tb.delegate = self super.view.addSubview(tb) fetch_data() } func tableView(tableview: UITableView, numberOfRowsInSection section: Int) -> Int { let rows = Person_data.count return rows } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell() cell.textLabel?.text = Person_data[indexPath.row].name return cell } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetch_data() // reload at this point } func fetch_data() { let tb_fetchRequest = NSFetchRequest(entityName: "Person") do { let tb_fetchResults = try my_moc.executeFetchRequest(tb_fetchRequest) as? [Person] Person_data = tb_fetchResults! } catch let error as NSError { print("request error: \(error)") } } } ```
2015/10/28
[ "https://Stackoverflow.com/questions/33401216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5500118/" ]
Your problem is that `tb` is a local variable, so it is not visible outside of `viewDidLoad()`. If you make `tb` a property (a.k.a. instance variable) of your view controller, then you can use it from any of the controller’s methods: ``` class ViewController3: UIViewController, UITableViewDataSource, UITableViewDelegate { var Person_data = [Person]() private var tb: UITableView? // Now the scope of tb is all of ViewController3... override func viewDidLoad() { super.viewDidLoad() // ...so it is visible here... tb = UITableView(frame: CGRect(x: 10, y: 50, width: 200, height:600), style: UITableViewStyle.Plain) ... } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetch_data() tb?.reloadData() // ...and it is also visible here. } ``` Note that in your code, the fact that `tb` is a local variable doesn’t mean that your `UITableView` object disappears when `viewDidLoad()` finishes. It means that your *reference* to the `UITableView` disappears. The table view object itself lives on because it is added to your view hierarchy, but you don’t have a reference to it anymore because your variable went out of scope. For further reading on the distinction between variables and the objects they reference, search for “scope” and “pass by reference.”
You can access your `tableView` `IBOutlet` in `viewWillAppear:`, you can also call `reloadData`. I'm not sure why you think you can't, but it should work fine.
16,620,065
I am writing server and client and i have some integers to pass. In my server application i am recieving an integer from the client. In the client do i call ntohl or htonl on the integer? If i call either one of these, when i recieve the integer do i have to call ntohl or htonl again? Or do i only call ntohl/htonl on the server side, but not the client side? In other words, when/where and how many times do i use htonl or ntohl for each integer? Also, do i have to do ntohl/htonl for strings/chars arrays? Does chars have to be converted?
2013/05/18
[ "https://Stackoverflow.com/questions/16620065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2189390/" ]
> > In the client do i call ntohl or htonl on the integer? > > > It has nothing to do with whether you are the client or the server. It has to do with whether you are sending or receiving. If you are sending, you want network byte order, so you call `htonl`(). If you are receiving, you want host order, so you call `ntohl().` > > If i call either one of these, when i recieve the integer do i have to call ntohl or htonl again? > > > Yes. The sender should have put the data into network byte order; the receiver has to put it into host order, for his local host. > > In other words, when/where and how many times do i use htonl or ntohl for each integer? > > > `htonl()` when sending; `ntohl()` when receiving.
The typical setup in this scenario would be to call `htonl` in the client (because you want to put the integer into *network* i.e. *protocol* order) and `ntohl` in the server (because you want to convert back from network to *host* order). There is no equivalent of `ntohl` etc for strings (although you do have to make arrangements for the client and server to agree on the character encoding used, i.e. by having both sides use UTF-8).
53,978
When I started a new ME3 game, it asked me to choose if Ashley, Kaiden, or Numerous died. Who are the numerous? I chose *numerous* because I hoped that meant some no-names, but if *numerous* is the entire ME2 cast that would be quite fail. Who are numerous? **In order to clear up some confusion, when you start a new game, the following individuals are dead, *regardless* of your selection at this point in creation:** * Jack * Thane * Wrex * Samara (Not listed on the wall because it's assumed she was never recruited, but died at Morinth's hands) * All *Mass Effect 2* Normandy Crew Members *except* for Doctor Chakwas (this means Ken, Gabby, Chambers) * One of Ashley or Kaiden. If you select 'Numerous', this will automatically be whichever one of the two is the same sex as Shepard. Otherwise, you will have chosen this. * The original Council **All answers should provide concrete evidence of any claims made. Please do not speculate. Please keep in mind that the *default profile* includes several notable casualties. This question is about which casualties make the 'Numerous' selection *distinct*.**
2012/03/07
[ "https://gaming.stackexchange.com/questions/53978", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/2577/" ]
The following is the memorial plaque wall when you start with a new character and select the "numerous" option. As you'll note, most of the squad members from Mass Effect 2 are still alive: ![the numerous that died](https://i.stack.imgur.com/Uho0b.jpg) Those names underlined in blue are the original crew members of the Normandy SR-1 who died in the beginning of Mass Effect 2, along with the two squad members Ashley Williams and Urdnot Wrex (marked by blue squares). Kaidan was chosen to be alive because I was playing a female Shepard; when playing a male Shepard, Ashley will be the Vermire survivour. Those names underlined in orange are all crew and squad members from the Normandy SR-2. Those marked with an orange circle, Gabriella Daniels, Kenneth Donnelly, and Kelly Chambers, would have all made notable appearances in Mass Effect 3 had they not died. More specifically, the former two can be brought back aboard the Normandy in their usual positions as engineers, and Kelly Chambers is a potential romance/fish keeper\* depending on your interactions with her in the previous game. Thane Krios and Jacqueline Nought (Jack) appear to be the only squad member from Mass Effect 2 that's listed as having died, and are highlighted on the wall by the orange square. Everyone else not on this list is presumed to be alive, and not one of the "numerous who died." In particular, Garrus, Tali, Miranda, and Jacob are all listed as alive. However, the game will act as though you never met Samara/Mordinth, Grunt, Katsumi, and Zaeed, effectively killing them. It will also act as though the original Council died during the attack on the Citadel in Mass Effect 1. \*that is, she returns your fish from Mass Effect 2 to you; you need the aquarium VI or extreme patience [to keep them alive](https://gaming.stackexchange.com/questions/53861/how-do-i-keep-my-fish-from-dying) The problem of course is that this is the same list of people who would have died if you had simply chosen the Ashley/Kaidan option. In comparing the two save files, one from a "numerous" selection, and one from a "Kaidan" selection (using male Shepard to keep a consistent Vermire casualty), there's actually very few differences between the two scenarios. The tables below illustrate the difference in game variables before you perform any action: ``` PlotID | Numerous | Kaidan dies --------+----------+------------ 17807 | true | false 18005 | false | true 18122 | false | true 21569 | false | true PlotInt | Numerous | Kaidan dies --------+----------+------------ 10393 | (unset) | 3 ``` At the moment it's unfortunately unclear what these changes represent, because they don't directly map to any of the significant and/or labeled plot events that the game has. Presumably they have some noticeable impact, however, so I'm going to keep digging until I get to the bottom of this.
Per the [Rarity Guide](http://www.rarityguide.com/articles/articles/1653/1/Mass-Effect-3-Character-Creation-Guide/Page1.html): > > **Numerous** > > > The deaths of numerous squadmates and friends have begun to play a significant role in Commander Shepard's psychological profile. The burden of inevitable combat loss after so many high-risk missions weighs heavily on Shepard. > > > Note: Numerous means that Either Kaidan or Ashely, as well as many other crew members, died. There will be a memorial later in the game aboard the Normandy mentioning those deaths, if you choose this option. > > > Edit: Removed memorial wall image and name list.
232,675
I am trying to figure out how to add user information and specific meta data to a separate table through PHP. I would prefer to do this when a user posted to the `wp_users` and `wp_usermeta` table. I am using the WooCommerce Auction plugin and the Salient theme. Also if I made a PHP file that ran a query to pull the data and then insert, where is a good place I can call that function to ensure the table is up to date? This is the function I've created. ``` add_action('user_register', 'save_to_donors',10,1); function save_to_donors( $user_id ) { $single = true; $user_email = get_userdata($user_id); $fn= get_user_meta($user_id, 'first_ name', $single ); $ln= get_user_meta($user_id, 'last_name', $single ); $em= $user_email->user_email; $ph= get_user_meta($user_id, 'billing_phone', $single ); $ad= get_user_meta($user_id, 'billing_address_1', $single ); $ci= get_user_meta($user_id, 'billing_city', $single ); $st= get_user_meta($user_id, 'billing_state', $single ); $zi= get_user_meta($user_id, 'billing_postcode',$single ); $do= get_user_meta($user_id, '_money_spent', $single ); $sql = "INSERT INTO donors (user_id,first_name,last_name,email," . "phone,address,city,state,zip,amount_donated)". "VALUES('$user_id','$fn','$ln','$em','$ph','$ad','$ci','$st','$zi','$do')"; $result = mysqli_query($wpdb, $sql) or die('Write Error!'); } ```
2016/07/20
[ "https://wordpress.stackexchange.com/questions/232675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98590/" ]
Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table. use this: ``` add_action('woocommerce_order_status_completed', 'save_to_donors',10,1); ``` instead of this: ``` add_action('user_register', 'save_to_donors',10,1); ``` also change `$user_id` to `$order_id` as the parameter being passed into your function. You will need to make some changes to your function since now `$order_id` will be passed into your function instead of `$user_id`. You can use some of the following code to get the `$order` object and `$user_id` I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different. ``` $order = new WC_Order( $order_id ); $user_id = $order->user_id; $billing_address = $order->get_billing_address(); $billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page $shipping_address = $order->get_shipping_address(); $shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page ``` Info on the use of this hook [woocommerce\_order\_status\_completed](http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/) Info on how to [get user id from order id](https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce)
**NOTE:** This answer looks irrelevant to the OP's question after further analysis of the added/updated function in the question. Im leaving this answer in place and creating a new answer for historical use, since part of the question seems applicable. You could use something like the following to create user meta when users are added to the user table. Put this in the functions.php file of your theme. ``` function myplugin_registration_save( $user_id ) { if ( isset( $_POST['first_name'] ) ) update_user_meta( $user_id, 'your_key', // name of key $your_value // value of your key ); } add_action( 'user_register', 'myplugin_registration_save', 10, 1 ); ``` To retrieve this data for later use use the function: ``` get_user_meta($user_id, 'your_key', $single); ``` More info on [user\_register hook](https://codex.wordpress.org/Plugin_API/Action_Reference/user_register) More info on [update\_user\_meta()](https://codex.wordpress.org/Function_Reference/update_user_meta) More info on [get\_user\_meta()](https://codex.wordpress.org/Function_Reference/get_user_meta)
84,337
EDIT: I have just noticed that the linked page on the Dutch identification requirement has changed. I do not know when or why it changed. It now reads > > Identificeren bij dubbele nationaliteit > > > Heeft u naast de Nederlandse nationaliteit een andere nationaliteit? Dan kunt u zich in Nederland identificeren met uw Nederlandse identiteitsbewijs. Dat is geen wettelijke verplichting, maar werkt in de praktijk voor de meeste situaties het makkelijkst. > > > Translation, with emphasis added to show changes from the earlier version: > > Identifying yourself if you have dual nationality > > > If you have another nationality in addition to that of the Netherlands, you *may* identify yourself in the Netherlands using your Netherlands identification document. *This is not a legal requirement, but is simplest in most situations.* > > > --- Original question: In the Netherlands, there is a legal requirement to be able to show identification. Dutch citizens who are dual nationals must use their Dutch identification to comply with the law. > > Identificeren bij dubbele nationaliteit > > > Heeft u naast de Nederlandse nationaliteit een andere nationaliteit? Dan moet u zich in Nederland identificeren met uw Nederlandse identiteitsbewijs. > > > Translation: > > Identifying yourself if you have dual nationality > > > If you have another nationality in addition to that of the Netherlands, you must identify yourself in the Netherlands using your Netherlands identification document. > > > Source: <https://www.rijksoverheid.nl/onderwerpen/identificatieplicht/vraag-en-antwoord/met-welke-identiteitsbewijzen-kan-ik-mij-identificeren> It's not clear to me whether the law is meant to include in its scope the inspection of passports on crossing external borders, but it is certainly possible to read it as such. Government examples of situations in which authorities can demand ID do not include border controls; see, for example, <https://www.rijksoverheid.nl/onderwerpen/identificatieplicht/vraag-en-antwoord/wie-mag-vragen-naar-mijn-identiteitsbewijs-en-wanneer>. But the file [Informatieblad Identificatieplicht](https://www.rijksoverheid.nl/onderwerpen/identificatieplicht/documenten/brochures/2011/10/17/identificatieplicht) says that the "Marechaussee can ask for your ID in the course of their duties." The Marechaussee is the [border control authority](https://www.defensie.nl/english/organisation/marechaussee/contents/tasks-of-the-royal-netherlands-marechaussee) for the Netherlands. So the question, as indicated in the title, is whether a Dutch national who also has another nationality can use the foreign passport to enter the Netherlands. If it makes a difference, consider that the traveler lives outside the Schengen area and the EU, and is visiting for a short time rather than immigrating.
2016/12/14
[ "https://travel.stackexchange.com/questions/84337", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/19400/" ]
I suppose I may be one of a few people who can actually answer this question from experience - me, some family members, and some friends have all experienced this. This is all assuming your foreign passport is one that you can travel to the Netherlands with. If you are a Dutch citizen but have never been issued any Dutch identity documents, the border officers won't see anything out of the ordinary and will admit you to the Netherlands. If you are a Dutch citizen but have been issued Dutch identity documents - even if these are no longer valid - the border officers will probably be able to see that you are a Dutch citizen. In this case, things get a bit messy. They will probably ask you a few questions about your citizenship and why you do not have any Dutch identification documents. Then they will let you through. Officially, the law seems to be ambiguous on this point. I've heard Dutch government officials give both points. In practice, you will almost certainly be admitted to the country without any fines or legal issues, as the officials will see you are following the spirit of the law if perhaps not the letter. If you need to be 100% certain, if you hate the legal gray area, or if you absolutely need to avoid any delays, the easiest option is to travel to an adjacent country and then enter over land, where there is no border inspection. For example, Brussels is just 30 miles from the Dutch border and two hours away from Amsterdam, and if you are in the east of the country then Weeze airport is literally within walking distance of the Dutch border. As an added benefit: Weeze and Brussels are both usually cheaper to fly into than Amsterdam. I, as well as a handful of friends in the Netherlands, have been stopped by police and government officials who demanded IDs several times. In all of these situations I provided only my American driver's license and was completely fine - even when I mentioned that I was a Dutch citizen. In other situations my friends have used passports from other countries and they have been completely fine. The letter of the law obviously disagrees with these police officers and officials, but in reality Dutch police/officials are very reasonable and only interested in the spirit of the law. **The chance of getting a grumpy officer that doesn't like your situation - and tries to not admit you to the country or send you to jail - are absolutely microscopic.**
EDIT: [...als je door de douane gaat, zit je op internationaal grondgebied. (...) Dit heeft echter weinig te maken met rechtspraak. In het Verdrag van Tokyo is vastgelegd wie en wanneer jurisdictie heeft. *In het geval van Schiphol heeft de Nederlandse wetshandhaving de jurisdictie*, welke kan lopen tot in het vliegtuig zelf.](http://www.wereldwijzer.nl/showthread.php?t=87632&s=7d0c274b9c05a99459ae82cbbff5eb0a&p=551939&viewfull=1#post551939) Meaning: the law, if any, also applies to passport control at the border. END EDIT So you are saying the law states that if you have dual citizenship you are required to show the Dutch ID. I have not been able to pin down the law that states this requirement. The link you posted to an information leaflet of the Dutch government states clearly that you should show your Dutch ID if you have one, but that doesn't mean it's the law. The law that deals with the requirement to be able to identify oneself does not say anything about dual citizens. <http://wetten.overheid.nl/BWBR0006297/2014-01-20> On the other hand, on <https://www.rijksoverheid.nl/onderwerpen/nederlandse-nationaliteit/inhoud/dubbele-nationaliteit> it is stated that the Dutch government does not keep track of dual citizenship of its citizens anymore (since 2014). This would explain why the information leaflet tells you to use your Dutch ID: it saves time, for the people that have to make sure you are not breaking any laws for being in NL. If you show the police your US passport and there is no mention of an entry date to Schengen in their system, they have to check that you are not staying in NL illegally and that could just be prevented if they knew that you are a Dutch citizen. So my answer to your question: you do not get a fine for showing your foreign passport at the border, because you do not break any law by doing that. However, you will be asked your estimated length of stay. If you do not intend to stay any longer than is allowed for any other US citizen, there is no problem. Possibly they recognize you in their database as a Dutch citizen and then if you cannot explain why you didn't show your Dutch ID, you will have to explain. That's all. The same goes for ID controls in the country, for example if you commit a traffic offence. There is no law that states that you get fined for showing a foreign ID as dual citizen, but police does have the mandate to control your right to be there. If you cannot prove that you are staying legally they have to hand you over to the "alien police" (yes, that's what they call it in NL). If you happened to enter for say 30 days, but then stay on for a year because you changed your mind you might get in trouble with the police if you do not show your Dutch ID (because you are not carrying it on you). It has probably happened before and that's why they don't like it: it's a huge waste of time and resources. I'm judging this all based on my experience of living in the Netherlands for 10 years in my youth: There are many rules that you have to follow, but if you do not behave you will only get punished or fined for breaking the law, not for breaking a rule. Of course you don't make many friends if you break too many rules...
19,776,835
iI have a project that part of the goal is to have the shortest code possible. Ive done everything i can think of to make it as compact as i can but I'm wondering if there are any more shortcuts for the following code ``` public static void read(String[] input) throws IOException { for (String s : input) { BufferedReader b = new BufferedReader(new FileReader(s)); while (b.ready()) { String[] val = b.readLine().split(" "); for (String c : val) System.out.println(c); } b.close(); } } ```
2013/11/04
[ "https://Stackoverflow.com/questions/19776835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2318068/" ]
It depends what you mean by "compact". You can for example change ``` String[] val = b.readLine().split(" "); for (String c : val) System.out.println(c); ``` into ``` for (String c : b.readLine().split(" ")) System.out.println(c); ``` Or use little different approach using `Scanner` class which would make your code shorter and more readable. ``` public static void read(String[] input) throws IOException { for (String s : input) { Scanner scanner = new Scanner(new File(s)); while (scanner.hasNext()) System.out.println(scanner.next()); scanner.close(); } } ``` --- You can also try this way (concept based on Christian Fries answer) ``` public static void read(String[] input) throws IOException { for (String s : input) System.out.println(new Scanner(new File(s)).useDelimiter("\\Z").next().replace(' ', '\n')); } ``` As you can see this will not let you `close` Scanner, but since `File` resource is not `Closable` you don't have to invoke its `close` method so this approach seems safe.
Instead of using `split(" ")`, then a for loop to print each element of the result array on a line you may use ``` System.out.println(b.readLine.replace(' ','\n')); ``` that is ``` public static void read(String[] input) throws IOException { for (String s : input) { BufferedReader b = new BufferedReader(new FileReader(s)); while (b.ready()) System.out.println(b.readLine.replace(' ','\n')); b.close(); } } ```
32,654,890
I'm still new to the prepared statement, so forgive me for my stupid mistakes. At the moment I try to select something from outside the database. Either though there is no output. ``` $stmt = $mysqli->prepare("SELECT title FROM media"); $stmt->bind_param("s", $title); $stmt->execute(); $stmt->bind_result($a); $stmt->fetch(); printf("Title: ", $title, $a); $stmt->close(); ```
2015/09/18
[ "https://Stackoverflow.com/questions/32654890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3428833/" ]
First, strings are immutable, while lists are mutable. This means you can change an existing list object: ``` >>> l = [1,2,3] >>> id(l) 140370614775608 >>> l.append(4) >>> l [1,2,3,4] >>> id(l) 140370614775608 ``` You cannot change a string object, however; you can only create a new string object using the first as a starting point. ``` >>> s1 = "hello" >>> id(s1) 140370614929376 >>> s1.upper() 'HELLO' >>> id(s1) 140370614929376 ``` In Python, the convention is that a method either modifies an object and returns `None`, or returns a new, modified object while leaving the original alone.
.upper() returns a new string, which you assign to test1. The string you operated on ("hello") is not modified. Indeed, it couldn't be since strings are immutable in Python. .reverse() modifies in-place. That means the object ["hello", "world"] got modified. Unfortunately, you don't have a variable pointing to that object, so you can't see that. This is a convention in Python. Functions that modify in-place return None, whereas functions that create a modified copy return that copy.
8,002
Most RPGs teach you that casual violence is the best solution to all your in-game problems. This is so well established a part of the vast majority of RPGs that there are entire satire RPGs like Greg Costikyan's [Violence](http://www.costik.com/Violence%20RPG1.pdf) and John Tynes' [Power Kill](http://johntynes.com/revland2000/rl_powerkill.html) dedicated to showcasing the issue. Even now that the '80's anti-RPG hysteria is past, you see more sober critiques of endemic violence in RPGs in places like [this Slate article](http://www.slate.com/articles/news_and_politics/hey_wait_a_minute/2008/03/orc_holocaust.html). In most RPGs, PCs become inured to murder and other antisocial activities very quickly, and enter the depths of depravity that wouldn't be appropriate in the worst parts of the world. Armed robbery, mass murder, and genocide become routine parts of an adventurer's day, something only stick-in-the-mud characters with the most extremely stated ethics object to. [Total war](http://en.wikipedia.org/wiki/Total_war), even though it is not properly applied to just any conflict, is a PC's friend and they generally escalate any conflict in that direction. The sophistication of the gamer mindset towards introspection on this issue can be demonstrated in that the most meaningful question usually debated about in-game violence is some variant on "but should we kill the noncombatant children" or "can we just murder people out of hand as long as they're from a typically evil race?" In the real world, we generally a priori regard anyone having to have this discussion as a monster already. (P.S. The "wipe out a given evil race" thing isn't the point of this question; it is only mentioned to indicate that it's only "that far" that usually causes ethical handwringing from players, when that is a really quite extreme case and we should be uncomfortable with casual violence a lot sooner. ) What I'd like to have is a more realistic in-game treatment of conflict. People getting wounded and giving up, taking and ransoming of prisoners, not always escalating a fistfight to weapons, not always escalating weapon combat to killing, etc. Heck, as I write this, I'm watching an episode of Adventure Time with my daughter and the protagonists snuck in and rescued a princess kidnapped by the Ice King and then exit right next to his sleeping form. I thought, "If this were D&D they'd all be carefully coordinating a *coup de grace* to kill him in his sleep on the grounds that he inconvenienced them." The problem isn't limited to D&D of course, sci-fi PCs are happy to neutron bomb planets for convenience too, for example. I'm not part of the "D&D is Satanic" crowd obviously, but I frankly do have compunctions about continually playing in games where the taught behavior is uncomfortably equivalent to the worst examples of human behavior we see on the nightly news. How can I give my PCs a newfound respect for human life?
2011/05/21
[ "https://rpg.stackexchange.com/questions/8002", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/140/" ]
Don't Make Killing What the Game is About ----------------------------------------- D&D laid this trap for us ages ago when XP became about what you could kill, not what you could accomplish. RPGs in large part followed suit, and became *The Great Big Game of What Can I Kill?* Asking players in a game like that to not kill everything they can is folly. It's like asking Monopoly players to not buy stuff, charge rent, or pass Go. You're changing the game significantly. Fortunately, RPGs aren't Monopoly, and you **can** change the rules to a certain extent without making it a totally different game.. Whether you're trying to change the timbre of a current game or trying to make the next one you run different, there are steps you can take. **Before the Game Begins** * You can choose a system that is built around a different advancement mechanic * You can let your players know that killing will have consequences - a frank discussion about in-game-behavior expectations can do wonders + Get buy-in from your players regarding this change - it's a real shift for some groups + Let them know your goals for the change - Is it more drama? Tougher choices? Or just a shift to a "stealth" gaming style? **In the Middle of an Existing Game** As GM, you have some control over what a continuing game is about, even though [System Does Matter](http://www.indie-rpgs.com/articles/11/). So if you're locked into a system that's about killing everything you see, there are still things you can do. But you're going to have to let people know that the game is changing, one way or another. Do it out-of-game with a discussion as above. Or do it in-game by having the PCs transported out of their world to another place (or another plane!) and make it clear from the get-go that their baseline assumptions of reality are now wrong. You're in charge of the economies in the game. Yes, *economies*. Plural. Everything that has an ebb and flow, everything that is gathered and used is an economy: * XP * Money * Magic in its many forms (scrolls, potions, wands, spellbooks and "memory slots") * Health and healing * Ammunition - including arrows, bolts, and bullets * Sanity / Morality The list goes on, I'm sure. The point is - you can make the decision about killing into something that has an impact on one or more in-game economies. The simplest example is an XP-penalty for killing opponents (or an XP-bonus for a fatality-free mission). But you can hammer clerics for killing by taking their spells / blessings from them to show the displeasure of their god - assuming the god isn't a god of death or chaos or something and then, wouldn't the rest of the party be *hunting* that cleric? If a wizard kills a sentient creature with a spell, give him the XP but then hit him with "feedback" from the death of that creature. Roll (or choose) another spell he has memorized and make him forget it due to strain. Or make lethal spells cost more magic points to cast, or whatever causes pain in the economy of magic. Make magical items rare and make murder bad for them: * A blessed sword that loses its powers if it kills a helpless or innocent creature * A magical sword that feeds on that "death feedback" and becomes ever more malevolent and powerful on its own, seeking to make the wielder its puppet Or make magical weapons entirely non-existent. Not every character has powerful supernatural forces as the source of his power, though, and murder has been a tool of successful people in the real world forever. So what to do about the mundane killers in your party? **Treat them like murderers**: Everyone who knows what they've done should recoil from them. Authorities, if they exist, should come after them. The families of their victims should declare vendetta or even war. Offer rewards for their capture and death. **Make them feel like murderers**: Haunt them with the memories of their deeds. Nightmares are supported in all systems. If your game has them, saddle them with mental problems from guilt, like paranoia, delusions, hallucinations, compulsions, and phobias. No guilt? No conscience? That's psychopathy, ladies and gents - is that who you want to play? Really? Lady Macbeth was a thoroughly-motivated cold-blooded killer and she *still* ended up with a bunch of mental disadvantages. Soldiers and police can be haunted for the rest of their lives by the memory of killing someone *who was actively trying to kill them*.
Murderous cretins? Love the term. You, as the GM, are totally in control of this. Creating the setting and the cultures is purely under your control. I will tell you from experience, if you create and use cultures with certain values, most players will work with it; and those that work agaainst them will do so from that position of their own volition. This is a roleplaying game; and you can make that part of the role they need to play. Create tribal groups that people trade with, for example. Orcs in most of my settings, and other humanoid races, are tribal but do not eat their young or attack on sight. If your PCs are looked at with disdain for improperly lowering the boom, it teaches them. If they get thrown in jail for using ancient coinage or items that obviously came from someone's tomb, they'll be more circumspect. If the priest-types are told that they need to shrive a.k.a hear the confessions of, the spirits of the dead opponents, it may not stop, but it may give them pause to see these things in a new light. Similarly, create the same kind of human drama as 'World in Motion' events for your players. Have the local gossip in the taverns be about a hanging judge, or have the local broadsheet carry gossip from a humanitarian mission to a goblin tribe that is suffering from the plague. Hell, do a good enough job, and if the EXP or social rewards are there, the PCs might try to go help save the goblins. When players are younger, this is hard, but as they get older and deal with real life issues, injecting your setting with competing philosophies and religious tenets just adds depth to the world. It fosters a more realistic feel, which will have a synergistic effect of making more realistic, and less 2-dimensional PCs.
5,111,098
I'm a Java newbie, and also new to OOP. I have been a procedural programmer for years, but now trying to learn OOP. I am trying to write a basic program for practice as I go through an online Java course. It's a program to track people's score for games. Here's what I'd like to happen: 1. Ask user for the number of players. 2. Ask for the names of the players. 3. Display the main program window for tracking score. I am using Swing. My code currently displays a JTextField for #1 above. My thoughts were that I'd put an ActionListenter on the JTextField which would get/store the number of players when the user hits enter. This works. But the next steps are where I'm having problems with the OOP. Here is the code for my ActionListener: ``` private class InputHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String enteredText = e.getActionCommand(); numPlayers = Integer.parseInt(enteredText.trim()); } } ``` Since I need the program to wait until I have numPlayers, I decided to instantiate the class to get the player names inside of that ActionListener. However, since this class is an ActionListener, there are restrictions on what I can/can't do in there. The class I want to instantiate is called GetPlayerNames, and it's just a public class that extends JFrame. I have tried putting this into actionPerformed (within InputHandler): ``` GetPlayerNames temp = new GetPlayerNames(numPlayers); ``` (I used "temp" here because I don't need to do anything with this variable...it's just the only way I could get it to work), but of course this gives a compiler warning because "temp" is never used. And of course, it's messy and bad form. Help?
2011/02/24
[ "https://Stackoverflow.com/questions/5111098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449077/" ]
The issue ended up being that my code was completely relying on the auto-start functionality that is available only in IIS 7.5. I was able to discover the issue with the help of the Failed Request Tracing feature in IIS, and I have now modified my global.asax.cs file so that the application will be properly initialized, regardless of how/when it is loaded.
If you are running your web application on IIS 7.5 or above, please ensure that the role services for IIS are enabled properly. The role services of interest are : ASP.NET, Basic Authentication, HTTP Redirection, ISAPI filters, etc. You could go to the role services via Add or Remove programs - Turn Windows features on or off. Hope this helps. Regards, Kiran Banda
382,833
Just like $\pi$ is the ratio of a circle's circumference to its diameter? I know that the tangent line to the function $e^x$ has a slope of $e^x$ at that point, but is there some other geometric representation? Thanks!
2013/05/06
[ "https://math.stackexchange.com/questions/382833", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64460/" ]
In this article <http://arxiv.org/abs/0704.1282>, Jonathan Sondow describes a geometric construction of the number $e$ that's different in flavor from the other answers. The idea is that his construction is a geometric representation of the identity $$\sum\_{i=1}^\infty\frac{1}{n!}.$$ It's very readable for anyone who's familiar with convergence of sequences, so anyone who's taken and understood second-semester calculus.
I don't think it's just a matter of the tangent line at the general point having slope $e^x$. Rather, as the graph crosses the $y$-axis, the slope is exactly one. In fact, this gives us a way to approximate $e$ in the first place. Examine the graphs of functions of the form $f(x)=a^x$. As $a$ increases, these get steeper. When $a=2$, the slope of the graph as it crosses the $y$-axis is around $0.69$. When $a=3$, the slope of the graph as it crosses the $y$-axis is about $1.09$. There is a very special number between $2$ and $3$ where the slope is exactly $1$. This number is probably a bit closer to $3$ than to $2$. ![enter image description here](https://i.stack.imgur.com/TGSno.png)
44,838,591
I have a (large) dataframe of the form: ``` Variable Country 2007-Q1 2007-Q2 2007-Q3 2007-Q4 2008-Q1 2008-Q2 2008-Q3 2008-Q4 Var1 AR:Argentina 69.8 67.3 65 63.6 60.4 56.6 54.4 57.3 Var2 AR:Argentina 191.298 196.785 196.918 207.487 209.596 219.171 216.852 213.124 Var3 AR:Argentina 594.67 606.157 620.783 652.59 662.784 663.191 676.188 735.065 Var4 AR:Argentina 49.6 47.5 45.2 44.4 41.7 38.7 36.8 39.3 Var5 AR:Argentina 135.971 138.885 137.005 144.903 144.757 149.803 146.492 146.102 Var6 AR:Argentina 422.679 427.808 431.909 455.75 457.752 453.288 456.791 503.906 Var8 AR:Argentina 9.657 10.755 11.856 13.267 14.47 16.523 16.727 16.235 ``` Essentially, every row has 4 columns of data for each year, sorted by quarter. I want to turn this into annual data. One way to do this is to simply sum up every 4 columns (so 2008-Q1:2008-Q4 would be summed, for example). Another way, I suppose, would be to filter columns that share a common year in (2007-\*\* or something) and then run `RowSums()` on them but this sounds like it would be much more inefficient. I'm hoping to get back a data frame that looks like: `Variable Country 2007 2008` `Var1 AR:Argentina SUMXX SUMXX` Or even better: `Country Year Var1 Var2` `AR:Argentina 2007 SUMXX SUMYY` `AR:Argentina 2008 SUMXX SUMYY`. The second format would be much preferred but the first format is fine as well. The main thing is that I need to be able to select the data for a variable, for a country, for all years -relatively easily. If I can select for all countries all years for any given variable - even better (second format). Is there any easy way to accomplish this, aside from running a nested loop etc?
2017/06/30
[ "https://Stackoverflow.com/questions/44838591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/625609/" ]
[![enter image description here](https://i.stack.imgur.com/SVwEB.png)](https://i.stack.imgur.com/SVwEB.png) ``` <TextView android:textSize="18sp" android:autoLink="web" android:clickable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:text="http://www.example.com" tools:ignore="HardcodedText" /> ``` It's No required declear layout id and no code from java side. it's works from xml Use Autolink 1. * For website `android:autoLink="web"` 2. * For call `android:autoLink="phone"` 3. * For email `android:autoLink="email"` 4. * For map `android:autoLink="web"` 5. * For all `android:autoLink="all"`
Just add this attribute to your TextView `android:autoLink="web"` e.g ``` <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:gravity="center" android:autoLink="web" android:clickable="true" android:text="https://www.google.co.in"/> ```
4,867,861
Hey, I was wondering how I could make the user being able to change the background of the app? I have 3 Images that the user will be able to choose from. I've seen it in many apps. How would I do this? If possible please provide some code! :) Thank you in advance!
2011/02/01
[ "https://Stackoverflow.com/questions/4867861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547960/" ]
short answer: you don't do it this way. you let grails use the id to link the objects in the database. then if you need to access the fleas name you can override its `toString()` method to return the fleas name. or you access that property like any other in controllers/services or gsps.
If Flea is consistently used in this way, in other words it is not a one off. Such that the Person table also has flea\_name as the foreign key why not ``` static mapping = { id generator: 'assigned', name: 'name' } ``` Depending on the version of Hibernate/Grails you are on, you might loose access to the actual id column. Or if this is a one off case you could change Puppy ``` class Puppy{ String fleaName static transients = ['flea'] Flea getFlea() { Flea.findByName(fleaName) } } ```
28,182,848
I am looking for a correct implementation method to display/hide my adsense ads on mobile and desktops. Right now I am using this current method which gives us 2 console errors. The current method is: We use 2 classes "mobileShow" and "mobileno" to tag the ads accordingly to where we want to show them. So if we want the responsive adsense code to be shown on mobiles we use mobileshow if we want to hide the big rectangular ads from mobiles we use mobileno. The code we are using is the following: ``` .mobileShow {display: none;} .mobileShow {display: inline;} @media only screen and (min-device-width : 320px) and (max-device-width : 480px) .mobileno{display:none;} @media (max-width: 767px) ``` As far as we know google adsense policy allows display:none if it is for a usage like implementing responsive layouts. Our problem is the we receive the following error 2 times in the chrome development console: 2 x **Uncaught Error: Cannot find a responsive size for a container of width=0px and data-ad-format=auto adsbygoogle.js:41** We have tested several times we know that is something wrong with the above code. We are looking a way to implement the current "solution" with no errors. We would be very grateful if someone helps us out.
2015/01/28
[ "https://Stackoverflow.com/questions/28182848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4500924/" ]
You have several problems. 1. I don't think your code really is what you posted. Regardless of what other problems you have, the posted code defines the variable `$http`. 2. You are setting `$scope.user` not to a user (as the commented-out code would), not to a *promise to fetch a user* (which would be sensible), but to a function that will return a promise to fetch a user. Re-examine your code to find out where you misplaced some curly-brackets.
So after some hours reading about AJAX calls and asynchronous programming, I figured it out. I leave it here for anybody who might get stuck as well. Thanks again to @PSL for getting me on the right track. After a while and trying to solve my Problem I ended up with this: ``` groupifyApp.controller('DashboardCtrl', function ($rootScope, $scope, $routeParams, $route, $http) { $scope.page = {title:"Preferences", dashboardActive: "active", manageActive: "", inboxActive:"", preferencesActive:""}; $scope.user = {}; //$scope.user = {"name":"Test User","cal":{"entries":[{"id":0,"day":0,"start":1.25,"duration":1.0},{"id":1,"day":0,"start":4.0,"duration":1.75},{"id":2,"day":0,"start":4.75,"duration":0.5},{"id":3,"day":0,"start":5.75,"duration":0.75},{"id":4,"day":0,"start":6.5,"duration":0.25},{"id":5,"day":0,"start":7.5,"duration":0.25},{"id":6,"day":0,"start":9.5,"duration":1.75},{"id":7,"day":0,"start":10.75,"duration":0.5},{"id":8,"day":0,"start":11.75,"duration":0.75},{"id":9,"day":1,"start":0.75,"duration":0.5},{"id":10,"day":1,"start":1.25,"duration":0.25},{"id":11,"day":1,"start":2.0,"duration":0.5},{"id":12,"day":1,"start":2.75,"duration":0.5},{"id":13,"day":1,"start":3.5,"duration":0.25},{"id":14,"day":1,"start":4.5,"duration":0.5},{"id":15,"day":1,"start":6.5,"duration":1.5},{"id":16,"day":1,"start":7.75,"duration":0.75},{"id":17,"day":1,"start":8.25,"duration":0.25},{"id":18,"day":1,"start":11.25,"duration":0.5},{"id":19,"day":2,"start":0.0,"duration":0.25},{"id":20,"day":2,"start":1.25,"duration":0.75},{"id":21,"day":2,"start":1.75,"duration":0.25},{"id":22,"day":2,"start":2.5,"duration":0.5},{"id":23,"day":2,"start":4.25,"duration":1.25},{"id":24,"day":2,"start":5.75,"duration":0.75},{"id":25,"day":2,"start":6.75,"duration":0.75},{"id":26,"day":2,"start":7.75,"duration":0.75},{"id":27,"day":2,"start":9.0,"duration":1.0},{"id":28,"day":2,"start":9.75,"duration":0.25},{"id":29,"day":2,"start":10.75,"duration":0.5},{"id":30,"day":3,"start":0.25,"duration":0.5},{"id":31,"day":3,"start":0.75,"duration":0.25},{"id":32,"day":3,"start":1.25,"duration":0.25},{"id":33,"day":3,"start":2.5,"duration":0.5},{"id":34,"day":3,"start":3.5,"duration":0.75},{"id":35,"day":3,"start":4.0,"duration":0.25},{"id":36,"day":3,"start":4.75,"duration":0.5},{"id":37,"day":3,"start":5.5,"duration":0.5},{"id":38,"day":3,"start":6.0,"duration":0.25},{"id":39,"day":3,"start":6.5,"duration":0.25},{"id":40,"day":3,"start":7.25,"duration":0.25},{"id":41,"day":3,"start":8.0,"duration":0.5},{"id":42,"day":3,"start":8.5,"duration":0.25},{"id":43,"day":3,"start":9.5,"duration":0.75},{"id":44,"day":3,"start":10.75,"duration":0.5},{"id":45,"day":3,"start":11.25,"duration":0.25},{"id":46,"day":3,"start":11.75,"duration":0.25},{"id":47,"day":4,"start":1.5,"duration":1.5},{"id":48,"day":4,"start":2.0,"duration":0.25},{"id":49,"day":4,"start":3.25,"duration":0.5},{"id":50,"day":4,"start":4.0,"duration":0.25},{"id":51,"day":4,"start":4.75,"duration":0.25},{"id":52,"day":4,"start":7.25,"duration":2.0},{"id":53,"day":4,"start":7.75,"duration":0.25},{"id":54,"day":4,"start":8.25,"duration":0.25},{"id":55,"day":4,"start":9.75,"duration":0.75},{"id":56,"day":4,"start":11.0,"duration":0.25}]},"age":-1900,"username":"testUser","id":0}; getFullUser($http, $scope.user); //$scope.slots = $scope.user.slots; alert(JSON.stringify($scope.user)); ``` }); And my function ``` function getFullUser($http, user) { $http({method: "GET", url: "api/user", headers: { 'Content-Type': 'application/json', 'token': localStorage.token}}) .then(function(result) { user = result.data; alert(JSON.stringify(user)); }); ``` } Note that they are both in 2 different files, so just calling `$scope.user = result.data;` was **not** an option. I wasn't really sure how this could even work, because in other programming languages such as C#, Java, etc. my getFullUser function would change its variable *user* only in its own scope and nothing would have happened outside. Then after reading about callbacks and other solutions I came up with the idea not to hand over a **variable** such as *user*, but to hand over a **function** *setUserCallback* that will be executed when the result ist fetched from my RestService. So I ended up with this (which works just fine): ``` groupifyApp.controller('DashboardCtrl', function ($rootScope, $scope, $routeParams, $route, $http) { $scope.page = {title:"Preferences", dashboardActive: "active", manageActive: "", inboxActive:"", preferencesActive:""}; $scope.user = {}; //$scope.user = {"name":"Test User","cal":{"entries":[{"id":0,"day":0,"start":1.25,"duration":1.0},{"id":1,"day":0,"start":4.0,"duration":1.75},{"id":2,"day":0,"start":4.75,"duration":0.5},{"id":3,"day":0,"start":5.75,"duration":0.75},{"id":4,"day":0,"start":6.5,"duration":0.25},{"id":5,"day":0,"start":7.5,"duration":0.25},{"id":6,"day":0,"start":9.5,"duration":1.75},{"id":7,"day":0,"start":10.75,"duration":0.5},{"id":8,"day":0,"start":11.75,"duration":0.75},{"id":9,"day":1,"start":0.75,"duration":0.5},{"id":10,"day":1,"start":1.25,"duration":0.25},{"id":11,"day":1,"start":2.0,"duration":0.5},{"id":12,"day":1,"start":2.75,"duration":0.5},{"id":13,"day":1,"start":3.5,"duration":0.25},{"id":14,"day":1,"start":4.5,"duration":0.5},{"id":15,"day":1,"start":6.5,"duration":1.5},{"id":16,"day":1,"start":7.75,"duration":0.75},{"id":17,"day":1,"start":8.25,"duration":0.25},{"id":18,"day":1,"start":11.25,"duration":0.5},{"id":19,"day":2,"start":0.0,"duration":0.25},{"id":20,"day":2,"start":1.25,"duration":0.75},{"id":21,"day":2,"start":1.75,"duration":0.25},{"id":22,"day":2,"start":2.5,"duration":0.5},{"id":23,"day":2,"start":4.25,"duration":1.25},{"id":24,"day":2,"start":5.75,"duration":0.75},{"id":25,"day":2,"start":6.75,"duration":0.75},{"id":26,"day":2,"start":7.75,"duration":0.75},{"id":27,"day":2,"start":9.0,"duration":1.0},{"id":28,"day":2,"start":9.75,"duration":0.25},{"id":29,"day":2,"start":10.75,"duration":0.5},{"id":30,"day":3,"start":0.25,"duration":0.5},{"id":31,"day":3,"start":0.75,"duration":0.25},{"id":32,"day":3,"start":1.25,"duration":0.25},{"id":33,"day":3,"start":2.5,"duration":0.5},{"id":34,"day":3,"start":3.5,"duration":0.75},{"id":35,"day":3,"start":4.0,"duration":0.25},{"id":36,"day":3,"start":4.75,"duration":0.5},{"id":37,"day":3,"start":5.5,"duration":0.5},{"id":38,"day":3,"start":6.0,"duration":0.25},{"id":39,"day":3,"start":6.5,"duration":0.25},{"id":40,"day":3,"start":7.25,"duration":0.25},{"id":41,"day":3,"start":8.0,"duration":0.5},{"id":42,"day":3,"start":8.5,"duration":0.25},{"id":43,"day":3,"start":9.5,"duration":0.75},{"id":44,"day":3,"start":10.75,"duration":0.5},{"id":45,"day":3,"start":11.25,"duration":0.25},{"id":46,"day":3,"start":11.75,"duration":0.25},{"id":47,"day":4,"start":1.5,"duration":1.5},{"id":48,"day":4,"start":2.0,"duration":0.25},{"id":49,"day":4,"start":3.25,"duration":0.5},{"id":50,"day":4,"start":4.0,"duration":0.25},{"id":51,"day":4,"start":4.75,"duration":0.25},{"id":52,"day":4,"start":7.25,"duration":2.0},{"id":53,"day":4,"start":7.75,"duration":0.25},{"id":54,"day":4,"start":8.25,"duration":0.25},{"id":55,"day":4,"start":9.75,"duration":0.75},{"id":56,"day":4,"start":11.0,"duration":0.25}]},"age":-1900,"username":"testUser","id":0}; getFullUser($http, function(data) { $scope.user = data; }); //$scope.slots = $scope.user.slots; alert(JSON.stringify($scope.user)); }); ``` And my function: ``` function getFullUser($http, setUserCallback) { $http({method: "GET", url: "api/user", headers: { 'Content-Type': 'application/json', 'token': localStorage.token}}) .then(function(result) { setUserCallback(result.data); }); ``` } I'm not used to this mind-set of callbacks. Defining what a method should do as an result beforehand is/was a new concept.
420,800
``` Checkbox[,] checkArray = new Checkbox[2, 3]{{checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}}; ``` I am getting error . How do I initialize it?
2009/01/07
[ "https://Stackoverflow.com/questions/420800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42564/" ]
OK, I think I see what's happening here. You're trying to initialize an array at a class level using this syntax, and one of the checkboxes is also a class level variable? Am I correct? You can't do that. You can only use static variables at that point. You need to move the init code into the constructor. At the class level do this: ``` CheckBox[,] checkArray; ``` Then in your constructor: ``` public Form1() { InitializeComponent(); checkArray = new CheckBox[2, 3] { { checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}}; } ```
Initialized each element of array in the constructor and it worked. .
108,585
I have strange problem with Wolfram *Mathematica*'s function `RegionPlot` ``` RegionPlot[x - y == 0, {x, 0, 100}, {y, 0, 100}] ``` the result is: [![enter image description here](https://i.stack.imgur.com/GUquX.jpg)](https://i.stack.imgur.com/GUquX.jpg) But when I try ``` RegionPlot[x - y == 1, {x, 0, 100}, {y, 0, 100}] ``` [![enter image description here](https://i.stack.imgur.com/HTRCu.jpg)](https://i.stack.imgur.com/HTRCu.jpg) Do you know what I am doing wrong? Thanks!
2016/02/28
[ "https://mathematica.stackexchange.com/questions/108585", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/38129/" ]
What do you want ``` ContourPlot[x - y == 1, {x, 0, 100}, {y, 0, 100}] ``` [![enter image description here](https://i.stack.imgur.com/9QDVY.gif)](https://i.stack.imgur.com/9QDVY.gif) or should it be ``` RegionPlot[x - y < 1, {x, 0, 100}, {y, 0, 100}] ``` [![enter image description here](https://i.stack.imgur.com/N71Fa.gif)](https://i.stack.imgur.com/N71Fa.gif) Addendum for exercise. You have to define a region! ``` reg = ImplicitRegion[x - y == 1, {x, y}]; RegionPlot@reg ``` [![enter image description here](https://i.stack.imgur.com/cNM3D.gif)](https://i.stack.imgur.com/cNM3D.gif) ``` reg = ImplicitRegion[x - y == 1 && 0 < x < 100 && 0 < y < 100, {x, y}]; RegionPlot@reg ``` [![enter image description here](https://i.stack.imgur.com/LCgN4.gif)](https://i.stack.imgur.com/LCgN4.gif) RegionPlot will only visualize two-dimensional regions. See the documentation "Possible Issues".
Due to the sampling pattern used by RegionPlot, it is lucky that it finds the line in your first example. Consider the output of ``` noisyFunction[x_, y_] := Module[{}, Sow[{x, y}]; x - y ]; ListPlot[ Take[ Reap[ RegionPlot[noisyFunction[x, y] == 0, {x, 0, 100}, {y, 0, 100}] ][[2, 1]], {4, -1}] ] ``` The clustering of samples around the line is easily seen. But RegionPlot is not lucky for your second example. ``` ListPlot[ Take[ Reap[ RegionPlot[noisyFunction[x, y] == 1, {x, 0, 100}, {y, 0, 100}] ][[2, 1]], {4, -1}] ] ``` One should use EvaluationMonitor if one is going to be serious about inspecting the evaluation set of a function fed to a plot or numerical search.
139,695
Say I had a cellphone, let's call it cellphone A, and made a perfect copy of it - SIM card and all - and let's call this one cellphone B. If I were to call someone on cellphone A, what exactly would happen to both cellphone A and B? This stems from a short film I'm planning where a character goes back in time with his smartphone, and his younger self - that is now in the same time as him - makes a phone call. EDIT: This takes place in modern-day Australia, specifically Victoria. Also, the call from cellphone A is to emergency services.
2019/02/21
[ "https://worldbuilding.stackexchange.com/questions/139695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/61612/" ]
1. At every moment in time the network (= the central computers of the mobile communications operator) has an idea of where a certain SIM is. (Or it has an idea that a certain SIM is nowhere.) This is accomplished by the phone actively broadcasting its identity (SIM + IMEI) to the network and selecting one of the towers which answer. (This is necessary so that the network knows to which tower to send the data packets intended for that SIM.) A phone which has informed the network of its presence and has been accepted for placing and receiving calls is said to be *registered* on the network. 2. If you power up two phones with the same SIM, the network will instantly realize that something is fishy. Exacly what the network will do depends on the network; it may be that a second registration with the same SIM will fail; or when the second phone tries to register to the network with the same SIM, the first phone will be deregistered; or they may both be deregistered and the account marked as fraudulent etc. 3. In any case, *at most* one of the two phones will be registered on the network, and the other will be put in "emergency calls only" mode. It may happen that they will occasionaly switch between which phone is registered with the network and which is in emergency calls only mode. But, for certain, they will never be registered on the network both at the same time.
Depends on where you are. Much of europe allows cloned sims. The most recently used one will be used for incoming calls. Apparently in the U.S. this gets the cellular network *really* confused.
62,138
What Windows (preferably XP) batch command will list all of the network connections that appear in the Network Connections dialog? I've tried `RASDIAL`, `IPCONFIG`, `NETSTAT`, and `NET` commands with various option combinations, but they only seem to show those that are actually connected. I want to see the ones not connected as well. **CLARIFICATION:** I want to be able to see dialups, wireless, firewire, LAN, miniport, VPN, etc. connections whether connected, disconnected, disabled, etc. just like in the Network Connections dialog.
2009/10/28
[ "https://superuser.com/questions/62138", "https://superuser.com", "https://superuser.com/users/9240/" ]
See this Windows script : [List Items in the Network Connections Folder](https://web.archive.org/web/20150514022917/http://www.thescriptlibrary.com/default.asp?Action=Display&Level=Category3&ScriptLanguage=VBScript&Category1=Desktop%20Management&Category2=Special%20Folders&Title=List%20Items%20in%20the%20Network%20Connections%20Folder): ``` Const NETWORK_CONNECTIONS = &H31;& Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS) Set objFolderItem = objFolder.Self Wscript.Echo objFolderItem.Path Set colItems = objFolder.Items For Each objItem in colItems Wscript.Echo objItem.Name Next ``` > > **Description:** Reports the path to the Network Connections folder, and then lists any items found in that folder. For Windows NT 4.0 and > Windows 98, this script requires Windows Script Host 5.1 and Internet > Explorer 4.0 or later. > > >
Maybe this from a batch file? ``` NetSh Interface httpstunnel Show Interfaces NetSh Interface IPv4 Show Interfaces NetSh Interface IPv6 Show Interfaces ```
1,397,199
My team uses sourcetree as our git client. There is a third-party plugin in our project. It needs several configuration files. These files cannot be generated automatically. They store account name, login tokens and some temporary options, which shouldn't be shared. But everyone still needs this file, otherwise it will report error. So now they always stay in our "uncommitted changes" section which is annoying. I have 2 options: 1. Remove these files from git repository. Add them into .gitignore. Ask all my team members to add these files back to their local project with their own settings. 2. See if there are tricks like "ignoring a tracked file without deleting it". (Basically I feel if option 2 was possible, git should have some logic like "If local doesn't have this file, use remote version. If local has this file, ignore". The logic feels bad, easy to generate bugs.)
2019/01/22
[ "https://superuser.com/questions/1397199", "https://superuser.com", "https://superuser.com/users/988539/" ]
This is what you want to do: 1. Add all the files, individually or in a folder, that you want to remove from the repo but keep locally to **.gitignore**. 2. Execute **git rm --cached put/here/your/file.ext** for each file or **git rm --cached folder/\\*** if they are in a folder. (It is /\\* because you need to escape the \*) 3. Commit your changes. 4. Push to remote. After having done this, you will effectively *"ignore tracked files without deleting them"*, removing them from the repo and keeping all of them untouched in your system. Then when your team pulls the changes, they will pull the **.gitignore** file and their individual configuration files will not be overwritten by the ones in the repo because you have ignored them and deleted them from it. Also, because now the new **.gitignore** is ignoring these files, everybody will have their own version of them not showing in the "uncommitted changes".
There is no easy solution to this. But you can try out the following: A) Put `foo.cfg` in `.gitignore` and push. Ask everyone to keep a save copy of `foo.cfg` outside their local repository. Let them push and copy that deleted file `foo.cfg` back in place. B) Rename `foo.cfg` to `foo.default.cfg` put `foo.cfg` in gitignore, push and ask every member in your team to pull, then localy renaming `foo.default.cfg` to `foo.cfg`. After that, you need to delete `foo.default.cfg`, push, and everyone has to pull again. C) Put `foo.cfg` in `.gitignore` and push. Ask everyone to pull. Now for everyone the `foo.cfg` is deleted. They can restory it by `git checkout HEAD^ foo.cfg`. Now the file is still staged, so they need to call `git reset HEAD`. Now it works.
31,448,504
I have created 30 scrollable tabs using tablayout. So first three tabs are visible on screen and rest of them are invisible which can be scroll using swipe gesture. The problem is when I am selecting last tab programmatically but it is not get visible (tab layout not get scrolled to last tab). How can I make tablayout to scroll to last tab?
2015/07/16
[ "https://Stackoverflow.com/questions/31448504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308763/" ]
If your `TabLayout` is used in conjunction with a `ViewPager`, which is common, simply add the following in the `onCreate()` method in your Activity: ``` tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout); ``` That some of your tabs are not being shown indicates the tabMode attribute is set to `app:tabMode="scrollable"`.
This solution worked for me. My situation is a little bit different though; in my case, I am using the TabLayout with a ViewPager and adding more views and calling notifyDataSetChange(). The solution is to set a callback on the observer of TabLayout and scroll when the children are actually added to the TabLayout. Here is my example: ``` /** Keep in mind this is how I set my TabLayout up... PagerAdapter pagerAdapter = new PagerAdapter(...); ViewPager pager = (ViewPager)findViewById(...); pager.setAdapter(pagerAdapter); TabLayout tabLayout = (TabLayout)findViewById(...); tabLayout.setupWithViewPager(pager); */ public void loadTabs(String[] topics) { animateTabsOpen(); // Irrelevant to solution // Removes fragments from ViewPager pagerAdapter.clear(); // Adds new fragments to ViewPager for (String t : topics) pagerAdapter.append(t, new TestFragment()); // Since we need observer callback to still animate tabs when we // scroll, it is essential to keep track of the state. Declare this // as a global variable scrollToFirst = true; // Alerts ViewPager data has been changed pagerAdapter.notifyOnDataSetChanged(); // Scroll to the beginning (or any position you need) in TabLayout // using its observer callbacks tabs.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { /** We use onGlobalLayout() callback because anytime a tab is added or removed the TabLayout triggers this; therefore, we use it to scroll to the desired position we want. In my case I wanted to scroll to the beginning position, but this can easily be modified to scroll to any position. */ if (scrollToFirst) { tabs.getTabAt(0).select(); tabs.scrollTo(0, 0); scrollToFirst = false; } } }); } ``` Here is my code for the PagerAdapter if you need it too lol: ``` public class PagerAdapter extends FragmentStatePagerAdapter { private List<Fragment> fragments; private List<String> titles; public PagerAdapter(FragmentManager fm) { super(fm); this.fragments = new ArrayList<>(); this.titles = new ArrayList<>(); } /** * Adds an adapter item (title and fragment) and * doesn't notify that data has changed. * * NOTE: Remember to call notifyDataSetChanged()! * @param title Fragment title * @param frag Fragment * @return This */ public PagerAdapter append(String title, Fragment frag) { this.titles.add(title); this.fragments.add(frag); return this; } /** * Clears all adapter items and doesn't notify that data * has changed. * * NOTE: Rememeber to call notifyDataSetChanged()! * @return This */ public PagerAdapter clear() { this.titles.clear(); this.fragments.clear(); return this; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } @Override public int getCount() { return fragments.size(); } @Override public int getItemPosition(Object object) { int position = fragments.indexOf(object); return (position >= 0) ? position : POSITION_NONE; } } ```
2,647,384
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of $n^3$, the cube above will have volume of $(n-1)^3$ and so on until the top which will have a volume of $1^3$. You are given the total volume of the building. Being given m can you find the number n of cubes you will have to build? $V = n^3 + (n-1)^3+(n-2)^3+...+1^3$ So far I thought I can use arithmetic sequence : $V= (n-0)^3+(n-1)^3+(n-2)^3+...+(n-(n-2))^3+(n-(n-1))^3$ $V = x(\frac{n^3+1}{2})$ where $x =$ number of cubes then I get stuck here.
2018/02/12
[ "https://math.stackexchange.com/questions/2647384", "https://math.stackexchange.com", "https://math.stackexchange.com/users/527628/" ]
Here's a cute trick. *If the problem is well-posed*, then the solution must be independent of $f$. Therefore, you can take $$ f(x)\equiv1 $$ which is consistent with the hypotheses, and calculate $$ \int\_{-2}^8x\ \mathrm dx\equiv 30 $$ Easy peasy!
You're given: $$I=\int\_{-2}^8xf(x)dx$$ Use the $a+b-x$ property on this definite integral to get: $$\begin{align} I&=\int\_{-2}^8 (6-x)\cdot f(6-x)dx \\ &=\int\_{-2}^8 (6-x)\cdot f(x)dx \tag{$\because f(6-x)=f(x)$ given} \\ &=6\int\_{-2}^8f(x)-I \end{align}$$ and you can solve it from here.
74,389,040
In my program, I have a RecyclerView with an adapter, in which I'm checking which element of RecyclerView is clicked. ``` override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentBreakfast = breakfastList[position] holder.breakfastTitle.text = context.getText(currentBreakfast.breakfastStringResourceId) holder.breakfastImage.setImageResource(currentBreakfast.breakfastImageResourceId) holder.breakfastImage.setOnClickListener { holder.itemView.findNavController().navigate(R.id.action_breakfastFragment_to_DetailsFragment) showDetails(currentBreakfast) } } ``` I want to pass the data about specific clicked element, such as **imageId**, **stringId**, **Name**, etc. to another fragment **DetailsFragment** in which I would like to display further data How can I do it?
2022/11/10
[ "https://Stackoverflow.com/questions/74389040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15158080/" ]
You need to send your fragment to the adapter from where you are calling i guess it's breakfastFragment, just add `this` to it: ``` BreakfastAdapter( requireActivity(), breakfastList, this ) ``` And your Adapter get that `fragment`: ``` open class BreakfastAdapter( private val context: Context, private var breakfastList: ArrayList<Breakfast>, private val fragment: Fragment ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { ``` And you can use that `fragment` to be able to navigate from it: ``` holder.breakfastImage.setOnClickListener { // create a bundle to hold data you want to send val bundle = bundleOf( "breakfastImageResourceId" to currentBreakfast.breakfastImageResourceId, "breakfastStringResourceId" to currentBreakfast.breakfastStringResourceId, "kcal" to currentBreakfast.kcal ) // add this bundle when you move to another fragment. fragment.findNavController().navigate(R.id.action_breakfastFragment_to_DetailsFragment, bundle) } ``` In another fragment get that value and see them in the Log like below: ``` // create below variables private var mBreakfastImageResourceId: Int = 0 private var mBreakfastStringResourceId: Int = 0 private var mKcal: Int = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Now we set above values with what we sent from adapter arguments?.let { if (it["breakfastImageResourceId"] != null) { mBreakfastImageResourceId = it.getInt("BreakfastImageResourceId")!! } if (it["breakfastStringResourceId"] != null) { mBreakfastStringResourceId = it.getInt("breakfastStringResourceId")!! } if (it["kcal"] != null) { mKcal = it.getInt("kcal")!! } } return inflater.inflate(R.layout.fragment_question_stats, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // now you can do whatever you want with mBreakfastImageResourceId, mBreakfastStringResourceId and mKcal. } ``` P.S. I just made up some variable and class names because you did not share them, just change it with yours correct ones.
There are several ways to it. I suggest you have a look at this answer (the accepted one) : [How to pass data from adapter to fragment?](https://stackoverflow.com/questions/71888926/how-to-pass-data-from-adapter-to-fragment) And then go to the section called "A more Kotlin way to do it is to ignore interfaces and just pass a function instead". This is the approach I also use myself. Here is an exampe of how my Adapter for the RecyclerView is defined: ``` class ReportAdapter(var reports: List<Report>,val clickFunc : (Report) -> (Unit)) : RecyclerView.Adapter<ReportAdapter.ViewHolder>() {...} ``` Then you need to attach the callback function to a click listener inside your viewholder - in my example it looks like this (every item in the list has a cardview - defined in the xml file): ``` itemView.report_cardview_item.setOnClickListener { clickFunc(report) } ``` Then in the callback function you pass to the RecylerView Adapter you can navigate to a details fragment with the relevant data - one of my callback functions (which is passed to the Adapter upon creation) simply looks like this (defined in the Fragment that "owns" the RecyclerView): ``` private fun reportClicked(report:Report) { val action = ReportsFragmentDirections.actionNavReportsToReportDetailFragment(report) findNavController().navigate(action) } ``` (here using my navigation graph to create an Action to use for the NavController) My adapter is easily initialized with some data and a reference to the callback function: ``` adapter = ReportAdapter(reports,::reportClicked) ```
11,535
I have been trying to analyse NDE stories from a meditator's point of view. The way people change after a NDE is, in some cases, similar to the changes a person goes through after meditating for a while (i. e. less materialist, more calm, serene, not affraid of dying, less attachment to the "I"...). It is a life changing experience just like meditation when taken seriously. In general NDE fits well in the Dhamma, showing for instance that the mind does not depend upon the body. Let's accept NDE as true for a while. What I don't get and want some help is: almost all NDE are nice and positive (similarly to going to heaven). In the Dhamma we usually hear that most people are reborn in the awful planes due to their kamma. Some monks even say people sometimes get a glimpse of their future realm of rebirth. That would suggest NDE should be bad and traumatic for most people, but it is not! I don't believe so many people are going to be reborn in heaven, based on the way people live and all ignorance and anger in the world. Also, most people after a NDE claim to have seen and talked to dead family members or even pets, would that imply necessarily that they were all in the hungry ghost realm? Or could they be devas, but keeping the same old shape?! I know fitting NDE 100% into the Dhamma may be impossible, but I appreciate any help!
2015/09/14
[ "https://buddhism.stackexchange.com/questions/11535", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/533/" ]
I recommend studying the [Six Yogas of Naropa](https://en.wikipedia.org/wiki/Six_Yogas_of_Naropa#The_six_yogas) and The Tibetan Book of the Dead, specificlaly the pre-[Bardo](https://en.wikipedia.org/wiki/Bardo) stages which is the Buddhist equivalent of NDE. One thing in particular that is mentioned is that people's wishful thinking will be actualized. If a person believed in the Buddha, they will see the Buddha, if a person believed they were a bad person, they will see hell. This is a precursor to the **actual** stage of Bardo and is also why it is important to die happy. I have read some good books about this topic, some of which explains tricks and tactics to succeed in gaining Enlightenment after death (mainly it involves maintaining composure and not being alarmed by anything that may arise) from the Tibetan school.
I think the psychics who are able to see the spirit world says that some people goes to hell. Because their minds are so corrupted, they believe that they deserve to be in hell and as a result they go these lower planes. The near death experiences are so peaceful and blissful because people become free from body. Its perfectly normal to have blissful experiences when you go to the home. I rarely have short astral projection experiences and I enter to the void state that I think every people who dies is able to experience more fully. Anita Moorjiani talked about her near death experience and she said that she was feeling other people's feelings and immediately getting detached from these feelings and she also experienced unconditional love. I think what near death and astral projection experiences proves is that the physical dimension is the most dense and slow plane. So the people who does bad deeds are already having their consequences when they re-born in the physical world. For most people the only way to become free from this cycle is to start their spiritual journey/spiritual practice while they are in the physical world.
2,502,660
Here's the sample code: ``` class TestAO { int[] x; public TestAO () { this.x = new int[5] ; for (int i = 0; i<x.length; i++) x[i] = i; } public static void main (String[]arg) { TestAO a = new TestAO (); System.out.println (a) ; TestAO c = new TestAO () ; c.x[3] = 35 ; TestAO[] Z = new TestAO[3] ; Z[0] = a ; Z[1] = (TestAO b = new TestAO()) ; Z[2] = c ; } } ``` When I try to compile this I get an error message at the line `Z[1]` which reads as follows: ``` TestAO.java:22: ')' expected Z[1] = (TestAO b = new TestAO()) ; ^ ``` What I'm trying to do here is create an instance of the object TestAO that I want to be in that index within the assignment of the value at that index instead of creating the instance of the object outside of the array like I did with `a`. Is this legal and I'm just making some syntax error that I can't see (thus causing the error message) or can what I'm trying to do just not be done? EDIT: in regard to Mark's answer here is my follow up question: is there a shorter way to assign values to the instance variables of an object in the array of objects than this: (without writing any special constructors) ``` Z[1] = new TestAO() ; Z[1].x[4] = 80085 ; ```
2010/03/23
[ "https://Stackoverflow.com/questions/2502660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282315/" ]
Declaring variable like this is impossible. Just write "Z[1] = new TestAO();" and if you want another reference "TestAO b = Z[1]";
What you're really doing here is assigning the result of an assignment to Z[1]. The return type of an assignment in Java is boolean, so the way you're doing it is not going to work. Try: ``` Z[1] = new TestAO(); ```
3,909,711
I'm currently trying to implement the A\* pathfinding algorithm using C++. I'm having some problems with pointers... I usually find a way to avoid using them but now I guess I have to use them. So let's say I have a "node" class(not related to A\*) implemented like this: ``` class Node { public: int x; Node *parent; Node(int _x, Node *_parent) : x(_x), parent(_parent) { } bool operator==(const Node &rhs) { return x == rhs.x && parent == rhs.parent; } }; ``` It has a value (in this case, int x) and a parent (a pointer to another node) used to navigate through nodes with the parent pointers. Now, I want to have a list of nodes which contains all the nodes that have been or are being considered. It would look like this: ``` std::vector<Node> nodes; ``` I want a list that contains pointers pointing to nodes inside the *nodes* list. Declared like this: ``` std::vector<Node*> list; ``` However, I'm definitely not understanding pointers properly because my code won't work. Here's the code I'm talking about: ``` std::vector<Node> nodes;//nodes that have been considered std::vector<Node*> list;//pointers to nodes insided the nodes list. Node node1(1, NULL);//create a node with a x value of 1 and no parent Node node2(2, &node1);//create a node with a x value of 2 and node1 being its parent nodes.push_back(node1); list.push_back(&nodes[0]); //so far it works //as soon as I add node2 to nodes, the pointer in "list" points to an object with //strange data, with a x value of -17891602 and a parent 0xfeeefeee nodes.push_back(node2); list.push_back(&nodes[1]); ``` There is clearly undefined behaviour going on, but I can't manage to see where. Could somebody please show me where my lack of understanding of pointers breaks this code and why?
2010/10/11
[ "https://Stackoverflow.com/questions/3909711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395386/" ]
One problem is that push\_back can force a reallocation of the vector, i.e. it creates a larger block of memory, copies all existing elements to that larger block, and then deletes the old block. That invalidates any pointers you have to elements in the vector.
just adding to the existing answers; instead of the raw pointers, consider using some form of smart pointer, for example, if boost is available, consider shared\_ptr. ``` std::vector<boost::shared_ptr<Node> > nodes; ``` and ``` std::list<boost::shared_ptr<Node> > list; ``` Hence, you only need to create a single instance of Node, and it is "managed" for you. Inside the Node class, you have the option of a shared\_ptr for parent (if you want to ensure that the parent Node does not get cleaned up till all child nodes are removed, or you can make that a weak\_ptr. Using shared pointers may also help alleviate problems where you want to store "handles" in multiple containers (i.e. you don't necessarily need to worry about ownership - as long as all references are removed, then the object will get cleaned up).
3,051,257
I have many nodes and some of them are under the screen's edge. Tho treeview is scrollable, there is no vertical scrollbar on the right. How can i show it?
2010/06/16
[ "https://Stackoverflow.com/questions/3051257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47672/" ]
I wrote an S-Expression parser in C# using [OMeta#](http://ometasharp.codeplex.com/). It can parse the kind of S-Expressions that you are giving in your examples, you just need to add decimal numbers to the parser. The code is available as [SExpression.NET](https://github.com/databigbang/SExpression.NET) on github and a related article is available [here](http://blog.databigbang.com/parsing-s-expressions-in-c-using-ometa/). As an alternative I suggest to take a look at the [YaYAML](https://github.com/jagregory/yayaml) YAML parser for .NET also written using OMeta#.
Here's a relatively simple (and hopefully, easy to extend) solution: ``` public delegate object Acceptor(Token token, string match); public class Symbol { public Symbol(string id) { Id = id ?? Guid.NewGuid().ToString("P"); } public override string ToString() => Id; public string Id { get; private set; } } public class Token : Symbol { internal Token(string id) : base(id) { } public Token(string pattern, Acceptor acceptor) : base(pattern) { Regex = new Regex(string.Format("^({0})", !string.IsNullOrEmpty(Pattern = pattern) ? Pattern : ".*"), RegexOptions.Compiled); ValueOf = acceptor; } public string Pattern { get; private set; } public Regex Regex { get; private set; } public Acceptor ValueOf { get; private set; } } public class SExpressionSyntax { private readonly Token Space = Token("\\s+", Echo); private readonly Token Open = Token("\\(", Echo); private readonly Token Close = Token("\\)", Echo); private readonly Token Quote = Token("\\'", Echo); private Token comment; private static Exception Error(string message, params object[] arguments) => new Exception(string.Format(message, arguments)); private static object Echo(Token token, string match) => new Token(token.Id); private static object Quoting(Token token, string match) => NewSymbol(token, match); private Tuple<Token, string, object> Read(ref string input) { if (!string.IsNullOrEmpty(input)) { var found = null as Match; var sofar = input; var tuple = Lexicon.FirstOrDefault(current => (found = current.Item2.Regex.Match(sofar)).Success && (found.Length > 0)); var token = tuple != null ? tuple.Item2 : null; var match = token != null ? found.Value : null; input = match != null ? input.Substring(match.Length) : input; return token != null ? Tuple.Create(token, match, token.ValueOf(token, match)) : null; } return null; } private Tuple<Token, string, object> Next(ref string input) { Tuple<Token, string, object> read; while (((read = Read(ref input)) != null) && ((read.Item1 == Comment) || (read.Item1 == Space))) ; return read; } public object Parse(ref string input, Tuple<Token, string, object> next) { var value = null as object; if (next != null) { var token = next.Item1; if (token == Open) { var list = new List<object>(); while (((next = Next(ref input)) != null) && (next.Item1 != Close)) { list.Add(Parse(ref input, next)); } if (next == null) { throw Error("unexpected EOF"); } value = list.ToArray(); } else if (token == Quote) { var quote = next.Item3; next = Next(ref input); value = new[] { quote, Parse(ref input, next) }; } else { value = next.Item3; } } else { throw Error("unexpected EOF"); } return value; } protected Token TokenOf(Acceptor acceptor) { var found = Lexicon.FirstOrDefault(pair => pair.Item2.ValueOf == acceptor); var token = found != null ? found.Item2 : null; if ((token == null) && (acceptor != Commenting)) { throw Error("missing required token definition: {0}", acceptor.Method.Name); } return token; } protected IList<Tuple<string, Token>> Lexicon { get; private set; } protected Token Comment { get { return comment = comment ?? TokenOf(Commenting); } } public static Token Token(string pattern, Acceptor acceptor) => new Token(pattern, acceptor); public static object Commenting(Token token, string match) => Echo(token, match); public static object NewSymbol(Token token, string match) => new Symbol(match); public static Symbol Symbol(object value) => value as Symbol; public static string Moniker(object value) => Symbol(value) != null ? Symbol(value).Id : null; public static string ToString(object value) { return value is object[] ? ( ((object[])value).Length > 0 ? ((object[])value).Aggregate(new StringBuilder("("), (result, obj) => result.AppendFormat(" {0}", ToString(obj))).Append(" )").ToString() : "( )" ) : (value != null ? (value is string ? string.Concat('"', (string)value, '"') : (value is bool ? value.ToString().ToLower() : value.ToString())).Replace("\\\r\n", "\r\n").Replace("\\\n", "\n").Replace("\\t", "\t").Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\\"", "\"") : null) ?? "(null)"; } public SExpressionSyntax() { Lexicon = new List<Tuple<string, Token>>(); Include(Space, Open, Close, Quote); } public SExpressionSyntax Include(params Token[] tokens) { foreach (var token in tokens) { Lexicon.Add(new Tuple<string, Token>(token.Id, token)); } return this; } public object Parse(string input) { var next = Next(ref input); var value = Parse(ref input, next); if ((next = Next(ref input)) != null) { throw Error("unexpected ", next.Item1); } return value; } } public class CustomSExpressionSyntax : SExpressionSyntax { public CustomSExpressionSyntax() : base() { Include ( // "//" comments Token("\\/\\/.*", SExpressionSyntax.Commenting), // Obvious Token("false", (token, match) => false), Token("true", (token, match) => true), Token("null", (token, match) => null), Token("\\-?[0-9]+\\.[0-9]+", (token, match) => double.Parse(match)), Token("\\-?[0-9]+", (token, match) => int.Parse(match)), // String literals Token("\\\"(\\\\\\n|\\\\t|\\\\n|\\\\r|\\\\\\\"|[^\\\"])*\\\"", (token, match) => match.Substring(1, match.Length - 2)), // Identifiers Token("[_A-Za-z][_0-9A-Za-z]*", NewSymbol) ); } } public class Node { } public class HearPerceptorState : Node { public string Ident { get; set; } public double Value { get; set; } } public class HingeJointState : Node { public string Ident { get; set; } public double Value { get; set; } } public class Polar : Tuple<double, double, double> { public Polar(double a, double b, double c) : base(a, b, c) { } } public class ForceResistancePerceptorState : Node { public string Ident { get; set; } public Polar Polar { get; set; } } public class Test { public static void Main() { var input = @" ( (Hear 12.3 HelloWorld) (HJ LAJ1 -0.42) (FRP lf (pos 2.3 1.7 0.4)) ) "; // visit DRY helpers Func<object, object[]> asRecord = value => (object[])value; Func<object, Symbol> symbol = value => SExpressionSyntax.Symbol(value); Func<object, string> identifier = value => symbol(value).Id; // the SExpr visit, proper Func<object[], Node[]> visitAll = null; Func<object[], Node> visitHear = null; Func<object[], Node> visitHJ = null; Func<object[], Node> visitFRP = null; visitAll = all => all. Select ( item => symbol(asRecord(item)[0]).Id != "Hear" ? ( symbol(asRecord(item)[0]).Id != "HJ" ? visitFRP(asRecord(item)) : visitHJ(asRecord(item)) ) : visitHear(asRecord(item)) ). ToArray(); visitHear = item => new HearPerceptorState { Value = (double)asRecord(item)[1], Ident = identifier(asRecord(item)[2]) }; visitHJ = item => new HingeJointState { Ident = identifier(asRecord(item)[1]), Value = (double)asRecord(item)[2] }; visitFRP = item => new ForceResistancePerceptorState { Ident = identifier(asRecord(item)[1]), Polar = new Polar ( (double)asRecord(asRecord(item)[2])[1], (double)asRecord(asRecord(item)[2])[2], (double)asRecord(asRecord(item)[2])[3] ) }; var syntax = new CustomSExpressionSyntax(); var sexpr = syntax.Parse(input); var nodes = visitAll(asRecord(sexpr)); Console.WriteLine("SO_3051254"); Console.WriteLine(); Console.WriteLine(nodes.Length == 3); Console.WriteLine(nodes[0] is HearPerceptorState); Console.WriteLine(nodes[1] is HingeJointState); Console.WriteLine(nodes[2] is ForceResistancePerceptorState); } } ``` Testable here: <https://repl.it/CnLC/1> 'HTH,
626,605
I'm trying to localy add a dir to the global `$PATH` variable. I added the following to my `.bashrc`. ``` export PATH=$PATH:$VRS/bin ``` But `PATH` seems to get concatenated to itself over & over every time I open a shell (i.e. `PATH` keeps growing). Any ideas?
2013/08/01
[ "https://superuser.com/questions/626605", "https://superuser.com", "https://superuser.com/users/183983/" ]
In your script/`.bashrc`, just use: ``` PATH=$PATH:$VRS/bin ``` so that the change is temporarily only for the script/shell session you're running. The `export` command will make the change permanent.
Indeed, each time you open a shell, your `.bashrc` is executed. And thus, with your current code, your `PATH` will grow indefinitely. If you only need this change to path for your shell, you can just remove the `export`, and let in your `.bashrc`: ``` PATH=$PATH:$VRS/bin ``` If your need to have this change more global, move your line (and the code defining your `$VRS`) to file `~/.profile`, but by keeping the `export`. This file is only executed at login, not each time your open a shell. Or even to `/etc/profile` if you want this change to be for all users.
31,209,665
Why Javascript relational operator showing weird result when comparing three strings? Am i wrong or Javascript got buggy? ``` var number1 = 1 var number2 = 1 var number3 = 1 number1 == number2 //true number1 == number3 //true number2 == number3 //true number1 == number2 == number3 //true. Good! ``` Now the problemetic part: ``` var string1 = "a" var string2 = "a" var string3 = "a" string1 == string2 //true string2 == string3 //true string1 == string3 //true ``` Why the following gives false? ``` string1 == string2 == string3 //false. WHY IS THAT?? ```
2015/07/03
[ "https://Stackoverflow.com/questions/31209665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5072169/" ]
This: ``` string1 == string2 == string3 ``` means: ``` (string1 == string2) == string3 ``` which is to say: ``` true == string3 ``` That's not `true`, so it's `false`. If you want to see if the three strings are all the same, you need ``` string1 == string2 && string2 == string3 ``` *edit* — it all has to do with the type conversion implicit in the behavior of the `==` operator, along with the syntax of expressions and the rules of operator precedence. The `==` operator is *left associative*, which means that a string of `==` expressions as in this question is treated with left-weighted parentheses (as shown above in my answer). To break things down, after the first comparison you've got ``` true == string3 ``` So there's a boolean on the left side and a string on the right. The rules of the `==` operator say that in that case, you treat the comparison as a comparison between the *numeric* value of the boolean and the other operand, which gives ``` 1 == string3 ``` Now we've got a number and a string. In *that* case, the rules for `==` say to convert the string to a number, which gives ``` 1 == NaN ``` when `string3` is `"a"`. That comparison is between a number and another number, so it's a simple numeric equality test with the result `false`. Given all that, note that if the strings had been initialized like this: ``` var string1 = "1", string2 = "1", string3 = "1"; ``` then the expression ``` string1 == string2 == string3 ``` would be `true`. Similarly, and perhaps even more surprising than the result of the original test, ``` "2" == "2" == "1" ``` would be `true`!
First, best practice in Javascript is to avoid `==` and use `===` instead. The `==` operator tries very hard - some would say too hard - to come up with a valid way to compare its operands, so it can yield some surprising results. In your first example, this code: ``` number1 == number2 == number3 ``` is actually interpreted as this: ``` (number1 == number2) == number3 ``` That is, Javascript first compares `number1` and `number2`, yielding - in this case - `true`. It then compares the result (`true`) and `number3`... which is *also* true, because `true == 1` is a true statement in Javascript. That is, `true` has a numeric value of 1. (Note that even though *any* nonzero number evaluates as true, or at least truthy, in a Boolean context, only the number 1 tests as equal to `true` itself.) If you use `===`, you get a different result, since `true === 1` is false. In fact, `x === y` is always false if `x` and `y` are not the same type of value. When you get to the strings, you can see that this is not going to work even with `==`, because `true == s` is not true for most strings `s`. (The exception is if `s` is a string representation of the number "1", as then it is first converted to the number 1, which as we said above tests as `==` to `true`). If you want to compare that three things are all equal to each other, you need to compare two pairs of them and AND them together: ``` if ((number1 === number2) && (number2 === number3)) {...} ``` So, to sum up: if you set `number1` and friends to 2 instead of 1, you get `false` in the first example. If you set `string1` and friends to "1" instead of "a", you get `true` in the second. And if you use `===` instead of `==`, you avoid all the confusion.
27,711,131
I am trying to add AutoComplete in my html [JQUERY AUTOCOMPLETE FILE LINK](http://www.java2s.com/Open-Source/Javascript_Free_Code/UI/Download_jquery_ui_extensions_Free_Java_Code.htm) Here is how i have added it ``` <script src="<?php echo $site_root?>js/autocomplete/jquery.ui.autocomplete.autoSelect.js"></script> ``` Trying to access using ``` $("#username").autocomplete({ source: <?php echo $username; ?>, select: function(event, ui) { var username = ui.item.label; window.location = 'submissionForm.php?username=' + username; } }); ``` I am getting This error Cannot read property 'autocomplete' of undefined What is wrong?
2014/12/30
[ "https://Stackoverflow.com/questions/27711131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1921872/" ]
Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application. In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC. [Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timezone-for-applications-on-windows-azure.aspx)
In this modern times where infrastructure is scaled globally, it is good idea to save data in UTC and convert to a timezone based on users location preference. Please refere: <https://learn.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netframework-4.7.2>
51,678,049
Lets say I have a client that gives me db credentials, and they want to connect to the db with a secure/encrypted. They also enabled ssl in their mysql setup. When they give me their db creds, i dont want to ask them for keys and certs. So is it possible to have a encrypted secure connection via ssl when connecting to the clients db with out those items? **update:** so after further tinkering around ``` $db->ssl_set(NULL, NULL,'/path_to_self_signed_cert/ca.pem',NULL,''); $db->real_connect('hostname','username','password','dbname', 'port'socket', MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);` ``` doing this got me the outcome i wanted after running this ``` $db->query("SHOW STATUS LIKE 'Ssl_cipher';"); ``` displayed the cipher algorithm instead of being blank ``` ( [0] => Ssl_cipher [Variable_name] => Ssl_cipher [1] => DHE-RSA-AES128-SHA [Value] => DHE-RSA-AES128-SHA ) ``` but dont really know why this worked, is a self signed cert the proper way of doing this ?
2018/08/03
[ "https://Stackoverflow.com/questions/51678049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9059013/" ]
@rickjerrity i connect to my remote db via command line, and check the status by running `\s` and says `SSL: Cipher in use is DHE-RSA-AES256-SHA`. But when i connect to the same database using php and using the same credentials it says the cipher is empty. here is the code I used to connect to the remote db ``` $db = mysqli_init(); $db->real_connect('hostname','username','password','dbname'); $res = $db->query("SHOW STATUS LIKE 'Ssl_cipher';"); while ( $row = $res->fetch_array() ) { print_r($row); } $db->close(); ``` and the response is ``` [0] => Ssl_cipher [Variable_name] => Ssl_cipher [1] => [Value] => ```
No client side certificate or key should be needed for a secure db connection, besides the db credentials. PHP should verify SSL cert integrity upon connection. Any other PHP methods capable of verifying the connection's encryption status would be for sanity sake, like you mentioned. If you show some specific code examples we may be able to assist further.
12,122,346
I'm developing an email client in PHP for IMAP accounts. Which would be the most secure way to store the account's password being able to retrieve it afterward to check emails? I guess I should encrypt it somehow. However, how can I make sure that only my app will be able to decrypt it?
2012/08/25
[ "https://Stackoverflow.com/questions/12122346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77247/" ]
If you require login without any user interactions, then there is no secure solution. You'll need to rely on your OS's storage options which might prevent hostile unprivileged applications from reading the password. If the user entering a single password on startup is fine, then you can encrypt the other passwords with symmetric encryption, and then use a KDF, such as scrypt or PBKDF2 to derive the master key from the password (and a salt).
Store the passwords in an encrypted file; require the decryption key when starting the app.
61,181,987
The problem I have is that when I compile the image caption is displayed with brackets "[fig caption]"....................................................................................................................................... ``` \documentclass{elsarticle} \usepackage{verbatim} \usepackage{xcolor} \usepackage{booktabs} % For professional looking tables \usepackage{multirow} \usepackage{siunitx} \usepackage{framed} \usepackage{longtable} \usepackage{lscape} %\usepackage[ruled,vlined]{algorithm2e} \usepackage{amssymb} \usepackage{graphicx} \usepackage{amsmath} %\usepackage[ruled,vlined]{algorithm2e} \usepackage{slashbox} \usepackage{caption} \usepackage{natbib} \usepackage{graphicx} \usepackage{float} %\usepackage{subcaption} \usepackage{subfig} \usepackage{multirow} \usepackage{bigstrut} \usepackage{algorithmicx} \usepackage{algorithm} \usepackage[noend]{algpseudocode} \usepackage{lineno,hyperref} \usepackage{cleveref} \usepackage{array} \newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}} \modulolinenumbers[5] \journal{Journal of \LaTeX\ Templates} \usepackage{blindtext} \usepackage{amssymb} \usepackage{amsthm} \begin{figure} \subfigure[]{ \includegraphics[width=0.24\textwidth]{graph1} } \subfigure[]{\includegraphics[width=0.24\textwidth]{graph2}% } \subfigure[]{\includegraphics[width=0.24\textwidth]{graph3}}% \caption{Three simple graphs} \label{fig:three graphs} \end{figure} ```
2020/04/13
[ "https://Stackoverflow.com/questions/61181987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6819651/" ]
This issue has been addressed at Tex Stack Exchange, see [here.](https://tex.stackexchange.com/questions/538316/how-to-eliminate-brackets-from-caption-for-subfigures-in-latex) The proposed solution is to use the `subcaption` package, instead of `subfig`.
I had the same issue and found a solution here: <https://answerbun.com/tex-latex/latex-how-to-remove-round-brackets-in-the-caption-of-subfigures-using-subfloat/> I used the following package: \usepackage[caption=false]{subfig} And the following structure: \begin{figure}[H] ``` \captionsetup[subfloat]{labelformat=simple} %% Do not forget this command! \centering \subfloat[]{\includegraphics[width=0.49\textwidth]{fig1}}\hfill \subfloat[]{\includegraphics[width=0.49\textwidth]{fig2}}\hfill \\ \subfloat[]{\includegraphics[width=0.49\textwidth]{fig3}} \caption{General caption.} \label{fig:1} ``` \end{figure} It worked for me!
12,588,318
I am currently getting a relative url route as a String via: ``` String url = controllers.directory.routes.Directory.viewOrganisation( org.id ).url(); ``` This works fine however I would like to get the full absolute url. I am sure this is simple, I just can't seem to find it. Alternatively, how can I get the current domain within a view to add to the relative url?
2012/09/25
[ "https://Stackoverflow.com/questions/12588318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534099/" ]
Indeed it is simple and it was also answered on the Stack Follow this question: [How to reverse generate an absolute URL from a route on Play 2 Java?](https://stackoverflow.com/questions/11158750/how-to-reverse-generate-a-url-from-a-route-on-play-2-java) In very general you need: ``` routes.MyController.myMethod().absoluteURL(request()); ```
For Scala programmer: in Play 2.2.x the absoluteURL is overloaded in this way: ``` def absoluteURL(secure: Boolean = false)(implicit request: RequestHeader): String ``` So if you write just ``` routes.MyController.myMethod().absoluteURL(request) ``` you'll get an error: ``` Overloaded method value [absoluteURL] cannot be applied to (play.api.mvc.Request[play.api.mvc.AnyContent]) ``` There are two options. You either declare the request as implicit: ``` def myMethod() = Action { implicit request => ... } ``` and get rid of the parameters entirely (you can do it, because the other has a default value): ``` routes.MyController.myMethod().absoluteURL() ``` or you have to specify both parameters explicitly. I'm writing this answer here, because the question is "How to get absolute route url as String In Play framework 2" and the accepted answer is for Java only. The Scala version has it's nuances.
160,837
The [Nightwalker](https://www.dndbeyond.com/monsters/nightwalker) has the “Life Eater” trait, which says (MToF, p. 216; emphasis mine): > > A creature reduced to 0 hit points from damage dealt by the nightwalker **dies and can't be revived** by any means short of a *wish* spell. > > > The demon lord [Juiblex](https://www.dndbeyond.com/monsters/juiblex) has the “Regeneration” trait, which says (MToF, p. 151; emphasis mine): > > Juiblex regains 20 hit points at the start of its turn. If it takes fire or radiant damage, this trait doesn't function at the start of its next turn. Juiblex **dies only if it starts its turn with 0 hit points and doesn't regenerate**. > > > Imagine that a Nightwalker hits Juiblex and reduces its HP to 0. What happens? Would Juiblex be dead, or can it regenerate?
2019/12/05
[ "https://rpg.stackexchange.com/questions/160837", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/38414/" ]
Juiblex lives ============= One of the core guiding principles in 5e is that the [specific overrules the general](https://www.dndbeyond.com/sources/basic-rules/introduction#SpecificBeatsGeneral): > > This book contains rules, especially in parts 2 and 3, that govern how the game plays. That said, many racial traits, class features, spells, magic items, monster abilities, and other game elements break the general rules in some way, creating an exception to how the rest of the game works. **Remember this: If a specific rule contradicts a general rule, the specific rule wins.** > > > To understand how to resolve this, it is important to understand the basic rules so you can see which parts are being changes. Normally [when you are reduced to 0 hp](https://www.dndbeyond.com/sources/basic-rules/combat#Droppingto0HitPoints), you are knocked unconscious: > > When you drop to 0 hit points, you either die outright or fall unconscious, as explained in the following sections. > > > ... > > > When damage reduces you to 0 hit points and there is damage remaining, you die if the remaining damage equals or exceeds your hit point maximum. > > > ... > > > If damage reduces you to 0 hit points and fails to kill you, you fall unconscious. > > > ... > > > Whenever you start your turn with 0 hit points, you must make a special saving throw, called a death saving throw, to determine whether you creep closer to death or hang onto life. > > > ... > > > On your third [failed death save], you die. > > > How do Juiblex and the Nightwalker modify these rules? ------------------------------------------------------ We can see that Juiblex is an exception to this rule, it "dies only if it starts its turn with 0 hit points and doesn't regenerate." This means that Juiblex will survive any number of failed death saves, so long as they can regenerate. The Nightwalker also overrides some of these rules. Usually when a creature is reduced to 0 hp it is unconscious, unless it suffers instant death, and then it has to fail 3 death saves to die. However when reduced to "0 hit points from damage dealt by the nightwalker dies and can't be revived by any means short of a wish spell." So what happens if Juiblex is reduced to 0 hp by a Nightwalker? --------------------------------------------------------------- Well, Juiblex modifies the instant death and saving throws part of the rules. But the Nightwalker modifies what happens when you are reduced to 0 hit points. The key point is that the Nightwalker's ability makes something die. Normally something that dies, becomes dead. However, Juiblex has a special ability that modifies this expectation. In this case, Juiblex's ability modifies the general rule, so Juiblex survives.
Juiblex lives to ooze again. ---------------------------- Normally, the Nightwalker's attack dropping someone to 0 HP would kill them instantly. However, Juiblex doesn't die because Juiblex can only die at the start of his own turn. Then at the start of his turn, he regenerates and doesn't die. Why does Juiblex's protection override the Nightwalker's instant-death effect? For the same reason it overrides the normal rule that a creature dies at 0 HP: because Juiblex can't die. If we resolved the situation in favor of Juiblex dying ("the rule says he dies, it doesn't say 'unless the creature is Juiblex'") then that ability would do literally nothing. We assume it's intended to do something, and that requires it to take precedence over mechanics that say Juiblex would die.
61,147,352
Whenever dynamically loading a class using the URLClassLoader I get a NoSuchMethodException when trying to execute a method with a custom data type as a parameter. It finds methods with standard types like String and int but not the custom type. **Loaded Class:** ``` public void execute(ProcessingData data){ System.out.println("entered execute(ProcessingData data"); ``` **Calling Class:** ``` URLClassLoader loader = new URLClassLoader(new URL[] {new File(alg.getPath()).toURI().toURL()}, AlgorithmLoader.class.getClassLoader()); // Load class into memory Class<?> algClass = Class.forName(className, true, loader); logger.logInfo("Loaded class. Attempting to invoke execute(data) on aircraft: "+ data.getFlightData().getAircraftId()); Method processMethod = null; try { Object obj = algClass.newInstance(); processMethod = algClass.getDeclaredMethod("execute", ProcessingData.class); processMethod.invoke(obj, data); } catch (final NoSuchMethodException exception) { logger.logInfo(exception.toString()); } loader.close(); ```
2020/04/10
[ "https://Stackoverflow.com/questions/61147352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7940371/" ]
The best solution would be to alter the styles with a class. This is typically how themes work. You set a class on the body that alters the things you want changed. ```js window.setTimeout( function () { document.body.classList.add("luckyGreen") }, 4000) window.setTimeout( function () { document.body.classList.remove("luckyGreen") }, 8000) ``` ```css pre { background-color: #CCC; } body.luckyGreen { color:green; } body.luckyGreen pre { background-color: #CFC; } ``` ```html <pre> Hello there </pre> X <pre> Hello there </pre> Y <pre> Hello there </pre> ``` But for some reason you want to alter a class, you can write a new css rule. ```js function addRule() { var styleEl = document.createElement('style'); document.head.appendChild(styleEl); var styleSheet = styleEl.sheet; var ruleStr = "pre { background-color: red; }" styleSheet.insertRule(ruleStr, styleSheet.cssRules.length); } window.setTimeout(addRule, 4000) ``` ```html <pre> Hello there </pre> X <pre> Hello there </pre> Y <pre> Hello there </pre> ```
In this case you need to use `getElementsByTagName` as follows: ``` var tags = document.getElementsByTagName("pre"); for(var i = 0; i < tags.length; i++) tags[i].style.color = "white"; ```
29,881,052
I just start to using angularjs and I want to display youtube thumbnail image from the youtube video url ... is there a way to display video thumbnail when people insert url in input and then click the button, ``` PLUNKER ``` <http://plnkr.co/edit/9SBbTaDONuNXvOQ7lkWe?p=preview>
2015/04/26
[ "https://Stackoverflow.com/questions/29881052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978703/" ]
Youtube provide default thumbnail image of its video. You can use below sample URL to create thumbnail image. ``` http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg ``` Where you need to search id from the given url & create url like above will give you thumbnail image. **Controller** ``` app.controller('MyCtrl', ['$scope', function($scope) { $scope.inputs = []; $scope.addInput = function() { $scope.inputs.push({ field: '' }); } $scope.removeInput = function(index) { $scope.inputs.splice(index, 1); } $scope.set2 = function($ayd) { var thumb = getParameterByName(this.input.ayd, 'v'), url = 'http://img.youtube.com/vi/' + thumb + '/default.jpg'; this.thumb = url } function getParameterByName(url, name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } } ]); ``` There many ways to do this, you can refer [**from here**](https://stackoverflow.com/a/2068371/2435473) [**Working Plunkr**](http://plnkr.co/edit/dPvWitN1LcDrrus1O3DV?p=preview) Here
this works for me :D ``` <video> <source [src]="yourvideo.mp4"> </video> ```
35,491,913
i am passing a url as a param value via URL. <http://www.domain1.com?url=http://domain.com> i would like to set conditions for adding additional param to a querystring of that passed url. (for example: if domain is 111.com, foo=123 should be added). i tried ``` $url = preg_replace('{http://www.111.com}','http://www.111.com?foo=111/',$_GET['url']); $url = preg_replace('{http://www.222.com}','http://www.222.com?foo2=222/',$_GET['url']); ``` but this is not working when there is a file name or other params. ....any assistance is appreciated.
2016/02/18
[ "https://Stackoverflow.com/questions/35491913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908654/" ]
`npm install -g graceful-fs graceful-fs@latest` works for me. This installs the latest version of graceful-fs!!
You don't need to worry about it and there's nothing wrong with the dependency as it only affects development. The gulp team is aware of the issue. > > We are aware of the graceful-fs deprecation warning upon install of gulp 3.x. > > > This is due to: > 1. our graceful-fs devDependency > 2. the vinyl-fs dependency > > > Both of which we are unable to upgrade due to API breaking changes. > > > There is nothing wrong with the dependency, especially since it is > only used in development. We will be updating or removing it in gulp 4 > and the message will go away. > > > <https://github.com/gulpjs/gulp/issues/1571>
38,879,470
I'm trying to make a program which checks if an entered number is a [happy number](https://en.wikipedia.org/wiki/Happy_number). My code finds each of the numbers after squaring and adding but when it reaches 1, i'd expect it to print "that is a happy number". I cant see anything wrong with the code but i could be missing something simple. Here is the code: ``` number = raw_input('What number?') dictionary = {} counter = 0 counter_2 = 0 while counter_2 < 20: counter_2 += 1 if number != 1: for n in str(number): n = int(n)**2 counter += 1 dictionary ['key{}'.format(counter)] = n added = sum(dictionary.values()) dictionary = {} number = str(added) print number else: print 'that is a happy number' ```
2016/08/10
[ "https://Stackoverflow.com/questions/38879470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6701353/" ]
avoid all that `Select`/`Selection` an refer to fully qualified ranges try this (commented) code: ``` Option Explicit Sub copytoarchive() Dim destSht As Worksheet Workbooks.Open ("C:\...\FileToCopyTo.xlsx") '<- at opening a workbook it becomes the active one Set destSht = ActiveWorkbook.Worksheets("Archive") '<-- set the destination worksheet in the activeworkbook With ThisWorkbook.Worksheets("DIC") '<--refer to your source worksheet in the workbook this macro resides in With .Range(.Range("A4:Q4"), .Range("A4:Q4").End(xlDown)) '<--| refer to your range whose values are to be copied destSht.Cells(destSht.Rows.Count, 1).End(xlUp).Offset(1).Resize(.Rows.Count, .Columns.Count).Value = .Value '<--| copy values in a equally sized range in destination worksheet starting at the first empty cell in column "A" End With End With destSht.Parent.Close True '<--| close the destination workbook, which is obtained as the Parent object of the destination worksheet End Sub ``` just change "C:...\FileToCopyTo.xlsx" with your actual destination workbook full path be aware that such a range as you selected may incur in an error should there be no filled rows below "A4:B4"
You can certainly copy a range from a closed workbook. <http://www.rondebruin.nl/win/s3/win024.htm> I don't believe you can save data to a closed workbook. I can't even imagine how that would work.
26,020,990
I have a problem when I pass data through from one function to a class that it is updating the data that I am passing in the origination class in even though I am not doing it by reference. ``` <?php namespace core\Test\Libraries; public function hasPurchasedCorrectProducts() { $testData = []; $testData['one'] = new \stdClass(); $testData['one']->qty = 2; (new \core\Libraries\Debug())->printData($testData, false); // see below #1 (new StupidTest())->test($testData); (new \core\Libraries\Debug())->printData($testData, false);exit; // see below #3 } } <?php namespace core\Test\Libraries; class StupidTest { private $availableProducts; public function test($availableProducts) { $this->availableProducts = $availableProducts; $this->availableProducts['one']->qty = ($this->availableProducts['one']->qty - 1) ; (new \core\Libraries\Debug())->printData($this->availableProducts, false); // see below #2 } } ``` 1 = ``` Array ( [one] => stdClass Object ( [qty] => 2 ) ) ``` 2 = ``` Array ( [one] => stdClass Object ( [qty] => 1 ) ) ``` 3 = ``` Array ( [one] => stdClass Object ( [qty] => 1 ) ) ``` How is $testData in #3 getting updated?
2014/09/24
[ "https://Stackoverflow.com/questions/26020990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/968337/" ]
You should be able to just use: ``` \File ``` Namespaces are relative to the namespace you declare for the class you are writing. Adding a "\" in front of a call to a class is saying that we want to look for this class in the root namespace which is just "\". The Laravel File class can be accessed this way because it is an alias that has an declared in the root namespace.
Assuming you have file something like that: ``` <?php namespace Chee\Image; class YourClass { public function method() { File::delete('path'); } } ``` you should add `use` directive: ``` <?php namespace Chee\Image; use Illuminate\Support\Facades\File; class YourClass { public function method() { File::delete('path'); } } ``` Otherwise if you don't use PHP is looking for `File` class in your current namespace so it is looking for `Chee\Image\File`. You could look at [How to use objects from other namespaces and how to import namespaces in PHP](https://stackoverflow.com/questions/24607045/difference-between-obj-new-arrayobject-obj-new-arrayobject) if you want
6,929,019
Can [F-Script](http://www.fscript.org/) be used to inspect iOS applications that are running on the simulator or iPhone/iPad hardware? If so, how do I attach the object browser to my custom objects?
2011/08/03
[ "https://Stackoverflow.com/questions/6929019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259912/" ]
I think it would make sense to store a schema update version in the database. The update script would read the current version and based on that, have it execute all of the previous update scripts in order until it is current. This would be a going-forward approach, since your old schema versions would not have the version number stored. If you could identify a distinguishing characteristic to each prior schema update - then it could still work. So, your update logic would have to be in a script and your release package would have to ship with all previous update sql files.
What I have done is maintain a dev copy of each database version, as it exists for a particular version, and use the redgate tools to generate the scripts I need. If I need a script to upgrade from V1.3 to V2.5, I pick those two databases and the scripts get generated. You might be able to do it all in a single script, but you'll need to do it by hand. Why not use a tool like redgate for this and make your life simple? <http://www.red-gate.com/products/sql-development/sql-compare/>
26,454,879
Can a textarea adapt it's height while inserting text? I want to hide the textarea's borders, so that users feel they'r typing in an unlimited space. (The textarea's height should be increased by height of one line when a new line starts) One way I guessed, is to; copy all texts into a div with same width on each keystroke, then measure the height of the div, then set the div's height for textarea. One problem I noticed, is scroll bars width that should be subtracted from main width, and on different devices we have 0 to 16px variable scroll bar width..., any suggestions?
2014/10/19
[ "https://Stackoverflow.com/questions/26454879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543240/" ]
Here is What you want First: html here is the text area with id : ta ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea rows="10" cols="10" id="ta"> </textarea> ``` And here is the jquery code which works as follows: which increases the height (the rows number) of the text area each time you get into the last line ```js $('#ta').keypress( function(){ var rows=$('#ta').attr('rows'); var text=$('#ta').val(); var lines=text.split('\n'); if(lines.length==rows){ rows++; $('#ta').attr('rows',rows); } }); ``` And this css just for hide the border of the textarea so the user feels that he/she writes in the page ```css #ta{ border: 0; } ```
You can easily achieve what you're trying to do using **[elastic.js](http://unwrongest.com/projects/elastic/)**, it's a simple one-line solution. ```js $('#note').elastic(); ``` ```css textarea#note { width:100%; display:block; resize: none; border: none; } textarea:focus { outline: none; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://jquery-elastic.googlecode.com/svn-history/r37/trunk/jquery.elastic.js"></script> <textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea> ```
38,597
I need to create a PDF file automatically (preferable via a batch process / command-line, the optimum would be something XSLT/SAXON-based). The PDF will have many pages (ca. 500), and each page contains nothing but a set of (partially overlapping) images (in scalable format, e.g. SVG or WMF). But there is only a basic set of ~20 images used for this, and the various pages differ one from another only in the particular choice out of these 20 images. The problem: If I use XSL-FO and feed it into the Apache FOP then the result is a PDF of approx. 300 MB file-size, because the image data is fed multiple times into the PDF. Now I am looking for a possibility to create a PDF in a way such that the image data of these 20 images are present only once in the PDF, and each PDF-page uses only "links"/references to this set of image data (so that the resulting PDF-file has only ~2MB file-size). I know that the PDF-language as such features such references, but of course, I am not interested to build a PDF-file directly, "low Level" ;-) Any help/ideas would be highly appreciated! Thanks a lot!
2017/01/06
[ "https://softwarerecs.stackexchange.com/questions/38597", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/28829/" ]
For any platform I cannot recommend [GIMP](https://www.gimp.org/) enough. * Cross Platform OS-X, Linux, Windows * Free, gratis & open source * Very powerful You can also extend it with a large number of plug-ins but I would recommend starting with [GMIC](http://gmic.eu/gimp.shtml)
For many years, the main alternative to Photoshop I have found is [Pixelmator](http://www.pixelmator.com/mac/), although the new kid on the block is [Affinity Photo](https://affinity.serif.com/photo/). Both are built for the Mac and are in the $30-40.
7,337
Puffer fish is known for having a anti-predation defense mechanism of having toxin-exuding spikes. Are there predators which evolved specifically to prey on puffer fish? (presumably, by evolving immunity to the toxin)? I know that sharks eat them, but I doubt sharks evolved to be immune specifically to puffer fish toxin, since their evolutionary development preceded puffer fish's.
2013/02/24
[ "https://biology.stackexchange.com/questions/7337", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/185/" ]
[Wikipedia](http://en.wikipedia.org/wiki/Tetraodontidae#Natural_defenses) has some revealing information here: > > Not all puffers are necessarily poisonous; Takifugu oblongus, for example, is a fugu puffer that is not poisonous, and *toxin level varies wildly even in fish that are*. A puffer's neurotoxin is not necessarily as toxic to other animals as it is to humans, and puffers are eaten routinely by some species of fish, such as lizardfish and tiger sharks. Also, Japanese fish farmers have grown nonpoisonous puffers by controlling their diet. > > > It seems that susceptibility to tetrodotoxin varies a lot from one animal to another, and so some natural variation might allow a reasonable amount of predation to occur. I also wonder whether the variation in the amount of toxin in the fish implies that the fish are often depleted. There are cases of animals who have evolved a resistance to Tetrodotoxin, but for the most part its may the predators you are thinking of. The toxin is synthesized by a symbiotic bacteria and is found not only in fugu but also blue-ringed octopus, rough-skinned newts and some sea slugs. These animals probably all began with enough intrinsically low sensitivity to the toxin to take on the symbiont and probably evolved to be completely insensitive. To find a predator that would have co-evolved a similar resistance you would look for a predator that particularly favors the envenomed animal. In the case of the rough skinned newt, [its suspected that the common garter snake is an example of such co-evolution](http://news.stanford.edu/news/2008/march12/newts-031208.html). Others may be out there to discover - its probably difficult to watch marine animals to know what their typical predators are.
I know there are species of sea snakes that actually aren't bothered by the puffer fish's toxins! So they will eat them easily because puffer fish are extremely slow swimmers. Besides that sharks are the only other species, in specific Tiger Sharks don't have any consequences to consuming pufferfish.
47,964,293
Let's say i have a java method: ``` private String (StringUtility stringUtil) { String maxValue = stringUtil.getMaxValue() } ``` Now, the StringUtility holds the maxValue and read it from configuration field loaded by Spring and **won't be changed during run time**. this method is going to be called every 1ms. So, if the maxVlue won't be changed once it was loaded, is there another way to pass it to the method instead to get it every time we call the method and avoid a load when calling the stringUtil every time just to get the maxValue? Thank you.
2017/12/24
[ "https://Stackoverflow.com/questions/47964293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2603808/" ]
Try this: ``` Array(0...9).map({String($0)}).map({ Character($0) }) ``` In the **code** above, we are taking each `Int` from `[Int]`, transform it into `String` using the String constructor/initializer (in order words we're applying the String initializer **(a function that takes something and returns a string)** to your `[Int]` using `map` an higher order function), once the first operation is over we'd get `[String]`, the second operation uses this new `[String]` and transform it to `[Character]`. if you wish to read more on string visit [here](https://developer.apple.com/documentation/swift/string). > > @LeoDabus proposes the following: > > > ``` Array(0...9).map(String.init).map(Character.init) //<-- no need for closure ``` Or instead of having two operations just like we did earlier, you can do it with a single iteration. `Array(0...9).map({Character("\($0)")})` > > @Alexander proposes the following > > > ``` Array((0...9).lazy.map{ String($0) }.map{ Character($0) }) (0...9).map{ Character(String($0)) } //<-- where you don't need an array, you'd use your range right away ```
``` func convertArray(array: [Int]) -> [Character] { return array.map { Character(String($0)) } } ```
1,904,782
I recently discovered that a method in a derived class can only access the base class's protected instance members through an instance of the derived class (or one of its subclasses): ``` class Base { protected virtual void Member() { } } class MyDerived : Base { // error CS1540 void Test(Base b) { b.Member(); } // error CS1540 void Test(YourDerived yd) { yd.Member(); } // OK void Test(MyDerived md) { md.Member(); } // OK void Test(MySuperDerived msd) { msd.Member(); } } class MySuperDerived : MyDerived { } class YourDerived : Base { } ``` I managed to work around this restriction by adding a static method to the base class, since Base's methods are allowed to access Base.Member, and MyDerived can call that static method. I still don't understand the reason for this limitation, though. I've seen a couple different explanations, but they fail to explain why MyDerived.Test() is still allowed to access MySuperDerived.Member. The Principled Explanation: *'Protected' means it's only accessible to that class and its subclasses. YourDerived **could** override Member(), creating a new method that should only be accessible to YourDerived and its subclasses. MyDerived can't call the overridden yd.Member() because it's not a subclass of YourDerived, and it can't call b.Member() because b might actually be an instance of YourDerived.* OK, but then why can MyDerived call msd.Member()? MySuperDerived could override Member(), and that override should only be accessible to MySuperDerived and its subclasses, right? You don't really know until runtime whether you're calling an overridden member or not. And when the member is a field, it can't be overridden anyway, but access is still forbidden. The Pragmatic Explanation: *Other classes might add invariants that your class doesn't know about, and you must use their public interface so they can maintain those invariants. If MyDerived could directly access protected members of YourDerived, it could break those invariants.* My same objection applies here. MyDerived doesn't know what invariants MySuperDerived might add, either -- it might be defined in a different assembly by a different author -- so why can MyDerived access its protected members directly? I get the impression that this compile-time limitation exists as a misguided attempt to solve a problem that can really only be solved at runtime. But maybe I'm missing something. Does anyone have an example of a problem that would be caused by letting MyDerived access Base's protected members through a variable of type YourDerived or Base, but does *not* exist already when accessing them through a variable of type MyDerived or MySuperDerived? -- UPDATE: I know the compiler is just following the language specification; what I want to know is the purpose of that part of the spec. An ideal answer would be like, "If MyDerived could call YourDerived.Member(), $NIGHTMARE would happen, but that can't happen when calling MySuperDerived.Member() because $ITSALLGOOD."
2009/12/15
[ "https://Stackoverflow.com/questions/1904782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231049/" ]
UPDATE: This question was the subject of my blog in January 2010. Thanks for the great question! See: <https://blogs.msdn.microsoft.com/ericlippert/2010/01/14/why-cant-i-access-a-protected-member-from-a-derived-class-part-six/> --- > > Does anyone have an example of a > problem that would be caused by > letting MyDerived access Base's > protected members through a variable > of type YourDerived or Base, but does > not exist already when accessing them > through a variable of type MyDerived > or MySuperDerived? > > > I am rather confused by your question but I am willing to give it a shot. If I understand it correctly, your question is in two parts. First, what attack mitigation justifies the restriction on calling protected methods through a less-derived type? Second, why does the same justification not motivate preventing calls to protected methods on equally-derived or more-derived types? The first part is straightforward: ``` // Good.dll: public abstract class BankAccount { abstract protected void DoTransfer(BankAccount destinationAccount, User authorizedUser, decimal amount); } public abstract class SecureBankAccount : BankAccount { protected readonly int accountNumber; public SecureBankAccount(int accountNumber) { this.accountNumber = accountNumber; } public void Transfer(BankAccount destinationAccount, User user, decimal amount) { if (!Authorized(user, accountNumber)) throw something; this.DoTransfer(destinationAccount, user, amount); } } public sealed class SwissBankAccount : SecureBankAccount { public SwissBankAccount(int accountNumber) : base(accountNumber) {} override protected void DoTransfer(BankAccount destinationAccount, User authorizedUser, decimal amount) { // Code to transfer money from a Swiss bank account here. // This code can assume that authorizedUser is authorized. // We are guaranteed this because SwissBankAccount is sealed, and // all callers must go through public version of Transfer from base // class SecureBankAccount. } } // Evil.exe: class HostileBankAccount : BankAccount { override protected void Transfer(BankAccount destinationAccount, User authorizedUser, decimal amount) { } public static void Main() { User drEvil = new User("Dr. Evil"); BankAccount yours = new SwissBankAccount(1234567); BankAccount mine = new SwissBankAccount(66666666); yours.DoTransfer(mine, drEvil, 1000000.00m); // compilation error // You don't have the right to access the protected member of // SwissBankAccount just because you are in a // type derived from BankAccount. } } ``` Dr. Evil's attempt to steal ONE... MILLION... DOLLARS... from your swiss bank account has been foiled by the C# compiler. Obviously this is a silly example, and obviously, fully-trusted code could do anything it wants to your types -- fully-trusted code can start up a debugger and change the code as its running. Full trust means *full* trust. Don't actually design a real security system this way! But my point is simply that the "attack" that is foiled here is someone attempting to do an end-run around the invariants set up by SecureBankAccount, to access the code in SwissBankAccount directly. That answers your first question, I hope. If that's not clear, let me know. Your second question is "Why doesn't SecureBankAccount also have this restriction?" In my example, SecureBankAccount says: ``` this.DoTransfer(destinationAccount, user, amount); ``` Clearly "this" is of type SecureBankAccount or something more derived. It could be any value of a more derived type, including a new SwissBankAccount. Couldn't SecureBankAccount be doing an end-run around SwissBankAccount's invariants? Yes, absolutely! And because of that, the authors of SwissBankAccount are *required* to *understand* everything that their base class does! You can't just go deriving from some class willy-nilly and hope for the best! The implementation of your base class is allowed to call the set of protected methods exposed by the base class. If you want to derive from it then you are required to read the documentation for that class, or the code, and understand under what circumstances your protected methods will be called, and write your code accordingly. *Derivation is a way of sharing implementation details; if you don't understand the implementation details of the thing you are deriving from then don't derive from it.* And besides, the base class is always written *before* the derived class. The base class isn't up and changing on you, and presumably you trust the author of the class to not attempt to break you sneakily with a future version. (Of course, a change to a base class can always cause problems; this is yet another version of the brittle base class problem.) The difference between the two cases is that when you derive from a base class, you have the behaviour of *one* class *of your choice* to understand and trust. That is a tractable amount of work. The authors of SwissBankAccount are required to precisely understand what SecureBankAccount guarantees to be invariant before the protected method is called. But they should not have to understand and trust *every possible behaviour* of *every possible cousin class* that just happens to be derived from the same base class. Those guys could be implemented by anyone and do anything. You would have no ability whatsoever to understand any of their pre-call invariants, and therefore you would have no ability to successfully write a working protected method. Therefore, we save you that bother and disallow that scenario. And besides, we *have* to allow you to call protected methods on receievers of potentially more-derived classes. Suppose we didn't allow that and deduce something absurd. Under what circumstances could a protected method *ever* be called, if we disallowed calling protected methods on receivers of potentially-more-derived classes? The only time you could ever call a protected method in that world is if you were calling your own protected method from a sealed class! Effectively, protected methods could almost *never* be called, and the implementation that was called would always be the most derived one. What's the point of "protected" in that case? Your "protected" means the same thing as "private, and can only be called from a sealed class". That would make them rather less useful. So, the short answer to both your questions is "because if we didn't do that, it would be impossible to use protected methods at all." We restrict calls through less-derivedtypes because if we don't, it's impossible to safely *implement* any protected method that depends on an invariant. We allow calls through potential subtypes because if we do not allow this, then *we don't allow hardly any calls at all*. Does that answer your questions?
<http://msdn.microsoft.com/en-us/library/bcd5672a.aspx> > > A protected member of a base class is > accessible in a derived class **only** if > the access occurs through the derived > class type. > > > There's documentation of the "what?" question. Now I wish I knew "Why?" :) Clearly `virtual` has nothing to do with this access restriction. Hmm, I think you're on to something with the sibling thing... MyDerived shouldn't be able to call YourDerived.Member If MyDerived can call Base.Member, it might actually be working on an instance of YourDerived and might actually be calling YourDerived.Member Ah, here is the same question: [C# protected members accessed via base class variable](https://stackoverflow.com/questions/1836175/c-protected-members-accessed-via-base-class-variable/1836932#1836932)
58,007,014
My flutter app sends a http request to my google-app-engine backend. In this request, a user's vote on a simple either-or-question is send and then stored in a mysql database. When that is done, the user sees another question and again votes. So, question, voting, question, voting, question, voting and so on. Now, the user is not supposed to see the same question twice. Therefor, my mysql query that gets another question has a condition saying "download a question that user hasnt voted for yet". This works perfectly in like 99% of the cases. But in rare cases it happens that the user sees the same question again and again in a row for like 4 or 5 times, which tells me that my app might download the "next" question (which, in this case is the same question again) before the vote was stored in my database. To debug this, I am trying to understand the technical stuff going on in background. Specifically, I need to know when the 200 statuscode fires after my app has send a users vote in a request. This is my serverside part when a voting is send: else if (operation.equals("voteFav")){ ``` out.println("vote received"); // get userID and favID Integer userID = Integer.valueOf(request.getParameter("userID")); String creatorID = request.getParameter("creatorID"); Integer favID = Integer.valueOf(request.getParameter("favID")); String voter = request.getParameter("voterName"); String winpic = request.getParameter("winpic"); try{ Connection conn = DriverManager.getConnection(mysqlUrl); PreparedStatement ps; ResultSet rs; String query; // prepare Statement if(winpic.equals("1")) query = "INSERT INTO faved (favID, userID, voting) VALUES (?,?,1)"; else if(winpic.equals("2")) query = "INSERT INTO faved (favID, userID, voting) VALUES (?,?,2)"; else query = "INSERT INTO faved (favID, userID, voting) VALUES (?,?,-1)"; ps = conn.prepareStatement(query); ps.setInt(1, favID); ps.setInt(2, userID); // send vote to database ps.execute(); ps.close(); // close connection out.flush(); conn.close(); } catch (Exception e) { out.print("Fehler voting: " + e); out.flush(); } } ``` My question is: When does clientside statusCode 200 fire? Does it fire immediately when I use the PrintWriter to write back "vote received" in the first line? Or does it only fire when I close the connection? Hope it gets clear :)
2019/09/19
[ "https://Stackoverflow.com/questions/58007014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9372863/" ]
I come late but have more info for future readers. I just met this bug in my App for iOS 11 and iOS 12. The bug is solved by Apple since iOS 13.0. So if you support previous version, you still need to apply the workaround from @AlanS, or not use custom colors in storyboard and xib : ``` func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if #available(iOS 13.0, *) { // Fix iOS 12 storyboard color bug. } else { view.backgroundColor = UIColor.black } } ```
Faced with this issue recently I had xib file for table cell and custom colors in xcasset. Colors are single appearance (dark mode not supported). In cell swift class I have bool variable with didSet, where few outlets are modified: view.backgroundColor and label.textColor. Their values are based on variable value. There are ternar conditions so I was sure that color will be selected correctly. On devices with iOS 12 (checked on 12.1 and 12.4 real and simulators) color didn't change at start but only after cell reuse. After finding this question and few experiments, I have found that: Setting custom color in xib file (no matter, if they have dark version or not) was performed after my didSet block and overrides my conditions results. And since I have set one of possible color in xib, I though that problem in data. So I have reset outlets colors to default in xib and now it works In case if you have to display some default color before some conditions, I guess putting it in init methods (awakeFromNib, viewDidLoad etc) should work This bug was fixed in 13.0+ Duplicating answer from <https://developer.apple.com/forums/thread/649009>
44,141,165
I have a file that I want to import into a database table, but I want to have a piece in each row. In the import, I need to indicate for each row the offset (first byte) and length (number of bytes) I have the following files: ``` *line_numbers.txt* -> Each row contains the number of the last row of a record in *plans.txt*. *plans.txt* -> All the information required for all the rows. ``` I have the following code: ``` #Starting line number of the record sLine=0 #Starting byte value of the record offSet=0 while read line do endByte=`awk -v fline=${sLine} -v lline=${line} \ '{if (NR > fline && NR < lline) \ sum += length($0); } \ END {print sum}' plans.txt` echo "\"plans.txt.${offSet}.${endByte}/\"" >> lobs.in sLine=$((line+1)) offSet=$((endByte+offSet)) done < line_numbers.txt ``` This code will write in the file *lobs.in* something similar to: ``` "plans.txt.0.504/" "plans.txt.505.480/" "plans.txt.984.480/" "plans.txt.1464.1159/" "plans.txt.2623.515/" ``` This means, for example, that the first record starts at byte *0* and continues for the next *504* bytes. The next starts at byte *505* and continues for the next *480* bytes. I still have to run more tests, but It seems to be working. My problem is It is very very slow for the volume I need to process. Do you have any performance tips? I looked in a way to insert the loop in `awk`, but I need 2 input files and I don't know how to process It without the while. Thank you!
2017/05/23
[ "https://Stackoverflow.com/questions/44141165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054688/" ]
Awsome question, I wondered about the same thing recently, thanks! I did it, with **tabulizer** `‘0.2.2’` as @hrbrmstr also suggests. If you are using *R > 3.5.x*, I'm providing following solution. Install the three packages in specific order: ``` # install.packages("rJava") # library(rJava) # load and attach 'rJava' now # install.packages("devtools") # devtools::install_github("ropensci/tabulizer", args="--no-multiarch") ``` ***Update:*** After just testing the approach again, it looks like it's enough to just do `install.packages("tabulizer")` now. `rJava` will be installed automatically as a dependency. Now you are ready to extract tables from your PDF reports. ``` library(tabulizer) ## load report l <- "https://sedl.org/afterschool/toolkits/science/pdf/ast_sci_data_tables_sample.pdf" m <- extract_tables(l, encoding="UTF-8")[[2]] ## comes as a character matrix ## Note: peep into `?extract_tables` for further specs (page, location etc.)! ## use first row as column names dat <- setnames(type.convert(as.data.frame(m[-1, ]), as.is=TRUE), m[1, ]) ## example-specific date conversion dat$Date <- as.POSIXlt(dat$Date, format="%m/%d/%y") dat <- within(dat, Date$year <- ifelse(Date$year > 120, Date$year - 100, Date$year)) dat ## voilà # Speed (mph) Driver Car Engine Date # 1 407.447 Craig Breedlove Spirit of America GE J47 1963-08-05 # 2 413.199 Tom Green Wingfoot Express WE J46 1964-10-02 # 3 434.220 Art Arfons Green Monster GE J79 1964-10-05 # 4 468.719 Craig Breedlove Spirit of America GE J79 1964-10-13 # 5 526.277 Craig Breedlove Spirit of America GE J79 1965-10-15 # 6 536.712 Art Arfons Green Monster GE J79 1965-10-27 # 7 555.127 Craig Breedlove Spirit of America, Sonic 1 GE J79 1965-11-02 # 8 576.553 Art Arfons Green Monster GE J79 1965-11-07 # 9 600.601 Craig Breedlove Spirit of America, Sonic 1 GE J79 1965-11-15 # 10 622.407 Gary Gabelich Blue Flame Rocket 1970-10-23 # 11 633.468 Richard Noble Thrust 2 RR RG 146 1983-10-04 # 12 763.035 Andy Green Thrust SSC RR Spey 1997-10-15 ``` Hope it works for you. **Limitations:** Of course, the table in this example is quite simple and maybe you have to mess around with `gsub` and this kind of stuff.
Here is a different approach that works well on the PDF "https://sedl.org/afterschool/toolkits/science/pdf/ast\_sci\_data\_tables\_sample.pdf". You have the result of the output below. ``` library(RDCOMClient) path_PDF <- "C:\\ast_sci_data_tables_sample.pdf" path_Word <- "C:\\Temp.docx" #################################################################### #### Step 1 : We use the OCR of Word to convert the PDF in word #### #################################################################### wordApp <- COMCreate("Word.Application") wordApp[["Visible"]] <- TRUE wordApp[["DisplayAlerts"]] <- FALSE doc <- wordApp[["Documents"]]$Open(normalizePath(path_PDF), ConfirmConversions = FALSE) doc$SaveAs2(path_Word) ############################################################## #### Step 2 : We extract the table from the word document #### ############################################################## nb_Tables <- doc$tables()$count() list_Table <- list() for(l in 1 : nb_Tables) { print(l) nb_Row <- doc$tables(l)$Rows()$Count() nb_Col <- doc$tables(l)$Columns()$Count() mat_Temp <- matrix(NA, nrow = nb_Row, ncol = nb_Col) for(i in 1 : nb_Row) { for(j in 1 : nb_Col) { mat_Temp[i, j] <- tryCatch(doc$tables(l)$cell(i, j)$range()$text(), error = function(e) NA) } } list_Table[[l]] <- mat_Temp } list_Table [[1]] [,1] [,2] [1,] " Number of Coils \r\a" " Number of Paperclips\r\a" [2,] "5 \r\a" "3, 5, 4\r\a" [3,] " 10 \r\a" " 7, 8, 6\r\a" [4,] " 15 \r\a" "\t \t11, 10, 12\r\a" [5,] " 20 \r\a" "\t \t15, 13, 14\r\a" [[2]] [,1] [,2] [,3] [,4] [1,] "Speed (mph)\r\a" "Driver\r\a" "Car\r\a" "Engine\r\a" [2,] "407.447\r\a" "Craig Breedlove\r\a" "Spirit of America \r\a" "GE J47\r\a" [3,] "413.199\r\a" "Tom Green \r\a" "Wingfoot Express \r\a" "WE J46 \r\a" [4,] "434.22\r\a" "Art Arfons\r\a" "Green Monster \r\a" "GE J79 \r\a" [5,] "468.719\r\a" "Craig Breedlove\r\a" "Spirit of America\r\a" "GE J79 \r\a" [6,] "526.277\r\a" "Craig Breedlove\r\a" "Spirit of America\r\a" "GE J79 \r\a" [7,] "536.712\r\a" "Art Arfons\r\a" "Green Monster \r\a" "GE J79 \r\a" [8,] "555.127\r\a" "Craig Breedlove\r\a" "Spirit of America, Sonic 1 \r\a" "GE J79 \r\a" [9,] "576.553\r\a" "Art Arfons\r\a" "Green Monster \r\a" "GE J79 \r\a" [10,] "600.601\r\a" "Craig Breedlove\r\a" "Spirit of America, Sonic 1\r\a" "GE J79 \r\a" [11,] "622.407\r\a" "Gary Gabelich\r\a" "Blue Flame \r\a" "Rocket \r\a" [12,] "633.468\r\a" "Richard Noble \r\a" "Thrust 2 \r\a" "RR RG 146 \r\a" [13,] "763.035\r\a" "Andy Green\r\a" "Thrust SSC\r\a" "RR Spey\r\a" [14,] "\r\a" "\r\a" "\r\a" NA [,5] [1,] "Date\r\a" [2,] "8/5/63\r\a" [3,] "10/2/64\r\a" [4,] "10/5/64\r\a" [5,] "10/13/64\r\a" [6,] "10/15/65\r\a" [7,] "10/27/65\r\a" [8,] "11/2/65 \r\a" [9,] "11/7/65 \r\a" [10,] "11/15/65 \r\a" [11,] "10/23/70 \r\a" [12,] "10/4/83 \r\a" [13,] "10/15/97\r\a" [14,] NA [[3]] [,1] [,2] [1,] " Time (drops of water) \r\a" " Distance (cm)\r\a" [2,] "\t \t1 \r\a" " 10,11,9\r\a" [3,] "\t \t2 \r\a" " 29, 31, 30\r\a" [4,] "\t \t3 \r\a" " 59, 58, 61\r\a" [5,] "\t \t4 \r\a" " 102, 100, 98\r\a" [6,] "\t \t5 \r\a" " 122, 125, 127 \r\a" ```
15,314,781
I want to try and get the latest movie I checked on the IcheckMovies site and display it on my website. I don't know how, I've read about php\_get\_contents() and then getting an element but the specific element I want is rather deep in the DOM-structure. Its in a div in a div in a list in a ... So, this is the link I want to get my content from: <http://www.icheckmovies.com/profiles/robinwatchesmovies> and I want to get the first title of the movie in the list. Thanks so much in advance! EDIT: So using the file\_get\_contents() method ``` <?php $html = file_get_contents('http://www.icheckmovies.com/profiles/robinwatchesmovies/'); echo $html; ?> ``` I got this html output. Now, I just need to get 'Smashed' so the content of the href link inside the h3 inside a div inside a div inside a list. This is where I don't know how to get it. ``` ... <div class="span-7"> <h2>Checks</h2> <ol class="itemList"> <li class="listItem listItemSmall listItemMovie movie"> <div class="listImage listImageCover"> <a class="dvdCoverSmall" title="View detailed information on Smashed (2012)" href="/movies/smashed/"></a> <div class="coverImage" style="background: url(/var/covers/small/10/1097928.jpg);"></div> </div> <h3> <a title="View detailed information on Smashed (2012)" href="/movies/smashed/">Smashed</a> </h3> <span class="info">6 days ago</span> </li> <li class="listItem listItemSmall listItemMovie movie"> <li class="listItem listItemSmall listItemMovie movie"> </ol> <span> </div> ... ```
2013/03/09
[ "https://Stackoverflow.com/questions/15314781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401273/" ]
``` import re with open('myLargeFile.txt', 'r') as myFile: numbersList = re.findall('{"number":(\d{9})', myFile.read(), re.DOTALL) print numbersList ``` This will create a list that only contains 9 digit numbers that appear after the string `{"number":` If the numbers you are looking for might have more or less then 9 digits, use this reg ex instead: ``` numbersList = re.findall('{"number":(\d{x,y})', myFile.read(), re.DOTALL) ``` , and replace x and y to fit your needs. x stands for the lowest number of digits that the numbers are allowed to have, and y for the highest. For example, if you want to find all numbers that have in between 5 and 9 digits, the reg ex would become: ``` numbersList = re.findall('{"number":(\d{5,9})', myFile.read(), re.DOTALL) ```
``` import re s = '76360247039795},{"number":522141635,"catalog"' nl = re.findall('"number":(\d{9})', s) ```
22,487,878
I'm receiving a JSON package like: ``` { "point_code" : { "guid" : "f6a0805a-3404-403c-8af3-bfddf9d334f2" } } ``` I would like to tell Rails that both `point_code` and `guid` are required, not just permitted. This code seems to work but I don't think it's good practice since it returns a string, not the full object: ``` params.require(:point_code).require(:guid) ``` Any ideas how I could do this?
2014/03/18
[ "https://Stackoverflow.com/questions/22487878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563762/" ]
OK, ain't pretty but should do the trick. Assume you have params :foo, :bar and :baf you'd like to require all for a Thing. You could say ``` def thing_params [:foo, :bar, :baf].each_with_object(params) do |key, obj| obj.require(key) end end ``` `each_with_object` returns obj, which is initialized to be params. Using the same params obj you require each of those keys in turn, and return finally the object. Not pretty, but works for me.
This question came up in my google search for a different case ie, when using a "multiple: true" as in: ``` <%= form.file_field :asset, multiple: true %> ``` Which is a totally different case than the question. However, in the interest of helping out here is a working example in Rails 5+ of that: ``` form_params = params.require(:my_profile).permit({:my_photos => []}) ```
29,261,917
I'm just learning how to use python and lists. I have a sample list like the one below. ``` list = [['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Ferrari','150,000','10,000km'],['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Porsche','200,210','10,000km'],['Ferrari','110,000','10,000km'],['Porsche','400,000','10,000km'], ``` I'm trying to run a loop that checks if the 2nd element in each nested list is greater than 350,000, then prints the car, price, and mileage if it is. I've used different `for` loops with an `if` statement inside of it, but can't figure it out.
2015/03/25
[ "https://Stackoverflow.com/questions/29261917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2266768/" ]
Firstly do not name your variable `list` as it shadows the builtin. This is a very simple approach of solving your problem ``` >>> l = [['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Ferrari','150,000','10,000km'],['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Porsche','200,210','10,000km'],['Ferrari','110,000','10,000km'],['Porsche','400,000','10,000km']] >>> for i in l: ... if (int(i[1].replace(',','')) > 350000): # Remove all the , in your string and type cast it to an integer ... print i ... ['Porsche', '400,000', '10,000km'] ``` You can do it in a list comprehension as in `[i for i in l if int(i[1].replace(',','')) > 350000 ]` which will do everything for you in a single line
The answer above is excellent, though for anyone just starting out with programming in general you may be confused with the following: ``` int(`i[1]`.replace(',','')) ``` What that is doing is taking your item in the list, for example `['Porsche', '400,000', '10,000km']`, and next if finds the second element in that list which in this case is `'400,000'`. It does this with `i[1]`. You now have found the element you want to check if its larger than 350,000. However, the element you have is a string, not a number. You must convert this string to a integer. The first step in doing this is to remove the special characters (the commas). The function `.replace(',','')` does this by looking for ',' and replacing with nothing (effectively removing anything with a ','). At this point you have a string without any special characters in it, you have taken '400,000' and turned it into '400000'. You now have to turn it into a integer for python to understand whether or not its smaller or larger than 350000. Thankfully, python makes this very easy. The function `int()` does all the work. Specifically, `int('400000')` turns '400000' into 40000. You may now compare 400000 to 350000 and move along with your day.
41,452,847
I need to make a function that reads a string input and converts the odd indexed characters in the string to upperCase and the even ones to lowerCase. ``` function alternativeCase(string){ for(var i = 0; i < string.length; i++){ if (i % 2 != 0) { string[i].toUpperCase(); } else { string[i].toLowerCase(); } } return string; } ``` How to fix my code?
2017/01/03
[ "https://Stackoverflow.com/questions/41452847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7317826/" ]
``` function alternativeCase(string){ return string.split('').map(function(c,i) { return i & 1 ? c.toUpperCase() : c.toLowerCase(); }).join(''); } ``` --- ### Update 2019 These days it's pretty safe to use ES6 syntax: ```js const alternativeCase = string => string.split('') .map((c,i) => i & 1 ? c.toUpperCase() : c.toLowerCase()).join(''); ```
Strings in JavaScript are immutable, Try this instead: ```js function alternativeCase(string){ var newString = []; for(var i = 0; i < string.length; i++){ if (i % 2 != 0) { newString[i] = string[i].toUpperCase(); } else { newString[i] = string[i].toLowerCase(); } } return newString.join(''); } ```
65,805,249
I want to update the UI whenever a new document is added to a collection: this is the tricky part because using this code: ``` db.collection("Messages").addSnapshotListener { querySnapshot, error in guard let snapshot = querySnapshot else { print("Error fetching snapshots: \(error!)") return } snapshot.documentChanges.forEach { diff in if (diff.type == .added) { print("New document: \(diff.document.data())") } } } ``` I receive all of the documents of the collection firsthand. So how can I update the view depending on which document is added?
2021/01/20
[ "https://Stackoverflow.com/questions/65805249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14220454/" ]
``` cartItem.map((food,index)=> { if(food.food_id == newFoodItem.food_id && food.id == newFoodItem.id){ const AllFoodData = cartItem AllFoodData[index] = newFoodItem AsyncStorage.setItem('@Add_cart_Item', JSON.stringify(AllFoodData)) .then(() => {}) .catch(err => console.log(err)) ToastAndroid.showWithGravityAndOffset('Cart Replace Successfully',ToastAndroid.LONG,ToastAndroid.BOTTOM,25,50 ) } }) ```
So basically what i want to achieve here is to add the msg object to the existing Messages Array. Since lsitings is an Array of objects using the `.map` i can spread through each object and check if the id of that object is each to my `msg.id`. if that is true then i want to return a copy the that specific listing and edit the Messages Array within `[msg, ...item.Messages]` otherwise return the existing item. ``` setListings(listings=> listings.map(item => { if(item.id === msg.id) { return { ...item, Messages: [msg, ...item.Messages] } } return item; })); }); ```
72,479,232
This shader works on laptop but for some reason it keeps failing on mobile I assume i'm doing something wrong with the precision but i don't know what here is the error: > > THREE.WebGLProgram: shader error: 0 35715 false gl.getProgramInfoLog > invalid shaders THREE.WebGLShader: gl.getShaderInfoLog() fragment > 0:434: S0032: no default precision defined for variable 'float[4]'1: > #version 300 es 2: #define varying in 3: out highp vec4 pc\_fragColor; > > > and here is the shader code in the js tab: <https://codepen.io/uiunicorn/pen/QWQrQBB> full: ``` export const terrain_shader = (function() { const _VS_1 = ` // Triplanar Attributes in vec4 weights1; in vec4 weights2; // Outputs out vec3 vCoords; out vec4 vWeights1; out vec4 vWeights2; `; const _VS_2 = ` vCoords = transformed.xyz; vWeights1 = weights1; vWeights2 = weights2; `; const _VS = ` // Attributes in vec3 coords; in vec3 color; in vec4 weights1; in vec4 weights2; // Outputs out vec2 vUV; out vec4 vColor; out vec3 vNormal; out vec3 vCoords; out vec4 vWeights1; out vec4 vWeights2; void main(){ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); vUV = uv; vNormal = normal; vColor = vec4(color, 1); vCoords = position.xyz; vWeights1 = weights1; vWeights2 = weights2; } `; const _PS = ` precision highp float; precision highp int; precision highp sampler2DArray; uniform sampler2DArray TRIPLANAR_normalMap; uniform sampler2DArray TRIPLANAR_diffuseMap; uniform sampler2D TRIPLANAR_noiseMap; in vec3 vCoords; in vec4 vWeights1; in vec4 vWeights2; const float _TRI_SCALE = 10.0; float sum( vec3 v ) { return v.x+v.y+v.z; } vec4 hash4( vec2 p ) { return fract( sin(vec4(1.0+dot(p,vec2(37.0,17.0)), 2.0+dot(p,vec2(11.0,47.0)), 3.0+dot(p,vec2(41.0,29.0)), 4.0+dot(p,vec2(23.0,31.0))))*103.0); } vec4 _TerrainBlend_4(vec4 samples[4]) { float depth = 0.2; float ma = max( samples[0].w, max( samples[1].w, max(samples[2].w, samples[3].w))) - depth; float b1 = max(samples[0].w - ma, 0.0); float b2 = max(samples[1].w - ma, 0.0); float b3 = max(samples[2].w - ma, 0.0); float b4 = max(samples[3].w - ma, 0.0); vec4 numer = ( samples[0] * b1 + samples[1] * b2 + samples[2] * b3 + samples[3] * b4); float denom = (b1 + b2 + b3 + b4); return numer / denom; } vec4 _TerrainBlend_4_lerp(vec4 samples[4]) { return ( samples[0] * samples[0].w + samples[1] * samples[1].w + samples[2] * samples[2].w + samples[3] * samples[3].w); } // Lifted from https://www.shadertoy.com/view/Xtl3zf vec4 texture_UV(in sampler2DArray srcTexture, in vec3 x) { float k = texture(TRIPLANAR_noiseMap, 0.0025*x.xy).x; // cheap (cache friendly) lookup float l = k*8.0; float f = fract(l); float ia = floor(l+0.5); // suslik's method (see comments) float ib = floor(l); f = min(f, 1.0-f)*2.0; vec2 offa = sin(vec2(3.0,7.0)*ia); // can replace with any other hash vec2 offb = sin(vec2(3.0,7.0)*ib); // can replace with any other hash vec4 cola = texture(srcTexture, vec3(x.xy + offa, x.z)); vec4 colb = texture(srcTexture, vec3(x.xy + offb, x.z)); return mix(cola, colb, smoothstep(0.2,0.8,f-0.1*sum(cola.xyz-colb.xyz))); } vec4 _Triplanar_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec4 dx = texture_UV(tex, vec3(pos.zy / _TRI_SCALE, texSlice)); vec4 dy = texture_UV(tex, vec3(pos.xz / _TRI_SCALE, texSlice)); vec4 dz = texture_UV(tex, vec3(pos.xy / _TRI_SCALE, texSlice)); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); return dx * weights.x + dy * weights.y + dz * weights.z; } vec4 _TriplanarN_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { // Tangent Reconstruction // Triplanar uvs vec2 uvX = pos.zy; // x facing plane vec2 uvY = pos.xz; // y facing plane vec2 uvZ = pos.xy; // z facing plane // Tangent space normal maps vec3 tx = texture_UV(tex, vec3(uvX / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 ty = texture_UV(tex, vec3(uvY / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 tz = texture_UV(tex, vec3(uvZ / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); // Get the sign (-1 or 1) of the surface normal vec3 axis = sign(normal); // Construct tangent to world matrices for each axis vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0))); vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x; mat3 tbnX = mat3(tangentX, bitangentX, normal); vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y))); vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y; mat3 tbnY = mat3(tangentY, bitangentY, normal); vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0))); vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z; mat3 tbnZ = mat3(tangentZ, bitangentZ, normal); // Apply tangent to world matrix and triblend // Using clamp() because the cross products may be NANs vec3 worldNormal = normalize( clamp(tbnX * tx, -1.0, 1.0) * weights.x + clamp(tbnY * ty, -1.0, 1.0) * weights.y + clamp(tbnZ * tz, -1.0, 1.0) * weights.z ); return vec4(worldNormal, 0.0); } vec4 _Triplanar(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec4 dx = texture(tex, vec3(pos.zy / _TRI_SCALE, texSlice)); vec4 dy = texture(tex, vec3(pos.xz / _TRI_SCALE, texSlice)); vec4 dz = texture(tex, vec3(pos.xy / _TRI_SCALE, texSlice)); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); return dx * weights.x + dy * weights.y + dz * weights.z; } vec4 _TriplanarN(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec2 uvx = pos.zy; vec2 uvy = pos.xz; vec2 uvz = pos.xy; vec3 tx = texture(tex, vec3(uvx / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 ty = texture(tex, vec3(uvy / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 tz = texture(tex, vec3(uvz / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 weights = abs(normal.xyz); weights *= weights; weights = weights / (weights.x + weights.y + weights.z); vec3 axis = sign(normal); vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0))); vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x; mat3 tbnX = mat3(tangentX, bitangentX, normal); vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y))); vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y; mat3 tbnY = mat3(tangentY, bitangentY, normal); vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0))); vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z; mat3 tbnZ = mat3(tangentZ, bitangentZ, normal); vec3 worldNormal = normalize( clamp(tbnX * tx, -1.0, 1.0) * weights.x + clamp(tbnY * ty, -1.0, 1.0) * weights.y + clamp(tbnZ * tz, -1.0, 1.0) * weights.z); return vec4(worldNormal, 0.0); } void main() { vec3 worldPosition = vCoords; float weightIndices[4] = float[4](vWeights1.x, vWeights1.y, vWeights1.z, vWeights1.w); float weightValues[4] = float[4](vWeights2.x, vWeights2.y, vWeights2.z, vWeights2.w); // TRIPLANAR SPLATTING w/ NORMALS & UVS vec3 worldSpaceNormal = normalize(vNormal); vec4 diffuseSamples[4]; vec4 normalSamples[4]; for (int i = 0; i < 4; ++i) { vec4 d = vec4(0.0); vec4 n = vec4(0.0); if (weightValues[i] > 0.0) { d = _Triplanar_UV( worldPosition, worldSpaceNormal, weightIndices[i], TRIPLANAR_diffuseMap); n = _TriplanarN_UV( worldPosition, worldSpaceNormal, weightIndices[i], TRIPLANAR_normalMap); d.w *= weightValues[i]; n.w = d.w; } diffuseSamples[i] = d; normalSamples[i] = n; } vec4 diffuseBlended = _TerrainBlend_4(diffuseSamples); vec4 normalBlended = _TerrainBlend_4(normalSamples); vec3 diffuse = diffuseBlended.xyz; vec3 finalColour = diffuse; // finalColour = vec3(sin(worldPosition.x), sin(worldPosition.y), sin(worldPosition.z)); gl_FragColor = vec4(finalColour, 1); } `; const _PS_1 = ` precision mediump sampler2DArray; uniform sampler2DArray TRIPLANAR_normalMap; uniform sampler2DArray TRIPLANAR_diffuseMap; uniform sampler2D TRIPLANAR_noiseMap; in vec3 vCoords; in vec4 vWeights1; in vec4 vWeights2; const float _TRI_SCALE = 10.0; float sum( vec3 v ) { return v.x+v.y+v.z; } vec4 hash4( vec2 p ) { return fract( sin(vec4(1.0+dot(p,vec2(37.0,17.0)), 2.0+dot(p,vec2(11.0,47.0)), 3.0+dot(p,vec2(41.0,29.0)), 4.0+dot(p,vec2(23.0,31.0))))*103.0); } vec4 _TerrainBlend_4(vec4 samples[4]) { float depth = 0.2; float ma = max( samples[0].w, max( samples[1].w, max(samples[2].w, samples[3].w))) - depth; float b1 = max(samples[0].w - ma, 0.0); float b2 = max(samples[1].w - ma, 0.0); float b3 = max(samples[2].w - ma, 0.0); float b4 = max(samples[3].w - ma, 0.0); vec4 numer = ( samples[0] * b1 + samples[1] * b2 + samples[2] * b3 + samples[3] * b4); float denom = (b1 + b2 + b3 + b4); return numer / denom; } vec4 _TerrainBlend_4_lerp(vec4 samples[4]) { return ( samples[0] * samples[0].w + samples[1] * samples[1].w + samples[2] * samples[2].w + samples[3] * samples[3].w); } // Lifted from https://www.shadertoy.com/view/Xtl3zf vec4 texture_UV(in sampler2DArray srcTexture, in vec3 x) { float k = texture(TRIPLANAR_noiseMap, 0.0025*x.xy).x; // cheap (cache friendly) lookup float l = k*8.0; float f = fract(l); float ia = floor(l+0.5); // suslik's method (see comments) float ib = floor(l); f = min(f, 1.0-f)*2.0; vec2 offa = sin(vec2(3.0,7.0)*ia); // can replace with any other hash vec2 offb = sin(vec2(3.0,7.0)*ib); // can replace with any other hash vec4 cola = texture(srcTexture, vec3(x.xy + offa, x.z)); vec4 colb = texture(srcTexture, vec3(x.xy + offb, x.z)); return mix(cola, colb, smoothstep(0.2,0.8,f-0.1*sum(cola.xyz-colb.xyz))); } vec4 _Triplanar_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec4 dx = texture_UV(tex, vec3(pos.zy / _TRI_SCALE, texSlice)); vec4 dy = texture_UV(tex, vec3(pos.xz / _TRI_SCALE, texSlice)); vec4 dz = texture_UV(tex, vec3(pos.xy / _TRI_SCALE, texSlice)); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); return dx * weights.x + dy * weights.y + dz * weights.z; } vec4 _TriplanarN_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { // Tangent Reconstruction // Triplanar uvs vec2 uvX = pos.zy; // x facing plane vec2 uvY = pos.xz; // y facing plane vec2 uvZ = pos.xy; // z facing plane // Tangent space normal maps vec3 tx = texture_UV(tex, vec3(uvX / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 ty = texture_UV(tex, vec3(uvY / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 tz = texture_UV(tex, vec3(uvZ / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); // Get the sign (-1 or 1) of the surface normal vec3 axis = sign(normal); // Construct tangent to world matrices for each axis vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0))); vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x; mat3 tbnX = mat3(tangentX, bitangentX, normal); vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y))); vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y; mat3 tbnY = mat3(tangentY, bitangentY, normal); vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0))); vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z; mat3 tbnZ = mat3(tangentZ, bitangentZ, normal); // Apply tangent to world matrix and triblend // Using clamp() because the cross products may be NANs vec3 worldNormal = normalize( clamp(tbnX * tx, -1.0, 1.0) * weights.x + clamp(tbnY * ty, -1.0, 1.0) * weights.y + clamp(tbnZ * tz, -1.0, 1.0) * weights.z ); return vec4(worldNormal, 0.0); } vec4 _Triplanar(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec4 dx = texture(tex, vec3(pos.zy / _TRI_SCALE, texSlice)); vec4 dy = texture(tex, vec3(pos.xz / _TRI_SCALE, texSlice)); vec4 dz = texture(tex, vec3(pos.xy / _TRI_SCALE, texSlice)); vec3 weights = abs(normal.xyz); weights = weights / (weights.x + weights.y + weights.z); return dx * weights.x + dy * weights.y + dz * weights.z; } vec4 _TriplanarN(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) { vec2 uvx = pos.zy; vec2 uvy = pos.xz; vec2 uvz = pos.xy; vec3 tx = texture(tex, vec3(uvx / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 ty = texture(tex, vec3(uvy / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 tz = texture(tex, vec3(uvz / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1); vec3 weights = abs(normal.xyz); weights *= weights; weights = weights / (weights.x + weights.y + weights.z); vec3 axis = sign(normal); vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0))); vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x; mat3 tbnX = mat3(tangentX, bitangentX, normal); vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y))); vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y; mat3 tbnY = mat3(tangentY, bitangentY, normal); vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0))); vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z; mat3 tbnZ = mat3(tangentZ, bitangentZ, normal); vec3 worldNormal = normalize( clamp(tbnX * tx, -1.0, 1.0) * weights.x + clamp(tbnY * ty, -1.0, 1.0) * weights.y + clamp(tbnZ * tz, -1.0, 1.0) * weights.z); return vec4(worldNormal, 0.0); } `; const _PS_2 = ` { vec3 worldPosition = vCoords; float weightIndices[4] = float[4](vWeights1.x, vWeights1.y, vWeights1.z, vWeights1.w); float weightValues[4] = float[4](vWeights2.x, vWeights2.y, vWeights2.z, vWeights2.w); // TRIPLANAR SPLATTING w/ NORMALS & UVS vec3 worldSpaceNormal = normalize(vNormal); vec4 diffuseSamples[4]; // vec4 normalSamples[4]; for (int i = 0; i < 4; ++i) { vec4 d = vec4(0.0); // vec4 n = vec4(0.0); if (weightValues[i] > 0.0) { d = _Triplanar_UV( worldPosition, worldSpaceNormal, weightIndices[i], TRIPLANAR_diffuseMap); // n = _TriplanarN_UV( // worldPosition, worldSpaceNormal, weightIndices[i], TRIPLANAR_normalMap); d.w *= weightValues[i]; // n.w = d.w; } diffuseSamples[i] = d; // normalSamples[i] = n; } vec4 diffuseBlended = _TerrainBlend_4(diffuseSamples); // vec4 normalBlended = _TerrainBlend_4(normalSamples); diffuseColor = sRGBToLinear(diffuseBlended); // normal = normalBlended.xyz; } `; return { VS: _VS, PS: _PS, VS1: _VS_1, VS2: _VS_2, PS1: _PS_1, PS2: _PS_2, }; })(); ``` thanks for reading update I have tried adding: ``` precision mediump sampler2DArray; precision mediump float; precision mediump int; uniform sampler2DArray TRIPLANAR_normalMap; uniform sampler2DArray TRIPLANAR_diffuseMap; uniform sampler2D TRIPLANAR_noiseMap; ``` to: const \_PS\_1 and \_PS still the error persists doing this also throw a new error: > > Uniforms with the same name but different type/precision > > > i was able to make this error go away by adding: ``` precision mediump float; ``` to the vertex shaders but i'm still left with the original error of: ``` no default precision defined for variable 'float[4]'1 ``` **UPDATE** tried adding ``` renderer.precision="mediump"; ``` and lowp this had no effect i've also notice the texture of the ground which is the same problem on mobile well it will not show up.. and i get the same issue in firefox the browser its working in correctly is chrome, here is the site: <http://wonder-3d.hol.es/ADz(1)z/115(1)> here is the shader file: <http://wonder-3d.hol.es/ADz(1)z/src/terrain-shader.js> small issue with chrome: In chrome if i have dev tools open and close it before the the ground texture has loaded the texture will not show up like in firefox and mobile but that's only if you do that with dev tools exactly, if you don't it works fine... so it's not a big issue i can make the terrain texture show up again by re-opening dev tools though and everything works as intended. thanks for any help.
2022/06/02
[ "https://Stackoverflow.com/questions/72479232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3112634/" ]
**OpenGL** specification doesn't define precision qualifier for fragment shaders, this means you should define it by yourself. You should add these two lines to your shader code under **const \_PS\_1** declaration: ``` precision highp float; // Define float precision precision highp int; // Define int precision ``` resulting in the following: ``` const _PS_1 = ` precision mediump sampler2DArray; precision highp float; // Define float precision precision highp int; // Define int precision uniform sampler2DArray TRIPLANAR_normalMap; uniform sampler2DArray TRIPLANAR_diffuseMap; uniform sampler2D TRIPLANAR_noiseMap; in vec3 vCoords; in vec4 vWeights1; in vec4 vWeights2; ``` For good performance, always use the lowest precision that is possible. This is especially important on lower-end hardware. Good rules of thumb are: > > * For world space positions and texture coordinates, use \*\*highp float \*\* precision. > * For everything else (vectors, HDR colors, etc.), start with \*\*mediump float \*\* precision. Increase only if necessary. > > >
I had the exact same issue as you on certain Android phones (Android 12). It has to do with the way you're initializing your arrays `weightIndices` and `weightValues`. **Replace:** ```c float weightIndices[4] = float[4](vWeights1.x, vWeights1.y, vWeights1.z, vWeights1.w); ``` **With (same for weightValues):** ```c float weightIndices[4]; weightIndices[0] = vWeights1.x; weightIndices[1] = vWeights1.y; weightIndices[2] = vWeights1.z; weightIndices[3] = vWeights1.w; ```
218,562
In [Stack Overflow is getting a place of its own](https://meta.stackexchange.com/q/212631/152515), the estimated time of arrival was around the middle of January: > > I'm *extremely* pleased to announce that we've finally worked out the remaining details, and will be proceeding with the split in six to eight weeks. No, I'm not kidding, we're shooting for somewhere around the middle of January. Seriously, stop laughing, six to eight weeks is a *perfectly* reasonab .. I digress. > > > It's February now, though, so I'm wondering: what's the current estimated time of arrival for the new Meta Stack Overflow? I am absolutely not planning to hassle the development team here. I'm quite content whenever Meta Stack Exchange arrives, and if they need more time, they should definitely take it, since this is something that should be done right. I'm still curious about *when* it might happen, though! --- A day later: I've just learned that [6-8 weeks is a meme](https://meta.stackexchange.com/a/19514/152515) for when there *isn't* an ETA. Was there no ETA to begin with, and is there no specific ETA now? (Other than a perpetual ETA of 6-8 weeks)
2014/02/04
[ "https://meta.stackexchange.com/questions/218562", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/152515/" ]
***Update - March 2nd 2014*** *Work on the back end of this is well underway, there's a lot of code specific checks to see if Meta SO is actually Meta SO, and some other stuff that's currently being addressed. I will put out a meta post when we near the ~1 week to blast off milestone to let folks know. I don't think it'll be much longer.* --- It *really was* six to eight weeks when I posted it, according to our schedule. Work has started on it, the community team side has prepared new copy, figured out how the help center and /about is going to work, identified a bunch of unresolved Stack Overflow specific things that should migrate back to MSO once both sites go live and other stuff. We're the ones pushing the project. What we're waiting for right now is the developers to finish up some work overhauling our login system and some things associated with it. Once that's done, they're going to start by letting us know when we should be telling everyone to look out for maintenance mode. It's going to happen. Every time I see a perfectly valid support question down voted here by people that *barely use Stack Overflow itself*, I want to scream. It's still a major priority, and it has been progressing - just not visibly.
In [a comment on January 22](https://meta.stackexchange.com/questions/212631/stack-overflow-is-getting-a-place-of-its-own#comment703507_212631) Tim Post said: > > We just met again about it today, due to a bit of backlog with the SSL stuff, it's probably going to be around the first week of Feb. I'll update the post again as soon as I have a firmer time frame. However yes, this is going forward and soon - the community team end of it is moving, we just have to let the devs clear some room off their plates before we go full throttle. > > > As far as I can see that's the latest official update.