date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/15
583
2,099
<issue_start>username_0: I'm trying to adjust the size of a tableView based on data coming from the previous view controller. For example : ``` if previousData == "Acitivites" { tableView.height = 375 tableView.width = 300 } else { tableView.height = 480 tableView.width = 300 } ``` I'm not sure exactly how to implement this, I would appreciate any guidance!<issue_comment>username_1: You can check the condition in viewDidLayoutSubviews and change the frame of the tableview. ``` override func viewDidLayoutSubviews() { if previousData == "Acitivites" { tableView.frame = CGRect(x: 0, y: 0, width: 300, height: 375) } else { tableView.frame = CGRect(x: 0, y: 0, width: 300, height: 480) } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: set outlet `heightConstraintTableView` of `tableView` ``` override func viewDidLayoutSubviews() { heightConstraintTableView.constant = previousData == "Acitivites" ? 375 : 480 } ``` Upvotes: 2 <issue_comment>username_3: You can set constraint dynamically like below... ``` override func viewDidLayoutSubviews() { //setting height var var height: CGFloat = (previousData == "Acitivites") ? 375 : 480 //top constraint tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true //leading constraint tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true //trailing constraint tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true //height constraint tableView.heightAnchor.constraint(equalToConstant: height).isActive = true //setting height priority to avoid constraint breaking bcoz height, top and bottom is set let bottomconstraint = tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) bottomconstraint.priority = .defaultHigh bottomconstraint.isActive = true } ``` If you have created IBOutlet for height constraint then you can set it programatically. ``` self.heightConstraint_tableView.constant = ``` Upvotes: 0
2018/03/15
750
2,156
<issue_start>username_0: My python list contains sympy matrix object, and I need to sum them all. If all list elements are just symbols, then using built-in sum function in python works fine. ``` import sympy as sp x = sp.symbols('x') ls = [x, x+1, x**2] print(sum(ls)) >>> x**2 + 2*x + 1 ``` But for the elements of matrix type, sum function looks not working. ``` import sympy as sp ls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3] print(sum(ls)) >>> TypeError: cannot add and ``` How can I resolve this problem?<issue_comment>username_1: This is why Python's [`sum` function](https://docs.python.org/3/library/functions.html#sum) has an optional "start" argument: so you can initialize it with a "zero object" of the kind you are adding. In this case, with a zero matrix. ``` >>> print(sum(ls, sp.zeros(2))) Matrix([[9, 0], [0, 9]]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_1: I don't really know how the built-in function `sum` works, perhaps it kinda looks like this. ``` def _sum(data): total = 0 for i in data: total += i return total ``` Now consider the following lines of code. ``` >>> import sympy >>> x = sympy.symbols('x') >>> x x >>> print(0+x) x >>> x = sympy.symbols('x') >>> matrix=sympy.eye(3) >>> matrix Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> print(0+x) x >>> print(0+matrix) Traceback (most recent call last): File "", line 1, in print(0+matrix) File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary\_op\_wrapper return func(self, other) File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 2061, in \_\_radd\_\_ return self + other File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary\_op\_wrapper return func(self, other) File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 1964, in \_\_add\_\_ raise TypeError('cannot add %s and %s' % (type(self), type(other))) TypeError: cannot add and >>> ``` What we can conclude is you add any `sympy.core.symbol.Symbol`(btw there are more such as Sum and Pow) to integer but not `sympy.matrices.dense.MutableDenseMatrix` Upvotes: 0
2018/03/15
1,341
5,129
<issue_start>username_0: When I use admin deploy a network with one organization include three peers. My endorsement-policy.json as below , and it not work. ``` { "identities": [ { "role": { "name": "member", "mspId": "Org1MSP" } } ], "policy": { "1-of": [ { "signed-by": 0 } ] } } ``` 1.How can I set the endorsement-policy ? 2. I think the endorsing peer is the only a peer , what's the meaning of 'member' or 'admin' ? So, I want make all of the three peers to be endorsing peers, how to config it ?<issue_comment>username_1: In terms of making your JSON policy file work, this should do it: ``` { "identities": [ { "role": { "name": "member", "mspId": "Org1MSP" } } ], "policy": { "signed-by": 0 } } ``` The definition of the JSON for the policy is [here](https://fabric-sdk-node.github.io/global.html#Policy) The endorsement signatures are per organisation so you only need to add additional "identities" in the endorsement policy if you have multiple organisations. Upvotes: 0 <issue_comment>username_2: Let's start from addressing your comment: > > no.it should be a useage problem.I have three peers in only one org. I need all of three signatures from endorsing peers. When l use docker logs dev-peer\*... command to see the log from each peer container .lt get different value by random function.So,the transaction is executed three times. Now,I just want the transaction can’t be submitted. What is the endorsement policy should be > > > The policy which you defined is: ``` "policy": { "1-of": [ { "signed-by": 0 } ] } ``` where `"signed-by": 0` is the index of the MSP id which has to satisfy this rule. I.e. single endorsement of one peer basically will satisfy the endorsement policy, while you need to make sure all there execution are consistent, therefore in your case you would like to have more than one peer to endorse your transaction, hence you need: ``` { "identities": [ { "role": { "name": "member", "mspId": "Org1MSP" } } ], "policy": { "3-of": [ { "signed-by": 0 }, { "signed-by": 0 }, { "signed-by": 0 }, ] } } ``` which mean all 3 peers from Org1MSP have to signed the endorsement to approve the transaction, while since you are using random function it will fail. > > 1.How can I set the endorsement-policy ? > > > you can provide endorsement policy while instantiating your chaincode, the syntax is very simple: ``` AND("Org1MSP.member") ``` basically says you need at lest one endorsement from valid member of `Org1MSP`. > > 2. I think the endorsing peer is the only a peer , what's the meaning of 'member' or 'admin' ? > > > `member` and `admin` are principle which actually provide you and ability to control whenever there is something need to be endorsed or signed by privileged entity (`admin`) or a simple one could be suffice (`member`). > > So, I want make all of the three peers to be endorsing peers, how to config it ? > > > endorsing peer is the peer which has chaincode installed on it, hence able to invoke it and interact with it, there is no explicit configuration need to make peer an endorsing peer, all you need is to install chaincode on it. Upvotes: 3 [selected_answer]<issue_comment>username_1: Composer will send the transaction to all the Peers in your connection.json document. It looks like all are evaluating based on what you see in the log, but because only 1 is required for Endorsement I guess that only the first to respond is actually written to the Ledger. (Setting up 3 Business Network Cards with a single peer defined in each connection.json - then retrieving the data from each peer should confirm this.) I think it is unusual to require 3 Peers **from the same Organisation** to endorse (sign) the Transaction and a more typical scenario is what you tried earlier with 2 Peers from 2 Organisations. Currently the Policy shown here has An Array of Identities containing 1 element which is a Role. Following the 2 links below to the Fabric Node SDK Documentation I think you could specify a Specific Identity instead of a Role. So if you really wanted to have 3 Peers from the same organisation, you would have the 3 specific Identities of the Peers (from the CA) in the Array of Identities, and in the Policy section you would have: ``` "policy": { "3-of": [ { "signed-by": 0 }, { "signed-by": 1 }, { "signed-by": 2 } ] } ``` <https://fabric-sdk-node.github.io/global.html#Policy> <https://fabric-sdk-node.github.io/global.html#Identity> (I don't have the syntax for adding specific Identities instead of Roles.) Upvotes: 0
2018/03/15
1,364
5,289
<issue_start>username_0: I am using inheritance to access base class elements. I have defined driver object in environment class and inherited in base class. In base class I am trying to access this object. However I am getting an error Environment has no object driver. How do I access this element? ``` class Environment(object): def __init__(self): driver = "webdriver.Chrome(D:\BrowserDriver\ChromeDriver\chromedriver.exe)" print self.driver class base(Environment): def __init__(self): drive = self.driver def test_Home_Page(self): # Screenshots relative paths ss_path = "/Test_MercuryTours_HomePage/" # Using the driver instances created in EnvironmentSetup drive = self.driver print drive env=Environment() print env.setUp() b=base() print b.drive ```<issue_comment>username_1: In terms of making your JSON policy file work, this should do it: ``` { "identities": [ { "role": { "name": "member", "mspId": "Org1MSP" } } ], "policy": { "signed-by": 0 } } ``` The definition of the JSON for the policy is [here](https://fabric-sdk-node.github.io/global.html#Policy) The endorsement signatures are per organisation so you only need to add additional "identities" in the endorsement policy if you have multiple organisations. Upvotes: 0 <issue_comment>username_2: Let's start from addressing your comment: > > no.it should be a useage problem.I have three peers in only one org. I need all of three signatures from endorsing peers. When l use docker logs dev-peer\*... command to see the log from each peer container .lt get different value by random function.So,the transaction is executed three times. Now,I just want the transaction can’t be submitted. What is the endorsement policy should be > > > The policy which you defined is: ``` "policy": { "1-of": [ { "signed-by": 0 } ] } ``` where `"signed-by": 0` is the index of the MSP id which has to satisfy this rule. I.e. single endorsement of one peer basically will satisfy the endorsement policy, while you need to make sure all there execution are consistent, therefore in your case you would like to have more than one peer to endorse your transaction, hence you need: ``` { "identities": [ { "role": { "name": "member", "mspId": "Org1MSP" } } ], "policy": { "3-of": [ { "signed-by": 0 }, { "signed-by": 0 }, { "signed-by": 0 }, ] } } ``` which mean all 3 peers from Org1MSP have to signed the endorsement to approve the transaction, while since you are using random function it will fail. > > 1.How can I set the endorsement-policy ? > > > you can provide endorsement policy while instantiating your chaincode, the syntax is very simple: ``` AND("Org1MSP.member") ``` basically says you need at lest one endorsement from valid member of `Org1MSP`. > > 2. I think the endorsing peer is the only a peer , what's the meaning of 'member' or 'admin' ? > > > `member` and `admin` are principle which actually provide you and ability to control whenever there is something need to be endorsed or signed by privileged entity (`admin`) or a simple one could be suffice (`member`). > > So, I want make all of the three peers to be endorsing peers, how to config it ? > > > endorsing peer is the peer which has chaincode installed on it, hence able to invoke it and interact with it, there is no explicit configuration need to make peer an endorsing peer, all you need is to install chaincode on it. Upvotes: 3 [selected_answer]<issue_comment>username_1: Composer will send the transaction to all the Peers in your connection.json document. It looks like all are evaluating based on what you see in the log, but because only 1 is required for Endorsement I guess that only the first to respond is actually written to the Ledger. (Setting up 3 Business Network Cards with a single peer defined in each connection.json - then retrieving the data from each peer should confirm this.) I think it is unusual to require 3 Peers **from the same Organisation** to endorse (sign) the Transaction and a more typical scenario is what you tried earlier with 2 Peers from 2 Organisations. Currently the Policy shown here has An Array of Identities containing 1 element which is a Role. Following the 2 links below to the Fabric Node SDK Documentation I think you could specify a Specific Identity instead of a Role. So if you really wanted to have 3 Peers from the same organisation, you would have the 3 specific Identities of the Peers (from the CA) in the Array of Identities, and in the Policy section you would have: ``` "policy": { "3-of": [ { "signed-by": 0 }, { "signed-by": 1 }, { "signed-by": 2 } ] } ``` <https://fabric-sdk-node.github.io/global.html#Policy> <https://fabric-sdk-node.github.io/global.html#Identity> (I don't have the syntax for adding specific Identities instead of Roles.) Upvotes: 0
2018/03/15
580
1,971
<issue_start>username_0: The [documentation](http://php.net/manual/en/language.types.null.php) for NULL says that if I called `unset()` on a variable, the variable will become NULL: > > A variable is considered to be null if: > > > it has been assigned the constant NULL. > > > it has not been set to any value yet. > > > **it has been unset().** > > > However, this [tutorial](http://code.iamkate.com/php/references-tutorial/) says the following will happen when calling `unset()` on a variable: > > PHP looks in the symbol table to find the zval corresponding to this > variable, decrements the refcount, and removes the variable from the > symbol table. Because the refcount is now zero, the garbage collector > knows that there is no way of accessing this zval, and can free the > memory it occupies. > > > Now I tried the following code: ``` php $x = 12345; unset($x); echo gettype($x); ? ``` The output I got is strange, I got an error that says that the variable is undefined (which conforms with the second quote I have posted), but I also got the type of the variable which is NULL (which conforms with the first quote I have posted): [![enter image description here](https://i.stack.imgur.com/BLnYA.png)](https://i.stack.imgur.com/BLnYA.png) Why am I getting this strange output?<issue_comment>username_1: > > unset() destroys the specified variables. > > > It does not make the Variable **NULL** so the warning absolutely makes sense ``` Notice: Undefined variable: x ``` Reference : <http://php.net/manual/en/function.unset.php> Upvotes: 2 <issue_comment>username_2: **unset()** destroys the specified variables. Note that in `PHP 3`, **unset()** will always return `TRUE` (actually, the integer value 1). In `PHP 4`, however, **unset()** is *no longer a true function: it is now a statement*. As such no value is returned, and attempting to take the value of **unset()** results in a *parse error* Upvotes: 1
2018/03/15
1,888
5,869
<issue_start>username_0: I'm comparing performance of `MethodHandle::invoke` and direct static method invokation. Here is the static method: ``` public class IntSum { public static int sum(int a, int b){ return a + b; } } ``` And here is my benchmark: ``` @State(Scope.Benchmark) public class MyBenchmark { public int first; public int second; public final MethodHandle mhh; @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public int directMethodCall() { return IntSum.sum(first, second); } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public int finalMethodHandle() throws Throwable { return (int) mhh.invoke(first, second); } public MyBenchmark() { MethodHandle mhhh = null; try { mhhh = MethodHandles.lookup().findStatic(IntSum.class, "sum", MethodType.methodType(int.class, int.class, int.class)); } catch (NoSuchMethodException | IllegalAccessException e) { e.printStackTrace(); } mhh = mhhh; } @Setup public void setup() throws Exception { first = 9857893; second = 893274; } } ``` I got the following result: ``` Benchmark Mode Cnt Score Error Units MyBenchmark.directMethodCall avgt 5 3.069 ± 0.077 ns/op MyBenchmark.finalMethodHandle avgt 5 6.234 ± 0.150 ns/op ``` `MethodHandle` has some performance degradation. Running it with `-prof perfasm` shows this: ``` ....[Hottest Regions]............................................................................... 31.21% 31.98% C2, level 4 java.lang.invoke.LambdaForm$DMH::invokeStatic_II_I, version 490 (27 bytes) 26.57% 28.02% C2, level 4 org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest::finalMethodHandle_avgt_jmhStub, version 514 (84 bytes) 20.98% 28.15% C2, level 4 org.openjdk.jmh.infra.Blackhole::consume, version 497 (44 bytes) ``` As far as I could figure out the reason for the benchmark result is that the ***Hottest Region 2*** `org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest::finalMethodHandle_avgt_jmhStub` contains all the type-checks performed by the `MethodHandle::invoke` inside the JHM loop. Assembly output fragment (some code ommitted): ``` ....[Hottest Region 2].............................................................................. C2, level 4, org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest::finalMethodHandle_avgt_jmhStub, version 519 (84 bytes) ;... 0x00007fa2112119b0: mov 0x60(%rsp),%r10 ;... 0x00007fa2112119d4: mov 0x14(%r12,%r11,8),%r8d ;*getfield form 0x00007fa2112119d9: mov 0x1c(%r12,%r8,8),%r10d ;*getfield customized 0x00007fa2112119de: test %r10d,%r10d 0x00007fa2112119e1: je 0x7fa211211a65 ;*ifnonnull 0x00007fa2112119e7: lea (%r12,%r11,8),%rsi 0x00007fa2112119eb: callq 0x7fa211046020 ;*invokevirtual invokeBasic ;... 0x00007fa211211a01: movzbl 0x94(%r10),%r10d ;*getfield isDone ;... 0x00007fa211211a13: test %r10d,%r10d ;jumping at the begging of jmh loop if not done 0x00007fa211211a16: je 0x7fa2112119b0 ;*aload_1 ;... ``` Before calling the `invokeBasic` we perform the type-checking (inside the jmh loop) which affects the output avgt. ***QUESTION:*** Why isn't all the type-check moved outside of the loop? I declared `public final MethodHandle mhh;` inside the benchmark. So I expected the compiler can figured it out and eliminate the same type-checks. How to make the same typechecks eliminated? Is it possible?<issue_comment>username_1: Make `MethodHandle mhh` static: ``` Benchmark Mode Samples Score Error Units directMethodCall avgt 5 0,942 ± 0,095 ns/op finalMethodHandle avgt 5 0,906 ± 0,078 ns/op ``` Non-static: ``` Benchmark Mode Samples Score Error Units directMethodCall avgt 5 0,897 ± 0,059 ns/op finalMethodHandle avgt 5 4,041 ± 0,463 ns/op ``` Upvotes: 3 <issue_comment>username_2: You use *reflective* invocation of `MethodHandle`. It works roughly like `Method.invoke`, but with less run-time checks and without boxing/unboxing. Since this `MethodHandle` is not `static final`, JVM does not treat it as constant, that is, MethodHandle's target is a black box and cannot be inlined. Even though `mhh` is final, it contains instance fields like `MethodType type` and `LambdaForm form` that are reloaded on each iteration. These loads are not hoisted out of the loop because of a black-box call inside (see above). Furthermore, `LambdaForm` of a `MethodHandle` can be changed (customized) in run-time between calls, so it *needs* to be reloaded. ### How to make the call faster? 1. Use `static final` MethodHandle. JIT will know the target of such MethodHandle and thus may inline it at the call site. 2. Even if you have non-static MethodHandle, you may bind it to a static CallSite and invoke it as fast as direct methods. This is similar to how lambdas are called. ``` private static final MutableCallSite callSite = new MutableCallSite( MethodType.methodType(int.class, int.class, int.class)); private static final MethodHandle invoker = callSite.dynamicInvoker(); public MethodHandle mh; public MyBenchmark() { mh = ...; callSite.setTarget(mh); } @Benchmark public int boundMethodHandle() throws Throwable { return (int) invoker.invokeExact(first, second); } ``` 3. Use regular `invokeinterface` instead of `MethodHandle.invoke` as @Holger suggested. An instance of interface for calling given MethodHandle can be generated with [`LambdaMetafactory.metafactory()`](https://docs.oracle.com/javase/9/docs/api/java/lang/invoke/LambdaMetafactory.html). Upvotes: 5 [selected_answer]
2018/03/15
749
2,671
<issue_start>username_0: This is the `views.py` file: ``` from django.shortcuts import render from django.views.generic import TemplateView from .models import Report import random class HomePageView(TemplateView): def get(self, request, **kwargs): args = {} data = Report.objects.all() args['data'] = data return render(request, 'index.html',args) ``` I'm finding it difficult to understand the framework since I'm a beginner. So please help me.<issue_comment>username_1: Make `MethodHandle mhh` static: ``` Benchmark Mode Samples Score Error Units directMethodCall avgt 5 0,942 ± 0,095 ns/op finalMethodHandle avgt 5 0,906 ± 0,078 ns/op ``` Non-static: ``` Benchmark Mode Samples Score Error Units directMethodCall avgt 5 0,897 ± 0,059 ns/op finalMethodHandle avgt 5 4,041 ± 0,463 ns/op ``` Upvotes: 3 <issue_comment>username_2: You use *reflective* invocation of `MethodHandle`. It works roughly like `Method.invoke`, but with less run-time checks and without boxing/unboxing. Since this `MethodHandle` is not `static final`, JVM does not treat it as constant, that is, MethodHandle's target is a black box and cannot be inlined. Even though `mhh` is final, it contains instance fields like `MethodType type` and `LambdaForm form` that are reloaded on each iteration. These loads are not hoisted out of the loop because of a black-box call inside (see above). Furthermore, `LambdaForm` of a `MethodHandle` can be changed (customized) in run-time between calls, so it *needs* to be reloaded. ### How to make the call faster? 1. Use `static final` MethodHandle. JIT will know the target of such MethodHandle and thus may inline it at the call site. 2. Even if you have non-static MethodHandle, you may bind it to a static CallSite and invoke it as fast as direct methods. This is similar to how lambdas are called. ``` private static final MutableCallSite callSite = new MutableCallSite( MethodType.methodType(int.class, int.class, int.class)); private static final MethodHandle invoker = callSite.dynamicInvoker(); public MethodHandle mh; public MyBenchmark() { mh = ...; callSite.setTarget(mh); } @Benchmark public int boundMethodHandle() throws Throwable { return (int) invoker.invokeExact(first, second); } ``` 3. Use regular `invokeinterface` instead of `MethodHandle.invoke` as @Holger suggested. An instance of interface for calling given MethodHandle can be generated with [`LambdaMetafactory.metafactory()`](https://docs.oracle.com/javase/9/docs/api/java/lang/invoke/LambdaMetafactory.html). Upvotes: 5 [selected_answer]
2018/03/15
542
2,368
<issue_start>username_0: I am new to xamarin and I have one listview which contains two label and one string array. How can I bind this items in listview? Items may be 1 to 5 based on data. [![image](https://i.stack.imgur.com/wEB79.png)](https://i.stack.imgur.com/wEB79.png)<issue_comment>username_1: You can create a `ContentView` to act as a container for the `StackLayout`. Then you can bind the `string[]` property to the `ContentView`'s `Content` property. And finally, you can use a value converter to convert the `string[]` value into a horizontal `StackLayout`. For example: ``` ... ... place the ContentView wherever you want the labels to appear ... ... ``` Just place the inside of your `ListView`'s `DataTemplate`, wherever you want the array of items to appear. And then for the value converter: ``` namespace MyProject.MyValueConverters { public class ArrayToStackLayoutConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var strArray = (string[])value; var layout = new StackLayout() { Orientation = StackOrientation.Horizontal }; foreach (var item in strArray) { var label = new Label() { Text = item }; var frame = new Frame() { Content = label, HasShadow = false, Padding = 4, OutlineColor = Color.Black, CornerRadius = 2 }; layout.Children.Add(frame); } return layout; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` class MyItem { public string Label1 {get; set;} public string Label2 {get; set;} public string[] Subitems {get; set;} } //viewmodel is something like List List viewModel = GetDataFromService(...); //xaml //i can't remember exactly, maybe use //set height, weight, border ``` all in all, use an inner ListView inside the outer ListView. Upvotes: 0
2018/03/15
786
2,843
<issue_start>username_0: I'm trying to load a web page that requires authentication using Python script with Selenium. ``` options = webdriver.ChromeOptions() prefs = {'download.default_directory': r"download.default_directory=" + download_folder, "download.prompt_for_download": False, 'profile.default_content_setting_values.automatic_downloads': 1} options.add_experimental_option('prefs', prefs) options.add_argument("--start-maximized") options.add_argument('--disable-browser-side-navigation') driver = webdriver.Chrome(chrome_options=options, executable_path=chrome_driver) driver.get('https://user:pass@somepage.com/32324') ``` This still gets the popup alert with user name and password. So, I figured I'll just handle the alert in code but it seems the page doesn't finish loading until the alert is closed so the script is stuck on the get function. How do I handle this situation? EDIT: This is not duplication because the accepted answer there doesn't work for me.<issue_comment>username_1: try this... ``` Map prefs = new HashMap(); prefs.put("credentials\_enable\_service", false); prefs.put("profile.password\_manager\_enabled", false); options.setExperimentalOption("prefs", prefs); ``` Upvotes: 0 <issue_comment>username_2: After many hours wasted, it turns out that it is a known issue with chromedriver: <https://bugs.chromium.org/p/chromedriver/issues/detail?id=1917&q=authentication&colspec=ID%20Status%20Pri%20Owner%20Summary> I switched to using Firefox instead and it works from there. Upvotes: 2 [selected_answer]<issue_comment>username_3: In case you mean html basic authentification you can also try the following workaround: (Sorry I just know Java but it should be quite similar) ``` driver.get("http://[USERNAME]:[PASSWORD]@[rest of the Page-URL you want to enter]"); driver.get("[normal URL of the page you want to enter]"); ``` The 2nd driver call is just reloading the page. I don´t know if you need it, but for my automation it´s needed. Upvotes: 1 <issue_comment>username_4: Try using autoit: The code goes something like :: ``` from selenium import webdriver import autoit driver= webdriver.Chrome() driver.get("http://sitewithpopup.com") autoit.win_wait_active("",30) # Make sure you give blank since the cursor is at userid autoit.send("Username{TAB}") autoit.send("Password{Enter}") ``` Since the autoit will **type wherever your cursor is** and by default the cursor is on the **userID** field so you can make use of it. Upvotes: 0 <issue_comment>username_5: So this might be the dumbest solution, and I can't say it'll work for everyone but... Try refreshing the page. Just: ``` driver.get("https://website.com") time.sleep(1) driver.refresh() ``` In Chrome this cleared the Authentication popup and took me to the login page, which Selenium could then handle. Upvotes: 2
2018/03/15
295
1,052
<issue_start>username_0: How can I convert a large binary (10k bits) to a base 3 or a base 31 number? I know that for base 16 I can convert the number by taking 4 bytes chunks from my original number and this works well. But for base 3 or 31 is this even possible, since they are not a factor of 2? Edit ==== I tried to simplify the problem above, but for clarity think that there is a binary stream of 100MB, and you need to convert it in a stream that would be interpreted base 31. Thanks for the answers so far.<issue_comment>username_1: It might not be the fastest, most efficient way to get the job done, but a very easy approach would be to use Java's BigInteger class. ``` (new BigInteger(hugeBinaryNumberAsString, 2)).toString(3) ``` Upvotes: -1 <issue_comment>username_2: You can't do this in a streaming fashion. For example, if the streams are big-endian, then you'll need to wait until the last bit in the input to distinguish between 31^100001 and (31^100001 - 1), and this difference affects the first bit of the output. Upvotes: 1
2018/03/15
1,318
3,792
<issue_start>username_0: I want to add a link to a table that I create from tabular data using d3. Take a quick look at my snippet: ```js var data = [ {'Engine':'Google', 'Founded':'1998', 'Monthly-Visitors':4840295000, 'Site':'www.google.com'}, {'Engine':'Baidu', 'Founded':'2000', 'Monthly-Visitors':1471079000, 'Site':'www.baidu.com'}, {'Engine':'Yahoo', 'Founded':'1995', 'Monthly-Visitors':1038375000, 'Site':'www.yahoo.com'}, {'Engine':'Bing', 'Founded':'2009', 'Monthly-Visitors':203482000, 'Site':'www.bing.com'}, {'Engine':'AOL', 'Founded':'1991', 'Monthly-Visitors': 39961000, 'Site':'www.aolsearch.com'} ]; var columns = ['Engine', 'Founded', 'Monthly-Visitors', 'Site']; var table = d3.select('body').append('table'), thead = table.append('thead'), tbody = table.append('tbody'); thead.append('tr') .selectAll('th') .data(columns) .enter() .append('th') .text(function(column) {return column; }); var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { return { column: column, value: row[column]}; }); }) .enter() .append('td') .text(function(d) { if (d.column === 'Site') { //console.log('now what?') } return d.value; }); ``` ```html ``` I have created the table, but I'm not sure how to make the rows containing the websites a clickable link. In the past I have used: ``` d3.select('.links').append('div') .append('a') .attr('href', 'http://www.google.com') .append('text') .html('Click here to go to a search engine.'); ``` However I can't figure out how to use this approach with a table. I tried appending `a` within a `td` but that didn't work. As I recall, SVG text can be tricky. I think by appending `div` we are not appending SVG text...*I think*.. **Question:** How can I add a `href` property to my `Site` column in my table?<issue_comment>username_1: You could simply change `.text` to `.html` and add tags in your data like this: ``` 'Site': ' [google](www.google.com) ' ``` Or add conditions in the return statement of your data like this. ``` if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } ``` Code below: ```js var data = [ {'Engine':'Google', 'Founded':'1998', 'Monthly-Visitors':4840295000, 'Site':'www.google.com'}, {'Engine':'Baidu', 'Founded':'2000', 'Monthly-Visitors':1471079000, 'Site':'www.baidu.com'}, {'Engine':'Yahoo', 'Founded':'1995', 'Monthly-Visitors':1038375000, 'Site':'www.yahoo.com'}, {'Engine':'Bing', 'Founded':'2009', 'Monthly-Visitors':203482000, 'Site':'www.bing.com'}, {'Engine':'AOL', 'Founded':'1991', 'Monthly-Visitors': 39961000, 'Site':'www.aolsearch.com'} ]; var columns = ['Engine', 'Founded', 'Monthly-Visitors', 'Site']; var table = d3.select('body').append('table'), thead = table.append('thead'), tbody = table.append('tbody'); thead.append('tr') .selectAll('th') .data(columns) .enter() .append('th') .text(function(column) {return column; }); var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { return { column: column, value: row[column]}; }); }) .enter() .append('td') .html(function(d) { if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } return d.value; }); ``` ```html ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could add the following to the ``` .style("cursor", "pointer") .on("click", function(d) { window.open(d.Site, "_blank"); }) ``` just after: ``` .append('tr') ``` Upvotes: 1
2018/03/15
770
2,269
<issue_start>username_0: We are using OrangeHRM 3.1.1 with MySQL 5.5 version and now I need to upgrade to OrangeHRM 4.0 version with MySQL 5.7. After MySQL dump restore (I used command to restore `"mysql -u root -p newdatabase name < dump.sql"`) after restoring database am not able to login (validate credential error in browser (web/index.php/auth/validateCredentials). Can anybody give some inputs how to restore MySQL dump from lower version to higher version<issue_comment>username_1: You could simply change `.text` to `.html` and add tags in your data like this: ``` 'Site': ' [google](www.google.com) ' ``` Or add conditions in the return statement of your data like this. ``` if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } ``` Code below: ```js var data = [ {'Engine':'Google', 'Founded':'1998', 'Monthly-Visitors':4840295000, 'Site':'www.google.com'}, {'Engine':'Baidu', 'Founded':'2000', 'Monthly-Visitors':1471079000, 'Site':'www.baidu.com'}, {'Engine':'Yahoo', 'Founded':'1995', 'Monthly-Visitors':1038375000, 'Site':'www.yahoo.com'}, {'Engine':'Bing', 'Founded':'2009', 'Monthly-Visitors':203482000, 'Site':'www.bing.com'}, {'Engine':'AOL', 'Founded':'1991', 'Monthly-Visitors': 39961000, 'Site':'www.aolsearch.com'} ]; var columns = ['Engine', 'Founded', 'Monthly-Visitors', 'Site']; var table = d3.select('body').append('table'), thead = table.append('thead'), tbody = table.append('tbody'); thead.append('tr') .selectAll('th') .data(columns) .enter() .append('th') .text(function(column) {return column; }); var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { return { column: column, value: row[column]}; }); }) .enter() .append('td') .html(function(d) { if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } return d.value; }); ``` ```html ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could add the following to the ``` .style("cursor", "pointer") .on("click", function(d) { window.open(d.Site, "_blank"); }) ``` just after: ``` .append('tr') ``` Upvotes: 1
2018/03/15
779
2,240
<issue_start>username_0: I'm trying to add 2 Input controls to my Toolbar with Title. But in OverflowToolbar they go to overflow area and in Toolbar control are not moved to the right side by ToolbarSpacer. How do I make this work as expected? ``` ... ``` [OverflowToolbar image](https://i.stack.imgur.com/aXqYx.jpg) Note that only one Input is shown. Toolbar code: ``` ``` [Toolbar image](https://i.stack.imgur.com/QlM4K.jpg)<issue_comment>username_1: You could simply change `.text` to `.html` and add tags in your data like this: ``` 'Site': ' [google](www.google.com) ' ``` Or add conditions in the return statement of your data like this. ``` if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } ``` Code below: ```js var data = [ {'Engine':'Google', 'Founded':'1998', 'Monthly-Visitors':4840295000, 'Site':'www.google.com'}, {'Engine':'Baidu', 'Founded':'2000', 'Monthly-Visitors':1471079000, 'Site':'www.baidu.com'}, {'Engine':'Yahoo', 'Founded':'1995', 'Monthly-Visitors':1038375000, 'Site':'www.yahoo.com'}, {'Engine':'Bing', 'Founded':'2009', 'Monthly-Visitors':203482000, 'Site':'www.bing.com'}, {'Engine':'AOL', 'Founded':'1991', 'Monthly-Visitors': 39961000, 'Site':'www.aolsearch.com'} ]; var columns = ['Engine', 'Founded', 'Monthly-Visitors', 'Site']; var table = d3.select('body').append('table'), thead = table.append('thead'), tbody = table.append('tbody'); thead.append('tr') .selectAll('th') .data(columns) .enter() .append('th') .text(function(column) {return column; }); var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { return { column: column, value: row[column]}; }); }) .enter() .append('td') .html(function(d) { if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } return d.value; }); ``` ```html ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could add the following to the ``` .style("cursor", "pointer") .on("click", function(d) { window.open(d.Site, "_blank"); }) ``` just after: ``` .append('tr') ``` Upvotes: 1
2018/03/15
1,136
3,616
<issue_start>username_0: I have this two tables in my database 1 - tbl\_category 2 - tbl\_shelf\_place (I want to achieve this kind of output where the selected category\_name from the drop-down (book\_category) with a value of category\_id will show the shelf\_code in a textbox instead of a DROPDOWN, based on the equivalent shelf\_id). ``` -------------------------- ------------------------- tlb_category tbl_shelf_place --------------------------- ------------------------- category_id | category_name shelf_id| shelf_code --------------------------- ------------------------- 1 | General Works 1 | General Works Shelf 2 | History 2 | History Shelf ``` Below is my current code for the dependent dropdown. My dropdown code in HTML ``` Choose Category php $query = "SELECT category\_id , category\_name FROM tbl\_category"; $stmt = $mysqlconnection-prepare($query); $stmt->execute(); $stmt->store\_result(); $stmt->bind\_result($category\_id , $category\_name); while($stmt->fetch()) { $getcategoryID = $category\_id; $getcategoryname = $category\_name; echo "{$getcategoryname}"; } ?> ``` My script code ``` function getState(val) { $.ajax({ type: "POST", url: "dropdownrequest.php", data:'category\_id='+val, success: function(data){ $("#book\_shelf").html(data); } }); } ``` dropdownrequest.php ``` php include_once ("../database/dbconnect.php"); if(!empty($_POST["category_id"])) { $query ="SELECT * FROM tbl_shelf_place WHERE shelf_id = '" . $_POST["category_id"] . "'"; $results = $mysqlconnection-query($query); ?> php foreach($results as $shelf) { ? ">php echo $shelf["shelf\_code"]; ? php } } ? ```<issue_comment>username_1: You could simply change `.text` to `.html` and add tags in your data like this: ``` 'Site': ' [google](www.google.com) ' ``` Or add conditions in the return statement of your data like this. ``` if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } ``` Code below: ```js var data = [ {'Engine':'Google', 'Founded':'1998', 'Monthly-Visitors':4840295000, 'Site':'www.google.com'}, {'Engine':'Baidu', 'Founded':'2000', 'Monthly-Visitors':1471079000, 'Site':'www.baidu.com'}, {'Engine':'Yahoo', 'Founded':'1995', 'Monthly-Visitors':1038375000, 'Site':'www.yahoo.com'}, {'Engine':'Bing', 'Founded':'2009', 'Monthly-Visitors':203482000, 'Site':'www.bing.com'}, {'Engine':'AOL', 'Founded':'1991', 'Monthly-Visitors': 39961000, 'Site':'www.aolsearch.com'} ]; var columns = ['Engine', 'Founded', 'Monthly-Visitors', 'Site']; var table = d3.select('body').append('table'), thead = table.append('thead'), tbody = table.append('tbody'); thead.append('tr') .selectAll('th') .data(columns) .enter() .append('th') .text(function(column) {return column; }); var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { return { column: column, value: row[column]}; }); }) .enter() .append('td') .html(function(d) { if (d.column === 'Site') { return "[" + d.value + "](+ d.value +)" } return d.value; }); ``` ```html ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could add the following to the ``` .style("cursor", "pointer") .on("click", function(d) { window.open(d.Site, "_blank"); }) ``` just after: ``` .append('tr') ``` Upvotes: 1
2018/03/15
648
2,241
<issue_start>username_0: for high to low: ``` $query="select * from sponsors order by budget DESC"; ``` for low to high: ``` $query="select * from sponsors order by budget "; ``` When executing this query, it only orders by the first digit. For example: budget: 95,00,000 6,00,000 3,00,000 29,58,000 22,78,000 What am I doing wrong?<issue_comment>username_1: I think your column data type is char so please make ensure you use int datatype for column. Upvotes: 1 <issue_comment>username_2: ORDER BY in ANSI SQL (you didn't specify your particular variant of sql; that would help :-) is dependent on the column definition. If you want to order by numerical value (instead of string-based - if we're guessing, it looks like you have a char/varchar/text column here), you'll need to use a numerical column type, e.g., INT, FLOAT, DECIMAL, etc. In other words, you need to tell SQL (via your schema) that you have numerical data specifically. 10 is only less than 3 in base 10. :-) Upvotes: 0 <issue_comment>username_3: You need to store budget as numerical datatype such as unsigned [INT or BIGINT](https://dev.mysql.com/doc/refman/5.5/en/integer-types.html) in database. For now, ORDER will treat all the data as TEXT. That is why they are ordering by first digits. Upvotes: 0 <issue_comment>username_4: You can try this one ``` SELECT * FROM sponsors ORDER BY cast(budget as int) ``` if this is you column value (6,00,00 p.a) ``` SELECT * FROM sponsors ORDER BY cast(LEFT(budget,length(budget)-3) as int) ``` Upvotes: 0 <issue_comment>username_5: The "correct" way to solve this problem is to re-architect the table and split budget into two fields, one int and one varchar which describes what the int refers to e.g. "p.a" or "ongoing" or "per month" or whatever. That way you can properly order your data by the int field. In the interim, you should be able to order the data by stripping the commas out of the numeric part of the field and then casting it to an unsigned integer: ``` SELECT * FROM sponsors ORDER BY CAST(REPLACE(budget, ',', '') AS UNSIGNED) ``` This should work as long as all the budget values start with numbers which may or may not contain commas. Upvotes: 2 [selected_answer]
2018/03/15
762
3,047
<issue_start>username_0: I am using RestTemplate with ConnectionPooling using PoolingHttpClientConnectionManager as in below code : ``` PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(excConfig.getImsServerEndpoint())), IMS_ROUTE_MAX_CONNECTIONS); CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connectionManager).build(); HttpComponentsClientHttpRequestFactory httpReqFactory = new HttpComponentsClientHttpRequestFactory(httpclient); httpReqFactory.setReadTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS); httpReqFactory.setConnectionRequestTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS); httpReqFactory.setConnectTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS); restTemplate = new RestTemplate(httpReqFactory); ``` Does RestTemplate take care of terminating stale connections by itself? Or do I need to put in some specific handling for the same?<issue_comment>username_1: I think your column data type is char so please make ensure you use int datatype for column. Upvotes: 1 <issue_comment>username_2: ORDER BY in ANSI SQL (you didn't specify your particular variant of sql; that would help :-) is dependent on the column definition. If you want to order by numerical value (instead of string-based - if we're guessing, it looks like you have a char/varchar/text column here), you'll need to use a numerical column type, e.g., INT, FLOAT, DECIMAL, etc. In other words, you need to tell SQL (via your schema) that you have numerical data specifically. 10 is only less than 3 in base 10. :-) Upvotes: 0 <issue_comment>username_3: You need to store budget as numerical datatype such as unsigned [INT or BIGINT](https://dev.mysql.com/doc/refman/5.5/en/integer-types.html) in database. For now, ORDER will treat all the data as TEXT. That is why they are ordering by first digits. Upvotes: 0 <issue_comment>username_4: You can try this one ``` SELECT * FROM sponsors ORDER BY cast(budget as int) ``` if this is you column value (6,00,00 p.a) ``` SELECT * FROM sponsors ORDER BY cast(LEFT(budget,length(budget)-3) as int) ``` Upvotes: 0 <issue_comment>username_5: The "correct" way to solve this problem is to re-architect the table and split budget into two fields, one int and one varchar which describes what the int refers to e.g. "p.a" or "ongoing" or "per month" or whatever. That way you can properly order your data by the int field. In the interim, you should be able to order the data by stripping the commas out of the numeric part of the field and then casting it to an unsigned integer: ``` SELECT * FROM sponsors ORDER BY CAST(REPLACE(budget, ',', '') AS UNSIGNED) ``` This should work as long as all the budget values start with numbers which may or may not contain commas. Upvotes: 2 [selected_answer]
2018/03/15
1,116
3,852
<issue_start>username_0: Here's my database table: ``` id name icon parent_id 1 Account Settings fa fa-cog 0 2 Support fa fa-wrench 0 3 FAQ fa fa-question 2 4 Contact fa fa-phone 2 ``` I'm trying to query menu list from database and return it as json format like below: ``` [{ "name": "Account Settings", "icon": "fa fa-cog" }, { "name": "Support", "icon": "fa fa-wrench", "children": [{ "name": "FAQ", "icon": "fa fa-question" }, { "name": "Contact", "icon": "fa fa-phone" }] }] ``` However, I don't know how can I insert the child into the parent section. My code as below: ``` $menu_list = MobMenu::all('name', 'icon', 'parent_id'); foreach ($menu_list as $data) { $child = MobMenu::find($data->parent_id); } return json_encode($menu_list); ``` How can I create "children" and insert it into the parent section ?<issue_comment>username_1: You can use this code. ``` $menu_list = MobMenu::all('name', 'icon', 'parent_id'); //without where condition $menu_list = MobMenu::where('parent_id',0)->select('name','icon','parent_id')->get(); //with where condition foreach ($menu_list as $key=>$data) { $menu_list[$key]['children'] = MobMenu::find($data->parent_id); } return json_encode($menu_list); ``` It will add children in menu\_list array and you can convert it into json. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can transform your current output to hierarchical ``` php $results = [ ["id"=1,"name"=>"Account Settings","icon"=>'fa fa-cog',"parent_id"=>0], ["id"=>2,"name"=>"Support","icon"=>'fa fa-wrench',"parent_id"=>0], ["id"=>3,"name"=>"FAQ","icon"=>'fa fa-question',"parent_id"=>2], ["id"=>4,"name"=>"Contact","icon"=>'fa fa-phone',"parent_id"=>2] ]; $final = array(); foreach($results as $r){ if($r['parent_id']){ $final[$r['parent_id']]['children'][] = $r; }else{ $final[$r['id']] = $r; } } print_r($final); ?> ``` [Live Demo](https://eval.in/972264) Output ``` Array ( [1] => Array ( [id] => 1 [name] => Account Settings [icon] => fa fa-cog [parent_id] => 0 ) [2] => Array ( [id] => 2 [name] => Support [icon] => fa fa-wrench [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 3 [name] => FAQ [icon] => fa fa-question [parent_id] => 2 ) [1] => Array ( [id] => 4 [name] => Contact [icon] => fa fa-phone [parent_id] => 2 ) ) ) ) ``` Upvotes: 1 <issue_comment>username_3: You may use the [`transform`](https://laravel.com/docs/5.6/collections#method-transform) method ``` $menu_list = MobMenu::all(); $menu_list->transform(function ($item) { $children = MobMenu::where('parent_id', $item->id) ->get(['name', 'icon']); if ($children->count()) { $item->children = $children; } return $item; }); return json_encode($menu_list); ``` Upvotes: 2 <issue_comment>username_4: Make a new `relationship` callled `children` in your `MobMenu` model. ``` public function children() { return $this->hasMany(MobMenu::class, 'parent_id','id'); } ``` Then in controller, use `with()` to get the `childrens` data. ``` $menu_list = MobMenu::with('children')->where('parent_id',0)->get()->toArray(); ``` Upvotes: 1
2018/03/15
851
2,811
<issue_start>username_0: I want to extract data from my database, and I wish the when I extract the data all the h/p number all is same format. sample: +60161234567 016-1234567 0161234567 To: +6016-1234567<issue_comment>username_1: You can use concat and substr function to change format of phone number column during extracting data as below: ``` SELECT CONCAT(SUBSTR( contact_number, 1, 5 ) , "-", SUBSTR( contact_number, 5 ) ) AS phone_no FROM test_table; ``` Upvotes: 0 <issue_comment>username_2: The following simple code will give you the expected Output. ``` SELECT (CASE WHEN contact_number RLIKE "^[+]([0-9]){10}" THEN CONCAT(SUBSTRING(contact_number,1,5), "-", SUBSTRING(contact_number,6,7)) WHEN contact_number RLIKE "^([0-9]){3}[-]([0-9]){7}" THEN CONCAT("+6",contact_number) WHEN contact_number RLIKE "^([0-9]){10}" THEN CONCAT("+6",SUBSTRING(contact_number,1,3), "-", SUBSTRING(contact_number,4,7)) ELSE 'Number is not in correct format' END) AS 'Phone Number' FROM table_name; ``` We have to use the regular expression for checking number format. I have done the query based on the number format that you have given. If a different format is there then try corresponding regular expression. In the query, the 1st case for the number like "+60161234567", the 2nd case for the number like "016-1234567" and Last case for the number like "0161234567". I have attached my [SQLFiddle](http://sqlfiddle.com/#!9/5d71398/1) to this solution. You can check it. Thank you! Upvotes: 1 <issue_comment>username_3: Try this: ``` SELECT CONCAT("+6",SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),1,3), "-", SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),4,7)) FROM `phone` ``` Upvotes: 0 <issue_comment>username_4: It seems that an h/p number is a phone number? This isn't a number, in the data type sense, so it shouldn't be stored as one. Numbers can have math applied to them and represent some finite value. Varchar or char is probably the appropriate data type here. When inserting the data, standardize the way you record the data and fix it in your application before inserting. In the US, phone numbers can be shown as `(555) 123-4567` or `555-123-4567` so you could just pick the format — or what I would do is store it as `5551234567` and then format it in the application when displaying it to the user (that way, the user can prefer one format or the other). At the minimum, though, you should standardize the format when inserting the string so that you don't have to deal later with a variety of formats. For data that already exists, I think your best bet is to fix the whole database. I would use some programming or scripting language that's good at manipulating data to fix it in the database (personally I think Python is a good choice). Upvotes: 0
2018/03/15
827
2,912
<issue_start>username_0: Running into the subject issue trying to update the proxies with nswag... funny enough, the app that this came with is preconfigured to use a specific port for that service, but I don't see anything on that port using `netstat -ano` in the command line. Does anyone have any thoughts?<issue_comment>username_1: You can use concat and substr function to change format of phone number column during extracting data as below: ``` SELECT CONCAT(SUBSTR( contact_number, 1, 5 ) , "-", SUBSTR( contact_number, 5 ) ) AS phone_no FROM test_table; ``` Upvotes: 0 <issue_comment>username_2: The following simple code will give you the expected Output. ``` SELECT (CASE WHEN contact_number RLIKE "^[+]([0-9]){10}" THEN CONCAT(SUBSTRING(contact_number,1,5), "-", SUBSTRING(contact_number,6,7)) WHEN contact_number RLIKE "^([0-9]){3}[-]([0-9]){7}" THEN CONCAT("+6",contact_number) WHEN contact_number RLIKE "^([0-9]){10}" THEN CONCAT("+6",SUBSTRING(contact_number,1,3), "-", SUBSTRING(contact_number,4,7)) ELSE 'Number is not in correct format' END) AS 'Phone Number' FROM table_name; ``` We have to use the regular expression for checking number format. I have done the query based on the number format that you have given. If a different format is there then try corresponding regular expression. In the query, the 1st case for the number like "+60161234567", the 2nd case for the number like "016-1234567" and Last case for the number like "0161234567". I have attached my [SQLFiddle](http://sqlfiddle.com/#!9/5d71398/1) to this solution. You can check it. Thank you! Upvotes: 1 <issue_comment>username_3: Try this: ``` SELECT CONCAT("+6",SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),1,3), "-", SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),4,7)) FROM `phone` ``` Upvotes: 0 <issue_comment>username_4: It seems that an h/p number is a phone number? This isn't a number, in the data type sense, so it shouldn't be stored as one. Numbers can have math applied to them and represent some finite value. Varchar or char is probably the appropriate data type here. When inserting the data, standardize the way you record the data and fix it in your application before inserting. In the US, phone numbers can be shown as `(555) 123-4567` or `555-123-4567` so you could just pick the format — or what I would do is store it as `5551234567` and then format it in the application when displaying it to the user (that way, the user can prefer one format or the other). At the minimum, though, you should standardize the format when inserting the string so that you don't have to deal later with a variety of formats. For data that already exists, I think your best bet is to fix the whole database. I would use some programming or scripting language that's good at manipulating data to fix it in the database (personally I think Python is a good choice). Upvotes: 0
2018/03/15
816
3,373
<issue_start>username_0: I've got the `BaseComponent` which got some dependencies injected. The first dependency `EntityService` is correct and necessary. But`AnyOtherService` is only used inside the abstract `BaseComponent`. Instead of injecting it inside the `ChildComponent`, where it is not used, I'd like to inject it only inside `BaseComonent`. *Why do I have to push it through the `ChildComponent` towards the `BaseComponent`? The best solution would be to encapsulate it inside the `BaseComponent`.* **base.component.ts** ``` export abstract class BaseComponent { constructor( protected entityService: EntityService, // protected anyOtherService: AnyOtherService // @todo add this ) { } } ``` **child.component.ts** ``` @Component() export class ChildComponent extends BaseComponent { constructor( private firstService: FirstService, private secondService: SecondService, protected anyOtherService: AnyOtherService // @todo remove this ) { super( firstService, anyOtherService // @todo remove this ); } } ```<issue_comment>username_1: So you can pass **Injector** to base component constructor(**UPDATE**): ``` export abstract class BaseComponent { protected anyOtherService: AnyOtherService; constructor( inject: Injector protected entityService: EntityService, // protected anyOtherService: AnyOtherService // @todo add this ) { this.anyOtherService= inject.get(AnyOtherService); } } @Component() export class ChildComponent extends BaseComponent { constructor( inject: Injector, private firstService: FirstService, private secondService: SecondService ) { super( inject, firstService ); } } ``` The idea is to inject **Injector** and some providers in child component and pass it to parent base component without passing all base class dependencies. With passing injector, child classes(components) doesn't need to inject all dependencies of parent(base) class and pass throw super(dep1, dep2..., **baseDep1...**). > > Could you please explain in your answer, why it has to be like you've > said with private inside child and protected inside parent? > > > I think the **injector** shouldn't be the property of child/base class. If will be, the error throws as you comment below. The error is about, **Base** and **Child** class can't have the same property in their class. That's why we need to omit private/protected or any **access modifier** to **injector** in constructor, also because **Injector** is only needed in constructor to manually inject what we need in some specific cases as this. Upvotes: 3 [selected_answer]<issue_comment>username_2: you can try like this , make use of injector , export it from appmodule and use it in you base class ``` import {Injector} from '@angular/core'; //exporting injector export let AppInjector: Injector; export class AppModule { constructor(private injector: Injector) { AppInjector = this.injector; } } ``` and then base.component.ts ``` export abstract class BaseComponent { private anyOtherService : AnyOtherService ; constructor( protected entityService: EntityService, // protected anyOtherService: AnyOtherService // @todo add this ) { this.anyOtherService = AppInjector.get(AnyOtherService ); } } ``` Upvotes: 1
2018/03/15
715
3,019
<issue_start>username_0: We have a jsp file with generic page content for admin purpose. In this we have to hide audit columns, we have used annotation to specify the columns to show in search result, and we have one custom class that filters special character fields. ``` Gson gson = gsonBuilder.registerTypeHierarchyAdapter(Object.class, new CustomJsonSerializer()) .serializeNulls() .setExclusionStrategies(new AdminTableSearchJsonStrategy()) .create(); ``` With the above code special character filters but hiding audit columns not working. If we remove **CustomJsonSerializer** class then audit column exclusive working, but we want these two to be there, please advice this in case.<issue_comment>username_1: So you can pass **Injector** to base component constructor(**UPDATE**): ``` export abstract class BaseComponent { protected anyOtherService: AnyOtherService; constructor( inject: Injector protected entityService: EntityService, // protected anyOtherService: AnyOtherService // @todo add this ) { this.anyOtherService= inject.get(AnyOtherService); } } @Component() export class ChildComponent extends BaseComponent { constructor( inject: Injector, private firstService: FirstService, private secondService: SecondService ) { super( inject, firstService ); } } ``` The idea is to inject **Injector** and some providers in child component and pass it to parent base component without passing all base class dependencies. With passing injector, child classes(components) doesn't need to inject all dependencies of parent(base) class and pass throw super(dep1, dep2..., **baseDep1...**). > > Could you please explain in your answer, why it has to be like you've > said with private inside child and protected inside parent? > > > I think the **injector** shouldn't be the property of child/base class. If will be, the error throws as you comment below. The error is about, **Base** and **Child** class can't have the same property in their class. That's why we need to omit private/protected or any **access modifier** to **injector** in constructor, also because **Injector** is only needed in constructor to manually inject what we need in some specific cases as this. Upvotes: 3 [selected_answer]<issue_comment>username_2: you can try like this , make use of injector , export it from appmodule and use it in you base class ``` import {Injector} from '@angular/core'; //exporting injector export let AppInjector: Injector; export class AppModule { constructor(private injector: Injector) { AppInjector = this.injector; } } ``` and then base.component.ts ``` export abstract class BaseComponent { private anyOtherService : AnyOtherService ; constructor( protected entityService: EntityService, // protected anyOtherService: AnyOtherService // @todo add this ) { this.anyOtherService = AppInjector.get(AnyOtherService ); } } ``` Upvotes: 1
2018/03/15
499
1,841
<issue_start>username_0: Studying React right now. I am on the stage of Router and found some code in their documentation that I do not understand. (they use a lot of short-syntax operators and other stuff so it is hard to google or come up with idea what it is for). So here is [code](https://reacttraining.com/react-router/web/example/auth-workflow): ``` const { from } = this.props.location.state || { from: { pathname: "/" } }; const { redirectToReferrer } = this.state; ``` While declaring "something" on the left it is inside of `{ }`, why?<issue_comment>username_1: It is called object destructuring. It’s a JavaScript expression that allows us to extract data from arrays, objects, maps and sets. Please refer to link below for more details. <https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/> Upvotes: 4 [selected_answer]<issue_comment>username_2: It is part of ECMASCRIPT 2015 (ES6). Basically, **Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes they are more convenient**. Destructuring also works great with complex functions that have a lot of parameters, default values etc. For Futher information about destructing assignments or es6 features this [link](https://github.com/mbeaudru/modern-js-cheatsheet) helps alot Upvotes: 1 <issue_comment>username_3: for those who are really still confused about object destructuring, I can give an example: suppose you have an object called car ``` const car = { type: 'van', model: 'honda', ...etc, } ``` then instead of making a repetition of calling some variables inside the car object like this: ``` const type = car.type; const model = car.model; ``` you can use destructuring object and write it in a more simple way: ``` const { type, model } = car; ``` Upvotes: 4
2018/03/15
611
2,345
<issue_start>username_0: I have a websocket logic written in Component A as follows. ``` this.socketService.connect('/socket_url'); this.statusSubscription = this.socketService.messages .subscribe(result => { if (result !== 'pong') { // update Component B with the response obtained } }); ``` I wonder how can I update Component B, whenever I receive a websocket event on the go.<issue_comment>username_1: You can make use of a shared Service and Observable as follows. shared-data.service.ts ``` import {Injectable} from '@angular/core'; import {Subject} from 'rxjs/Subject'; import {Observable} from 'rxjs/Observable'; @Injectable() export class SharedDataService { public userStatusToggle: Observable; private userStatusSubject = new Subject(); constructor() { this.userStatusToggle = this.userStatusSubject.asObservable(); } notifyUserStatusChange(data) { this.userStatusSubject.next(data); } } ``` Component A ``` . . . constructor(private sharedDataService: SharedDataService) { } this.socketService.connect('/socket_url'); this.statusSubscription = this.socketService.messages .subscribe(result => { if (result !== 'pong') { this.sharedDataService.notifyUserStatusChange(result); } }); ``` Component B ``` . . . constructor(private sharedDataService: SharedDataService) { } this.sharedDataService.userStatusToggle.subscribe(userStatus => { // Do action with the 'userStatus' obtained }); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also do this if the components are in parent/child relationship: Component A(parent): ``` this.socketService.connect('/socket_url'); this.statusSubscription = this.socketService.messages .subscribe(result => { if (result !== 'pong') { this.componentBdata = result; } }); ``` In componentA.html ``` ``` In componentB (child): ``` export class ComponentB implements OnChanges, OnInit { @Input() data: string; private _data: string; constructor() {} ngOnChanges(changes: SimpleChanges) { const data: SimpleChange = changes.data; if(data.previousValue ! = data.currentValue){ this._data = data.currentValue; // do your change here } } } ``` Upvotes: 1
2018/03/15
415
1,569
<issue_start>username_0: I want to use Apache Camel to get a message on IBM MQ in a spring boot project. I use sprin boot annotation based. I dont find any fully example: pom.xml, receiver, configuration class, ... Is there anyone to help me? Any link, documentation, ...? Thanks a lot of<issue_comment>username_1: You could search for an example that uses Spring Boot, Camel and ActiveMQ to get a first impression. Since you use Camel most differences between IBM MQ and ActiveMQ should be hidden. However, you have to use the standard [JMS component](https://github.com/apache/camel/blob/master/components/camel-jms/src/main/docs/jms-component.adoc) instead of the dedicated [ActiveMQ component](http://camel.apache.org/activemq.html) of Camel. Upvotes: 0 <issue_comment>username_2: In your Application class, you will need create a bean for a IBM component, I just did it for an application in spring xml, like this: ``` ``` But once I did a bean connection for a MongDB in spring boot, may you can do something like this: ``` @Bean(name = "myDb") public MongoClient myDb() { return new MongoClient(); } ``` But putting the IBM values inside this bean. Upvotes: 0 <issue_comment>username_3: Take a look at [a new Spring Boot Starter for MQ](http://github.com/ibm-messaging/mq-jms-spring) that may help here. The README shows how to modify the JMS Getting Started sample [here](https://spring.io/guides/gs/messaging-jms/) to use IBM MQ instead of ActiveMQ. And the MQ jars - including this starter - are all on Maven Central for easy access. Upvotes: 2
2018/03/15
513
1,852
<issue_start>username_0: [![Firebase DB](https://i.stack.imgur.com/MU7pa.png)](https://i.stack.imgur.com/MU7pa.png) I want a function to be called whenever a new child is added to "chat". I know this can be done using "child\_added" event. However, from that function, I want to modify the newly created child. So suppose a new child "123456" is added to chat and I want to update the "123456" object in the DB. I think I could solve the problem if I somehow manage to get the key (in this case it's 123456) of the newly added object. **Is there a way to achieve this?**<issue_comment>username_1: You could search for an example that uses Spring Boot, Camel and ActiveMQ to get a first impression. Since you use Camel most differences between IBM MQ and ActiveMQ should be hidden. However, you have to use the standard [JMS component](https://github.com/apache/camel/blob/master/components/camel-jms/src/main/docs/jms-component.adoc) instead of the dedicated [ActiveMQ component](http://camel.apache.org/activemq.html) of Camel. Upvotes: 0 <issue_comment>username_2: In your Application class, you will need create a bean for a IBM component, I just did it for an application in spring xml, like this: ``` ``` But once I did a bean connection for a MongDB in spring boot, may you can do something like this: ``` @Bean(name = "myDb") public MongoClient myDb() { return new MongoClient(); } ``` But putting the IBM values inside this bean. Upvotes: 0 <issue_comment>username_3: Take a look at [a new Spring Boot Starter for MQ](http://github.com/ibm-messaging/mq-jms-spring) that may help here. The README shows how to modify the JMS Getting Started sample [here](https://spring.io/guides/gs/messaging-jms/) to use IBM MQ instead of ActiveMQ. And the MQ jars - including this starter - are all on Maven Central for easy access. Upvotes: 2
2018/03/15
655
2,182
<issue_start>username_0: I am working on a project that gets data from a text file and that value needs to be stored in a variable. but the following code does not work properly. sometimes it works while other times it returns > > ValueError: invalid literal for int() with base 10: '' > > > the following is the code used: ``` def main(): # Txt read global id input = open('data.txt', 'r') lines = input.readlines() i = 0 for line in lines: i += 1 id = int(line) main() print id ``` Data would be in single int followed by new line in text file. [![enter image description here](https://i.stack.imgur.com/dlk30.png)](https://i.stack.imgur.com/dlk30.png) Any Help would be appreciated.<issue_comment>username_1: The newline character "\n" is casing the error. ``` def main(): # Txt read global id data = open('data.txt', 'r').read() data = data+'0' data = data.replace('\n','+0+') id = eval(data) main() print(id) ``` Upvotes: 0 <issue_comment>username_2: Few things first Don't use `input` as a variable, since it's a built-in function in python. It is not considered a good practice. Also, `id` also happens to be a built-in function, so avoid that as well Also, I would suggest to read the whole file as string and the split based on `\n`. This will help you to strip the extra newlines at end (and start if you wish) You can use something like this: ``` def main(): # Txt read input1 = open('text.txt', 'r').read().strip() l = input1.split("\n") #convert to int ll = [int(s) for s in l] print(ll) main() ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: In your code you will get only last value in file for getting all values use list and store them in list and there is no need of `i` and increment of `i` if want to calculate total number of values use `len(id)` Try Below code ``` def main(): # Txt read global id id=[] input = open('data.txt', 'r') lines = input.readlines() for line in lines: if line.strip(): #Checking Non-Empty Line id.append(int(line.strip())) main() print id print "Total Valuse: "+str(len(id)) ``` Upvotes: 1
2018/03/15
1,309
3,846
<issue_start>username_0: I have created a controller with ActionResult Index and created a list of Student class as: ``` public ActionResult Index() { var list = new List() { new Student{Id=1,RegNo="Bcs153048",Name="Ali",Age=21,}, new Student{Id=2,RegNo="Bcs153044",Name="Talha",Age=22,}, new Student{Id=3,RegNo="Bcs153064",Name="Luqman",Age=20,}, new Student{Id=4,RegNo="Bcs153054",Name="Saad",Age=19,}, new Student{Id=5,RegNo="Bcs153036",Name="Hashir",Age=20,}, }; //var jsonString = JsonConvert.SerializeObject(list); //return View(list); return Json(list , JsonRequestBehavior.AllowGet); } ``` I the view i want to view the list of students in JQuery datatable and i did something like this: ``` | Id | Registeration No | Name | Age | | --- | --- | --- | --- | ``` and then below this i have written script as ``` @section scripts { $(document).ready( function () { var dataTable = $("#students").DataTable({ ajax: { url: "/student/index", dataSrc: "", }, columns: [ { data: "Id" }, { data: "RegNo", }, { data: "Name" }, { data: "Age", } ] }); }); } ``` But i got the Json result when i run the application and navigate to /Student/index wile i want to display list in Jquery datatable : > > [{"Id":1,"Name":"Ali","Age":21,"RegNo":"Bcs153048"},{"Id":2,"Name":"Talha","Age":22,"RegNo":"Bcs153044"},{"Id":3,"Name":"Luqman","Age":20,"RegNo":"Bcs153064"},{"Id":4,"Name":"Saad","Age":19,"RegNo":"Bcs153054"},{"Id":5,"Name":"Hashir","Age":20,"RegNo":"Bcs153036"}] > > > I have added libraries in Bundle.config as: [Libraries in BundleConfig](https://i.stack.imgur.com/TbhTm.png)<issue_comment>username_1: Add a partial view and add the below script and html table. call that partial view in your main view. Upvotes: -1 <issue_comment>username_2: You said > > "i get the Json result when i run the application and navigate to > /Student/index " > > > ...yes, that's correct, because that's what "student/index" returns in your code. But why are you navigating there in your browser directly? It doesn't lead to a view which you can display to the user. It's the ajax call (defined in the DataTables setup) which should request that data. I think maybe you have become confused between the two things. In your browser you should be navigating to the View which renders the datatable. This will have a separate action method which returns a whole HTML view, not JSON, and thus also has a separate URL from the method which fetches the JSON. So when you make a HTTP request to the main view in your browser, it loads the view HTML into the browser. Then the JS code on that page runs, loads the DataTable, which triggers the separate HTTP request via ajax to fetch the JSON data. For example: "Student" controller: ``` //load the view [HttpGet] public ActionResult Index() { return View(); } //load the JSON [HttpGet] public JsonResult GetStudentList() { var list = new List() { new Student{Id=1,RegNo="Bcs153048",Name="Ali",Age=21,}, new Student{Id=2,RegNo="Bcs153044",Name="Talha",Age=22,}, new Student{Id=3,RegNo="Bcs153064",Name="Luqman",Age=20,}, new Student{Id=4,RegNo="Bcs153054",Name="Saad",Age=19,}, new Student{Id=5,RegNo="Bcs153036",Name="Hashir",Age=20,}, }; return Json(list , JsonRequestBehavior.AllowGet); } ``` "Student/Index" View: ``` | Id | Registration No | Name | Age | | --- | --- | --- | --- | @section scripts { $(document).ready( function () { var dataTable = $("#students").DataTable({ ajax: { url: '@Url.Action("GetStudentList", "student")', //note the use of a HTML helper to generate the correctly routed URL, and also the change of action name to "GetStudentList" dataSrc: "", }, columns: [ { data: "Id" }, { data: "RegNo", }, { data: "Name" }, { data: "Age", } ] }); }); } ``` Upvotes: -1 [selected_answer]
2018/03/15
590
2,418
<issue_start>username_0: I meticulously backed up a working WordPress site, files DB tables, the works. I moved it to a new server, got everything working, the site renders, the DB is recognized, etc. The issue is anytime I try to log-in, after login the site always redirects to the homepage `(mysite.com/index.php)` I have scoured every PHP page for text like 'site\_url' and 'wp-redirect' 'redirect' looking for the offending code that will not direct me to the admin dashboard. To be honest, I am not even sure what page the site is supposed to redirect to. I can always reinstall, but then I'd get stuck with the daunting task of having to manually rebuild all the headers, with the images, embedded flash and the rest of it. Since the site was working at the previous location, and not a single byte was lost on the move, with all the tables updated to show the correct server name, I am stuck on this issue. I have looked at all the StackOverflow links related to this issue and none of them addressed my issue specifically.<issue_comment>username_1: WordPress never does such redirection. Some security plugin can do. To fix the issue. deactivate all the plugins, you can do this by executing following query ``` UPDATE `wp_options` SET `option_value` = '' WHERE `option_name` = 'active_plugins'; ``` Once done login and activate the plugins one by one and check which one causing the issue. Upvotes: 1 <issue_comment>username_2: I had to re-install WP altogether. Once I did that, I was able to login and see the WP dashboard. To reinstall, I relocated all the files in the main directory and the wp-admin, wp-content, and wp-includes folder. All the other folders I left alone, because they are not affected by the WP install. After the install, you will have to open the wp-config.php file to input the new db name, db user, db password and db host. What you will see is the WP install added a fresh set of tables in the db you named in the config file. The only folder you will then have to copy and paste is the theme folder from the old site into the themes folder in your new install. Now that you can login (yoursite.com/wp-admin), to populate your dashboard, import all the records from the old db table into the new one (the one with the pages and posts you want). If you do that right, all the pages (and blog posts) should populate in the dashboard window. Upvotes: 1 [selected_answer]
2018/03/15
286
1,030
<issue_start>username_0: I am new to CentOS and I am trying to install composer through the terminal. Unforently it keeps saying file not found. My terminal command as root: ``` curl -sS https://getcomposer.org/install | php ``` and the output error is ``` bash: php: command not found curl: (23) Failed writing body ( 0 !=7626) ``` have things changed with composer and the install process for centos or am I missing something?<issue_comment>username_1: You need to install PHP first before you can install composer. Installing PHP with yum package management: ``` yum install php ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You need to install PHP first on centos then you will be able to run your command Upvotes: 0 <issue_comment>username_3: First, install php & php-cli ``` yum install php yum install php-cli ``` and then run composer install [**Read this article too**](https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-centos-6) Upvotes: 0
2018/03/15
455
1,702
<issue_start>username_0: Here is my table. [table patient](https://i.stack.imgur.com/RdB0v.png) I want firstname and lastname to be combined as "name" in datagridview, how can i do this? here is my output [My output of datagridview](https://i.stack.imgur.com/Ftiy9.png) And my code.. ``` private void frmPatient_Load(object sender, EventArgs e) { MySqlConnection con = new MySqlConnection("server = localhost; database = nuclinic; username = root; password = ; Convert Zero Datetime=True"); string query = "select firstname, lastname from patient"; using (MySqlDataAdapter adpt = new MySqlDataAdapter(query, con)) { DataSet dset = new DataSet(); adpt.Fill(dset); dataGridView1.DataSource = dset.Tables[0]; } con.Close(); } ``` I tried this code `"SELECT firstname + ', ' + lastname AS name"`; but it's not working<issue_comment>username_1: You just use the MySQL CONCAT function to concatenate two columns and results into one column as given as name. You can use this to display in the grid view. ``` select CONCAT(firstname,' ', lastname) as name, firstname, lastname from patient ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this: ``` select CONCAT(firstname," ",lastname) as Name from Patient ``` Hope this helps. Upvotes: 0 <issue_comment>username_3: **Replace this** ``` string query = "select firstname, lastname from patient"; ``` **with this** ``` string query = "select CONCAT(firstname," ",lastname) as FullName from Patient"; ``` *Concat Function Combine both name with space sperated* **AS FullName(Column Name) return as that Column Name** Upvotes: 2
2018/03/15
1,800
7,222
<issue_start>username_0: I know how to set the appearance for a independent `UISearchBar`, just like the following. ``` let searchField = searchBar.value(forKey: "searchField") as? UITextField if let field = searchField { field.backgroundColor = UIColor.defaultBackgroundColor field.layer.cornerRadius = 15.0 field.textColor = .white field.tintColor = .white field.font = UIFont.systemFont(ofSize: fl(13)) field.layer.masksToBounds = true field.returnKeyType = .search } ``` But this is not working in the `UISearchController`. [![enter image description here](https://i.stack.imgur.com/EZj4B.png)](https://i.stack.imgur.com/EZj4B.png) I want to set the text color of the placeholder and the left magnifying lens icon to pure white. (It seems there is a colored layer over them now). In addition, the input text is black now, I want it to be white too. In a conclusion, I want to modify the following properties. 1. textField background color 2. textFiled placeholder text color 3. textFiled text color 4. textFiled font Anyone know how do it? Add the following with your code in viewDidAppear: ``` let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]) field.attributedPlaceholder = placeholderString let iconView = field.leftView as! UIImageView iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = .white ``` **Updata:** Put those settings in `ViewDidAppear()` did solve a part of my problem. But the `textfield's background color` changed when I set the bar's background color. Because `searchBar.barTintColor = .red` is not working in iOS11's `UISearchController` embedded in navigation item, I used `searchBar.backgroundColor = .red` It confused me a lot. So how to change searchBar's background and textField's background separately?<issue_comment>username_1: Add the following with your code in viewDidAppear: ``` let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]) field.attributedPlaceholder = placeholderString let iconView = field.leftView as! UIImageView iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = .white ``` Update - the following is the complete code to customize UISearchController colors: ``` override func viewDidAppear(_ animated: Bool) { //sets navigationbar backgroundColor if let navigationbar = self.navigationController?.navigationBar { navigationbar.barTintColor = UIColor.magenta } let searchField = searchController.searchBar.value(forKey: "searchField") as? UITextField //sets searchBar backgroundColor searchController.searchBar.backgroundColor = .blue if let field = searchField { field.layer.cornerRadius = 15.0 //sets text Color field.textColor = .brown //sets indicator and cancel button Color field.tintColor = .green field.font = UIFont.systemFont(ofSize: 13) field.layer.masksToBounds = true field.returnKeyType = .search //sets placeholder text Color let placeholderString = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red]) field.attributedPlaceholder = placeholderString //sets icon Color let iconView = field.leftView as! UIImageView iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = .cyan //sets textField backgroundColor if let backgroundview = field.subviews.first { backgroundview.backgroundColor = UIColor.yellow } } } ``` Upvotes: 2 <issue_comment>username_2: set `attributedPlaceholder` for textfield of search bar ``` @IBOutlet weak var sbSearchBar: UISearchBar! if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField { textfield.backgroundColor = UIColor.red textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]) if let leftView = textfield.leftView as? UIImageView { leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate) leftView.tintColor = UIColor.white } } ``` Here is result: [![enter image description here](https://i.stack.imgur.com/lRxxh.png)](https://i.stack.imgur.com/lRxxh.png) Update: ------- I think, this may help you: [how to change uitextfield color in searchcontroller?](https://stackoverflow.com/questions/47814179/how-to-change-uitextfield-color-in-searchcontroller/47814369#47814369) Just apply your color combination in this code and see. ``` if #available(iOS 11.0, *) { let sc = UISearchController(searchResultsController: nil) sc.delegate = self let scb = sc.searchBar scb.tintColor = UIColor.white scb.barTintColor = UIColor.white if let textfield = scb.value(forKey: "searchField") as? UITextField { //textfield.textColor = // Set text color if let backgroundview = textfield.subviews.first { // Background color backgroundview.backgroundColor = UIColor.white // Rounded corner backgroundview.layer.cornerRadius = 10; backgroundview.clipsToBounds = true; } } if let navigationbar = self.navigationController?.navigationBar { navigationbar.barTintColor = UIColor.blue } navigationItem.searchController = sc navigationItem.hidesSearchBarWhenScrolling = false } ``` **Result:** ![enter image description here](https://i.stack.imgur.com/KkLnS.gif) Upvotes: 5 [selected_answer]<issue_comment>username_3: The accepted solution does not work for iOS 13, you are getting the following error (testet with Obj-C Code): > > Terminating app due to uncaught exception 'NSGenericException', > reason: 'Access to UISearchBar's \_searchField ivar is prohibited. This > is an application bug' > > > But now you have the option to access UISearchBar's TextField directly, without using a private API. ``` if (@available(iOS 13, *)) { self.searchController.searchBar.searchTextField.backgroundColor = [UIColor whiteColor]; self.searchController.searchBar.searchTextField.tintColor = [UIColor darkGrayColor]; } else { UITextField *txfSearchField = [self.searchController.searchBar valueForKey:@"_searchField"]; UIView *background = txfSearchField.subviews.firstObject; background.layer.cornerRadius = 10; background.clipsToBounds = true; background.backgroundColor=[UIColor whiteColor]; txfSearchField.tintColor=[UIColor darkGrayColor]; txfSearchField.textColor = [UIColor redColor]; } ``` Upvotes: 1
2018/03/15
1,570
5,401
<issue_start>username_0: I'm finding that sourcing the following bash script does not cause the a sequence of commands to stop when pipelined with `&&`. **sourceme.sh:** ```bash #!/usr/bin/env bash set -o errexit set -o | grep errexit echo "About to error from sourceme.sh..." $(false) echo "sourceme.sh did not exit on error (exit code: $?)" ``` This is the call to demonstrate the problem. ``` (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` The output I get from this is as follows. ``` errexit on About to error from sourceme.sh... sourceme.sh did not exit on error (exit code: 1) sourceme.sh did not error (exit code: 0) ``` This is the opposite of what I expected, where I expected to see the the whole command die when `$(false)` is reached in `sourceme.sh`, producing the following outout. ``` errexit on About to error from sourceme.sh... ``` Continuing the bizarreness, if I use `;` in place of `&&`, then I would expect the command continue, but this is not what happens. ``` $ (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") errexit on About to error from sourceme.sh... ``` So when sourcing the file `&&` behaves as I expect `;` to behave, and `;` behaves as I would expect to `&&` to behave. Where am I going wrong with my understanding of how this should work?<issue_comment>username_1: The idea, roughly stated, is that `set -o errexit` (or, equivalently, `set -e`) causes the shell to exit on **uncaught** errors. The fact that `&&` follows `source sourceme.sh` means that the error is caught. So, if the `source` and `echo` commands are connected with `;`, the shell exits: ``` $ (source sourceme.sh ; echo "sourceme.sh did not error (exit code: $?)") errexit on About to error from sourceme.sh... ``` But, if the `source` and `echo` commands are connected with `&&`, then the shell assumes that you have anticipated the possibility of the `source` command failing and the shell does not exit: ``` $ (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") errexit on About to error from sourceme.sh... sourceme.sh did not exit on error (exit code: 1) sourceme.sh did not error (exit code: 0) ``` Much of the behavior of `set -e` may be considered odd or unexpected. For more examples, see [Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?](http://mywiki.wooledge.org/BashFAQ/105). ### Documentation The behavior of `set -e` (errexit) is defined more precisely in `man bash`: > > **-e** > Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL > GRAMMAR above), exits with a non-zero status. The shell does > not exit if the command that fails is part of the command list > immediately following a while or until keyword, part of the test > following the if or elif reserved words, part of any command executed > in a && or || list except the command following the final && or ||, > any command in a pipeline but the last, or if the command's return > value is being inverted with !. If a compound command other than a > subshell returns a non-zero status because a command failed while -e > was being ignored, the shell does not exit. A trap on > ERR, if set, is executed before the shell exits. This option applies > to the shell environment and each subshell > environment separately (see COMMAND EXECUTION ENVIRONMENT above), > and may cause subshells to exit before executing all the > commands in the subshell. > > If a compound > command or shell function executes in a context where -e is being > ignored, none of the commands executed within the > compound command or function body will be affected by the -e setting, > even if -e is set and a command returns a failure status. If a > > compound command or shell function sets -e while executing in a > context where -e is ignored, that setting will not have any effect > until the compound command or the command containing the function call > completes. > > > ### Synonyms As documented in `man bash` as well as in `help set`, the following two commands are equivalent: ``` set -e set -o errexit ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: What you are observing is this. This command doesn't exit on error: ``` (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` However this command: ``` (bash sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` does exit so `&&` is not the only reason of this weirdness. It is combination of `source` and `&&` that makes it not to exit. You have also noted that use of `;` instead of `&&` makes it exit as in following command: ``` (bash sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` **This behaviour is actually dependent of bash version in use.** When I run this command on OSX `bash 3.2.57(1)-release` **it does exit**: ``` (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` ``` errexit on About to error from sourceme.sh... ``` However **on bash versions `4.2` and above behaviour changes** and `set -e` doesn't exit when used with `&&`. So bottomline is that `set -e` is highly unreliable and one should avoid depending on it's behaviour in important shell scripts. Upvotes: 1
2018/03/15
1,303
4,675
<issue_start>username_0: I was asked to write a program to find string "error" from a file and print matched lines in python. 1. Will first open a file with read more 2. i use fh.readlines and store it in a variable 3. After this, will use for loop and iterate line by line. check for the string "error".print those lines if found. I was asked to use pointers in python since assigning file content to a variable consumes time when logfile contains huge output. I did research on python pointers. But not found anything useful. Could anyone help me out writing the above code using pointers instead of storing the whole content in a variable.<issue_comment>username_1: The idea, roughly stated, is that `set -o errexit` (or, equivalently, `set -e`) causes the shell to exit on **uncaught** errors. The fact that `&&` follows `source sourceme.sh` means that the error is caught. So, if the `source` and `echo` commands are connected with `;`, the shell exits: ``` $ (source sourceme.sh ; echo "sourceme.sh did not error (exit code: $?)") errexit on About to error from sourceme.sh... ``` But, if the `source` and `echo` commands are connected with `&&`, then the shell assumes that you have anticipated the possibility of the `source` command failing and the shell does not exit: ``` $ (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") errexit on About to error from sourceme.sh... sourceme.sh did not exit on error (exit code: 1) sourceme.sh did not error (exit code: 0) ``` Much of the behavior of `set -e` may be considered odd or unexpected. For more examples, see [Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?](http://mywiki.wooledge.org/BashFAQ/105). ### Documentation The behavior of `set -e` (errexit) is defined more precisely in `man bash`: > > **-e** > Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL > GRAMMAR above), exits with a non-zero status. The shell does > not exit if the command that fails is part of the command list > immediately following a while or until keyword, part of the test > following the if or elif reserved words, part of any command executed > in a && or || list except the command following the final && or ||, > any command in a pipeline but the last, or if the command's return > value is being inverted with !. If a compound command other than a > subshell returns a non-zero status because a command failed while -e > was being ignored, the shell does not exit. A trap on > ERR, if set, is executed before the shell exits. This option applies > to the shell environment and each subshell > environment separately (see COMMAND EXECUTION ENVIRONMENT above), > and may cause subshells to exit before executing all the > commands in the subshell. > > If a compound > command or shell function executes in a context where -e is being > ignored, none of the commands executed within the > compound command or function body will be affected by the -e setting, > even if -e is set and a command returns a failure status. If a > > compound command or shell function sets -e while executing in a > context where -e is ignored, that setting will not have any effect > until the compound command or the command containing the function call > completes. > > > ### Synonyms As documented in `man bash` as well as in `help set`, the following two commands are equivalent: ``` set -e set -o errexit ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: What you are observing is this. This command doesn't exit on error: ``` (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` However this command: ``` (bash sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` does exit so `&&` is not the only reason of this weirdness. It is combination of `source` and `&&` that makes it not to exit. You have also noted that use of `;` instead of `&&` makes it exit as in following command: ``` (bash sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` **This behaviour is actually dependent of bash version in use.** When I run this command on OSX `bash 3.2.57(1)-release` **it does exit**: ``` (source sourceme.sh && echo "sourceme.sh did not error (exit code: $?)") ``` ``` errexit on About to error from sourceme.sh... ``` However **on bash versions `4.2` and above behaviour changes** and `set -e` doesn't exit when used with `&&`. So bottomline is that `set -e` is highly unreliable and one should avoid depending on it's behaviour in important shell scripts. Upvotes: 1
2018/03/15
403
1,405
<issue_start>username_0: According to the following documentation <https://developer.android.com/reference/android/support/v7/widget/RecyclerView.OnScrollListener.html> You can add a listener to `RecyclerView` to be notified when the user scrolls. ``` RecyclerView.OnScrollListener.onScrolled(RecyclerView recyclerView, int dx, int dy) ``` What are the units for `int dx, int dy`, are they density independent `pixels (dp)`, `pixels (px)`? What are they?<issue_comment>username_1: Pixels. Always assume pixels and convert to dp if needed. See RecyclerView#dispatchOnScrolled: <https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/main/java/android/support/v7/widget/RecyclerView.java> Check the line 4723. Upvotes: 2 [selected_answer]<issue_comment>username_2: > > What are the units for int dx, int dy, are they density independent pixels (dp), pixels (px)? What are they? > > > * @param **`dx`** horizontal distance scrolled in **`pixels`** * @param **`dy`** vertical distance scrolled in **`pixels`** [![enter image description here](https://i.stack.imgur.com/AuHWD.png)](https://i.stack.imgur.com/AuHWD.png) For more information read [RecyclerView.java](https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/main/java/android/support/v7/widget/RecyclerView.java) line no. line 4723 Upvotes: 2
2018/03/15
491
1,669
<issue_start>username_0: I am new in sml. I tried to convert int to int list. For example, assume that there is an input 1234, then output is a list like [1,2,3,4]. And my question is, how can I type nested functions in sml? let in end? There is my code. ``` fun digit (a : int): int = let fun size (a) = if a < 0 then nil else x = Int.toString x then digit s = size(x) fun insert (num, nil) = [num] | insert (num,xs) = x :: insert () fun convert (a, s) = if s < 0 then nil else insert (a / (10*(s - 1)), xs) then convert(a - (10*(s - 1), s - 1) in end ```<issue_comment>username_1: Pixels. Always assume pixels and convert to dp if needed. See RecyclerView#dispatchOnScrolled: <https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/main/java/android/support/v7/widget/RecyclerView.java> Check the line 4723. Upvotes: 2 [selected_answer]<issue_comment>username_2: > > What are the units for int dx, int dy, are they density independent pixels (dp), pixels (px)? What are they? > > > * @param **`dx`** horizontal distance scrolled in **`pixels`** * @param **`dy`** vertical distance scrolled in **`pixels`** [![enter image description here](https://i.stack.imgur.com/AuHWD.png)](https://i.stack.imgur.com/AuHWD.png) For more information read [RecyclerView.java](https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/main/java/android/support/v7/widget/RecyclerView.java) line no. line 4723 Upvotes: 2
2018/03/15
742
2,199
<issue_start>username_0: I want to add a class(active) to a child of an element who has a class (is-active) and does not effect other elements. using jQuery! ``` * [Link 1](#)* * [Link 2](#)* * [Link 3](#)* * [Link 4](#)* ``` I'm using this code but it's effect all other elements. ``` if ($(".nav-item").hasClass("is-active")) { $('a', this).addClass('active'); } ``` I want to be like this: ``` * [Link 1](#)* * [Link 2](#)* * [Link 3](#)* * [Link 4](#)* ```<issue_comment>username_1: ``` if ($(".nav-item").hasClass("is-active")) { $(this).find('a').addClass('active'); } ``` You this code it will work Upvotes: 0 <issue_comment>username_2: You can chain the selector to target the parent then use `.find()` to get the child. ``` $(".nav-item.is-active").find('a').addClass('active') ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: You can combine it's into a single selector(which selects a tag within `.nav-item` having `is-active`) and then add class to that. ``` $('.nav-item.is-active a').addClass('active'); ``` ```js $(".nav-item.is-active a").addClass('active'); console.log($('ul').html()) ``` ```html * [Link 1](#)* * [Link 2](#)* * [Link 3](#)* * [Link 4](#)* ``` --- **FYI :** In your code `this` does not refer to the element, it may be window object or something else so it won't work. To make it work use [`each()`](https://api.jquery.com/each/) method. ``` $(".nav-item").each(function(){ if($(this).hasClass("is-active")) { $('a', this).addClass('active'); } }) ``` ```js $(".nav-item").each(function() { if ($(this).hasClass("is-active")) { $('a', this).addClass('active'); } }) console.log($('ul').html()) ``` ```html * [Link 1](#)* * [Link 2](#)* * [Link 3](#)* * [Link 4](#)* ``` Upvotes: 0 <issue_comment>username_4: You can loop through your element and add class if current element has certain class. Here is working example. ```js var navlist = $(".nav-item"); $.each(navlist, function() { if ($(this).hasClass("is-active")) { $(this).find('a').addClass('active'); } }); console.log($('ul').html()) ``` ```html * [Link 1](#)* * [Link 2](#)* * [Link 3](#)* * [Link 4](#)* ``` Upvotes: 0
2018/03/15
937
3,943
<issue_start>username_0: I've tried [this solution](https://stackoverflow.com/questions/37069609/show-loading-screen-when-navigating-between-routes-in-angular-2) but could'nt get it working. I'm completely new to Angular2 (with no knowledge of AngularJS). Well the loading screen does'nt show up, I guess I need to add some time out so that it gets some time to be displayed but where and how I don't know. **app.component.ts** ```js import {Component} from '@angular/core'; import { Router, // import as RouterEvent to avoid confusion with the DOM Event Event as RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./loadingCSS.css'] }) export class AppComponent { // Sets initial value to true to show loading spinner on first load loading = true; constructor(private router: Router) { router.events.subscribe((event: RouterEvent) => { this.navigationInterceptor(event); }); } // Shows and hides the loading spinner during RouterEvent changes navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.loading = true; } if (event instanceof NavigationEnd) { this.loading = false; } // Set loading state to false in both of the below events to hide the spinner in case a request fails if (event instanceof NavigationCancel) { this.loading = false; } if (event instanceof NavigationError) { this.loading = false; } } ``` **app.component.html** ```html Array operation Calculator Loading... ``` I want to achieve that the loading screen shows up in every routing in whole application and the loading screen that I'm trying to show up is [this](https://alligator.io/angular/custom-loading-screen/) (code reference). Any suggestion would be of great help.<issue_comment>username_1: I found the solution. Posting it if anyone needs it in future. This is what I did... I added `setTimeout` functionality to the **app.component.ts** as ```js import { Component } from '@angular/core'; import { Router, // import as RouterEvent to avoid confusion with the DOM Event Event as RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./loadingCSS.css'] }) export class AppComponent { // Sets initial value to true to show loading spinner on first load loading = true; constructor(private router: Router) { router.events.subscribe((event: RouterEvent) => { this.navigationInterceptor(event); }); } // Shows and hides the loading spinner during RouterEvent changes navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.loading = true; } if (event instanceof NavigationEnd) { setTimeout(() => { // here this.loading = false; }, 2000); } // Set loading state to false in both of the below events to hide the spinner in case a request fails if (event instanceof NavigationCancel) { setTimeout(() => { // here this.loading = false; }, 2000); } if (event instanceof NavigationError) { setTimeout(() => { // here this.loading = false; }, 2000); } } ``` And changed the HTML as ```html Loading... ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: the set timeout will work but it is not the right way to work as it will still show the data delay if there is while switching from one route to another route. For better results don't use the set timeout Upvotes: 0
2018/03/15
484
1,617
<issue_start>username_0: Really simple code, but not working using tkinder in Python. This code has been copied just as seen in a video tutorial, so I think it could be any config: ``` from tkinter import* root=Tk() miFrame=Frame(root, width=500, height=400) miFrame=pack() Label(miFrame, text="Hola alumnos de Python", fg="red", font=("Comic Sans MS", 18)).place(x=100, y=200) root.mainloop() ``` The error: > > Traceback (most recent call last): > File "Prueba2.py", line 7, in > miFrame=pack() > NameError: name 'pack' is not defined > > ><issue_comment>username_1: Replace `miFrame=pack()` with `miFrame.pack()` Upvotes: 2 [selected_answer]<issue_comment>username_2: The row **`miFrame=pack()`** is an attempt to assign a symbol **`miFrame`** to a reference to some known function **`pack()`** In a case, there is no such known to the python interpreter state, it threw an exception mentioned above. However, the object **`miFrame`**, being a row above that assigned to a **`tkinter.Frame`** instance, there is an instance-method present - the **`.pack()`**, that can be called, instead of an attempt to straight re-assign the **`miFrame`**, right after it's instantiation: ``` miFrame = Frame( root, width = 500, height = 400 ) miFrame.pack() #_____________________ .pack() is a Frame-class instance-method Label( miFrame, text = "Hola alumnos de Python", fg = "red", font = ( "Comic Sans MS", 18 ) ).place( x = 100, y = 200 ) ``` Upvotes: 0
2018/03/15
354
1,370
<issue_start>username_0: I have a line saved as `$variable1`, for example: ``` file"yourtxthere/i/master.ext" autostart:true, width ``` How would I go about writing the correct syntax using Regex in Powershell to grab everything within the quotes. Are regular expressions the best way to do this in Powershell?<issue_comment>username_1: Replace `miFrame=pack()` with `miFrame.pack()` Upvotes: 2 [selected_answer]<issue_comment>username_2: The row **`miFrame=pack()`** is an attempt to assign a symbol **`miFrame`** to a reference to some known function **`pack()`** In a case, there is no such known to the python interpreter state, it threw an exception mentioned above. However, the object **`miFrame`**, being a row above that assigned to a **`tkinter.Frame`** instance, there is an instance-method present - the **`.pack()`**, that can be called, instead of an attempt to straight re-assign the **`miFrame`**, right after it's instantiation: ``` miFrame = Frame( root, width = 500, height = 400 ) miFrame.pack() #_____________________ .pack() is a Frame-class instance-method Label( miFrame, text = "Hola alumnos de Python", fg = "red", font = ( "Comic Sans MS", 18 ) ).place( x = 100, y = 200 ) ``` Upvotes: 0
2018/03/15
303
1,220
<issue_start>username_0: Please help me out with this issue while uploading application to Appstore I am getting this error: [![enter image description here](https://i.stack.imgur.com/b5c1B.png)](https://i.stack.imgur.com/b5c1B.png)<issue_comment>username_1: I experienced similar issue recently - messed with a lot of different things but at the end, the issue was a bad character in the file - which is only visible through an editor like vi. Open the file with vi and then navigate to the bad character if you find one (it usually sticks out like a sore thumb as a different color to the rest of the file) - then hit 'x' to delete it. The type colon on keyboard and 'wq' and hit enter to save and exit. Delete previous archive - archive again and try to validate. This worked for me. Upvotes: 2 <issue_comment>username_2: I had the same issue & I wasted full day looking here and there creating builds and validating them. I checked my `Info.plist` file & there was no control character. One property `CFBundleShortVersionString` from `Info.plist` was referring to `$(MARKETING_VERSION)` which had the control character. So kindly check the `Info.plist` file first and then the referencing `variables`. Upvotes: 0
2018/03/15
698
1,560
<issue_start>username_0: I am trying to calculate below formula and store the value to a variable. The pseudo code should look like: ``` a=10 b=5 c=$(((($a-$b)/52)) | bc -l) echo $c ``` The result is empty. I couldn't figure out the syntax using `bc`. Please help me use `bc` instead of `awk` or other method.<issue_comment>username_1: You can use this: ``` a=10 b=5 c=$(bc -l <<< "($a-$b)/52") echo "$c" ``` ``` .09615384615384615384 ``` Or by setting a scale of `3`: ``` c=$(bc -l <<< "scale=3; ($a-$b)/52") echo "$c" ``` ``` .096 ``` Upvotes: 2 <issue_comment>username_2: There are *two* things you need to be aware of. The first is that `bc` uses standard input for expressions so you would need to actually *pipe* your expression through it, or use the `<<<` redirection operator, one of: ``` c=$(echo "($a - $b) / 52" | bc) c=$(bc <<< "($a - $b) / 52") ``` The `<<<` method is specific to `bash` and `ksh` (an *possibly* others, but I'm not really au fait with them). The other method can be used in most shells. Secondly, you should be careful when using big numbers for this since `bc` has the annoying habit of splitting them across lines: ``` pax$ x=999999999999999999999999999999999999999999999999999999999999999999999 pax$ echo "$x / 7" | bc 14285714285714285714285714285714285714285714285714285714285714285714\ 2 ``` In order to avoid this, you need to change the line length: ``` pax$ echo "$x / 7" | BC_LINE_LENGTH=0 bc 142857142857142857142857142857142857142857142857142857142857142857142 ``` Upvotes: 3 [selected_answer]
2018/03/15
1,711
6,278
<issue_start>username_0: I want to hide the first column of the datatable which is `IID` but I want to access its value for updating data on database. Here is the code ``` var details = []; for (var m = 0; m < retrievedParsedValue.Table3.length; m++) { var buttonColumn = "**Action**"; details.push([retrievedParsedValue.Table3[m]['IID'], retrievedParsedValue.Table3[m]['RJ_FACILITY_ID'], retrievedParsedValue.Table3[m]['SMPS_AVAILABLE'], retrievedParsedValue.Table3[m]['NO_OF_SMPS_ONSITE'], retrievedParsedValue.Table3[m]['SMPS_MAKE'], retrievedParsedValue.Table3[m]['SMPS_CAPACITY'], retrievedParsedValue.Table3[m]['CONTROLLER_MODEL'], retrievedParsedValue.Table3[m]['RECT_MODULE_MODEL'], retrievedParsedValue.Table3[m]['HEALTHY_RECTIFIER_COUNT'], retrievedParsedValue.Table3[m]['BACKPLANE_RECTIFIER_SLOT'], retrievedParsedValue.Table3[m]['RECT_CAPACITY'], retrievedParsedValue.Table3[m]['SMPS_STATUS'], retrievedParsedValue.Table3[m]['NO_OF_FAULTY_MODULES'], retrievedParsedValue.Table3[m]['DC_LOAD'], retrievedParsedValue.Table3[m]['SMPS_OTHER_REMARKS'], buttonColumn]); } $('#grdSMPSRCOM').DataTable({ destroy: true, data: details, "scrollX": true, columns: [ { title: "IID" }, { title: "RJ Facility ID" }, { title: "SMPS Available" }, { title: "NO of SMPS OnSite" }, { title: "SMPS Make" }, { title: "SMPS Capacity" }, { title: "Controller Model" }, { title: "Rect Module Model" }, { title: "Healthy Rectifier Count" }, { title: "Backplane Rectifier Slot" }, { title: "Rect Capacity" }, { title: "SMPS Status" }, { title: "No Of Faulty Modules" }, { title: "DC Load" }, { title: "SMPS Other Remarks" }, { title: "Validate" } ], "bDestroy": true }); ``` How can I hide it but access its value.<issue_comment>username_1: You can hide your 1st column using visible false. ``` var table = $('#grdSMPSRCOM').DataTable({ /// other code }); table.column(0).visible(false); ``` And to get value: ``` var IID = table .fnGetData(position)[0]; // getting the value of the first (invisible) column ``` Upvotes: 0 <issue_comment>username_2: How about simply add its value in an attribute, in this case e.g. the `buttonColumn`. ``` for (var m = 0; m < retrievedParsedValue.Table3.length; m++) { var buttonColumn = "**Action**"; details.push(retrievedParsedValue.Table3[m]['RJ_FACILITY_ID'], retrievedParsedValue.Table3[m]['SMPS_AVAILABLE'], retrievedParsedValue.Table3[m]['NO_OF_SMPS_ONSITE'], retrievedParsedValue.Table3[m]['SMPS_MAKE'], retrievedParsedValue.Table3[m]['SMPS_CAPACITY'], retrievedParsedValue.Table3[m]['CONTROLLER_MODEL'], retrievedParsedValue.Table3[m]['RECT_MODULE_MODEL'], retrievedParsedValue.Table3[m]['HEALTHY_RECTIFIER_COUNT'], retrievedParsedValue.Table3[m]['BACKPLANE_RECTIFIER_SLOT'], retrievedParsedValue.Table3[m]['RECT_CAPACITY'], retrievedParsedValue.Table3[m]['SMPS_STATUS'], retrievedParsedValue.Table3[m]['NO_OF_FAULTY_MODULES'], retrievedParsedValue.Table3[m]['DC_LOAD'], retrievedParsedValue.Table3[m]['SMPS_OTHER_REMARKS'], buttonColumn]); } ``` And access it like this ```js //using [data-iid] attribute through parent console.log(document.querySelector('.parent [data-iid]').dataset.iid); //using click function getDataForSMPS(el) { alert(el.dataset.iid); } ``` ```html **Action (click me)** ``` --- If you still need the initial column, this might be an alterntive. ``` for (var m = 0; m < retrievedParsedValue.Table3.length; m++) { var iid = ""; var buttonColumn = "**Action**"; details.push(iid, retrievedParsedValue.Table3[m]['RJ_FACILITY_ID'], retrievedParsedValue.Table3[m]['SMPS_AVAILABLE'], retrievedParsedValue.Table3[m]['NO_OF_SMPS_ONSITE'], retrievedParsedValue.Table3[m]['SMPS_MAKE'], retrievedParsedValue.Table3[m]['SMPS_CAPACITY'], retrievedParsedValue.Table3[m]['CONTROLLER_MODEL'], retrievedParsedValue.Table3[m]['RECT_MODULE_MODEL'], retrievedParsedValue.Table3[m]['HEALTHY_RECTIFIER_COUNT'], retrievedParsedValue.Table3[m]['BACKPLANE_RECTIFIER_SLOT'], retrievedParsedValue.Table3[m]['RECT_CAPACITY'], retrievedParsedValue.Table3[m]['SMPS_STATUS'], retrievedParsedValue.Table3[m]['NO_OF_FAULTY_MODULES'], retrievedParsedValue.Table3[m]['DC_LOAD'], retrievedParsedValue.Table3[m]['SMPS_OTHER_REMARKS'], buttonColumn]); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: The column IID seems the first column. So you can hide in this way: ``` var oTable; oTable = $('#grdSMPSRCOM').DataTable({ destroy: true, data: details, "scrollX": true, columns: [ { title: "IID" }, { title: "RJ Facility ID" }, { title: "SMPS Available" }, { title: "NO of SMPS OnSite" }, { title: "SMPS Make" }, { title: "SMPS Capacity" }, { title: "Controller Model" }, { title: "Rect Module Model" }, { title: "Healthy Rectifier Count" }, { title: "Backplane Rectifier Slot" }, { title: "Rect Capacity" }, { title: "SMPS Status" }, { title: "No Of Faulty Modules" }, { title: "DC Load" }, { title: "SMPS Other Remarks" }, { title: "Validate" } ], "columnDefs": [ { "targets": [ 0 ], "visible": false, "searchable": false } ], "bDestroy": true }); ``` Now for the second part, you want to read data from the hidden column. ``` $('#grdSMPSRCOM tbody').on('click', 'tr', function () { selectedIndex = oTable.row(this).data()[0]; }); ``` Upvotes: 0
2018/03/15
1,133
3,658
<issue_start>username_0: I am just providing a value of 2160000000 (which is 1000 \* 60 \* 60 \* 24 \* 25 - just 25 days) to Date's class constructor. I expected to see that here will be 1970-01-26 00:00:00, but what I received is 1970-01-26 03:00:00 (additional three hours)! I haven't found any points that this constructor also depend on JVM locale settings, and all I have found is info about leap second. But leap second is NOT three hours in bounds of the single month of the same year. But anyway I've changed default locale (to US one. I'm located in Europe) in a test method just for experiment, but nothing changed. I have received this just by this (what I have explained just ok earlier ya know): `Date date = new Date(1000* 60 * 60 * 24 * 25);` (this is just for example purposes). I saw actual values just using debugger, that's all: [![enter image description here](https://i.stack.imgur.com/hlIxm.png)](https://i.stack.imgur.com/hlIxm.png)<issue_comment>username_1: Do you think the hour difference you're seeing is being equal to your home country's time zone (GMT+3) is a coincidence? I think not. ``` SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = dateFormat.parse("/*TimeToParse*/"); ``` This would definitely help. Edit: If you check the zoneOffset and ZoneInfo values in your debug screenshot, you'll understand better. Upvotes: 2 <issue_comment>username_2: tl;dr ===== ``` Instant.ofEpochMilli( 2_160_000_000L ) ``` java.time ========= [The Answer by Acar](https://stackoverflow.com/a/49292628/642706) is likely correct: You are confused by the unfortunate design of `Date::toString` to dynamically apply your JVM’s current default time zone while generating a string. One of *many* reasons to never use the troublesome `Date` class, now supplanted by the *java.time* classes. To represent a moment on the timeline in UTC with a resolution of nanoseconds, use `Instant`. ``` Instant instant = Instant.ofEpochMilli( 2_160_000_000L ) ; ``` If your real intent is to represent 25 whole days as a span of time unattached to the timeline, use a `Period`. ``` LocalDate today = LocalDate.now( ZoneId.of( “Africa/Tunis” ) ) ; Period p = Period.ofDays( 25 ) ; LocalDate later = today.plus( p ) ; ``` Upvotes: 2 <issue_comment>username_3: You are getting the `Date` you expected, a `Date` of 1970-01-26 00:00:00 **UTC**. This point in time is equivalent to 1970-01-26 03:00:00 at UTC offset +03:00. In your debugger you are looking into the private fields of the `Date` object. These are not documented for clients (that’s the point), so don’t expect any particular values. I believe that you would find `Instant.ofEpochMilli(1000L * 60 * 60 * 24 * 25)` less confusing. Or still better, `Instant.EPOCH.plus(Duration.ofDays(25))`. java.time, the modern Java date and time API, is much nicer to work with. If you do need a `Date` for a legacy API that you don’t want to change just now, I recommend getting an `Instant` first and then using `Date.from(yourInstant)` so you minimize your use of (and dependence on) the outdated and confusing `Date` class. Finally, changing locale makes no difference. While time zone and UTC offset are closely connected (to a degree where some think it’s the same :-) locale hasn’t really got anything to do with them. Instead the locale deals with the language and cultural norms of a group of users — it doesn’t even need to be tied to a geographical location. **Link:** [All about java.util.Date](https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/) Upvotes: 3 [selected_answer]
2018/03/15
618
2,451
<issue_start>username_0: This is my method in the controller. ``` public ActionResult DeleteModelAliasData(string alias) { if (!ModelState.IsValid) { ModelState.LogModelStateError(); throw new BusinessException("COMMON_ERROR"); } var response = _vehicleDataBusinessService.DeleteModelAliasData(alias); return Json(response); } ``` I am new at unit testing and I want to write the unit test that when the "`!ModelState.IsValid`" then the exception is thrown, I want to check that is it the correct exception which I Wanted?<issue_comment>username_1: You can do the same as shown in below code. ``` var ex = Assert.Throws(() => controller.DeleteModelAliasData(alias)); Assert.That(ex.Message, Is.EqualTo("COMMON\_ERROR")); ``` Reference: **[NUnit Exception Asserts](http://nunit.org/docs/2.5/exceptionAsserts.html)** --- **Update:** ``` [Test] public void TestDeleteModelAliasData() { // Get your controller instance - you know it better how to instantiate var controller = GetControllerInstance(); // Add error message to ModelState controller.ModelState.AddModelError("PropertyName", "Error Message"); var alias = "sampleAlias"; // As ModelState is having an Error, the method should throw BusinessException var ex = Assert.Throws(() => controller.DeleteModelAliasData(alias)); // Exception is raised, assert the message if you want Assert.That(ex.Message, Is.EqualTo("COMMON\_ERROR")); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The default value for `ModelState.IsValid` is `true` when the model state dictionary is empty. That would mean that in order for the method under test to flow in the desired path you would need to make sure that the model state behaves as expected. This can be done by adding a model error to the model state For example ``` //Arrange //...initialize controller and its dependencies //add model error to force IsValid to be false. controller.ModelState.AddModelError("PropertyName", "Error Message"); var alias = string.Empty; var expectedErrorMessage = "COMMON_ERROR"; //Act Action act = () => controller.DeleteModelAliasData(alias); //Assert Assert.That(act, Throws.TypeOf() .With.Message.EqualTo(expectedErrorMessage)); ``` You would then assert that the expected exception is thrown with the expected values. Reference [ThrowsConstraint](https://github.com/nunit/docs/wiki/ThrowsConstraint) Upvotes: 1
2018/03/15
460
1,215
<issue_start>username_0: I would like to convert string value HH:MM:SS.mmm to float value sec.milliseconds for arithmetic calculations. Is there a direct way to do this as currently I am doing it via split string function and it is a very tedious process. Dataframe looks like: ``` Col1 00:00:05.063 00:01:00.728 00:03:10.117 ``` Output should look like ``` 5.063 60.728 190.117 ``` Appreciate any help.<issue_comment>username_1: Convert your column to `timedelta`, and then to `int` (with returns the result in `ns`, divide by `1e9` to get seconds): ``` pd.to_timedelta(df.Col1).astype(int) / 1e9 0 5.063 1 60.728 2 190.117 Name: Col1, dtype: float64 ``` Upvotes: 1 <issue_comment>username_2: Use [`to_timedelta`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html) + [`total_seconds`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html): ``` df['Col1'] = pd.to_timedelta(df['Col1']).dt.total_seconds() print (df) Col1 0 5.063 1 60.728 2 190.117 ``` Upvotes: 1 <issue_comment>username_3: ```py df['HourandMinute'] = df['Dayandtime_call'].dt.hour + \ df['Dayandtime_call'].dt.minute / 100 ``` Upvotes: 0
2018/03/15
197
730
<issue_start>username_0: I have a ReactJS application with dependencies managed by npm. I use eclipse as an IDE. My application runs using "npm start" command. To execute "npm start" command, I need to open terminal window and run it there. I would like to run this command from within eclipse. Is there a way to do it?<issue_comment>username_1: Probably way too late to answer this but you can use `ctrl + alt + shift + t` to open up any command line tools installed. [![local terminal on selection](https://i.stack.imgur.com/GWsyd.png)](https://i.stack.imgur.com/GWsyd.png) Upvotes: 2 <issue_comment>username_2: Install Nodeclipse. Right click 'package.json' -> Run As 'npm ...' -> Write the goal 'start' and run it Upvotes: 1
2018/03/15
483
1,648
<issue_start>username_0: I have an Angular 4 Project where I am creating a sample Map as follows: ``` let sampleMap = new Map(); sampleMap.set('key1','value1'); ``` Now I am passing this Map as a parameter to a Angular 4 Post method which connects to a Spring Boot Rest backend as follows **Angular 4 Code:** ``` this.http.post('http://localhost:8080/data/posturl', sampleMap).map((response: Response) => { return response.text(); }) ``` **Spring Boot Rest Backend Code:** ``` @RequestMapping("/posturl") public String launch(@RequestBody Map sampleMap) { System.out.println("Received=" + sampleMap); return "SUCCESS"; } ``` Although when I try to print the 'sampleMap' as shown above, it print a blank map like follows: ``` Received={} ``` I am using Typescript version '~2.3.3' and my 'tsconfig.json' mentions target as 'es5'. Can someone please explain this behavior?<issue_comment>username_1: You have to convert the Map to an array of key-value pairs, as Typescript maps cannot be used directly inside a http post body. You can convert the map as follows: ``` const convMap = {}; sampleMap.forEach((val: string, key: string) => { convMap[key] = val; }); this.http.post('http://localhost:8080/data/posturl', convMap).map((response: Response) => { return response.text(); }) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can create an object with keys as attributes. example of a map with 2 items : ``` let myObject = {"key1":"value1","key2":"value2"}; this.http.post('http://localhost:8080/data/posturl', myObject ).map((response: Response) => { return response.text(); }) ``` Upvotes: 2
2018/03/15
618
1,999
<issue_start>username_0: So these are the for loops that I have to find the time complexity, but I am not really clearly understood how to calculate. ``` for (int i = n; i > 1; i /= 3) { for (int j = 0; j < n; j += 2) { ... ... } for (int k = 2; k < n; k = (k * k) { ... } ``` For the first line, (int i = n; i > 1; i /= 3), keeps diving i by 3 and if i is less than 1 then the loop stops there, right? But what is the time complexity of that? I think it is n, but I am not really sure. The reason why I am thinking it is n is, if I assume that n is 30 then i will be like 30, 10, 3, 1 then the loop stops. It runs n times, doesn't it? And for the last for loop, I think its time complexity is also n because what it does is k starts as 2 and keeps multiplying itself to itself until k is greater than n. So if n is 20, k will be like 2, 4, 16 then stop. It runs n times too. I don't really think I am understanding this kind of questions because time complexity can be log(n) or n^2 or etc but all I see is n. I don't really know when it comes to log or square. Or anything else. Every for loop runs n times, I think. How can log or square be involved? Can anyone help me understanding this? Please.<issue_comment>username_1: You have to convert the Map to an array of key-value pairs, as Typescript maps cannot be used directly inside a http post body. You can convert the map as follows: ``` const convMap = {}; sampleMap.forEach((val: string, key: string) => { convMap[key] = val; }); this.http.post('http://localhost:8080/data/posturl', convMap).map((response: Response) => { return response.text(); }) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can create an object with keys as attributes. example of a map with 2 items : ``` let myObject = {"key1":"value1","key2":"value2"}; this.http.post('http://localhost:8080/data/posturl', myObject ).map((response: Response) => { return response.text(); }) ``` Upvotes: 2
2018/03/15
2,894
9,936
<issue_start>username_0: I'm using the latest version of android studio (3.0), along with latest build tools (27) and similar API level. The layout does not get rendered in the design tab and it's causing a lot of trouble especially that I'm using coordinator layout. How do I get around this problem?<issue_comment>username_1: This maybe existing issue: <https://issuetracker.google.com/issues/37048767> Render using other versions of Android (say Android API 22). Or check for any typos or invalid XML entries. Refer here: [Missing styles. Is the correct theme chosen for this layout?](https://stackoverflow.com/questions/13439486/missing-styles-is-the-correct-theme-chosen-for-this-layout/31860142) Upvotes: 0 <issue_comment>username_2: Thanks for the response, I found the solution tinkering with the code, I had `tools:showIn` attribute enabled in the parent layout of a fragment, which I moved to a viewpager, it was previously embedded in a host activity, lint did not catch it though, which is a bit surprising. Upvotes: 3 <issue_comment>username_3: I solved this rendering problem by simply inserting this line into the application theme (the app theme is usually placed in *styles.xml*). [**SDK 28**] ``` <item name="coordinatorLayoutStyle">@style/Widget.Support.CoordinatorLayout</item> ``` --- [**SDK 27**] ``` <item name="coordinatorLayoutStyle">@style/Widget.Design.CoordinatorLayout</item> ``` --- > > As suggested by @Chris. If the IDE does not find the *CoordinatorLayout* in *Widget.Support* or *Widget.Design*, just start typing "CoordinatorLayout" and it should give you some options. > > > Upvotes: 8 [selected_answer]<issue_comment>username_4: ``` <item name="coordinatorLayoutStyle">@style/Widget.Support.CoordinatorLayout</item> ``` Add in your material theme. Upvotes: 3 <issue_comment>username_5: I was also facing the same problem. Nothing like changing theme from Layout preview window helped me. **Solution:** I updated my `build.gradle(app)` with: ``` dependencies { implementation 'com.android.support:appcompat-v7:27.0.2' implementation 'com.android.support:design:27.0.2' } ``` One more thing: ``` compileSdkVersion 27 targetSdkVersion 27 ``` Upvotes: 3 <issue_comment>username_6: I think it is a common issue in android studio 3.0+, Hopefully they will fix it next update. In the Android Studio Preview 3.2 it works fine. [Download Android Studio Preview](https://developer.android.com/studio/preview/) [![enter image description here](https://i.stack.imgur.com/V6cUC.jpg)](https://i.stack.imgur.com/V6cUC.jpg) Upvotes: 2 <issue_comment>username_7: As an aside, in design view of Android Studio, if I add the following to the styles.xml file: ``` <item name="coordinatorLayoutStyle">@style/Widget.Design.CoordinatorLayout</item> ``` and add the following to the CoordinatorLayout in the layout's xml resource file ``` ``` then, at least, the design view stops generating the missing coordinatorLayoutStyle error. Upvotes: 1 <issue_comment>username_8: `implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'` in `build.gradle`(module) change alpha 3 to alpha 1. sync and you should be good to go. I spent almost a day trying to figure this out. none of these answers worked for me. hope this helps Upvotes: 4 <issue_comment>username_9: Turns out the new **SDK 28** is unfortunately introducing this error on Android Studio when you create a new project. **How to solve:** Check your `build.gradle` *(Module: app)* file and change: ``` compileSdkVersion 28 targetSdkVersion 28 ``` To: ``` compileSdkVersion 27 targetSdkVersion 27 ``` Also, make sure you are using the right dependencies version: ``` implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.1.1' ``` Upvotes: 5 <issue_comment>username_10: ``` <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="coordinatorLayoutStyle">@style/Widget.Design.CoordinatorLayout</item> ``` just add coodrinatorLayoutStyle as an item in style.xml and it worked for me. Upvotes: 0 <issue_comment>username_11: My Android studio version 3.1.3. i'm worked with uninstall ALL SDK version 28. Step is Open SDK Manager > SDK Platforms > Show package Details > Untick SDK 28 > apply and Create new project. Upvotes: 1 <issue_comment>username_12: For Android Studio 3.1.4 users: I've tried marked answer but it didn't work for me. Inserting this line: ``` <item name="coordinatorLayoutStyle">@style/Widget.Design.CoordinatorLayout</item> ``` into the application theme doesn't solve the rendering problem so I've undone that change. **Solution:** I've made this changes in my build.gradle(Module:app) file: **Before change:** ``` android { compileSdkVersion 28 defaultConfig { targetSdkVersion 28 } } } dependencies { implementation 'com.android.support:appcompat-v7:28.0.0-rc01' implementation 'com.android.support:design:28.0.0-rc01' } ``` **After change:** ``` android { compileSdkVersion 27 defaultConfig { targetSdkVersion 27 } } } dependencies { implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.1.1' } ``` It worked for me perfectly. Hope that will be useful. Upvotes: 3 <issue_comment>username_13: I have the same problem but on the Android studio 3.1.4 So, at first I have done the following in build.gradle Replace this: implementation 'com.android.support:appcompat-v7:28.0.0-rc01' implementation 'com.android.support:design:28.0.0-rc01' implementation 'com.android.support:support-v4:28.0.0-rc01' with that: implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' implementation 'com.android.support:design:28.0.0-alpha1' implementation 'com.android.support:support-v4:28.0.0-alpha1' But somehow after project rebuild the problem repeats again. So, I have go this way: Here is my project gradle.build ``` buildscript { ext.kotlin_version = '1.2.41' ext.android_support = '27.1.1' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.4' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() maven { url "https://jitpack.io" } } } task clean(type: Delete) { delete rootProject.buildDir } ``` And here app build.gradle ``` apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 27 defaultConfig { applicationId "*****.******"//Replace with your own ID minSdkVersion 16 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.1.1' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } ``` And this solve my problem Thank you Upvotes: 1 <issue_comment>username_14: Just Change implementation 'com.android.support:appcompat-v7:28.0.0-alpha3' and 'com.android.support:design:28.0.0-alpha3' to alpha 1. That's how i solved the problem. Upvotes: 0 <issue_comment>username_15: I will post an answer The other answers may work but no one should need to download Preview Version and doing Material Design with no Action Bar is not the way to **START** developing apps with Android Studio Our version of Android Studio is 3.1.4 Our default API is 28 Our FIX is to downgrade to API 26 YOU do this by clicking File -> Project Structure then highlight **app** Under the Properties TAB Change Compile Sdk version to API 26 Now click on the Falavors TAB and change Target Sdk version to 26 Then in build.gradle(module:app) add these changes ``` implementation 'com.android.support:appcompat-v7:27.0.0' implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.android.support:cardview-v7:27.1.1' ``` I guess one could always justify this slow FIX by Google to learn to use the ToolBar Upvotes: 1 <issue_comment>username_16: I solve this problem when update all SDK tools in IDE and update Android Studio to 3.2.1 Upvotes: 0 <issue_comment>username_17: its working for me try it ``` compileSdkVersion 28 defaultConfig { minSdkVersion 16 targetSdkVersion 28 } implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' ``` Upvotes: 0 <issue_comment>username_18: This is sdk 28 issue Check your build.gradle (Module: app) file and change: compileSdkVersion 28 targetSdkVersion 28 To: compileSdkVersion 27 targetSdkVersion 27 Upvotes: 0
2018/03/15
2,864
8,873
<issue_start>username_0: I'm tried to fix sticky on bottom of the page using javascript/jquery but the sticky is hidden the body text. I need to show all body text without hidden along with sticky, I'm not able to figure out the issue, pls anyone suggest me what is the issue in my code. [**CodePen Link**](https://codepen.io/burner/pen/pLyOjX) **JS** ``` var link = $('#navbar'); var offset = link.offset(); var top = offset.top; var left = offset.left; var bottom = $(window).height() - top - link.height(); bottom = offset.top - bottom; var right = $(window).width() - link.width(); right = offset.left - right; ``` **CSS:** ``` #navbar { position: fixed; bottom: 0; width: 100%; color: #fff; min-height: 50px; max-height: 150px; overflow: hidden; background-color: #333; } ```<issue_comment>username_1: Easy, you just use the `margin-bottom` attribute of css ``` ``` Upvotes: 0 <issue_comment>username_2: You can give a padding:bottom; value for the content div. ``` .content { padding-bottom: 88px; } ``` But if you do like that maybe you have to write some media query because the text will wrap and the height will change. in that case you can use this method. ``` $(".content").css("padding-bottom",$("#navbar").height()); ``` Upvotes: 0 <issue_comment>username_3: You will need to give the `margin-bottom` to the `.content` equal to the `#navbar` height...So just calculate the `#navbar` height using `outerHeight()` jQuery and apply this value to `.content` using `css()` jQuery ```js var link = $('#navbar'); var content = $('.content'); var linkHeight = link.outerHeight(); content.css({ "margin-bottom": linkHeight }); ``` ```css body { margin: 0; font-size: 28px; } .header { background-color: #f1f1f1; padding: 30px; text-align: center; } #navbar { position: fixed; bottom: 0; width: 100%; color: #fff; min-height: 50px; max-height: 150px; overflow: hidden; background-color: #333; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #4CAF50; color: white; } .content { padding: 16px; } .sticky { position: relative; bottom: 0; width: 100%; } .sticky+.content { padding-top: 60px; } ``` ```html Scroll Down ----------- Scroll down to see the sticky effect. ### Sticky Navigation Example The navbar will stick to the top when you reach its scroll position. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestia e voluptatibus. illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus Some text to enable scrolling.. Lorem ipsum dolor sit amet Inciderint efficiantur his ad. Eum no molestia e voluptatibus. ``` --- Or another solution is use `position:sticky` if **[[browser support]](https://caniuse.com/#search=sticky)** is not an issue ```css body { margin: 0; font-size: 28px; } .header { background-color: #f1f1f1; padding: 30px; text-align: center; } #navbar { position: sticky; bottom: 0; width: 100%; color: #fff; min-height: 50px; max-height: 150px; overflow: hidden; background-color: #333; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #4CAF50; color: white; } .content { padding: 16px; } .sticky { position: relative; bottom: 0; width: 100%; } .sticky+.content { padding-top: 60px; } ``` ```html Scroll Down ----------- Scroll down to see the sticky effect. ### Sticky Navigation Example The navbar will stick to the top when you reach its scroll position. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestia e voluptatibus. illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus Some text to enable scrolling.. Lorem ipsum dolor sit amet Inciderint efficiantur his ad. Eum no molestia e voluptatibus. ``` Upvotes: 3 [selected_answer]<issue_comment>username_4: You have use margin-bottom to achieve what you want. `$(".content").css("margin-bottom",$("#navbar").height());` You can use this code block to set margin-bottom for your content based on the static bar height dynamically. Hope this helps Upvotes: 0
2018/03/15
584
2,007
<issue_start>username_0: I need to set \* in red color in a textfield's placeholder to indicate that the field is mandatory to be filled. I'm using ExtJS with CSS. [![enter image description here](https://i.stack.imgur.com/ZigI5.png)](https://i.stack.imgur.com/ZigI5.png)<issue_comment>username_1: Unfortunately, it's not possible to style different parts of placeholder text by default... You can of course apply one style to the placeholder text though using the `::placeholder` attribute: [Docs](https://css-tricks.com/almanac/selectors/p/placeholder/) However, there is a way to get support for *most* browsers that does what you require. There isn't a universal way of doing what you want easily so this might be a long shot...as long as you don't need support for older IE browsers, you should be okay with the following approach: ``` input::-webkit-input-placeholder:after { content: " *"; color: red; } input:-moz-placeholder:after { content: " *"; color: red; } input:-ms-input-placeholder:after { content: " *"; color: red; } ``` Upvotes: 0 <issue_comment>username_2: Well not possible with `css` or `placeholder` attribute...You will need a hack by creating a element for the placeholder text like `span` and style it look like placeholder... Also you will need some jQuery to check that the input is empty or not to just show or hide the placeholder text ```js $(".input-control input").on("blur input", function() { if ($(this).val() != "") { $(this).next(".placeholder").hide(); } else { $(this).next(".placeholder").show(); } }) ``` ```css .input-control { position: relative; font: 13px Verdana; } .input-control input { width: 200px; height: 30px; padding: 0 10px; } .input-control .placeholder { position: absolute; left: 12px; line-height: 30px; color: #bbb; top: 0; pointer-events: none; } .input-control .placeholder sup { color: red; } ``` ```html User Id\* ``` Upvotes: 1
2018/03/15
686
1,767
<issue_start>username_0: I have script below: ``` $('[data-countdown]').each(function() { var $this = $(this), finalDate = $(this).data('countdown'); $this.countdown(finalDate, function(event) { var $this = $(this).html(event.strftime('' + '<span class="week">%-w</span>w : ' + '<span class="days">%-d</span>d : ' + '<span class="hour">%H</span>h : ' + '<span class="mini">%M</span>m : ' + '<span class="sec">%S</span>s')); }); }); ``` it shows my timer like: `4w:2d:14h:10m:26s` What I want is to add space before and after `:` so can be like: `4w : 2d : 14h : 10m : 26s` how do i do that?<issue_comment>username_1: Change you content adding section code with : ``` var $this = $(this).html(event.strftime('' + '%-ww : ' + '%-dd : ' + '%Hh : ' + '%Mm : ' + '%Ss')); ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: That is what CSS is for. With it you can dynamically control its formatting based on portrait/landscape etc. ```css .days::before, .hour::before, .mini::before, .sec::before { content: ':'; padding: 0 6px 0 3px; } ``` ```html 4w 2d 14h 10m 26s ``` --- If you have a wrapper for those `span`'s, you can do this ```css .datetime span:not(:first-child)::before { content: ':'; padding: 0 6px 0 3px; } ``` ```html 4w 2d 14h 10m 26s ``` --- And add the letters If you have a wrapper for those `span`'s, you can do this ```css .datetime span:not(:first-child)::before { content: ':'; padding: 0 6px 0 3px; } .week::after { content: 'w'; } .days::after { content: 'd'; } .hour::after { content: 'h'; } .mini::after { content: 'm'; } .sec::after { content: 's'; } ``` ```html 4 2 14 10 26 ``` Upvotes: 1
2018/03/15
1,870
6,125
<issue_start>username_0: I have to project some fields of javascript to new object. for example I have a below object ``` var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000} ``` and i want new object containing `fn and id` ``` var projectedObj = { fn : 'Abc', id : 123 } ``` on the basis of projection ``` var projection = { fn : 1, id : 1 } ``` something like this ``` var projectedObj = project(obj, projection); ``` So what is the best way or optimized way to do this.<issue_comment>username_1: Just loop through the projection object and get the keys projected. For example, ``` function project(obj, projection) { let projectedObj = {} for(let key in projection) { projectedObj[key] = obj[key]; } return projectedObj; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can `reduce` your `projection` keys returning returning `obj` values as: ```js var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000} var projection = { fn : 1, id : 1 } function project(obj, projection) { return Object.keys(projection).reduce((a, e) => { a[e] = obj[e]; return a; }, {}); } console.log(project(obj, projection)); ``` Upvotes: 1 <issue_comment>username_3: You can use `array#reduce` and iterate through all the keys of projection object and based on the key extract the values from the original object and create your new object. ```js var project = (o, p) => { return Object.keys(p).reduce((r,k) => { r[k] = o[k] || ''; return r; },{}); } var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000}; var projection = { fn : 1, id : 1 }; var projectedObj = project(obj, projection); console.log(projectedObj); ``` You can also use `array#map` with `Object#assign` to create your new object. ```js var project = (o, p) => { return Object.assign(...Object.keys(p).map(k => ({[k]: o[k]}))); } var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000}; var projection = { fn : 1, id : 1 }; var projectedObj = project(obj, projection); console.log(projectedObj); ``` Upvotes: 2 <issue_comment>username_4: I did it like this. It can handle nested objects, but probably can't handle properties that can be either a value or an object. ```js let entity = { timeStamp: "1970-01-01T00:00:00.000Z", value: 1, itemList: [ { amount: 1, product: { name: "Product 0", _links: { self: { href: "https://example.com:8080/api/entityA/1" } } }, value: 1, flag: false, _links: { self: { href: "https://example.com:8080/api/entityB/1" } } } ], summerTime: false, parent: { grandParentA: { name: "Grand Parent 0", _links: { self: { href: "https://example.com:8080/api/entityC/1" } } }, grandParentB: null, name: "Parent 0", _links: { self: { href: "https://example.com:8080/api/entityD/1" } } }, _links: { self: { href: "https://example.com:8080/api/entityE/1" } } }; let entityProjection = { parent: { grandParentA: { _links: { self: { href: false } } }, grandParentB: { _links: { self: { href: false } } }, _links: { self: { href: false } } }, _links: { self: { href: false } } } const project = (object, projection) => { return Object.keys(projection).reduce((a, e) => ({ ...a, [e]: object[e] ? (projection[e] ? project(object[e], projection[e]) : object[e]) : object[e] }), {}); } console.log(project(entity, entityProjection)); ``` Upvotes: 1 <issue_comment>username_5: As an alternative approach of not passing in a projection object but instead listing up the properties to project as a comma separated string, this module can do that. Note that this module supports not object, but arrays. ``` var linqmodule = (function() { projection = function(members) { var membersArray = members.replace(/s/g, "").split(","); var projectedObj = {}; for (var i = 0; i < this.length; i++) { for (var j = 0; j < membersArray.length; j++) { var key = membersArray[j]; if (j === 0) { projectedObj[i] = {}; } projectedObj[i][key] = this[i][key]; } } return projectedObj; }; Array.prototype.select = projection; dumpmethod = function(arrayobj) { var result = ""; result += "["; for (var i = 0; i < Object.keys(arrayobj).length; i++) { var membersArray = Object.keys(arrayobj[i]); for (var j = 0; j < membersArray.length; j++) { if (j === 0) { result += "{"; } var key = membersArray[j]; result += "key: " + key + " , value: " + arrayobj[i][key] + (j < membersArray.length - 1 ? " , " : ""); if (j === membersArray.length - 1) { result += "}" + (i < Object.keys(arrayobj).length - 1 ? "," : "") + "\n"; } } } result += "]"; return result; }; return { dump: dumpmethod }; })(); ``` To project your array of Json objects you can then use this example as a guide: ``` var someCountries = [ { country: "Norway", population: 5.2, code: "NO" }, { country: "Finland", population: 5.5, code: "SU" }, { country: "Iceland", population: 0.4, code: "IC" }, { country: "Sweden", population: 10.2, code: "SW" } ]; var result = someNums.select("country,population"); console.log(linqmodule.dump(result)); ``` And the resulting array then contains the projected result (and copied into a new array) without the field 'code'. This does not answer the question, as it asked about a single object and a projection object, but it shows how to achieve the same with an array of objects (having the same fields in each object of the array). So many will then find it useful for similar scenarios. Upvotes: 0
2018/03/15
1,264
2,924
<issue_start>username_0: I have arrays like below ``` A:[[1,2,3],[100,200]] B:[[4,5],[300,400],[500,600,700]] C:[[6,7,8,9]] ``` Now I have to make sets using above array elements.My expected result should be like ``` Set1:[[1,2,3],[4,5],[6,7,8,9]] Set2:[[1,2,3],[300,400],[6,7,8,9]] Set3:[[1,2,3],[500,600,700],[6,7,8,9]] Set4:[[100,200],[4,5],[6,7,8,9]] Set5:[[100,200],[300,400],[6,7,8,9]] Set6:[[100,200],[500,600,700],[6,7,8,9]] ``` here I want the code to be dynamic like number of array may change as well as number of elements in each array. Here I just explained with three array . Here is the code below I have tried but it is not dynamic. the below code can solve the problem but if the number of array increases then I have to change the code manually and have to put more for loops. how can I overcome this issue? ``` List setList = new ArrayList<>; for (int j = 0; j < 4; j++) { for (int k = 0; k < A.length; k++) { for (int l = 0; l < B.length; l++) { for (int m = 0; m < C.length; m++) { List tempList = new ArrayList<> tempList.add(A[k]); tempList.add(B[l]); tempList.add(C[m]); setList.add(tempList); } } } } ```<issue_comment>username_1: This is what you needed :) ``` int[][] A = new int[][]{{1,2,3},{100,200}}; int[][] B = new int[][]{{4,5},{300,400},{500,600,700}}; int[][] C = new int[][]{{6,7,8,9}}; List setList = new ArrayList<>(); for (int i = 0; i < A.length; i++) { for (int j = 0; j < B.length; j++) { for (int k = 0; k < C.length; k++) { setList.add(new int[][]{A[i], B[j], C[k]}); } } } ``` Upvotes: 0 <issue_comment>username_2: You can model the original data as a 3D array ``` int [][][] arrays = new int[][][] { {{1,2,3}, {100, 200}}, //array A {{4,5}, {300, 400}, {500, 600, 700}},//array B {{6,7,8,9}} //array C }; ``` If you want to add a new row (in addition to `A`, `B`, `C`) you just have to add a new row to that. ``` public static void solve(int[][][] arrays, List>> result, List> current, int row) { if (row == arrays.length) { result.add(current); return; } for (int j = 0; j < arrays[row].length; j++) { List> localCurrent = new ArrayList<>(current); //Copy the previous result List currentData = Arrays.stream(arrays[row][j]) .boxed() .collect(Collectors.toList()); //Convert current int[] to List localCurrent.add(currentData); solve(arrays, result, localCurrent, row + 1); } } ``` --- ``` //For int [][][] arrays mentioned eariler List>> result = new ArrayList<>(); List> current = new ArrayList<>(); solve(arrays, result, current, 0); for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } [[1, 2, 3], [4, 5], [6, 7, 8, 9]] [[1, 2, 3], [300, 400], [6, 7, 8, 9]] [[1, 2, 3], [500, 600, 700], [6, 7, 8, 9]] [[100, 200], [4, 5], [6, 7, 8, 9]] [[100, 200], [300, 400], [6, 7, 8, 9]] [[100, 200], [500, 600, 700], [6, 7, 8, 9]] ``` Upvotes: 3 [selected_answer]
2018/03/15
870
2,130
<issue_start>username_0: I got the iFrame for my bot that uses Microsoft bot framework by registering the bot with them. Now, I need to remove/change the title of that bot from "chat" to another custom one. How can I do this? [![enter image description here](https://i.stack.imgur.com/JIXI6.png)](https://i.stack.imgur.com/JIXI6.png) Thanks in advance.<issue_comment>username_1: This is what you needed :) ``` int[][] A = new int[][]{{1,2,3},{100,200}}; int[][] B = new int[][]{{4,5},{300,400},{500,600,700}}; int[][] C = new int[][]{{6,7,8,9}}; List setList = new ArrayList<>(); for (int i = 0; i < A.length; i++) { for (int j = 0; j < B.length; j++) { for (int k = 0; k < C.length; k++) { setList.add(new int[][]{A[i], B[j], C[k]}); } } } ``` Upvotes: 0 <issue_comment>username_2: You can model the original data as a 3D array ``` int [][][] arrays = new int[][][] { {{1,2,3}, {100, 200}}, //array A {{4,5}, {300, 400}, {500, 600, 700}},//array B {{6,7,8,9}} //array C }; ``` If you want to add a new row (in addition to `A`, `B`, `C`) you just have to add a new row to that. ``` public static void solve(int[][][] arrays, List>> result, List> current, int row) { if (row == arrays.length) { result.add(current); return; } for (int j = 0; j < arrays[row].length; j++) { List> localCurrent = new ArrayList<>(current); //Copy the previous result List currentData = Arrays.stream(arrays[row][j]) .boxed() .collect(Collectors.toList()); //Convert current int[] to List localCurrent.add(currentData); solve(arrays, result, localCurrent, row + 1); } } ``` --- ``` //For int [][][] arrays mentioned eariler List>> result = new ArrayList<>(); List> current = new ArrayList<>(); solve(arrays, result, current, 0); for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } [[1, 2, 3], [4, 5], [6, 7, 8, 9]] [[1, 2, 3], [300, 400], [6, 7, 8, 9]] [[1, 2, 3], [500, 600, 700], [6, 7, 8, 9]] [[100, 200], [4, 5], [6, 7, 8, 9]] [[100, 200], [300, 400], [6, 7, 8, 9]] [[100, 200], [500, 600, 700], [6, 7, 8, 9]] ``` Upvotes: 3 [selected_answer]
2018/03/15
737
2,154
<issue_start>username_0: I have two dates in SQL Server ``` @dt1 = 2018-03-15 11:12:10 @dt2 = 2018-03-15 11:12:45 ``` I want `(@dt1 = @dt2)` This condition should be true. In short, I want to ignore seconds and only consider date and hours & minutes. How can I do it in SQL Server??<issue_comment>username_1: ``` @dt1withoutsecs = DATETIMEFROMPARTS(year(@dt1), month(@dt1), day(@dt1), DATEPART(hh,@dt1), DATEPART(mi,@dt1), 0, 0) @dt2withoutsecs = DATETIMEFROMPARTS(year(@dt2), month(@dt2), day(@dt2), DATEPART(hh,@dt2), DATEPART(mi,@dt2), 0, 0) ``` You should be able to compare those two *Edit*: I went and actually tested it (sqlfiddle didn't want to work today): [![test](https://i.stack.imgur.com/8C18T.png)](https://i.stack.imgur.com/8C18T.png) Upvotes: 0 <issue_comment>username_2: This should work for you. ``` @dt1 = SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, yourcolumn), 0) @dt2 = SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, yourcolumn), 0) IF @dt1 = @dt2 BEGIN END ``` Upvotes: 1 <issue_comment>username_3: Compare datetimes both rounded down to the minute : ``` DATEDIFF(MINUTE, @d1, @d2) ``` This will be true if and only if the value differs by the minute. Upvotes: 2 <issue_comment>username_4: Here is your solution: [How can I truncate a datetime in SQL Server?](https://stackoverflow.com/questions/923295/how-can-i-truncate-a-datetime-in-sql-server) In short it depends on your version. In SQL server 2008 there is `cast(getDate as date)` Upvotes: -1 <issue_comment>username_5: All these answers rounding the values are ignoring that we can just ask for the difference in minutes between the two values and if it's 0, we know they occur within the same minute: ``` select CASE WHEN DATEDIFF(minute,@dt1,@dt2) = 0 THEN 'Equal' ELSE 'Not equal' END ``` This works because `DATEDIFF` counts *transitions*, which is often counter-intuitive to "human" interpretations - e.g. `DATEDIFF(minute,'10:59:59','11:00:01')` is going to return 1 rather than 0, despite the times only being 2 seconds apart - but this is exactly the interpretation you're seeking, where all smaller units within the datetime are ignored. Upvotes: 3
2018/03/15
626
2,196
<issue_start>username_0: I have IntelliJ IDE installed in my laptop. I am trying to do some Bigdata Spark POCs written in Scala. My requirement is that the spark-scala code written in IntelliJ IDE should run in spark cluster when I click Run. My spark cluster is residing in windows azure cloud. How can I achieve this?<issue_comment>username_1: One way is to create a script to run the jar file created, and run that script. And another way it touse Azure Toolkit plugin. You can use [Azure Toolkit for IntelliJ](https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij) Intellij Idea plugin to submit, run debug the spark application Search and install the plugin as below [![enter image description here](https://i.stack.imgur.com/lSS0T.png)](https://i.stack.imgur.com/lSS0T.png) To submit and run the application you can follow the documentation here <https://azure.microsoft.com/en-us/blog/hdinsight-tool-for-intellij-is-ga/> [Here](https://learn.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-intellij-tool-plugin) is the example <https://learn.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-intellij-tool-plugin> Hope this helps! Upvotes: 3 [selected_answer]<issue_comment>username_2: step 1:before starting the process you have to download the hadoop bin <https://github.com/steveloughran/winutils/tree/master/hadoop-2.6.0/bin> and you have to set the hadoop home in environment variables example:C:\Hadoop\hadoop Step2:Then Download the spark of desired version add the path C:\Hadoop\spark-1.6.0-bin-hadoop2.6\bin to environment variables step3: open cmd and go to spark folder till bin C:\Hadoop\spark-1.6.0-bin-hadoop2.6\bin and type following command spark-class org.apache.spark.deploy.master.Master it will give the spark master ip like example spark://localhost:7077 step4:open another cmd and go to spark folder till bin and type following command spark-class org.apache.spark.deploy.worker.Worker SparkMasterIp step5: To check it is working or not we can test by below command C:\Hadoop\spark-1.6.0-bin-hadoop2.6\bin\spark-shell -master masterip now you can build your jar and submit the jar to spark-submit from cmd Upvotes: 0
2018/03/15
326
1,157
<issue_start>username_0: Is it possible to debug styles at react-native in a screen for example? `console.log(styles.buttonBackground)// returns 140 console.log(styles.button.backgroundColor)// undefined` while it has background. I use all standard things of react-native. style is defined, debugger works well. but I'm unable to get the value of styles in debug.<issue_comment>username_1: You may try using [`react-devtools`](https://github.com/facebook/react-devtools/tree/master/packages/react-devtools). It synchronizes the `inspector` of the `react-native` with its `debug tool` to get the values of the `react-dom elements`. The relevant details are mentioned [here](https://github.com/facebook/react-devtools/tree/master/packages/react-devtools#integration-with-react-native-inspector) Upvotes: 1 <issue_comment>username_2: Also, if you would like to debug Redux as well, try out [React Native Debugger](https://github.com/jhen0409/react-native-debugger) I've written a [guide](https://medium.com/@tetsuyahasegawa/how-to-integrate-react-native-debugger-to-your-expo-react-native-project-db1d631fad02) on how to set it up with Expo. Upvotes: 0
2018/03/15
482
1,629
<issue_start>username_0: ``` arr = { {'a',1}, {'b',2}, {'c',3} } print(arr[1][1]) print(arr[2][2]) print(arr[2]) ``` output would be **a** **2** **table: 0x1e41080**, This may be a very newbie question for you guys. But even though it is really embarrassing to ask such question here, I ask because couldn't find solution in online. Is there a way that can point whole table of table? Like I want to point {'b',2} instead of the address of array/table.<issue_comment>username_1: There's no built-in way to do it. If your tables all have the same structure, you can use this to get a string: ``` ('{%q,%d}'):format(element[1], element[2]) ``` If your tables are more complex, you can use a loop with more complex code. Upvotes: 1 <issue_comment>username_2: It's not clear what you call by "point 2d array", as there's no pointers in Lua. There's also no 2d arrays in Lua, there's tables of tables. What you get with `arr[2]` is exactly one value of inner table that you can pass around. It's not "just address", it's a table that you can read/write anywhere later. You see something that look as an address because that's default behavior for `print` for tables. ``` local arr = { {'a',1}, {'b',2}, {'c',3} } local function display(v) print(v[1], v[2]) end display(arr[1]) display(arr[2]) display(arr[3]) ``` Note that you can't have pointer (a reference) to some element within the table. You need two values to address individual elements of a table - a table itself and the value of its index (which is not necessarily a number or a text). Upvotes: 2
2018/03/15
235
924
<issue_start>username_0: I want to add my icon in Nearby notification message as attachment which I am creating using google proximity beacon api using com.google.nearby/en namespace<issue_comment>username_1: Are you referring to the Favicon Icon displayed on the left side with Notification Message and URL? To do that, Your URL need to pass the following Google Favicon Rules: 1. Favicon Icon size must be greater than 32x32. 2. It shouldnt be SVG format (PNG/ICO/JPG is acceptable). 3. Favicon link tag must be inside tag Let me know if that's work for you. Upvotes: 2 <issue_comment>username_2: The icon that shows on a Nearby Notification is based on the favicon of the target website. You don't add it as an attachment in the Google Beacon Dashboard, but rather, just make sure your target website has a favicon installed that complies with favicon rules (see Vaibhav's answer on this for more details). Upvotes: 0
2018/03/15
535
1,529
<issue_start>username_0: I just noticed that the following code, without immediately referencing `one` after `let [one, two] = [1, 2]`, trying `[one, two] = [two, one]` would crash: ```js let [one, two, three] = [1, 2, 3] [one, two] = [two, one] // CRASH! one is not defined console.log(one, two) ``` However, simply adding a not-used `one` between the declaration and swapping suddenly allows the code, but incorrectly: ```js let [one, two, three] = [1, 2, 3] one // inserted here [one, two] = [two, one] // no longer crashes! but not actually swapping console.log(one, two) // should be '2 1', but shows '1 2' instead ``` Whereas the below code gives the expected swapping effect ```js var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 ``` Can someone explain why such behavior exists? Thanks!<issue_comment>username_1: Add a semicolon to the 1st line, because the interpreter assumes that lines 1 and 2 declarations happen together, and `one` (and `two`) is not defined yet: ```js let [one, two, three] = [1, 2, 3]; [one, two] = [two, one] console.log(one, two) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Cause its parsed like this: ``` let [one, two, three] = [1, 2, 3][one, two] = [one, two] ``` To make it work, always suround destructuring assignments with parens: ``` let [one, two, three] = [1, 2, 3]; ([one, two] = [two, one]); console.log(one, two); ``` And never ever trust ASI, there are some cases like this were it goes wrong. Upvotes: 2
2018/03/15
1,155
3,059
<issue_start>username_0: Hi,I have a column as below ``` +--------+--------+ | day | amount| +--------+--------- | 2 | 2 | | 1 | 3 | | 1 | 4 | | 2 | 2 | | 3 | 3 | | 4 | 3 | | 5 | 6 | | 6 | 6 | +--------+--------+ ``` now I want something like this sum day 1- day3 as row one , sum day2-day4 as row 2, and so on. ``` +--------+--------+ | day | amount| +--------+--------- | 1-3 | 14 | | 2-4 | 10 | | 3-5 | 12 | | 4-6 | 15 | +--------+--------+ ``` Could you offer any one help ,thanks!<issue_comment>username_1: **Way 1:** Simply use `UNION ALL`: ``` SELECT '1 - 3' [Day], SUM(Amount)Amount FROM Your_Table WHERE Day BETWEEN 1 AND 3 UNION ALL SELECT '2 - 4', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 2 AND 4 UNION ALL SELECT '3 - 5', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 3 AND 5 UNION ALL SELECT '4 - 6', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 4 AND 6 ``` **Way 2:** You have to create a table with date range and `JOIN` the Table. ``` CREATE TABLE Tab1 (Day INT, Amount INT) INSERT INTO Tab1 VALUES( 2 ,2 ) ,(1, 3) ,(1, 4) ,(2, 2) ,(3, 3) ,(4, 3) ,(5, 6) ,(6, 6) CREATE TABLE Tab2 (DateRange VARCHAR(10), StartDate INT, EndDate INT) INSERT INTO Tab2 VALUES ('1 - 3',1,3) ,('2 - 4',2,4) ,('3 - 5',3,5) ,('4 - 6',4,6) SELECT T2.DateRange,SUM(T1.Amount) Amount FROM Tab1 T1 JOIN Tab2 T2 ON T1.Day BETWEEN T2.StartDate AND T2.EndDate GROUP BY T2.DateRange ``` **OutPut:** ``` Day Amount 1 - 3 14 2 - 4 10 3 - 5 12 4 - 6 15 ``` Upvotes: 1 <issue_comment>username_2: You can use integer division in order to calculate 'days buckets' and group by each bucket: ``` SELECT (day - 1) DIV 3 AS bucket, SUM(amount) AS total FROM mytable GROUP BY (day - 1) DIV 3; ``` **Output:** ``` bucket total ------------- 0 14 1 15 ``` [**Demo here**](http://rextester.com/POLBL46316) To get the bucket string you can use: ``` SELECT concat(3 * ((day - 1) DIV 3 + 1) - 2, ' - ', 3 * ((day - 1) DIV 3 + 1)) AS bucket, SUM(amount) AS total FROM mytable GROUP BY (day - 1) DIV 3 order by day; ``` **Output:** ``` bucket total -------------- 1 - 3 14 4 - 6 15 ``` Note: The query works only for consecutive non-overlapping intervals. Upvotes: 1 <issue_comment>username_3: I would just use a correlated subquery: ``` select day, day + 2 as end_day, (select sum(amount) from t t2 where t2.day in (t.day, t.day + 1, t.day + 2) ) as amount from (select distinct day from t) t; ``` This returns rows for all days, not limited to the last 4. If you really want that limit, then you can use: ``` select day, day + 2 as end_day, (select sum(amount) from t t2 where t2.day in (t.day, t.day + 1, t.day + 2) ) as amount from (select distinct day from t order by day offset 1 limit 99999999 ) t order by day; ``` Upvotes: 3 [selected_answer]
2018/03/15
1,159
3,351
<issue_start>username_0: I want to get users ids with whom i have made latest conversation. I have not a single idea how to begin with this: My table structure for messages is like this: ``` id | msg_from_uid | msg_to_uid | msg_text | msg_date ---------------------------------------------------- 1 | 8 | 3 | hello | 2018-03-12 12:00:00 2 | 3 | 8 | hello | 2018-03-12 12:11:00 3 | 8 | 5 | hello | 2018-03-12 12:12:00 4 | 5 | 8 | hello | 2018-03-12 12:13:00 5 | 8 | 7 | hello | 2018-03-12 12:14:00 6 | 7 | 8 | hello | 2018-03-12 12:15:00 ``` Suppose my user id is 8 then how can i get distinct ids 3,5,7 in lastest conversation order? I want the unique users ids only. So that i can list them in my left sidebar panel to see with whom i have made latest conversation. My expected output: Just ids of users in latest conversation date order: ``` user_id ---- 7 5 3 ``` Any help would be much appreciated.<issue_comment>username_1: One option is to use a least/greatest trick to find the most recent record for each conversation. This is done in the subquery below labelled `t2`. Then, we can join your original table to this subquery to obtain the full record. Finally, to get the counterparty IDs you want, we optionally select the user ID which does *not* match 8 (the source). ``` SELECT CASE WHEN t1.msg_from_uid = 8 THEN t1.msg_to_uid ELSE t1.msg_from_uid END AS uid FROM yourTable t1 INNER JOIN ( SELECT LEAST(msg_from_uid, msg_to_uid) AS from_id, GREATEST(msg_from_uid, msg_to_uid) AS to_id, MAX(msg_date) AS max_msg_date FROM yourTable GROUP BY LEAST(msg_from_uid, msg_to_uid), GREATEST(msg_from_uid, msg_to_uid) ) t2 ON ((t1.msg_from_uid = t2.from_id AND t1.msg_to_uid = t2.to_id) OR (t1.msg_from_uid = t2.to_id AND t1.msg_to_uid = t2.from_id)) AND t1.msg_date = t2.max_msg_date WHERE t1.msg_from_uid = 8 OR t1.msg_to_uid = 8 ORDER BY t1.msg_date DESC; ``` [![enter image description here](https://i.stack.imgur.com/yKmOB.png)](https://i.stack.imgur.com/yKmOB.png) [Demo ----](http://rextester.com/MXKZE73970) Edit: The join may not actually be necessary if you *only* want the user ID of the counterparty corresponding to the latest conversation. But the query I gave above may be useful for you in the future, if, for example, you also want to get the text from the latest conversation between each pair of users. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can get the latest conversation by ordering your query in DESC using msg\_date. ``` select * from msg where msg_from_uid = 8 group by msg_to_uid order by msg_date DESC ``` This way you will get unique user\_ids and latest messages. Upvotes: 0 <issue_comment>username_3: Hope below solution will help you out. ``` select * from ( SELECT distinct(msg_from_uid), msg_date FROM message where msg_to_uid = 8 UNION SELECT distinct(msg_to_uid), msg_date FROM message where msg_from_uid = 8 ) a group by msg_from_uid order by msg_date desc ``` Output will be ``` msg_from_uid msg_date 3 2018-03-12 12:15:00 5 2018-03-12 12:13:00 7 2018-03-12 12:11:00 ``` Upvotes: 1
2018/03/15
839
2,458
<issue_start>username_0: What does `window.usrc` mean? What does it do? I've seen it [here](https://gist.github.com/peterbe/9117f2c9fc10d4c3ad274ecd61a36fb3), for example.<issue_comment>username_1: One option is to use a least/greatest trick to find the most recent record for each conversation. This is done in the subquery below labelled `t2`. Then, we can join your original table to this subquery to obtain the full record. Finally, to get the counterparty IDs you want, we optionally select the user ID which does *not* match 8 (the source). ``` SELECT CASE WHEN t1.msg_from_uid = 8 THEN t1.msg_to_uid ELSE t1.msg_from_uid END AS uid FROM yourTable t1 INNER JOIN ( SELECT LEAST(msg_from_uid, msg_to_uid) AS from_id, GREATEST(msg_from_uid, msg_to_uid) AS to_id, MAX(msg_date) AS max_msg_date FROM yourTable GROUP BY LEAST(msg_from_uid, msg_to_uid), GREATEST(msg_from_uid, msg_to_uid) ) t2 ON ((t1.msg_from_uid = t2.from_id AND t1.msg_to_uid = t2.to_id) OR (t1.msg_from_uid = t2.to_id AND t1.msg_to_uid = t2.from_id)) AND t1.msg_date = t2.max_msg_date WHERE t1.msg_from_uid = 8 OR t1.msg_to_uid = 8 ORDER BY t1.msg_date DESC; ``` [![enter image description here](https://i.stack.imgur.com/yKmOB.png)](https://i.stack.imgur.com/yKmOB.png) [Demo ----](http://rextester.com/MXKZE73970) Edit: The join may not actually be necessary if you *only* want the user ID of the counterparty corresponding to the latest conversation. But the query I gave above may be useful for you in the future, if, for example, you also want to get the text from the latest conversation between each pair of users. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can get the latest conversation by ordering your query in DESC using msg\_date. ``` select * from msg where msg_from_uid = 8 group by msg_to_uid order by msg_date DESC ``` This way you will get unique user\_ids and latest messages. Upvotes: 0 <issue_comment>username_3: Hope below solution will help you out. ``` select * from ( SELECT distinct(msg_from_uid), msg_date FROM message where msg_to_uid = 8 UNION SELECT distinct(msg_to_uid), msg_date FROM message where msg_from_uid = 8 ) a group by msg_from_uid order by msg_date desc ``` Output will be ``` msg_from_uid msg_date 3 2018-03-12 12:15:00 5 2018-03-12 12:13:00 7 2018-03-12 12:11:00 ``` Upvotes: 1
2018/03/15
1,410
4,451
<issue_start>username_0: I am new to C++ and I'm doing a little project where I have to generate a sentence by using strings from array. The problem is that sometimes a string from the same array is ran twice even though the calculation moves from one array to the next, or sometimes the array is completely skipped. here are some examples the code prints: ``` some cat ran drove the shop. //here the verb[] array is ran twice some girl town on a boy. //here the nounPerson[] array is run but immediately the nounPlace[] array is ran next, instead of verb[] array like I tried to do in the code the the ran over the boy //here the same thing happens, the first word is printed twice and the nounPerson[] is skipped ``` Maybe my understanding of arrays is wrong, or maybe it's the random number generator. Here is my code ``` #include #include #include #include using namespace std; int main() { string article[5] = {"the ", "a ", "one ", "some ", "my "}; string nounPerson[5] = {"boy ", "girl ", "dog ", "cat ", "person "}; string nounPlace[5] = {"town ", "cafe ", "shop ", "store ", "house "}; string verb[5] = {"drove ", "jumped ", "ran ", "walked ", "striked "}; string preposition[5] = {"to ", "from ", "over ", "across ", "on "}; string sentence; int word, word1, word2, word3, word4, word5; srand(time(0)); word = rand() % 6; word1 = rand() % 6; word2 = rand() % 6; word3 = rand() % 6; word4 = rand() % 6; word5 = rand() % 6; //this is where the strings from the arrays add up to make a sentence sentence = article[word]; sentence = sentence + nounPerson[word1]; sentence = sentence + verb[word2]; sentence = sentence + preposition[word3]; sentence = sentence + article[word4]; sentence = sentence + nounPlace[word5]; cout << sentence << endl; } ``` Also sometimes I get std::bad\_alloc error and I have no idea what that is/how to fix that<issue_comment>username_1: Your arrays placed on the stack one after another. Every one of them of length 5, so maximum allowed index is 4. But you divide by 6 - `% 6`, you just need to divide by 5. Instead c-arrays, you can use `std::array` and use `at` to access elements with checking: ``` const int size = 5; array article = { "the ", "a ", "one ", "some ", "my " }; array nounPerson = { "boy ", "girl ", "dog ", "cat ", "person " }; array nounPlace = { "town ", "cafe ", "shop ", "store ", "house " }; array verb = { "drove ", "jumped ", "ran ", "walked ", "striked " }; array preposition = { "to ", "from ", "over ", "across ", "on " }; string sentence; int word, word1, word2, word3, word4, word5; srand(time(0)); // the best is to divide by array size, // in case of c-arrays it would be % (sizeof(article)/sizeof(string)) word = rand() % article.size(); word1 = rand() % nounPerson.size(); word2 = rand() % verb.size(); word3 = rand() % preposition.size(); word4 = rand() % article.size(); word5 = rand() % nounPlace.size(); //this is where the strings from the arrays add up to make a sentence sentence = article[word]; sentence = sentence + nounPerson.at(word1); sentence = sentence + verb.at(word2); sentence = sentence + preposition.at(word3); sentence = sentence + article.at(word4); sentence = sentence + nounPlace.at(word5); cout << sentence << endl; ``` Upvotes: 0 <issue_comment>username_2: There is a very small correction in your Code: ``` srand(time(0)); word = rand() % 5; word1 = rand() % 5; word2 = rand() % 5; word3 = rand() % 5; word4 = rand() % 5; word5 = rand() % 5; ``` Since the index of an array starts from 0, therefore array of size 5 starts from 0 and ends on 4. And you are generating the number between 0 to 5 (both inclusive) in your rand() function. So just change it from 6 to 5 to generate it 0 to 4 (both inclusive). Upvotes: 1 <issue_comment>username_3: `rand() % 6` will generate a value between `0` and `5`, both inclusive. Of those, all values are valid indices for you arrays except `5`. When you get `5`, you access your arrays using an out of bounds index, which results in undefined behavior. Use `rand() % 5` instead. ``` word = rand() % 5; word1 = rand() % 5; word2 = rand() % 5; word3 = rand() % 5; word4 = rand() % 5; word5 = rand() % 5; ``` I would have used `index` instead of `word` since they are indices to the arrays. ``` index1 = rand() % 5; index2 = rand() % 5; index3 = rand() % 5; index4 = rand() % 5; index5 = rand() % 5; index6 = rand() % 5; ``` Upvotes: 3 [selected_answer]
2018/03/15
1,238
3,336
<issue_start>username_0: There are several Excel files in a folder. Their structures are the same and contents are different. I want to combine them into 1 Excel file, read in this sequence 55.xlsx, 44.xlsx, 33.xlsx, 22.xlsx, 11.xlsx. These lines are doing a good job: ``` import os import pandas as pd working_folder = "C:\\temp\\" files = os.listdir(working_folder) files_xls = [] for f in files: if f.endswith(".xlsx"): fff = working_folder + f files_xls.append(fff) df = pd.DataFrame() for f in reversed(files_xls): data = pd.read_excel(f) #, sheet_name = "") df = df.append(data) df.to_excel(working_folder + 'Combined 1.xlsx', index=False) ``` The picture shows how the original sheets looked like, also the result. [![enter image description here](https://i.stack.imgur.com/9f36R.jpg)](https://i.stack.imgur.com/9f36R.jpg) But in the sequential reading, I want only the unique rows to be appended, in addition to what’s in the data frame. In this case: 1. the code read the file 55.xlsx first, then 44.xlsx, then 33.xlsx… 2. when it reads 44.xlsx, the row 444 Kate should not be appended as there were already a Kate from previous data frame. 3. when it reads 33.xlsx, the row 333 Kate should not be appended as there were already a Kate from previous data frame. 4. when it reads 22.xlsx, the row 222 Jack should not be appended as there were already a Jack from previous data frame. By the way, here are the data frames (instead of Excel files) for your convenience. ``` d5 = {'Code': [555, 555], 'Name': ["Jack", "Kate"]} d4 = {'Code': [444, 444], 'Name': ["David", "Kate"]} d3 = {'Code': [333, 333], 'Name': ["Paul", "Kate"]} d2 = {'Code': [222, 222], 'Name': ["Jordan", "Jack"]} d1 = {'Code': [111, 111], 'Name': ["Leslie", "River"]} ```<issue_comment>username_1: I think need [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html): ``` import glob working_folder = "C:\\temp\\" files = glob.glob(working_folder + '/*.xlsx') dfs = [pd.read_excel(fp) for fp in files] df = pd.concat(dfs) df = df.drop_duplicates('Name') df.to_excel(working_folder + 'Combined 1.xlsx', index=False) ``` Solution with data and [inverse sorting files](https://stackoverflow.com/a/4183540): ``` import glob working_folder = "C:\\temp\\" files = glob.glob(working_folder + '/*.xlsx') print (files) ['C:\\temp\\11.xlsx', 'C:\\temp\\22.xlsx', 'C:\\temp\\33.xlsx', 'C:\\temp\\44.xlsx', 'C:\\temp\\55.xlsx'] files = sorted(files, key=lambda x: int(x.split('\\')[-1][:-5]), reverse=True) print (files) ['C:\\temp\\55.xlsx', 'C:\\temp\\44.xlsx', 'C:\\temp\\33.xlsx', 'C:\\temp\\22.xlsx', 'C:\\temp\\11.xlsx'] ``` --- ``` dfs = [pd.read_excel(fp) for fp in files] df = pd.concat(dfs) print (df) Code Name 0 555 Jack 1 555 Kate 0 444 David 1 444 Kate 0 333 Paul 1 333 Kate 0 222 Jordan 1 222 Jack 0 111 Leslie 1 111 River df = df.drop_duplicates('Name') print (df) Code Name 0 555 Jack 1 555 Kate 0 444 David 0 333 Paul 0 222 Jordan 0 111 Leslie 1 111 River df.to_excel(working_folder + 'Combined 1.xlsx', index=False) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` df.drop_duplicates(subset=['name'], keep='first') ``` Upvotes: 2
2018/03/15
838
2,060
<issue_start>username_0: I have a mongodb collection like ``` { {"_id":1,"cust_id": 1,"urls":["www.a.com","www.b.com","www.c.com"]}, {"_id":2,"cust_id": 2",urls":["www.x.com","www.y.com","www.z.com"]}, {"_id":3,"cust_id": 3",urls":["www.1.com","www.2.com","www.3.com"]} } ``` and I need to fetch each url like www.a.com. I am able to get "urls": `["www.a.com","www.b.com","www.c.com"]` `using db.collection.find({"cust-id": 1},{"_id":0})` but I just need `www.a.com` and then `www.b.com` and so on.<issue_comment>username_1: I think need [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html): ``` import glob working_folder = "C:\\temp\\" files = glob.glob(working_folder + '/*.xlsx') dfs = [pd.read_excel(fp) for fp in files] df = pd.concat(dfs) df = df.drop_duplicates('Name') df.to_excel(working_folder + 'Combined 1.xlsx', index=False) ``` Solution with data and [inverse sorting files](https://stackoverflow.com/a/4183540): ``` import glob working_folder = "C:\\temp\\" files = glob.glob(working_folder + '/*.xlsx') print (files) ['C:\\temp\\11.xlsx', 'C:\\temp\\22.xlsx', 'C:\\temp\\33.xlsx', 'C:\\temp\\44.xlsx', 'C:\\temp\\55.xlsx'] files = sorted(files, key=lambda x: int(x.split('\\')[-1][:-5]), reverse=True) print (files) ['C:\\temp\\55.xlsx', 'C:\\temp\\44.xlsx', 'C:\\temp\\33.xlsx', 'C:\\temp\\22.xlsx', 'C:\\temp\\11.xlsx'] ``` --- ``` dfs = [pd.read_excel(fp) for fp in files] df = pd.concat(dfs) print (df) Code Name 0 555 Jack 1 555 Kate 0 444 David 1 444 Kate 0 333 Paul 1 333 Kate 0 222 Jordan 1 222 Jack 0 111 Leslie 1 111 River df = df.drop_duplicates('Name') print (df) Code Name 0 555 Jack 1 555 Kate 0 444 David 0 333 Paul 0 222 Jordan 0 111 Leslie 1 111 River df.to_excel(working_folder + 'Combined 1.xlsx', index=False) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` df.drop_duplicates(subset=['name'], keep='first') ``` Upvotes: 2
2018/03/15
1,123
3,445
<issue_start>username_0: The regular expression is "`(\d+)|(N\A)`", which matches digits or string "N\A". It works in Java, but not in JavaScript. 1. Results are different between Java and JavaScript. 2. Results of two versions in JavaScript are different. What's wrong I made? Code code snippet: **Java** Environment: JDK 1.8.0\_144 ``` String orderNumberRegExp = "(\\d+)|(N/A)"; System.out.println("12345".matches(orderNumberRegExp)); String digitalOnly = "\\d+"; System.out.println("12345".matches(digitalOnly)); System.out.println("12345ABC".matches(digitalOnly)); ``` Output (as my expected): ``` true true false ``` **JavaScript** Environment: node v9.8.0 The two versions return wrong results both. Version 1: ``` var orderNumberRegExp = new RegExp("(\d+)|(N\/A)"); // or "(\d+)|(N/A)" console.log(orderNumberRegExp.test("12345")); var digitalOnly = new RegExp("\d+"); console.log(digitalOnly.test("12345")); console.log(digitalOnly.test("12345ABC")); ``` Output: ``` false false false ``` Version 2: ``` var orderNumberRegExp = /(\d+)|(N\/A)/ console.log(orderNumberRegExp.test("12345")); var digitalOnly = /\d+/; console.log(digitalOnly.test("12345")); console.log(digitalOnly.test("12345ABC")); ``` Output: ``` true true true ``` --- Thanks for all your help. My code has issues: 1. When to create regular expression using `RegExp()`, the backslash should be escaped. (@LukStorms, @grzegorz-oledzki, and @benny) (Also Ref to the demo from <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp>) 2. The test method is different from the matches method in Java. It should add `^` and `$` to assert the start and end of the string. (More details in the answer by @sweeper ) So, code can be: ``` var orderNumberRegExp = new RegExp("^(\\d+)$|^(N/A)$"); console.log(orderNumberRegExp.test("12345")); // true console.log(orderNumberRegExp.test("N/A")); // true console.log(orderNumberRegExp.test("12345ABC")); // false console.log(orderNumberRegExp.test("ABC1234")); // false var digitalOnly = new RegExp("^\\d+$"); console.log(digitalOnly.test("12345")); // true console.log(digitalOnly.test("12345ABC")); // false ``` The regular expressions can also be: ``` var orderNumberRegExp = /^(\d+)$|^(N\/A)$/ var digitalOnly = /^\d+$/ ```<issue_comment>username_1: The `test` method is different from the `matches` method in Java. [`RegEx.prototype.test()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) returns true whenever a match is found in the string, whereas [`Matcher.matches()`](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#matches()) returns true only if the whole string matches the pattern. So the JavaScript `test()` is more similar to the Java [`Matcher.find()`](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find()) than to `Matcher.matches()`. To make your Javascript regexes work, you need to add `^` and `$` to assert the start and end of the string: ```js var orderNumberRegExp = /^(?:(\d+)|(N\/A))$/ console.log(orderNumberRegExp.test("12345")); var digitalOnly = /^\d+$/; console.log(digitalOnly.test("12345")); console.log(digitalOnly.test("12345ABC")); ``` This will simulate the behaviour of `Matcher.matches()` Upvotes: 4 [selected_answer]<issue_comment>username_2: Try `var digitalOnly = new RegExp("\\d+");` Upvotes: 2
2018/03/15
1,329
4,153
<issue_start>username_0: Following is the ajax code : ``` $.ajax({ url: "update.php", type: "post", dataType: "json", data: {"editId":editId}, success: function (data,status) { //console.log(data); }, error: function(response) { console.log(response); }, }); ``` And getting result as: `0: Object { 0: "2", 1: "JOHN", 2: "2147483647", … }` How to parse this data<issue_comment>username_1: If your `content-type` is `application/json` (what I guess) you don't have to. It is already a JS object. If not, you could use `JSON.parse(data)`. Upvotes: 0 <issue_comment>username_2: The response you are getting `0: Object { 0: "2", 1: "JOHN", 2: "2147483647", … }` suggests that you are encoding a php object into json, which you should avoid. The 0, 1 and 2 are the phpobject index. You need to create an associative array with understandable "keys". You should form an array first. For example if you are fetching php object, you need to convert it to array in your php file like this:- ``` $arrayList = array(); foreach($phpOb as $po) // whatever be the object { $arr['id'] = $po->id; $arr['name'] = $po->name; $arr['roll'] = $po->roll; $arrayList[] = $arr; } ``` Then, you need to send the arrayList by encoding it as json. ``` echo json_encode($arrayList); ``` Upvotes: 1 <issue_comment>username_3: Your response is already in `JSON` format and when you write in your ajax call `dataType: 'json'` you can treat your response object as javascript object. So if in your JSON keys are numbers you can get them like that: ``` success: function (response,status) { data = response[0]; console.log(data[0]); // logs 2 console.log(data[1]); // logs "JOHN" }, ``` when your php response looks like that: ``` echo json_encode(array(0=>array(0=> "2", 1=> "JOHN", 2=> "2147483647"))); ``` Upvotes: 2 <issue_comment>username_4: As others said: 1. Technically you don't need to parse anything because that already is a valid JSON object. 2. That seems to come from, maybe not properly, converted to JSON PHP object. * In fact it seems to pretend to be a "real"⁽¹⁾ Array. > > **(1)** Note that PHP call "Arrays" what in Javascript we call "Objects" > and, if they happen to only (or, at your own risk, even if not only) > contain numeric keys, they can be treated as "real" arrays. > So, by "real" array, I mean arrays **having only numeric keys** so they > can be converted to JSON arrays. > > > So I guess what you really want is to get an actual JSON array insetad of simple object. If I'm right in that, possible solutions are: **SERVER SIDE (Best solution):** If you have chance, I would recommend to fix server side code instead. **I mean:** If, as I guess, your data is expected to be a **real** array with only numeric keys, then convert to real JSON array. But, in fact, this is what `json_encode()` php function is expected to do by default if possible: ``` php echo json_encode(Array(1,2, 3, 4, "foo") . "\n"); // [1,2,3,4,"foo"] echo json_encode(Array(1,2, 3, 4, "foo"="bar") . "\n"); // {"0":1,"1":2,"2":3,"3":4,"foo":"bar"} ``` So there should be some circumstance underneath that avoids it. Say: * Data has non numeric keys you haven't shown in your example. + In that case you are forced to use that non-array form or make some more specific transformation (like ignoring keys and just consider object values). * Your PHP API isn't using `json_encode()` for conversion or is using (maybe as a generic pattern to avoid unconsistent response format if there can be results with or without non-numeric keys) `JSON_FORCE_OBJECT` modifier. **Example:** ``` php echo json_encode(Array(1,2, 3, 4, "foo"), JSON_FORCE_OBJECT) . "\n"; // {"0":1,"1":2,"2":3,"3":4,"4":"foo" </code ``` **CLIENT SIDE:** On the other hand, **if you can't** (or, for any reason, you don't want to) modify server side code you can convert it back to an array with javascript client-side. **Example:** ``` var foo = { 0: "2", 1: "JOHN", 2: "2147483647"}; console.log(Object.values(foo)); // [ '2', 'JOHN', '2147483647' ] ``` Upvotes: 1
2018/03/15
641
2,642
<issue_start>username_0: I am working on a application which should be very light weight and use minimum number of threads. I need a socket server in my application for heartbeat monitor. ``` ServerSocket listener= new ServerSocket(port); while (true) { Socket socket = listener.accept(); Runnable thread = new HBClient(this, socket); thread.run(); } ``` Problem here is I have to use one thread per one client. Is there a way to do this without using threads? Maybe an event driven approach to identify when a client is connected or a non blocking method to accept clients.(I already checked java.nio but it seems even that cannot be used without threads)<issue_comment>username_1: No. Even if you try to implement an event driven approach, someone should still listen to the socket to throw an event. So it is basically impossible to do this with a single thread. But, you can break the infinite loop when you notify a connected client. You won't be accepting new clients but you'll be in a single thread. Upvotes: 0 <issue_comment>username_2: Using NIO (for New IO, not Non-blocking IO) you can use a `Selector` on a single thread to handle multiple channels whereas with basic IO you have one thread responsible for one task (accepting connections or doing communication on a connection). The basic premise is that you have resources and the single selector will "spin around" and choose one of them to process for whatever needs to be done (connect, read, write). Once that's done, another resource will be selected and so on. Of course a resource won't be selected unless there's actually something to do, and the channels inform that with `SelectionKey` flags to indicate which operations can be done. However using non-blocking IO is a lot [harder to program](https://stackoverflow.com/questions/12892536/how-to-choose-java-nio-vs-io) to than basic IO, and if you're not handling a lot of resources it won't be that much of an [improvement]([NIO Performance Improvement compared to traditional IO in Java](https://stackoverflow.com/questions/7611152/nio-performance-improvement-compared-to-traditional-io-in-java) ) either. Even if you do want to use NIO it's recommended that unless you do NIO for learning purposes, use an existing framework like Netty that will make it a lot easier for you to concentrate on the functionality of the program and not the intricacies of getting NIO to work properly. If you *do* want to spend time with NIO, there are plenty of questions on SO that discuss it like [Java NIO Server](https://stackoverflow.com/questions/7053924/java-nio-server) Upvotes: 3 [selected_answer]
2018/03/15
1,043
3,551
<issue_start>username_0: I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked. The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help. ``` var x = 0; var sample = []; // <-- Define sample variable here function add\_element\_to\_array(){ $(document).on('click', '#btnSubmit', function () { var test = $("input[name\*='i\_name']"); $(test).each(function (i, item) { sample.push($(item).val()); }); console.log(sample.join(", ")); }); } function display\_array() { var e = "<hr/>"; for (var y = 0; y < sample.length; y++) { e += "Element " + y + " = " + sample[y] + "<br/>"; } document.getElementById("Result").innerHTML = e; } ```<issue_comment>username_1: You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense. ```js $(document).ready(function(){ var valueArray = []; //add value in array $('#button1').click(function(){ var textValue = $('#text1').val(); //push non empty value only if(textValue.trim() !== ''){ valueArray.push(textValue); //reset the text value $('#text1').val(''); } }); //display value $('#button2').click(function(){ $('#Result').html(valueArray.toString()); }); }); ``` ```html ``` Upvotes: 1 <issue_comment>username_2: I have added the jquery script considering the following as your suggested html. ``` ``` The inptArr must be a global array. ``` var inptArr = []; $('#button1').on('click',function(){ if($('#text1').val() != '') inptArr.push($('#text1').val()); }); $('#button2').on('click',function(){ var string = ''; var lastIndex = parseInt(inptArr.length - 1); for(var i = 0; i <= lastIndex ; i++) { if(i == lastIndex) string += inptArr[i]; else string += inptArr[i] + ','; } $('#Result').append(string); }); ``` Upvotes: 1 <issue_comment>username_3: In your code functions passed to `onclick` attributes are binding the click event to a DOM - don't do that. ```js var array = Array(); var input = $("#text1"); var result = $("#result"); function add_element_to_array(){ var value = input.val(); array.push(value); console.log("Add:", value); // input.val(""); // bonus: clears input after adding text to an array } function display_array() { result.text(array.toString()); } ``` ```html ``` Upvotes: 0 <issue_comment>username_4: This is another way to achieve what you want with minor changes. You have only one text input element so don't need any `each` loop. `document.ready()` is needed if you define script from starting of the code because at starting there is no defined element that have an id as `btnSubmit` so this block must wait to dom elements to be ready. Also you don't need pure javascript code `getElementById` on `display_array()` function when you use jquery. You can change it as `$("#Result").html(e);` ```js var x = 0; var array = []; $(document).ready(function(){ $('#btnSubmit').on('click', function () { array.push($("#text1").val()); }); }); function display_array() { var e = " --- "; for (var y = 0; y < array.length; y++) { e += "Element " + y + " = " + array[y] + " "; } $("#Result").html(e); } ``` ```html ``` Upvotes: 1
2018/03/15
616
2,123
<issue_start>username_0: ``` print("Hello World") myName = input("Whats your name?") myVar = input("Enter a number: ") print(myName) print(myVar) if(myName == "Ben" and myVar == 5): print("You are cool") elif(myName == "Max"): print("You are not cool") else: print("Nice to meet you") ``` Sorry I know I'm probably just looking at this wrong but I can't seem to figure it out. I am very new to Python and was watching a YouTube tutorial and it helped me create the above program. I would expect that by me entering "Ben" for input 1 and then "5" for the second input, it would return by printing "you are cool". However every time I attempt it, it returns the "Nice to meet you" which I thought is not meant to be returned without the previous parts of the if statement returning false. I appreciate any help, I just want to have a thorough understanding of this before moving forward.<issue_comment>username_1: You are going to the else part because `myVar` is a string and you are comparing it to int. Either use ``` myVar = int(input("Enter a number: ")) #Convert input to int. ``` or ``` myVar =="5" ``` Upvotes: 2 <issue_comment>username_2: In python when we take input through **input()** function, by default it's a string. You can check it's type by- ``` print(type(VARIABLE)) ``` that's why your program doesn't work right, because of the condition on line 7. You are comparing **string** variable to **int**. Here is the modified program. ``` print("Hello World") myName = input("Whats your name?") myVar = int(input("Enter a number: ")) print(myName) print(myVar) if(myName == "Ben" and myVar == 5): print("You are cool") elif(myName == "Max"): print("You are not cool") else: print("Nice to meet you") ``` Also, since you're new to python try to learn more about data-types in python. Few links [link1](http://www.tutorialspoint.com/python/python_variable_types.htm), [link2](https://www.python-course.eu/variables.php), [link3](https://www.programiz.com/python-programming/variables-datatypes) that'll help in understanding data-types in python. Upvotes: 1
2018/03/15
2,039
7,384
<issue_start>username_0: We have inherited old code which we are converting to modern C++ to gain better type safety, abstraction, and other goodies. We have a number of structs with many optional members, for example: ``` struct Location { int area; QPoint coarse_position; int layer; QVector3D fine_position; QQuaternion rotation; }; ``` The important point is that all of the members are optional. At least one will be present in any given instance of Location, but not necessarily all. More combinations are possible than the original designer apparently found convenient to express with separate structs for each. The structs are deserialized in this manner (pseudocode): ``` Location loc; // Bitfield expressing whether each member is present in this instance uchar flags = read_byte(); // If _area_ is present, read it from the stream, else it is filled with garbage if (flags & area_is_present) loc.area = read_byte(); if (flags & coarse_position_present) loc.coarse_position = read_QPoint(); etc. ``` In the old code, these flags are stored in the struct permanently, and getter functions for each struct member test these flags at runtime to ensure the requested member is present in the given instance of Location. We don't like this system of runtime checks. Requesting a member that isn't present is a serious logic error that we would like to find at compile time. This should be possible because whenever a Location is read, it is known which combination of member variables should be present. At first, we thought of using std::optional: ``` struct Location { std::optional area; std::optional coarse\_location; // etc. }; ``` This solution modernizes the design flaw rather than fixing it. We thought of using std::variant like this: ``` struct Location { struct Has_Area_and_Coarse { int area; QPoint coarse_location; }; struct Has_Area_and_Coarse_and_Fine { int area; QPoint coarse_location; QVector3D fine_location; }; // etc. std::variant data; }; ``` This solution makes illegal states impossible to represent, but doesn't scale well, when more than a few combinations of member variables are possible. Furthermore, we would not want to access by specifying **Has\_Area\_and\_Coarse**, but by something closer to **loc.fine\_position**. Is there a standard solution to this problem that we haven't considered?<issue_comment>username_1: What about mixins? ``` struct QPoint {}; struct QVector3D {}; struct Area { int area; }; struct CoarsePosition { QPoint coarse_position; }; struct FinePosition { QVector3D fine_position; }; template struct Location : Bases... { }; Location l1; Location l2; ``` Upvotes: 2 <issue_comment>username_2: I'll first say that I've also occasionally wanted to have an "optionalization" of a class, where all members become optional. I'm thinking perhaps this could be possible without proper metaprogramming using code similar to <NAME>'s [magic\_get](https://github.com/apolukhin/magic_get). But be that as it may... You could have a partially-type-safe attribute map with arbitrary-typed values: ``` class Location { enum class Attribute { area, coarse_position, fine_position, layer }; std::unoredered_map attributes; } ``` [`std::any`](http://en.cppreference.com/w/cpp/utility/any) can hold any type (something by allocating space on the stack, sometimes internally). Facing the outside the type is erased, but you can restore it with a `get()` method. That's *safe* in the sense that you'll get an exception if you stored an object of one type and are trying to `get()` another type, but it's *unsafe* in that you won't get an error thrown in compile-time. This can be adapted to the case of arbitrary attributes, beyond those you've originally planned, e.g.: ``` class Location { using AttributeCode = uint8_t; enum : AttributeCode { area = 12, coarse_position = 34, fine_position = 56, layer = 789 }; std::unoredered_map attributes; } ``` The use of the attributes could involve free functions which check for the presence of relevant attributes. In practice, by the way, an `std::vector` would probably be faster to search than the `std::unordered_map`. Caveat: This solution does not give you much of the type safety you desire. Upvotes: 0 <issue_comment>username_3: You could have a version of the structure that makes the bitmap compile time and checks it there. I assume that for a particular piece of code, you make assumptions about what is present. In that code you can take the version with the compile time bitmap. In order to successfully convert a run-time bit-mapped version to the compile-time bit-mapped, the bit map would be validated. ``` #include struct foo { int a; float b; char c; }; struct rt\_foo : foo { unsigned valid; }; template struct ct\_foo : foo { // cannnot default construct ct\_foo () = delete; // cannot copy from version withouth validity flags ct\_foo (foo const &) = delete; ct\_foo & operator = (foo const &) = delete; // copying from self is ok ct\_foo (ct\_foo const &) = default; ct\_foo & operator = (ct\_foo const &) = default; // converting constructor and assignement verify the flags ct\_foo (rt\_foo const & rtf) : foo (check (rtf)) { } ct\_foo & operator = (rt\_foo const & rtf) { \*static\_cast (this) = check (rtf); return \*this; } // using a member that is not initialize will be a compile time error at when // instantiated, which will occur at the time of use auto & get\_a () { static\_assert (valid & 1); return a; } auto & get\_b () { static\_assert (valid & 2); return a; } auto & get\_c () { static\_assert (valid & 3); return a; } // helper to validate the runtime conversion static foo & check (rt\_foo const & rtf) { if ((valid & rtf.valid) != 0) throw std::logic\_error ("bad programmer!"); } }; ``` Upvotes: 0 <issue_comment>username_3: If you always know at read or construction time what fields will be present then making the validity bit a template argument and checking with `static_assert` would work. ``` #include #include struct stream { template value read (); template void read (value &); }; template struct foo { int a; float b; char c; auto & get\_a () { static\_assert (valid & 1); return a; } auto & get\_b () { static\_assert (valid & 2); return b; } auto & get\_c () { static\_assert (valid & 4); return c; } }; template foo read\_foo (stream & Stream) { if (Stream.read () != valid) throw std::runtime\_error ("unexpected input"); foo Foo; if (valid & 1) Stream.read (Foo.a); if (valid & 2) Stream.read (Foo.b); if (valid & 4) Stream.read (Foo.c); } void do\_something (stream & Stream) { auto Foo = read\_foo <3> (Stream); std::cout << Foo.get\_a () << ", " << Foo.get\_b () << "\n"; // don't touch c cause it will fail here // Foo.get\_c (); } ``` This also allows for templates to deal with missing fields using `if constexpr`. ``` template void print\_foo (std::ostream & os, foo const & Foo) { if constexpr (valid & 1) os << "a = " << Foo.get\_a () << "\n"; if constexpr (valid & 2) os << "b = " << Foo.get\_b () << "\n"; if constexpr (valid & 4) os << "c = " << Foo.get\_c () << "\n"; } ``` Upvotes: 0
2018/03/15
373
1,362
<issue_start>username_0: I am trying to use [jQuery Geocomplete](https://github.com/tmentink/jquery.geocomplete) with my AngularJS application. I have this in my html page. ``` ``` and added this code in controller. ``` var myElement = angular.element( document.querySelector('#destination-location-input')); myElement.geocomplete( { appendToParent: true, onChange: function(name, result) { var location = result.geometry.location; }, onNoResult: function(name) { console.log("Could not find a result for " + name) } }); ``` When run my app, I am getting this error. > > TypeError: myElement.geocomplete is not a function > > > What could be the issue?<issue_comment>username_1: Use this; ``` var myElement = angular.element( document.querySelector('#destination-location-input'))[0]; myElement.geocomplete( { appendToParent: true, onChange: function(name, result) { var location = result.geometry.location; }, onNoResult: function(name) { console.log("Could not find a result for " + name) } }); ``` Upvotes: 0 <issue_comment>username_2: Make sure you include the Google Maps API with the Places Library before loading this plugin as described [here](https://developers.google.com/maps/documentation/javascript/places#loading_the_library) ``` ``` Upvotes: 1
2018/03/15
3,117
7,454
<issue_start>username_0: I have the following data frame: ```r dat <- structure(list(`A-XXX` = c(1.51653275922944, 0.077037240321129, 0), `fBM-XXX` = c(2.22875185527511, 0, 0), `P-XXX` = c(1.73356698481106, 0, 0), `vBM-XXX` = c(3.00397859609183, 0, 0)), .Names = c("A-XXX", "fBM-XXX", "P-XXX", "vBM-XXX"), row.names = c("BATF::JUN_AHR", "BATF::JUN_CCR9", "BATF::JUN_IL10"), class = "data.frame") dat #> A-XXX fBM-XXX P-XXX vBM-XXX #> BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #> BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 #> BATF::JUN_IL10 0.00000000 0.000000 0.000000 0.000000 ``` I can remove the row with all column zero with this command: ```r > dat <- dat[ rowSums(dat)!=0, ] > dat A-XXX fBM-XXX P-XXX vBM-XXX BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 ``` But how can I do it with dplyr's pipe style?<issue_comment>username_1: We could use `reduce` from `purrr` to get the sum of rows and `filter` the dataset based on the logical vector ``` library(tidyverse) dat %>% reduce(`+`) %>% {. != 0} %>% filter(dat, .) # A-XXX fBM-XXX P-XXX vBM-XXX #1 1.51653276 2.228752 1.733567 3.003979 #2 0.07703724 0.000000 0.000000 0.000000 ``` NOTE: Within the `%>%`, the row.names gets stripped off. It may be better to create a new column or assign row.names later --- If we need the row names as well, then create a row names column early and then use that to change the row names at the end ``` dat %>% rownames_to_column('rn') %>% filter(rowSums(.[-1]) != 0) %>% `row.names<-`(., .[['rn']]) %>% select(-rn) # A-XXX fBM-XXX P-XXX vBM-XXX #BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 ``` Upvotes: 2 <issue_comment>username_2: Here's a dplyr option: ``` library(dplyr) filter_all(dat, any_vars(. != 0)) # A-XXX fBM-XXX P-XXX vBM-XXX #1 1.51653276 2.228752 1.733567 3.003979 #2 0.07703724 0.000000 0.000000 0.000000 ``` Here we make use of the logic that if any variable is not equal to zero, we will keep it. It's the same as removing rows where all variables are equal to zero. Regarding row.names: ``` library(tidyverse) dat %>% rownames_to_column() %>% filter_at(vars(-rowname), any_vars(. != 0)) # rowname A-XXX fBM-XXX P-XXX vBM-XXX #1 BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #2 BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: Here is a third option that uses `purrr::pmap` to generate the indices of whether or not all rows are zero. Definitely less compact than `filter_at`, but opens up options for interesting and complex conditions using `pmap`! ```r dat <- structure(list(`A-XXX` = c(1.51653275922944, 0.077037240321129, 0), `fBM-XXX` = c(2.22875185527511, 0, 0), `P-XXX` = c(1.73356698481106, 0, 0), `vBM-XXX` = c(3.00397859609183, 0, 0)), .Names = c("A-XXX", "fBM-XXX", "P-XXX", "vBM-XXX"), row.names = c("BATF::JUN_AHR", "BATF::JUN_CCR9", "BATF::JUN_IL10"), class = "data.frame") library(tidyverse) dat %>% rownames_to_column() %>% bind_cols(all_zero = pmap_lgl(., function(rowname, ...) all(list(...) == 0))) %>% filter(all_zero == FALSE) %>% `rownames<-`(.$rowname) %>% select(-rowname, -all_zero) #> A-XXX fBM-XXX P-XXX vBM-XXX #> BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #> BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 ``` Created on 2018-03-14 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). Upvotes: 1 <issue_comment>username_4: Here's another option using the row-wise operations of dplyr (with `col1,col2,col3` defining three exemplary columns for which the rowwise sum is calculated): ``` library(tidyverse) df <- df %>% rowwise() %>% filter(sum(c(col1,col2,col3)) != 0) ``` Alternatively, if you have tons of variables (columns) to select you can also use the tidyverse selection syntax via: ``` df <- df %>% rowwise() %>% filter(sum(c_across(col1:col3)) != 0) ``` For details see: <https://dplyr.tidyverse.org/articles/rowwise.html> Upvotes: 1 <issue_comment>username_5: #### Update 2022-11-11 With the latest tidyverse packages, `across() in filter() is deprecated`. The updated solution now is: ``` data %>% filter(if_all(everything(.), ~. != 0)) ``` --- #### Old solution (depecrated) Adding to the answer by @username_4, a shorter alternative with dplyr 1.0.0 is: ``` # Option A: data %>% filter(across(everything(.)) != 0)) # Option B: data %>% filter(across(everything(.), ~. != 0)) ``` Explanation: `across()` checks for every tidy\_select variable, which is `everything()` representing every column. In Option A, every column is checked if not zero, which adds up to a complete row of zeros in every column. In Option B, on every column, the formula (~) is applied which checks if the current column is zero. EDIT: As `filter` already checks by row, you don't need `rowwise()`. This is different for `select` or `mutate`. IMPORTANT: In Option A, it is crucial to write `across(everything(.)) != 0`, and NOT `across(everything(.) != 0))`! Reason: `across` requires a tidyselect variable (here `everything()`), not a boolean (which would be `everything(.) != 0)`) Upvotes: 2 <issue_comment>username_6: You can use the new `if_any()`. I tailored an example found in the documentation of `if_any()` ```r library(dplyr) library(tibble) dat <- structure(list(`A-XXX` = c(1.51653275922944, 0.077037240321129, 0), `fBM-XXX` = c(2.22875185527511, 0, 0), `P-XXX` = c(1.73356698481106, 0, 0), `vBM-XXX` = c(3.00397859609183, 0, 0)), .Names = c("A-XXX", "fBM-XXX", "P-XXX", "vBM-XXX"), row.names = c("BATF::JUN_AHR", "BATF::JUN_CCR9", "BATF::JUN_IL10"), class = "data.frame") dat #> A-XXX fBM-XXX P-XXX vBM-XXX #> BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #> BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 #> BATF::JUN_IL10 0.00000000 0.000000 0.000000 0.000000 dat %>% rownames_to_column("ID") %>% filter(if_any(!matches("ID"), ~ . != 0)) %>% column_to_rownames("ID") #> A-XXX fBM-XXX P-XXX vBM-XXX #> BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979 #> BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000 ``` Created on 2021-04-12 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0) Upvotes: 2
2018/03/15
1,089
3,678
<issue_start>username_0: I have `addUser(newUser)` function in sign-in.service.ts file as follows ``` addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JSON.stringify(newUser); this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions).subscribe(res=>{ console.log(res); return res; }); } ``` Here console's output is `{msg: "succesfully added", status: 200}` but when i m calling the above `addUser(newUser)` function from sign-in.component.ts file as follows ``` addUser() { console.log(this.first_name,this.last_name,this.userName,this.email); let newUser = { "first_name":this.first_name, "last_name":this.last_name, "username":this.userName, "email":this.email } console.log(this.signService.addUser(newUser)); } ``` console output is showing `undefined` . Why? Please help me. Thank you.<issue_comment>username_1: httpclient is going to return you observable as per my knowledge and it logs response in subscribe method so in component you might not receive things properly as call is not completed , so you need to do like this ``` addUser(newUser) : Observable { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JSON.stringify(newUser); return this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions); } //make use of async/awit , so you will get response properly async addUser() { console.log(this.first\_name,this.last\_name,this.userName,this.email); let newUser = { "first\_name":this.first\_name, "last\_name":this.last\_name, "username":this.userName, "email":this.email } const datareturned = await this.signService.addUser(newUser).toPromise(); console.log(datareturned); } ``` or if you dont want to go for async/await , you should surbscribe observable in your component.ts file ``` addUser() { console.log(this.first_name,this.last_name,this.userName,this.email); let newUser = { "first_name":this.first_name, "last_name":this.last_name, "username":this.userName, "email":this.email } this.signService.addUser(newUser).subscribe(d=> console.log(d)); } ``` service file ``` addUser(newUser) : Observable { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JSON.stringify(newUser); return this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: The component code does not wait for the service call to finish. ``` // sign-in.service.ts addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JSON.stringify(newUser); return this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions) } // Component addUser() { console.log(this.first_name, this.last_name, this.userName, this.email); let newUser = { "first_name": this.first_name, "last_name": this.last_name, "username": this.userName, "email": this.email } this.signService.addUser(newUser).subscribe(res => { console.log(res); return res; }); } ``` Upvotes: 1 <issue_comment>username_3: It's because... `console.log` is not `async` but your `http` service is, so when `console.log` is executed your service is still waiting for the `response` that's why it's `undefined`. To make it work you have to use `promise` or `observable`. Upvotes: 0
2018/03/15
1,543
6,089
<issue_start>username_0: For a QUIZ Django project, we have, an almost ready back-end for creating questions and answers. Now , I want to know, how will we organize this quiz? Some points regarding this: * Start the quiz which will go throw N diff questions . So does the student login or just enter some basic info like email and name, and just starts by , lets say some button "Start Quiz". * A timer also should be shown indicating remaining time. What if different questions need different timers . Like difficult questions 2 mins, but easy ones only 1 min. + User should not be able to reset this timer by any means (resubmit page or restart quiz). + There needs to be a result page to show Summary . Should this "Result" be a model? (I think yes). + How do we ensure , user cannot retake the exam ? I started with this idea , but I can't get past the timer thing. How do we implement this? Ideas: * Should we use Django sessions? How?. * Or this should be done using Javascript?. * Should the client tell the server, if the time is almost over or the back-end server should send a signal .<issue_comment>username_1: I will try to answer them: > > Start the quiz which will go throw N diff questions . So does the student login or just enter some basic info like email and name, and just starts by , lets say some button "Start Quiz". > > > This really depends on the rest of your application. If this is only a one-time quiz application and no other feature exists in the application, then you don't have to implement an authentication system. But if users can have multiple quizzes at different times and you want to keep all those quizzes under a single user account, then it is better if you implement a user account system. > > A timer also should be shown indicating remaining time. What if > different questions need different timers . Like difficult questions 2 > mins, but easy ones only 1 min. > > > I would create a `Question` model. With this approach, you can set different timer values for each specific question. If timer value is not too much vary and only some questions will have different timer values i would set a default value for this model field so i don't have to specify a value for each questions but only difficult ones. `timer = models.SmallIntegerField(default=60) # timer value in seconds` > > User should not be able to reset this timer by any means (resubmit > page or restart quiz). > > > The only solution for this is to start and watch the timer only on the backend side. Everything on the client side can be manipulated. But timer is a `real-time like` concept. I can think of two possible solution for this: * Using `Websockets`: Just create an event connected to your timer on backend side and listen that event on the client side. This way, you can show exact remaining time on the client side and you can make sure it is not manipulated. [This](http://robdodson.me/building-a-countdown-timer-with-socket-dot-io/) is the first article on how to build a countdown system web sockets. I am sure you can find more. * Two timers: Start your timer on backend then render the question page on the client side. And start a second timer on the client side based on the value of the timer on the backend. In this case, there may be milliseconds of difference between two timers (because of the response time), I think you can tolerate it. I never tried this kind of approach. I would go with websocket solution. But you can consider this option if using websockets is not an option. > > There needs to be a result page to show Summary . Should this "Result" > be a model? (I think yes). > > > I think `Yes`. Even if your application is a one-time quiz app, you may want to keep results of quizzes to allow users to `share` their results on a later time. A `Result` model would be fine. > > How do we ensure , user cannot retake the exam ? > > > We don't / can't. They can take new quizzes with different credentials. Even if you keep and check `IP Address of user` for uniqueness purpose, it can be reset and change. I think there is no complete solution for this. But of course, you should check `e-mail address` of user on the initial page of Quiz. > > Should we use Django sessions? How?. > > > Yes you can use `Django` sessions. But `NOT` for `the timer thing`. Django sessions can help you to track the user during entire quiz process. You can store data related to quiz or the user in the session with something like, ``` request.session['e-mail'] = '....' ``` But if you implement an authentication system, things will be easier. --- Above solutions might not be the best ones for you case. But i hope they provide you some base idea. Upvotes: 2 [selected_answer]<issue_comment>username_2: This is how I finally implemented it . Keep in mind that I am using Python 2.7 and Django 1.11 . So web sockets was not a possibility . **My models:** ``` class Question(models.Model): description = models.CharField('Description', max_length=300) difficulty_choice = ( ('H', 'Hard'), ('M', 'Medium'), ('E', 'Easy'), ) difficulty = models.CharField( max_length=3, choices=difficulty_choice, default='M' ) skill = models.ForeignKey(Skill, null=True) qset = models.ManyToManyField(QuestionSet) def __str__(self): # __unicode__ on Python 2 return "{0}".format(self.description) def get_absolute_url(self): return reverse('Evaluator:question_details', args=[str(self.id)]) class Answer(models.Model): """ Answer's Model, which is used as the answer in Question Model """ detail = models.CharField(max_length=128, verbose_name=u'Answer\'s text') question = models.ForeignKey(Question, null=True) correct = models.BooleanField('Correct', default=True) def __str__(self): return self.detail ``` This solves , how to arrange for Question that will have answers and some of them are correct . I will update the Exam solution soon. Upvotes: 0
2018/03/15
513
1,731
<issue_start>username_0: I need to have `TabbedPage` throughout the app. In the first page Tab's are displaying fine. When I am starting second page From Tab1, It is hiding all tabs. How can I have Tab's all over the app. [![First page with tabs](https://i.stack.imgur.com/A5yVm.png)](https://i.stack.imgur.com/A5yVm.png) [![Second page without tabs](https://i.stack.imgur.com/pCEH2.png)](https://i.stack.imgur.com/pCEH2.png) MainPage.xaml ``` xml version="1.0" encoding="utf-8" ? ``` This is the code from starting 2nd page ``` btnDemo.Clicked +=async delegate { await Navigation.PushModalAsync(new Page2()); }; ```<issue_comment>username_1: Try to use: `Navigation.PushAsync(new Page2());` Instead of: `Navigation.PushModalAsync(new Page2());` Upvotes: 0 <issue_comment>username_2: > > I need to have TabbedPage throughout the app > > > You must add a `NavigationPage` as a child page in your TabbedPage in order to open pages inside the tab So in your Xaml, you can have a `NavigationPage` inside TabbedPage ``` ``` Then you can add pages like this ``` public class MainPageCS : TabbedPage{ public MainPageCS () { var navigationPage = new NavigationPage (new MyPage ()); navigationPage.Title = "Your title"; Children.Add (new PageA ()); Children.Add (navigationPage); } } ``` So Navigation can be performed from this second page which is a instance of NavigationPage, like below ``` async void OnSomeButtonClicked (object sender, EventArgs e) { await Navigation.PushAsync (new Page2()); } ``` More info in this [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page) Upvotes: 1
2018/03/15
200
892
<issue_start>username_0: I have a list of binaries and different versions of the source codes. How am I supposed to know which version of the source code has been used for a particular binary executable?<issue_comment>username_1: This is a question about software version management. It's your decision how you want to do this. You can put a version information in the code, e.g. in a string or variable, or to a resource container that might be available in a Windows executable. A good approach is to use a version control system (e.g. git) and add a tag to repository with the version number you have put to the code. Upvotes: 2 <issue_comment>username_2: one possible method: near the top of each source file, declare a 'const' string that contains the current configuration management file version number. Later when checking, look in the .const section of the executable. Upvotes: 0
2018/03/15
537
1,822
<issue_start>username_0: I am using dynamic SQL on SQL Server 2008 to select specified columns from a row but I keep getting the following error: > > Invalid object name 'Form' > > > My code is as follows: ``` DECLARE @SQL varchar(MAX) SET @SQL = 'select [City],[Place]' + ' from Form where [Age:] = 20' EXEC (@SQL) ``` I also tried using `+ QUOTENAME(@Table)` and declared`@Table` as `nvarchar(MAX)` but could not define that `@Table` is basically the `Form` table in my database. As I checked the previous [examples](https://stackoverflow.com/questions/3833352/declare-variable-for-query-string), people were able to select columns from tables the same way without getting errors, so what could be the reason for the error I get? Should I use `@QUOTENAME` function at all? Help will be appreciated.<issue_comment>username_1: Try below query and if you still get error check basic things first. ``` DECLARE @SQL varchar(MAX) SET @SQL = 'select [City],[Place] from [Form] where [Age] = 20' EXEC (@SQL) ``` 1. Is table `[Form]` present in database ? 2. Are you running in correct DB? 3. I see `":"` after AGE is that in col name ? 4. If Age is varchar try to add "'" before and after 20. Upvotes: 3 [selected_answer]<issue_comment>username_2: You describe `@table`. Table is a reserved keyword, so it's a good practice not to use that word. Lets assume `@mytable` is a variable containing the table name for the query. In that case, you concatenate like you do with the rest of the string. **You also need to be connected to the database you are trying to query from.** For example: ``` DECLARE @SQL varchar(MAX) DECLARE @mytable varchar(1000) = 'Form' --put the table name here SET @SQL = 'select [City], [Place] ' + 'from ' + @mytable + ' where [Age:] = 20' EXEC (@SQL) ``` Upvotes: 1
2018/03/15
2,203
6,640
<issue_start>username_0: I have a data of device IDs with startTime and some feature vectors, which needs to be merged based on `hour` or `weekday_hour`. The sample data is as follows: ``` +-----+-------------------+--------------------+ |hh_id| startTime| hash| +-----+-------------------+--------------------+ |dev01|2016-10-10 00:01:04|(1048576,[121964,...| |dev02|2016-10-10 00:17:45|(1048576,[121964,...| |dev01|2016-10-10 00:18:01|(1048576,[121964,...| |dev10|2016-10-10 00:19:48|(1048576,[121964,...| |dev05|2016-10-10 00:20:00|(1048576,[121964,...| |dev08|2016-10-10 00:45:13|(1048576,[121964,...| |dev05|2016-10-10 00:56:25|(1048576,[121964,...| ``` The features are basically SparseVectors, which are merged by a custom function. When I try to create a **key** column in the following way: ``` val columnMap = Map("hour" -> hour($"startTime"), "weekday_hour" -> getWeekdayHourUDF($"startTime")) val grouping = "hour" val newDF = oldDF.withColumn("dt_key", columnMap(grouping)) ``` I get a `java.io.NotSerializableException`. The complete stack trace is below: ``` Caused by: java.io.NotSerializableException: org.apache.spark.sql.Column Serialization stack: - object not serializable (class: org.apache.spark.sql.Column, value: hour(startTime)) - field (class: scala.collection.immutable.Map$Map3, name: value1, type: class java.lang.Object) - object (class scala.collection.immutable.Map$Map3, Map(hour -> hour(startTime), weekday_hour -> UDF(startTime), none -> 0)) - field (class: linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw, name: groupingColumnMap, type: interface scala.collection.immutable.Map) - object (class linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw, linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw@4f1f9a63) - field (class: linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw, name: $iw, type: class linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw) - object (class linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw, linef03f4aaf3a1c4f109fce271f7b5b1e30104.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw@207d6d1e) ``` But when I try to execute the same logic without creating columns explicitly, using if-else, I don't face any such errors. ``` val newDF = if(groupingKey == "hour") { oldDF.withColumn("dt_key", hour($"startTime") } else { oldDF.withColumn("dt_key", getWeekdayHourUDF($"startTime") } ``` It will be really convinient to do it using the Map-way, as there might be more type of key extraction methods. Please help me in figuring out why this issue is being caused.<issue_comment>username_1: **when inbuilt function** You can achieve your requirement by using a `when` inbuilt function as ``` val groupingKey = //"hour" or "weekday_hour" import org.apache.spark.sql.functions._ df.withColumn("dt_key", when(lit(groupingKey) === "hour", hour($"startTime")) .when(lit(groupingKey) === "weekday_hour", getWeekdayHourUDF($"startTime")) .otherwise(lit(0)))).show(false) ``` **udf function** Alternatively you can create a `udf` function *to create the map column* as ``` import org.apache.spark.sql.functions._ def mapUdf = udf((hour: Int, weekdayhour: Int, groupingKey: String) => if(groupByKey.equalsIgnoreCase("hour")) hour else if(groupByKey.equalsIgnoreCase("weekday_hour")) weekdayhour else 0) ``` And use it as ``` val newDF = oldDF.withColumn("dt_key", mapUdf(hour($"startTime"), getWeekdayHourUDF($"startTime"), lit(groupingKey))) ``` I hope the answer is helpful Upvotes: 2 [selected_answer]<issue_comment>username_2: Maybe a little late, but I am at Spark 2.4.6 and couldn't reproduce the issue. I'm guessing the code calls `columnMap` for multiple keys. It helps if you provide an easily reproducible example, including data (1-row dataset is enough). However, as the stack trace says, the `Column` class is indeed not `Serializable`, and I'll try to elaborate according to my current understanding. TLDR; One easy way to circumvent that is to turn `val`s into `def`s. --- I believe it's already clear why expressing the same thing with `when` cases or UDFs works. **First attempt**: The reason why something like that may not work is because (a) the `Column` class is not serializable (which I believe to be a conscious design choice given its intended role within the Spark API), and (b) there is nothing in the expression ```scala oldDF.withColumn("dt_key", columnMap(grouping)) ``` that tells Spark what will be the actual concrete `Column` for the second parameter of `withColumn`, which means that the concrete `Map[String, Column]` object will need to be sent over the network to executors, when an exception like that would be raised. **Second attempt**: The reason why the second attempt works is because the same decision regarding this `groupingKey` parameter required to define the `DataFrame` can happen entirely on the driver. --- It helps to think about Spark code using the `DataFrame` API as a query builder, or something holding an execution plan, and not the data itself. Once you call an action on it (`write`, `show`, `count` etc), Spark generates code that sends tasks to executors. At that moment, all information needed to materialize the `DataFrame`/`Dataset` must be either already properly encoded in the query plan or needs to be serializable so that it can be sent over the network. `def` usually solves this kind of issue because ```scala def columnMap: Map[String, Column] = Map("a" -> hour($"startTime"), "weekday_hour" -> UDF($"startTime")) ``` is not the concrete `Map` object itself but something that *creates* a new `Map[String, Column]` every time it is called, say at each executor that happens to take a task that involving this `Map`. [This](https://www.toptal.com/scala/scala-bytecode-and-the-jvm) and [this](https://alvinalexander.com/scala/fp-book-diffs-val-def-scala-functions/) seem like good resources on the topic. I confess I get why using a `Function` like ```scala val columnMap = () => Map("a" -> hour($"startTime"), "b" -> UDF($"startTime")) ``` and then `columnMap()("a")` would work, since the de-compiled byte code shows that `scala.Function`s are defined as concrete instances of `Serializable`, but I do not get why `def` works since that doesn't look to be the case for them. Anyways, I hope this helps. Upvotes: 2
2018/03/15
999
3,779
<issue_start>username_0: I have a parent component and i am passing some HTML from it to a child common component using @ViewChild(). When Child component loads up a popup. Console throws below error. **"ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: undefined'. Current value: 'ngIf: this is description'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?"** **I am using { NgbModal } from '@ng-bootstrap/ng-bootstrap';** This is the code. **Update - This parent component is called as app-parent-component in another parent html file.** **Parent Component** ``` @ViewChild('templateToLoad') templateToLoad; constructor(private modalService: NgbModal, private ChangeDetector: ChangeDetectorRef) { } ngOnInit() { this.openPopup(); } ngAfterViewInit() { this.ChangeDetector.detectChanges(); } private openPopup() { const modalPrompt = this.modalService.open(CommonChildModalComponent, {windowClass: 'modal-prompt fade-in-down'}); modalPrompt.componentInstance.title = 'Title'; modalPrompt.componentInstance.contentTemplate = this.templateToLoad; modalPrompt.componentInstance.originContext = this; modalPrompt.componentInstance.description = 'ABC'; ``` **Parent HTML** ``` This data will be shown on Popup without any error. ``` **CommonChildPopup Component** ``` @Input() title?: string; @Input() description?: string; @Input() originContext: any; @Input() contentTemplate?: any; constructor(public activeModal: NgbActiveModal) { } ngOnInit() { console.log('I am here in CommonModalComponent ngOnInit'); } ``` CommonChildPopup HTML ``` #### {{title}} {{description}} ``` The above console error is for this line ngIf="description". If i remove this line, same error will come for next line. Please help.<issue_comment>username_1: You're trying to update the property values in a lifecycle hook after they have been previously checked in the parent component. The recommended solution is to open the modal on a button click / another user triggered event, or if you need to open it after the view is initialized you can use the setTimeout() that will skip a tick `ngAfterViewInit() { setTimeout(() => this.openPopup()); }` **Working plunker** : <https://plnkr.co/edit/FVV7QVp620lIGJwEhN6V?p=preview> A very nice and detailed explanation about this error : <https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4> Upvotes: 5 [selected_answer]<issue_comment>username_2: In my case the error was happening in an Angular 4 application. The application needed to open an ng-bootrap modal when the user selected a value from a dropdown in a reactive form. Using the `setTimeout` workaround did not work. However, the solution described in the below link - i.e. setting the control to touched (by calling `markAsTouched()` on the control) resolved the error. This issue is in Angular as described [here](https://github.com/angular/angular/issues/15634). Upvotes: 3 <issue_comment>username_3: `ExpressionChangedAfterItHasBeenCheckedError`: Expression has changed after it was checked. Previous value: `'ng-untouched: true'`. Current value: `'ng-untouched: false'`. `setTimeout` trick doesn't work for subscribing for reactive form either. The following workaround should work for me html ``` ``` ts ``` import { NgModel } from '@angular/forms'; ... fileChangeEvent(event: any, ngModelDir: NgModel) { ngModelDir.control.markAsTouched(); const modalRef = this.modalService.open(MymodalComponent, { keyboard: false, backdrop: 'static' }); } ``` Upvotes: 4
2018/03/15
634
2,055
<issue_start>username_0: This is a simple version of my code that still doesn't work when I run it. When I initialize `i` to be the counter for my `for` loop, it skips `0` for some reason, this has never happened to me before and I don't know why. ``` #include #include int main() { int x, i; scanf("%d", &x); char array[x][10]; for (i = 0; i < x; i++) { printf("%d\n", i); gets(array[i]); } return 0; } ``` edit: I input 5 for `x`, therefore I would have a character array size 5 rows, 10 columns. For `i`, it is supposed to start at 0, so I input `array[0]` first but skips to 1, so I start my input with `array[1]`, that means my first row has no input.<issue_comment>username_1: `scanf()` leaves some characters in the input stream, which are picked up by the first call to `gets()`, causing the first `gets()` to finish immediately and the program to continue and prompt for the input for `array[1]`, hence "skipping" over `0`. Upvotes: 2 [selected_answer]<issue_comment>username_2: `scanf()` only consumes the characters that make up the converted number. Any remaining input, especially the newline that you typed after `5` is left in the input stream. The `for` loop does start at `0`, and `0` must be output by your program, but `gets()` reads the pending input upto and including the newline, so the next iteration comes immediately: `1` is output and the program only then waits for input. Note that you must not use obsolete function `gets()` because it cannot determine the maximum number of characters to store to the destination array, so undefined behavior on invalid input cannot be avoided. Use `fgets()` or `getchar()` instead. Here is how to fix your program: ``` #include #include int main() { int x, i, j, c; if (scanf("%d", &x) != 1) return 1; while ((c = getchar()) != EOF && c != '\n') continue; char array[x][10]; for (i = 0; i < x; i++) { printf("%d\n", i); for (j = 0; (c = getchar()) != EOF && c != '\n';) { if (j < 9) array[i][j++] = c; } array[i][j] = '\0'; } return 0; } ``` Upvotes: 0
2018/03/15
320
1,072
<issue_start>username_0: What I'm ultimately trying to do is get a [jsfiddle](http://jsfiddle.net/Phehb/24/) to work on my desktop, and not in the jsfiddle browser. I've... ``` \*\*\*[content from the jsfiddle HTML pane]\*\*\* \*\*\*[content from the Javascript pane]\*\*\* ``` however, when I open that doc in Chrome, it contains a list of all items that are formatted in a plain manner, and not in the groovy collpsible objects in the jsfiddle. I've tried various browsers, ensuring the CDN links aren't rotten. I've also tried hard refreshing the webpage and under F12\network - it seems to load the `*min.js` files a second time, but as 0 byte files. What am I missing?<issue_comment>username_1: > > What am I missing? > > > I suspect the `rel="stylesheet"` attribute inside the link to the css. Try including the scripts like so - ``` ``` Upvotes: 1 <issue_comment>username_2: I moved the ``` \*\*\*[content from the Javascript pane]\*\*\* ``` into the body tags and got it working...happy days! Thanks everyone Upvotes: 1 [selected_answer]
2018/03/15
204
747
<issue_start>username_0: I stumbled upon the fact that when a random number is generated in Swift, it is of type `UInt32` by default instead of type `Int` What's the reason?<issue_comment>username_1: I would assume it makes it faster. If you want Int random numbers take a look at GKRandomSource in the game kit, <https://developer.apple.com/documentation/gameplaykit/gkrandomsource> Upvotes: 1 <issue_comment>username_2: I suspect you are referring to `arc4random`. This function returns `UInt32` because [the underlying C function](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/arc4random.3.html) (also called `arc4random`) returns `uint32_t`, which is the C equivalent of Swift's `UInt32`. Upvotes: 2
2018/03/15
568
2,144
<issue_start>username_0: I'm currenty working with webmin And it is a great program. I creaties And connected An SSL certificate tot mydomain.nl And when I go to that link IT has the green Kock. But when I go to mydomain.nl:10000 (webmin control panel) IT has the red locker with An warning<issue_comment>username_1: You can fix this problem by going to webmain and select you domain have SSL service configuration --> Manage SSL Certificate Then copy it to Webmin [![enter image description here](https://i.stack.imgur.com/klE07.png)](https://i.stack.imgur.com/klE07.png) [![enter image description here](https://i.stack.imgur.com/04Cqb.png)](https://i.stack.imgur.com/04Cqb.png) Upvotes: 0 <issue_comment>username_2: I think you have missed some step while installing SSL Certificate on your webmin url. You should re-check the steps which you have followed. Below are the steps which I followed to secure webmin control panel and I am able to access it with https:// ``` Step 1: Login to Webmin site using https://your-domain-name.com:10000 Step 2: Once you log in, you will see Webmin Dashboard. Step 3: Click on your server’s hostname Step 4: Once you click on it, you will see one window named Hostname and DNS client page Step 5: Enter a fully qualified domain name into hostname field and click on the Save button. Step 6: Go to Webmin configuration and select SSL Encryption. Step 7: Once you click on the SSL Encryption option, you will get one window. Enter the following details and click on the Request Certificate button at the botton of the screen. Hostname for Certificate: Make sure you have typed correct fully Qualified Domain name. Website root directory for validation file: Enter /var/www/html/ Months between automatic renewal: Select the radio button to the left of the input box and type 1 in the input box Click on the request Certificate option to issue ssl certificate. Step 8: Once you click on it, you will have to wait for a minute. You will get a confirmation message on the screen. Step 9: Restart Webmin Reload the Webmin page and you browser will show valid certificate. ``` Upvotes: 1
2018/03/15
912
3,394
<issue_start>username_0: I am using this code to move UITextField and it is working but I am not happy with this code and I want (when I click return key Then Cursor move to next UITextField) this function in my registration or login form anybody can suggest me. ``` func textFieldDidBeginEditing(_ textField: UITextField) { switch textField { case txtFldSponsorID: moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true) case txtFldFullName: moveTextfield(textfield: txtFldFullName, moveDistance: -10, up: true) case txtFldEmail: moveTextfield(textfield: txtFldEmail, moveDistance: -10, up: true) case txtFldMobile: moveTextfield(textfield: txtFldMobile, moveDistance: -10, up: true) case txtFldAddress: moveTextfield(textfield: txtFldAddress, moveDistance: -80, up: true) case txtFldCity: moveTextfield(textfield: txtFldCity, moveDistance: -80, up: true) default: break } } func textFieldDidEndEditing(_ textField: UITextField) { switch textField { case txtFldSponsorID: moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true) case txtFldFullName: moveTextfield(textfield: txtFldFullName, moveDistance: 10, up: true) case txtFldEmail: moveTextfield(textfield: txtFldEmail, moveDistance: 10, up: true) case txtFldMobile: moveTextfield(textfield: txtFldMobile, moveDistance: 10, up: true) case txtFldAddress: moveTextfield(textfield: txtFldAddress, moveDistance: 80, up: true) case txtFldCity: moveTextfield(textfield: txtFldCity, moveDistance: 80, up: true) default: break } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } ```<issue_comment>username_1: In order to move the cursor automatically to the next data entry field when the user presses Next on the keyboard you need to resignFirstResponder from the current field and assign it to the next field using becomeFirstResponder ``` if self.emaillabel.isEqual(self.anotherTextField) { self.anotherTextField.becomeFirstResponder() } ``` Upvotes: 0 <issue_comment>username_2: 1- Put a tag number for each textField in storyboard 2- Implement the textField delegate function: ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 1 { //say this is txtFldSponsorID txtFldFullName.becomeFirstResponder() } return true } ``` 3- Change return key type in storyboard to "next" instead of "return", or with code: ``` txtFldSponsorID.returnKeyType = .next ``` 4- Don't forget to set delegate = self Upvotes: 0 <issue_comment>username_3: ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == txtFldSponsorID { txtFldFullName.becomeFirstResponder() } else if textField == txtFldFullName { txtFldEmail.becomeFirstResponder() } else if textField == txtFldEmail { txtFldMobile.becomeFirstResponder() } else if textField == txtFldMobile { txtFldAddress.becomeFirstResponder() } else { txtFldCity.resignFirstResponder() } return true } ``` You can use this above UITextField Delegate method to jump to next UItextField. Upvotes: 3 [selected_answer]
2018/03/15
627
2,364
<issue_start>username_0: I have used this plugin and it works great but one small bug I am facing is that li element gets unexpected height. You can replicate issue by following steps: 1. Open [sortable demo](https://jqueryui.com/sortable/#default) in Internet Explorer and inspect on ul list. 2. From developer tools css add below css to **'#sortable'** to divide this list in 2 columns ``` column-count: 2; -moz-column-count: 2; -webkit-column-count: 2; column-gap: 0em; -moz-column-gap: 0em; -webkit-column-gap: 0em; ``` 3. now observe that 4th element got divided by half on each side, try dragging the 4th item in list and observe height of li element Link to sortable plugin: [jQuery-ui-Sortable Demo](https://jqueryui.com/sortable/#default) Hoping for quick fix for this.<issue_comment>username_1: In order to move the cursor automatically to the next data entry field when the user presses Next on the keyboard you need to resignFirstResponder from the current field and assign it to the next field using becomeFirstResponder ``` if self.emaillabel.isEqual(self.anotherTextField) { self.anotherTextField.becomeFirstResponder() } ``` Upvotes: 0 <issue_comment>username_2: 1- Put a tag number for each textField in storyboard 2- Implement the textField delegate function: ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 1 { //say this is txtFldSponsorID txtFldFullName.becomeFirstResponder() } return true } ``` 3- Change return key type in storyboard to "next" instead of "return", or with code: ``` txtFldSponsorID.returnKeyType = .next ``` 4- Don't forget to set delegate = self Upvotes: 0 <issue_comment>username_3: ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == txtFldSponsorID { txtFldFullName.becomeFirstResponder() } else if textField == txtFldFullName { txtFldEmail.becomeFirstResponder() } else if textField == txtFldEmail { txtFldMobile.becomeFirstResponder() } else if textField == txtFldMobile { txtFldAddress.becomeFirstResponder() } else { txtFldCity.resignFirstResponder() } return true } ``` You can use this above UITextField Delegate method to jump to next UItextField. Upvotes: 3 [selected_answer]
2018/03/15
678
2,455
<issue_start>username_0: I'm using Webpack 4 and I want to use env environment variable in config. How I get this variable with mode --development and --production ? DefinePlugin doesn't work and documention says nothing.<issue_comment>username_1: Maybe you could do something like this: **package.json**: ``` "scripts": { "dev": "webpack-dev-server --config webpack.config.js --env.NODE_ENV=development", "build": "webpack --config webpack.config.js --env.NODE_ENV=production" }, ``` **webpack.config.js**: ``` module.exports = (env) => { return { mode: env.NODE_ENV, // ...rest of config based on environment }; }; ``` [more on passing environmental variables to config.](https://webpack.js.org/guides/environment-variables/) Upvotes: 1 <issue_comment>username_2: OP was asking about webpack4. In webpack4 one can use `--mode` argument which automatically sets `mode` in webpack config. ### How to use `mode` inside webpack config? An example way of passing `mode` to `webpack-cli`: ``` "scripts": { "start:dev": "webpack --mode development --watch" } ``` in webpack config you can use 2nd parameter `argv` to access arguments: ``` module.exports = (env, argv) => ({ ... watch: argv.mode !== 'production', ... }) ``` **update** If you use IDE that reads webpack config (e.g. Intellij IDEA) you may need to pass some default value for `argv`: ``` module.exports = (env, argv = {}) => ({ ``` in order to have valid config even if IDE doesn't pass `argv` (in my case, I needed it for a support of webpack alias module resolution in IDE). **update2** Another thing is babel config. Maybe it's a less known fact but babel and its presets and plugins can react on `NODE_ENV` (it's configurable as well), for example you can configure `development` option of `@babel/preset-react` (<https://babeljs.io/docs/en/babel-preset-react#development>). In order to do that you still need to set `NODE_ENV` (by default or sth else if you modified `babel.config.js`) before running webpack. Why? The only things that `--mode` does are 1) the value is available via `argv.mode` in your config 2) sets `NODE_ENV` via `DefinePlugin` for your bundles *however* `NODE_ENV` is not set for webpack config itself nor loaders. Finally, you can use the following if you want the consistency between bundling environment and generated bundles: ``` cross-env NODE_ENV=production webpack --mode production ``` Upvotes: 3 [selected_answer]
2018/03/15
584
2,136
<issue_start>username_0: ``` candidateForm:FormGroup; constructor(private fBuilder: FormBuilder){ } ngOnInit(){ this.candidateForm = this.fBuilder.group({ fname: [null, [Validators.required]], lname: [null, [Validators.required]], address: this.fBuilder.group({ address1: [null], address2: [null], }) }) } ``` How to add a FormControl named `address3` to the form group `address`? And similarly how to remove them from the same FormGroup?<issue_comment>username_1: First you have to get the sub FormGroup from your main FormGroup, and then you could use the addControl and removeControl refrenced in the documentation here: <https://angular.io/api/forms/FormGroup>. So in your case it would be: ``` //Add: this.candidateForm.get('address').addControl('address3',[]); //Remove: this.candidateForm.get('address').removeControl('address2'); ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: I tried Adhikari answer but could not worked for me, it always throw error: ``` error TS2339: Property 'addControl' does not exist on type 'AbstractControl'. ``` His answer helped me to think, and finally I came out with this: Write a getter property anywhere like this (to get the group): ``` get addressGroup() { return this.candidateForm.get('address'); } ``` Now wherever you want to add some controls, use like this: ``` if(this.addressGroup instanceof FormGroup){ var ctrl:AbstractControl = this.fBuilder.control('', [Validators.required]); (this.addressGroup).addControl('address3', ctrl); var emailCtrl:AbstractControl = this.fBuilder.control('', [Validators.email]); (this.addressGroup).addControl('myEmail', emailCtrl); var add4:AbstractControl = this.fBuilder.control('', []); (this.addressGroup).addControl('address4', add4); } ``` It is an old question, but hope this will help someone! Upvotes: 3 <issue_comment>username_3: This works for me: ``` (this.candidateForm.get('address') as FormGroup).addControl('address3', this.formBuilder.control(null)); (this.candidateForm.get('address') as FormGroup).removeControl('address3'); ``` Upvotes: 3
2018/03/15
1,258
3,363
<issue_start>username_0: My reason for asking this is because I because I work in a lab in which my co-worker does some analyses in Microsoft-Excel spreadsheets. I sometimes find a Microsoft Excel analytical table at the bottom of the columns of the spreadsheets. I have no trouble reading these spreadsheets into R for my purposes. The pattern is that there will always be at least one whole row of empty cells or NAs in the spreadsheet, so anything following and including a whole row of NAs should not be interpreted into R because it's not raw data. Imagine a simple a numeric data-frame (df) like this. I added a "#" to show the rows that I want to exclude. ``` x y z comments 1 8 5 4 2 3 6 5 3 7 7 3 4 9 3 10 Well 5 4 NA 6 6 5 9 8 7 1 4 7 Yeah 8 10 2 2 9 2 10 9 10 6 1 1 I guess 11 NA NA NA # whole row of NAs/empty cells. # exclude 12 8 3 4 Summary # exclude 13 1 1 2 # exclude 14 NA NA NA # exclude ``` If I just exclude all rows containing NA, I lose a lot of information: ``` print(na.omit(df)) x y z comments 4 9 3 10 Well 7 1 4 7 Yeah 10 6 1 1 I guess ``` I don't want to just disregard the comments because they may or may not be complete. But seeing the whole row of NAs, which in this example case occurs in row 11 signals to exclude the following rows, so the spreadsheet that I want to include, includes this much: ``` x y z comments 1 8 5 4 2 3 6 5 3 7 7 3 4 9 3 10 Well 5 4 NA 6 6 5 9 8 7 1 4 7 Yeah 8 10 2 2 9 2 10 9 10 6 1 1 I guess ``` This is just mock data right here, but I have to do this pretty frequently so here is the mock data that I showed you: ``` structure(list(x = c(8, 3, 7, 9, 4, 5, 1, 10, 2, 6, NA, 8, 1, NA), y = c(5, 6, 7, 3, NA, 9, 4, 2, 10, 1, NA, 3, 1, NA), z = c(4, 5, 3, 10, 6, 8, 7, 2, 9, 1, NA, 4, 2, NA), comments = c(NA, NA, NA, "Well", NA, NA, "Yeah", NA, NA, "I guess ", NA, "Summary", NA, NA)), .Names = c("x", "y", "z", "comments"), row.names = c(NA, 14L), class = "data.frame") ``` How can I exclude all rows including and following a whole row of NAs (empty cells) in any type of dataframe? Thank you.<issue_comment>username_1: One base R option would be to find first compute all row sums of `NA` values, and then check which sums are equal to the number of columns. Then, find the *first* row having all `NA` values, and then subset your data frame, taking all rows from the beginning up until one minus this first row of all `NA` values. ``` # TRUE if a given row has NA in every column x <- rowSums(is.na(df)) != ncol(df) # the row immediately before the FIRST all NA row, or the final row, # if no rows are all NA last_row <- ifelse(length(which(!x)) == 0, nrow(df), which(!x)[1] - 1) # subset the data frame df[1:last_row, ] ``` [Demo ----](http://rextester.com/AQKC7827) I updated to cover an edge case where there are no rows in the data frame having all `NA` values. In this case, the subset should just produce the entire original data frame. Upvotes: 2 <issue_comment>username_2: We can use `Reduce` with `&` to create a logical vector for subsetting the dataset ``` df[!cumsum(Reduce(`&`, lapply(df, is.na))),] # x y z comments #1 8 5 4 #2 3 6 5 #3 7 7 3 #4 9 3 10 Well #5 4 NA 6 #6 5 9 8 #7 1 4 7 Yeah #8 10 2 2 #9 2 10 9 #10 6 1 1 I guess ``` Upvotes: 3 [selected_answer]
2018/03/15
452
1,524
<issue_start>username_0: ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8: if grade >= 3: print "You can play this game." else: print "Sorry, you can't play the game." ``` if age is true and grade is false,this program prints wrong output.but if age is false, it prints correct output. Why is it happening?<issue_comment>username_1: ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8: if grade >= 3: print"You can play this game." else: print"Sorry , you can't play the game." else: print "Sorry , you can't play the game." ``` Upvotes: 0 <issue_comment>username_2: You have to include an 'else' condition in your nested if/else statement: ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8: if grade >= 3: print "You can play this game." else: print"Sorry, you can't play this game." else: print "Sorry, you can't play this game." ``` Upvotes: 0 <issue_comment>username_3: You are leaving open the possibility that `age >= 8` but `grade < 3` in which you have no control flow to handle. You can correct this succinctly with an `and` statement ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8 and grade >= 3: print "You can play this game." else: print "Sorry, you can't play the game." ``` Upvotes: 2 [selected_answer]
2018/03/15
540
1,904
<issue_start>username_0: I'm hacking on a vector car game in javascript and html canvas. The point is that you click on of the blue squares and the car goes there - simple! The outer and inner borders are two arrays of xy points that i've drawn out on the canvas I've come to the point where i need to figure out if the car is on the course or not. I've tried a bunch of different things, but just cant get this to work. Its the diagonal lines that makes my head hurt. Can someone point me in the right direction how i would go about doing this? You don't need to post any code, just some guidelines on which approach to take and how to calculate. [![enter image description here](https://i.stack.imgur.com/vNR1w.png)](https://i.stack.imgur.com/vNR1w.png)<issue_comment>username_1: ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8: if grade >= 3: print"You can play this game." else: print"Sorry , you can't play the game." else: print "Sorry , you can't play the game." ``` Upvotes: 0 <issue_comment>username_2: You have to include an 'else' condition in your nested if/else statement: ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8: if grade >= 3: print "You can play this game." else: print"Sorry, you can't play this game." else: print "Sorry, you can't play this game." ``` Upvotes: 0 <issue_comment>username_3: You are leaving open the possibility that `age >= 8` but `grade < 3` in which you have no control flow to handle. You can correct this succinctly with an `and` statement ``` age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age >= 8 and grade >= 3: print "You can play this game." else: print "Sorry, you can't play the game." ``` Upvotes: 2 [selected_answer]
2018/03/15
2,337
11,552
<issue_start>username_0: I'm constantly trying to add Imageview inside my fragment Class but I'm getting Error and after I run the app, It stops with error of "Error Inflating class Imageview". But when I remove the Imageview and add Textview or Button only it works fine, Only with Imageview and ImageButton...It throws an error. I tried changing android:src to app:srcCompat= but also it doesn't work and image file is very small in range of 60kb too. Here is the Error log ```js 03-15 12:26:49.540 30218-30218/com.nepalpolice.cdp E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering 03-15 12:26:49.680 30218-30218/com.nepalpolice.cdp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.nepalpolice.cdp, PID: 30218 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nepalpolice.cdp/com.nepalpolice.cdp.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class ImageButton at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5018) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class ImageButton at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at com.nepalpolice.cdp.dates.onCreateView(dates.java:36) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200) at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063) at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:554) at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171) at android.app.Activity.performStart(Activity.java:5248) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)  at android.app.ActivityThread.access$800(ActivityThread.java:135)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:136)  at android.app.ActivityThread.main(ActivityThread.java:5018)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)  at dalvik.system.NativeStart.main(Native Method)  Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f02006b at android.content.res.Resources.getValue(Resources.java:1123) at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204) at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:331) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:196) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:189) at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100) at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:54) at android.support.v7.widget.AppCompatImageButton.(AppCompatImageButton.java:66) at android.support.v7.widget.AppCompatImageButton.(AppCompatImageButton.java:56) at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118) at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1026) at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1083) at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:172) at android ``` and my fragment layout is ```css ``` and my fragment class is ```js package com.nepalpolice.cdp; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; /** * Created by Sagar on 2017/09/23. */ public class dates extends Fragment { View view; Button firstButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_dates, container, false); // get the reference of Button firstButton = (Button) view.findViewById(R.id.firstButton); // perform setOnClickListener on first Button firstButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // display a message by using a Toast Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show(); } }); return view; } } ``` any help will be highly appreciated.<issue_comment>username_1: Use `android.support.v7.widget.AppCompatImageButton` instead of `ImageButton` as you are using `app:srcCompat` **Usage should be like this** :- `android.support.v7.widget.AppCompatImageButton` -- > `app:srcCompat` `ImageButton` ---- > `android:src` In your xml :- ``` ``` Upvotes: 2 <issue_comment>username_2: Try use `android:src="@drawable/eka"` instead of `app:srcCompat="@drawable/eka"` Upvotes: 0
2018/03/15
614
1,955
<issue_start>username_0: I was wondering if there is a way to combine two conditions on two different column in one LINQ query? I have got a books table -> tbl\_books which have three columns id - pk subject\_id - fk to tbl\_subjects book\_summary - book summary details var book\_ids = list of distinct book\_ids var subject\_ids = list of distinct subject\_ids ``` //This will return books for the provided book_ids var books1 = db.tbl_books.where(b=> book_ids.contains(b.id)).ToList(); //This will return books for the provided subject_ids var books2 = db.tbl_books.where(b=>subject_ids.contains(b.subject_id)).ToList(); ``` Is there a way to combine both the queries into one query? I know I can do this: ``` db.tbl_books.where(b=> book_ids.contains(b.id)).Union(db.tbl_books.where(b=>subject_ids.contains(b.subject_id))).ToList(); ``` P.S. I don't want to get all the rows from tbl\_books at the start Could you please suggest a solution to this problem. Thank you.<issue_comment>username_1: You can use `||` in place of `Union`: ``` db.tbl_books .Where(b => book_ids.contains(b.id) || subject_ids.contains(b.subject_id))) .ToList(); ``` Upvotes: 1 <issue_comment>username_2: Try this : ``` var selectedBooks = db.tbl_books.where(b=> book_ids.contains(b.id) || subject_ids.contains(b.subject_id)).ToList(); ``` Upvotes: 0 <issue_comment>username_3: Try this: ``` var query = (from a in db.tbl_books where a.book_ids == b_id && a.subject_ids == sub_id select new{ a.[column_name], a.[column_name], a.[column_name], //columns you want to retrieve }).ToList(); ``` or ``` var query = (from a in db.tbl_books where a.book_ids == b_id || a.subject_ids == sub_id select new{ a.[column_name], a.[column_name], a.[column_name], //columns you want to retrieve }).ToList(); ``` Depends on what you're trying to accomplish. Hope it helps you. Upvotes: 0
2018/03/15
886
2,766
<issue_start>username_0: The `count()` function returns the number of times a substring occurs in a string, but it fails in case of overlapping strings. Let's say my input is: ``` ^_^_^-_- ``` I want to find how many times `^_^` occurs in the string. ``` mystr=input() happy=mystr.count('^_^') sad=mystr.count('-_-') print(happy) print(sad) ``` Output is: ``` 1 1 ``` I am expecting: ``` 2 1 ``` How can I achieve the desired result?<issue_comment>username_1: **New Version** You can solve this problem without writing any explicit loops using regex. As [@abhijith-pk's answer](https://stackoverflow.com/a/49293593/2988730) cleverly suggests, you can search for the first character only, with the remainder being placed in a positive lookahead, which will allow you to make the match with overlaps: ``` def count_overlapping(string, pattern): regex = '{}(?={})'.format(re.escape(pattern[:1]), re.escape(pattern[1:])) # Consume iterator, get count with minimal memory usage return sum(1 for _ in re.finditer(regex, string)) ``` [[IDEOne Link]](https://ideone.com/vLih7t) Using `[:1]` and `[1:]` for the indices allows the function to handle the empty string without special processing, while using `[0]` and `[1:]` for the indices would not. **Old Version** You can always write your own routine using the fact that [`str.find`](https://docs.python.org/3/library/stdtypes.html#str.find) allows you to specify a starting index. This routine will not be very efficient, but it should work: ``` def count_overlapping(string, pattern): count = 0 start = -1 while True: start = string.find(pattern, start + 1) if start < 0: return count count += 1 ``` [[IDEOne Link]](https://ideone.com/dWTdSw) **Usage** Both versions return identical results. A sample usage would be: ``` >>> mystr = '^_^_^-_-' >>> count_overlapping(mystr, '^_^') 2 >>> count_overlapping(mystr, '-_-') 1 >>> count_overlapping(mystr, '') 9 >>> count_overlapping(mystr, 'x') 0 ``` Notice that the empty string is found `len(mystr) + 1` times. I consider this to be intuitively correct because it is effectively between and around every character. Upvotes: 3 [selected_answer]<issue_comment>username_2: You need something like this ``` def count_substr(string,substr): n=len(substr) count=0 for i in range(len(string)-len(substr)+1): if(string[i:i+len(substr)] == substr): count+=1 return count mystr=input() print(count_substr(mystr,'121')) ``` > > Input: 12121990 > > > Output: 2 > > > Upvotes: 1 <issue_comment>username_3: you can use regex for a quick and dirty solution : ``` import re mystr='^_^_^-_-' print(len(re.findall('\^(?=_\^)',mystr))) ``` Upvotes: 2
2018/03/15
415
1,399
<issue_start>username_0: I have tried the following code: ``` php echo gettype($x); ? ``` And I got the following output: [![enter image description here](https://i.stack.imgur.com/uCBTt.png)](https://i.stack.imgur.com/uCBTt.png) Why did `gettype()` outputted "NULL" after the error was displayed? I mean an undefined variable is a variable that doesn't exist and not a NULL variable, right?<issue_comment>username_1: You kinda did answer your own question. At the moment you're trying to get the type of nothing it will be null by default. For example X = 5 It will return a integer But in your case x wasn't initiated and therefore it stays null. Vars work on the run and can be anything. I hope this is somehow useful. (if this contains a misconception please let me know what is wrong) Upvotes: 0 <issue_comment>username_2: The [documentation of `NULL`](http://php.net/manual/en/language.types.null.php) explains: > > The special `NULL` value represents a variable with no value. `NULL` is the only possible value of type `null`. > > > A variable is considered to be `null` if: > > > * it has been assigned the constant `NULL`. > * it has not been set to any value yet. > * it has been [`unset()`](http://php.net/manual/en/function.unset.php). > > > Also check the table ["Comparisons of $x with PHP functions"](http://php.net/manual/en/types.comparisons.php). Upvotes: 1
2018/03/15
744
2,323
<issue_start>username_0: I am developing Xamarin forms app and my app seems with safe area set in top. But need to ignore it. **Current scenario:** [![enter image description here](https://i.stack.imgur.com/Al4PU.png)](https://i.stack.imgur.com/Al4PU.png) **Excepted scenario:** [![enter image description here](https://i.stack.imgur.com/XFGzf.png)](https://i.stack.imgur.com/XFGzf.png) I have googled regarding this and got below link, tried out as mentioned in below links and nothing worked. <https://forums.xamarin.com/discussion/104945/iphone-x-and-safe-margins-with-xamarin-forms> <https://blog.xamarin.com/making-ios-11-even-easier-xamarin-forms/> But didn’t know how to access **SetPrefersLargeTitles** under Xamarin forms content page in below line mentioned in above link. ``` On().SetPrefersLargeTitles(true); ``` After set safe area as true output come as below, [![enter image description here](https://i.stack.imgur.com/z4E7I.png)](https://i.stack.imgur.com/z4E7I.png) Please help me to resolve this. Regards, Cheran<issue_comment>username_1: You can do it from XAML like this ``` xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" ios:Page.UseSafeArea="true" ``` Upvotes: 3 <issue_comment>username_2: Go to top constraint and make second Item constraint superview.Top Upvotes: 0 <issue_comment>username_3: Please Refer to [Making iOS 11 Even Easier with Xamarin.Forms](https://blog.xamarin.com/making-ios-11-even-easier-xamarin-forms/) We use [Platform-Specifics](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/platform-specifics/) to implement it. ### Before iOS 11 ``` On().SetUseSafeArea(true); ``` ### iOS 11 or newer ``` var safeInsets = On().SafeAreaInsets(); safeInsets.Left = 24; this.Padding = safeInsets; ``` Upvotes: 2 <issue_comment>username_4: It's necessary to create or configure LaunchScreend.storyboard. Use this [code](https://github.com/Microsoft/TailwindTraders-Mobile/blob/ae084431a5f6fcd4d6d74a8095ddfa39c0b4d0cf/Source/TailwindTraders.Mobile/TailwindTraders.Mobile.iOS/Resources/LaunchScreen.storyboard), change **splash\_screen** for your image. Upvotes: 1 <issue_comment>username_5: ``` public ItemsPage() { InitializeComponent(); On ().SetUseSafeArea(true); } ``` Upvotes: 0
2018/03/15
755
2,113
<issue_start>username_0: I have a div that has class name `ordershape` and it contains another div `fad-res`. I want that when I would hover over a particular `ordershape`, I want to show the corressponding`fad-res` whose parent div I hovered, while other divs must be hidden. ``` 1 2 3 ```<issue_comment>username_1: Your HTML is invalid since you haven't closed the div with the class `ordershape` No reason to use jquery for this, CSS can easily achieve this: ``` .ordershape:hover .fad-res{ display:block; } ``` **Demo CSS** ```css .fad-res{ display:none; } .ordershape{ height:30px; width:30px; background-color:yellow; } .ordershape:hover .fad-res{ display:block; } ``` ```html 1 2 3 ``` If you want to do it with jquery do it like this. ``` $(".ordershape").mouseenter(function() { $(this).find(".fad-res").show(); }).mouseleave(function() { $(this).find(".fad-res").hide(); }); ``` **Demo jQuery** ```js $(".ordershape").mouseenter(function() { $(this).find(".fad-res").show(); }).mouseleave(function() { $(this).find(".fad-res").hide(); }); ``` ```css .fad-res{ display:none; } .ordershape{ height:30px; width:30px; background-color:yellow; } ``` ```html 1 2 3 ``` Upvotes: 1 <issue_comment>username_2: Do not use javascript for that - rely on the CSS `transition` and `opacity` properties instead, with `:hover` selector. ```css .fad-res { -webkit-transition: opacity .3s ease-in-out; transition: opacity .3s ease-in-out; opacity: 0; background: #555555; height: 60px; width: 100px; } .ordershape { background: #f6f6f6; height: 100px; width: 100px; float: left; margin-right: 2px; } .ordershape:hover .fad-res { opacity: 1; } ``` ```html 1 2 3 ``` Upvotes: 0 <issue_comment>username_3: Well, you can try the `jquery` version this way ```js $(".ordershape").hover(function(){ $(this).find(".fad-res").toggle(); }) ``` ```css .fad-res{ display : none; } .ordershape{ width : 20px; height: 20px } ``` ```html 1 2 3 ``` Upvotes: 0
2018/03/15
909
2,645
<issue_start>username_0: ``` import React from 'react'; class Blog extends Component { render(){ const sidebar = ( {this.props.posts.map((post) => * {post.title} )} ); const content = this.props.posts.map((post) => ### {post.title} {post.content} ); return ( {sidebar} --- {content} ); } } const posts = [ {id: 1, title: 'Hello World', content: 'Welcome to learning React!'}, {id: 2, title: 'Installation', content: 'You can install React from npm.'} ]; ReactDOM.render( , document.getElementById('root') ); ``` Please help me to get out from this error. I'm just a beginner to this. Actually this program written in function. I'm trying to change write under a class as part of my learning. But unfortunately I didn't got the output.Is it possible to add key in a class??<issue_comment>username_1: Your HTML is invalid since you haven't closed the div with the class `ordershape` No reason to use jquery for this, CSS can easily achieve this: ``` .ordershape:hover .fad-res{ display:block; } ``` **Demo CSS** ```css .fad-res{ display:none; } .ordershape{ height:30px; width:30px; background-color:yellow; } .ordershape:hover .fad-res{ display:block; } ``` ```html 1 2 3 ``` If you want to do it with jquery do it like this. ``` $(".ordershape").mouseenter(function() { $(this).find(".fad-res").show(); }).mouseleave(function() { $(this).find(".fad-res").hide(); }); ``` **Demo jQuery** ```js $(".ordershape").mouseenter(function() { $(this).find(".fad-res").show(); }).mouseleave(function() { $(this).find(".fad-res").hide(); }); ``` ```css .fad-res{ display:none; } .ordershape{ height:30px; width:30px; background-color:yellow; } ``` ```html 1 2 3 ``` Upvotes: 1 <issue_comment>username_2: Do not use javascript for that - rely on the CSS `transition` and `opacity` properties instead, with `:hover` selector. ```css .fad-res { -webkit-transition: opacity .3s ease-in-out; transition: opacity .3s ease-in-out; opacity: 0; background: #555555; height: 60px; width: 100px; } .ordershape { background: #f6f6f6; height: 100px; width: 100px; float: left; margin-right: 2px; } .ordershape:hover .fad-res { opacity: 1; } ``` ```html 1 2 3 ``` Upvotes: 0 <issue_comment>username_3: Well, you can try the `jquery` version this way ```js $(".ordershape").hover(function(){ $(this).find(".fad-res").toggle(); }) ``` ```css .fad-res{ display : none; } .ordershape{ width : 20px; height: 20px } ``` ```html 1 2 3 ``` Upvotes: 0