id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
72f1d01735b0da5e22092ef7a1ae365e4367b80b
Stackoverflow Stackexchange Q: Unresolved reference async/await in PyCharm Sometimes in PyCharm 2017.1.4 with python3.6 async/await statements show as unresolved, although there aren't any errors and in next tab async/await not underlined as an error. Restarting fix this issue. How to fix that? A: I just hit the same problem. It was because the project interpreter was set to python2.7, the await/async keys are new as of python3, and not backward compatible. preferences>project>project-interpreter is where I could select the correction version.
Q: Unresolved reference async/await in PyCharm Sometimes in PyCharm 2017.1.4 with python3.6 async/await statements show as unresolved, although there aren't any errors and in next tab async/await not underlined as an error. Restarting fix this issue. How to fix that? A: I just hit the same problem. It was because the project interpreter was set to python2.7, the await/async keys are new as of python3, and not backward compatible. preferences>project>project-interpreter is where I could select the correction version. A: I encountered the same issue since I erroneously used the 'await' outside of an async method (Interpreter set to Python 3.6). 'await' is only valid in an 'async' method using Python 3.6. Pycharm correctly produces the error, but the message 'await unresolved' is not specific. A: In PyCharm 2022.1.2 this still seems to happen. If you are not using await outside of async method, your interpreter is setup correctly, etc. and the code is working fine, you can just surpress the warning: # noinspection PyUnresolvedReferences await ...
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:896101", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44639625" }
7b964c0c140d69d486dfdbf434e773562b1d455a
Stackoverflow Stackexchange Q: Using conn on view to render url I'm using Phoenix 1.3.0-rc and I would like to print a url in my json return using user_path(...). My controller: ... def show(conn, %{"id" => id}) do user = User.find(id) render(conn, "show.json", user: user) end ... My view: ... def render("show.json", %{user: user}) do %{ data: render_one(user, __MODULE__, "user.json"), links: render_one(user, __MODULE__, "links.json") } end ... def render("links.json", %{user: user}) do %{ self: "/api/v1/users/#{user.id}" } end ... I would like to write this: self: user_path(conn, :show, user.id) But I get this error: undefined function conn/0 A: You have to pass conn through to the view. Note that Phoenix.Controller.render/3 is not the same as Phoenix.View.render/3. "The former expects a connection and relies on content negotiation while the latter is connection-agnostic and typically invoked from your views".1 In your controller: def show(conn, %{"id" => id}) do user = User.find(id) render(conn, "show.json", user: user, conn: conn) end And your view: def render("show.json", %{user: user, conn: conn}) do %{ data: render_one(user, __MODULE__, "user.json"), links: render_one(user, __MODULE__, "links.json", conn: conn) } end ... def render("links.json", %{user: user, conn: conn}) do %{ self: user_path(conn, :show, user.id) } end * *https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/controller.ex#L156
Q: Using conn on view to render url I'm using Phoenix 1.3.0-rc and I would like to print a url in my json return using user_path(...). My controller: ... def show(conn, %{"id" => id}) do user = User.find(id) render(conn, "show.json", user: user) end ... My view: ... def render("show.json", %{user: user}) do %{ data: render_one(user, __MODULE__, "user.json"), links: render_one(user, __MODULE__, "links.json") } end ... def render("links.json", %{user: user}) do %{ self: "/api/v1/users/#{user.id}" } end ... I would like to write this: self: user_path(conn, :show, user.id) But I get this error: undefined function conn/0 A: You have to pass conn through to the view. Note that Phoenix.Controller.render/3 is not the same as Phoenix.View.render/3. "The former expects a connection and relies on content negotiation while the latter is connection-agnostic and typically invoked from your views".1 In your controller: def show(conn, %{"id" => id}) do user = User.find(id) render(conn, "show.json", user: user, conn: conn) end And your view: def render("show.json", %{user: user, conn: conn}) do %{ data: render_one(user, __MODULE__, "user.json"), links: render_one(user, __MODULE__, "links.json", conn: conn) } end ... def render("links.json", %{user: user, conn: conn}) do %{ self: user_path(conn, :show, user.id) } end * *https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/controller.ex#L156 A: You can use your Endpoint with the same result, like: alias MyAwesomeApp.Web.Endpoint ... use_path(Endpoint, :show, user)
stackoverflow
{ "language": "en", "length": 209, "provenance": "stackexchange_0000F.jsonl.gz:896183", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44639875" }
4eabb154fac553c20fb56a96df0adc8d4e4cc60b
Stackoverflow Stackexchange Q: Overriding @Value in Integration Test For one of my Spring beans(say Application class), I'm fetching the value of a property(my.property.flag=true/false) from a properties file(prop.properties) using @Value annotation. That works perfectly fine. I need to write an integration test(say ApplicationIt class) where I need to test with both the values of the property i.e. for both true and false. In my properties file, the value of the property is set to true. Is it possible to set the value dynamically to false from my Integration test? For Example, prop.properties: my.property.flag=true Application class file: @Component class Application { //This value is fetched from properties file //the value is set to true. @Value(${my.property.flag}) private String isTrue; ...... .......... } Integration Test: class ApplicationIT { //how can I set the value of isTrue here to false? } A: I want to mention good old reflection way. You can use spring provided utility class for it after you wired in your component: ReflectionTestUtils.setField(component, "isTrue", true) You can change it to any value you want in consequent tests
Q: Overriding @Value in Integration Test For one of my Spring beans(say Application class), I'm fetching the value of a property(my.property.flag=true/false) from a properties file(prop.properties) using @Value annotation. That works perfectly fine. I need to write an integration test(say ApplicationIt class) where I need to test with both the values of the property i.e. for both true and false. In my properties file, the value of the property is set to true. Is it possible to set the value dynamically to false from my Integration test? For Example, prop.properties: my.property.flag=true Application class file: @Component class Application { //This value is fetched from properties file //the value is set to true. @Value(${my.property.flag}) private String isTrue; ...... .......... } Integration Test: class ApplicationIT { //how can I set the value of isTrue here to false? } A: I want to mention good old reflection way. You can use spring provided utility class for it after you wired in your component: ReflectionTestUtils.setField(component, "isTrue", true) You can change it to any value you want in consequent tests A: Preferably, use constructor injection instead of field injection: @Component class Application { Application(@Value("${my.property.flag}") boolean flag) { ... } } This makes using mocks or test values as simple as passing an argument. A: You can specify test properties on the test class as follows: @RunWith(SpringRunner.class) @TestPropertySource(properties = {"spring.main.banner-mode=off", "my.property.flag=false"}) public class MyTest { Since Spring has a whole hierarchy of property overrides, this works pretty well, the downside being you need separate test classes for different values. If you're using Spring Boot, there's another annotation that provides the same functionality but also has more options for configuring your test environment. Example: @SpringBootTest(properties = {"spring.main.banner-mode=off", "my.property.flag=false"}) Again, you will need separate test classes to handle hard-coded test properties. A: I was bugged with this for a while and found this neat way to override the properties. It is quite useful if you need some programmatic initialization of the application context such as registering property sources like in that case but not only. The following approach uses ContextConfiguration's initializers. example for Spring Boot 1.5.x : @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {"management.port=0"}) @ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class) @DirtiesContext public abstract class AbstractIntegrationTest { private static int REDIS_PORT = 6379; @ClassRule public static GenericContainer redis = new GenericContainer("redis:3.0.6").withExposedPorts(REDIS_PORT); public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext ctx) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(ctx, "spring.redis.host=" + redis.getContainerIpAddress(), "spring.redis.port=" + redis.getMappedPort(REDIS_PORT)); } } } example for Spring Boot 2.x : @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {"management.port=0"}) @ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class) @DirtiesContext public abstract class AbstractIntegrationTest { private static int REDIS_PORT = 6379; @ClassRule public static GenericContainer redis = new GenericContainer("redis:3.0.6").withExposedPorts(REDIS_PORT); public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext ctx) { TestPropertyValues.of( "spring.redis.host:" + redis.getContainerIpAddress(), "spring.redis.port:" + redis.getMappedPort(REDIS_PORT)) .applyTo(ctx); } } }
stackoverflow
{ "language": "en", "length": 460, "provenance": "stackexchange_0000F.jsonl.gz:896206", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44639941" }
9d16287c0e40f9388168c74c9f31f394ff4ea306
Stackoverflow Stackexchange Q: Run ASP.Net Core API on Ubuntu Server in background I have a self-contained ASP.Net Core Web API on my external Ubuntu server. I access the server through PuTTY using SSH from Windows 7. Now when I run it, I do it through the Shell window. It then tells me the API is running and gives me the according adress used communicate with it, which works just fine. It also says I can shut it down if I hit another key. Now as soon as I close the Shell window, the API shuts down, which I do not want. I want it to keep running 24/7! How do I start it in a way it keeps running in the background?
Q: Run ASP.Net Core API on Ubuntu Server in background I have a self-contained ASP.Net Core Web API on my external Ubuntu server. I access the server through PuTTY using SSH from Windows 7. Now when I run it, I do it through the Shell window. It then tells me the API is running and gives me the according adress used communicate with it, which works just fine. It also says I can shut it down if I hit another key. Now as soon as I close the Shell window, the API shuts down, which I do not want. I want it to keep running 24/7! How do I start it in a way it keeps running in the background?
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:896219", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44639973" }
b7da4d2e9acbc28f35ca258761a1fda27c5f4f78
Stackoverflow Stackexchange Q: UINavigationController is nil in swift 3 In my main storyboard I have 1 Navigation controller and subsequent swift file NavigationCtr.swift. The viewController is in different xib. Now I want to push my viewController from the NavigationCtr class. let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil) self.navigationController!.pushViewController(vcFirst, animated: true) I am getting a exception fatal error: unexpectedly found nil while unwrapping an Optional value So when I trying to print from viewDidLoad print(self.navigationController) in NavigationCtr.swift class it is giving nil. So nothing works I created a new project in objective C and it works fine. Attached the storyboard image Any hint in the direct direction is highly appreciated. Note : - I am new to swift A: the main issue was using the self.navigationController As my storyboard only had navigationController I should just self keyword. as below let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil) self.pushViewController(vcFirst, animated: true)
Q: UINavigationController is nil in swift 3 In my main storyboard I have 1 Navigation controller and subsequent swift file NavigationCtr.swift. The viewController is in different xib. Now I want to push my viewController from the NavigationCtr class. let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil) self.navigationController!.pushViewController(vcFirst, animated: true) I am getting a exception fatal error: unexpectedly found nil while unwrapping an Optional value So when I trying to print from viewDidLoad print(self.navigationController) in NavigationCtr.swift class it is giving nil. So nothing works I created a new project in objective C and it works fine. Attached the storyboard image Any hint in the direct direction is highly appreciated. Note : - I am new to swift A: the main issue was using the self.navigationController As my storyboard only had navigationController I should just self keyword. as below let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil) self.pushViewController(vcFirst, animated: true) A: For the first controller, set it as rootController instead of push (show). self.navigationController = UINavigationController(rootViewController: vcFirst) Or set its view controllers self.navigationController = UINavigationController() navigationController.setViewControllers([vcfirst], animated: true)
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:896242", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640047" }
4d65e2568bb36895abdfb1b75c8e9c1ea4ef7c9e
Stackoverflow Stackexchange Q: How to import PostgreSQL database dump via node and pg I'm trying to import a PostgreSQL database dump, saved as a plain text file, into psql using the pg package in node. so far I'm reading in the file as a string, then attempting to import the string via the following method: var sql = fs.readFileSync('./dbDumpOutput').toString(); pg.connect('postgres://localhost:5432/testdb', function(err, client, done){ if(err){ console.log('error: ', err); process.exit(1); } client.query(sql, function(err, result){ done(); if(err){ console.log('error: ', err); process.exit(1); } process.exit(0); }); I'm getting the following error: error: { error: syntax error at or near "\" Is this a formatting issue with my dbdump that I'll have to parse out, or am I doing something else incorrectly? A: I got a working solution which I've provided below, using psql instead of pg. const { spawn } = require('child_process'); const child = spawn('createdb', ['psqltest']); child.on('exit', function (code, signal) { console.log('child process exited with ' + `code ${code} and signal ${signal}`); const cat = spawn('cat',['dbDumpOutput']); const imp = spawn('psql',['psqltest']); cat.stdout.pipe(imp.stdin); });
Q: How to import PostgreSQL database dump via node and pg I'm trying to import a PostgreSQL database dump, saved as a plain text file, into psql using the pg package in node. so far I'm reading in the file as a string, then attempting to import the string via the following method: var sql = fs.readFileSync('./dbDumpOutput').toString(); pg.connect('postgres://localhost:5432/testdb', function(err, client, done){ if(err){ console.log('error: ', err); process.exit(1); } client.query(sql, function(err, result){ done(); if(err){ console.log('error: ', err); process.exit(1); } process.exit(0); }); I'm getting the following error: error: { error: syntax error at or near "\" Is this a formatting issue with my dbdump that I'll have to parse out, or am I doing something else incorrectly? A: I got a working solution which I've provided below, using psql instead of pg. const { spawn } = require('child_process'); const child = spawn('createdb', ['psqltest']); child.on('exit', function (code, signal) { console.log('child process exited with ' + `code ${code} and signal ${signal}`); const cat = spawn('cat',['dbDumpOutput']); const imp = spawn('psql',['psqltest']); cat.stdout.pipe(imp.stdin); }); A: this is because plain text pg_dump uses COPY FROM STDIN, which ends up with \.. I think you can't use this COPY FROM STDIN brianc's pg module (otherwise there would be no need in this). you can try specifying --inserts on pg_dump to generate inserts instead. But I would recommend just using tools meant for pg_dump generated dump to restore, like psql
stackoverflow
{ "language": "en", "length": 229, "provenance": "stackexchange_0000F.jsonl.gz:896265", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640114" }
acb2885500ae286924de028a30d783f94c39864c
Stackoverflow Stackexchange Q: Can Airflow run streaming GCP Dataflow jobs? I am looking for orchestration software for streaming GCP Dataflow jobs - something that can provide alerting, status, job launching etc. akin to what this does on Kubernetes. The answer here suggests Airflow as they have some hooks into GCP - this would be nice because we have some other infrastructure that runs on Airflow. However I am not sure if this would be able to handle streaming jobs - my understanding is that Airflow is designed for tasks that will complete, which is not the case for a streaming job. Is Airflow appropriate for this? Or is there different software I should use? A: Its probably late, but answering for people who visit this topic in future. Yes you can definitely run dataflow streaming job from airflow. Use airflow version 1.9 or above. Link : https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/hooks/gcp_dataflow_hook.py https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/operators/dataflow_operator.py You dont need to put extra efforts for running streamin job. Above Dataflow operators run both batch and streaming jobs. It mark the airflow task successful as soon as dataflow streaming job start running (i.e. job is in running state)
Q: Can Airflow run streaming GCP Dataflow jobs? I am looking for orchestration software for streaming GCP Dataflow jobs - something that can provide alerting, status, job launching etc. akin to what this does on Kubernetes. The answer here suggests Airflow as they have some hooks into GCP - this would be nice because we have some other infrastructure that runs on Airflow. However I am not sure if this would be able to handle streaming jobs - my understanding is that Airflow is designed for tasks that will complete, which is not the case for a streaming job. Is Airflow appropriate for this? Or is there different software I should use? A: Its probably late, but answering for people who visit this topic in future. Yes you can definitely run dataflow streaming job from airflow. Use airflow version 1.9 or above. Link : https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/hooks/gcp_dataflow_hook.py https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/operators/dataflow_operator.py You dont need to put extra efforts for running streamin job. Above Dataflow operators run both batch and streaming jobs. It mark the airflow task successful as soon as dataflow streaming job start running (i.e. job is in running state)
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:896267", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640117" }
69932d0d998997c2f485a9df99f566dea6e04a3d
Stackoverflow Stackexchange Q: How to write Union All query in Query DSL Need to implement sql query like: SELECT A.class, A.section FROM STUDENT A INNER JOIN DEPARTMENT on A.student_id = B.id WHERE DEPT_NBR is not null UNION ALL SELECT A.class, A.section FROM TEACHER A INNER JOIN DEPARTMENT on A.teacher_id = B.id WHERE DEPT_NBR is not null How can I write such statement with QueryDSL ? ( I am not using any JPA). Any help/hint is much appreciated! A: so that others won't search for that too much... JPA doesn't support unions, hence querydsl when running on top of JPA doesn't support unions. It does support them when running on top of raw SQL though, see natros's answer for that.
Q: How to write Union All query in Query DSL Need to implement sql query like: SELECT A.class, A.section FROM STUDENT A INNER JOIN DEPARTMENT on A.student_id = B.id WHERE DEPT_NBR is not null UNION ALL SELECT A.class, A.section FROM TEACHER A INNER JOIN DEPARTMENT on A.teacher_id = B.id WHERE DEPT_NBR is not null How can I write such statement with QueryDSL ? ( I am not using any JPA). Any help/hint is much appreciated! A: so that others won't search for that too much... JPA doesn't support unions, hence querydsl when running on top of JPA doesn't support unions. It does support them when running on top of raw SQL though, see natros's answer for that. A: There are many examples that can help you. public void union_multiple_columns() throws SQLException { SubQueryExpression<Tuple> sq1 = query().from(employee).select(employee.firstname, employee.lastname); SubQueryExpression<Tuple> sq2 = query().from(employee).select(employee.lastname, employee.firstname); List<Tuple> list = query().union(sq1, sq2).fetch(); assertFalse(list.isEmpty()); for (Tuple row : list) { assertNotNull(row.get(0, Object.class)); assertNotNull(row.get(1, Object.class)); } } This example was taken from the project itself: https://github.com/querydsl/querydsl/blob/8f96f416270d0353f90a6551547906f3c217833a/querydsl-sql/src/test/java/com/querydsl/sql/UnionBase.java#L73
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:896270", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640128" }
ce8be7a23bf54fee76d98c5e04019ed97245eafc
Stackoverflow Stackexchange Q: accumulator in pyspark with dict as global variable Just for learning purpose, I tried to set a dictionary as a global variable in accumulator the add function works well, but I ran the code and put dictionary in the map function, it always return empty. But similar code for setting list as a global variable class DictParam(AccumulatorParam): def zero(self, value = ""): return dict() def addInPlace(self, acc1, acc2): acc1.update(acc2) if __name__== "__main__": sc, sqlContext = init_spark("generate_score_summary", 40) rdd = sc.textFile('input') #print(rdd.take(5)) dict1 = sc.accumulator({}, DictParam()) def file_read(line): global dict1 ls = re.split(',', line) dict1+={ls[0]:ls[1]} return line rdd = rdd.map(lambda x: file_read(x)).cache() print(dict1) A: For anyone who arrives at this thread looking for a Dict accumulator for pyspark: the accepted solution does not solve the posed problem. The issue is actually in the DictParam defined, it does not update the original dictionary. This works: class DictParam(AccumulatorParam): def zero(self, value = ""): return dict() def addInPlace(self, value1, value2): value1.update(value2) return value1 The original code was missing the return value.
Q: accumulator in pyspark with dict as global variable Just for learning purpose, I tried to set a dictionary as a global variable in accumulator the add function works well, but I ran the code and put dictionary in the map function, it always return empty. But similar code for setting list as a global variable class DictParam(AccumulatorParam): def zero(self, value = ""): return dict() def addInPlace(self, acc1, acc2): acc1.update(acc2) if __name__== "__main__": sc, sqlContext = init_spark("generate_score_summary", 40) rdd = sc.textFile('input') #print(rdd.take(5)) dict1 = sc.accumulator({}, DictParam()) def file_read(line): global dict1 ls = re.split(',', line) dict1+={ls[0]:ls[1]} return line rdd = rdd.map(lambda x: file_read(x)).cache() print(dict1) A: For anyone who arrives at this thread looking for a Dict accumulator for pyspark: the accepted solution does not solve the posed problem. The issue is actually in the DictParam defined, it does not update the original dictionary. This works: class DictParam(AccumulatorParam): def zero(self, value = ""): return dict() def addInPlace(self, value1, value2): value1.update(value2) return value1 The original code was missing the return value. A: For accumulator updates performed inside actions only, their value is only updated once that RDD is computed as part of an action A: I believe that print(dict1()) simply gets executed before the rdd.map() does. In Spark, there are 2 types of operations: * *transformations, that describe the future computation *and actions, that call for action, and actually trigger the execution Accumulators are updated only when some action is executed: Accumulators do not change the lazy evaluation model of Spark. If they are being updated within an operation on an RDD, their value is only updated once that RDD is computed as part of an action. If you check out the end of this section of the docs, there is an example exactly like yours: accum = sc.accumulator(0) def g(x): accum.add(x) return f(x) data.map(g) # Here, accum is still 0 because no actions have caused the `map` to be computed. So you would need to add some action, for instance: rdd = rdd.map(lambda x: file_read(x)).cache() # transformation foo = rdd.count() # action print(dict1) Please make sure to check on the details of various RDD functions and accumulator peculiarities because this might affect the correctness of your result. (For instance, rdd.take(n) will by default only scan one partition, not the entire dataset.)
stackoverflow
{ "language": "en", "length": 379, "provenance": "stackexchange_0000F.jsonl.gz:896290", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640184" }
b3f5bd0582c6247a6bd5d2141c2007ecd606c04c
Stackoverflow Stackexchange Q: How to provide a Jacobian to SciPy curve_fit I want to fit a sigmoidal curve to some data. Since SageMath's included find_fit function failed, I'm trying to use scipy.optimize.curve_fit directly. It's not doing a very good job and the outcome is extremely sensitive to the initial guess, often getting stuck on it, so I'm trying to provide a Jacobian in the hope that this will help. What form does the Jacobian function need to take? Right now, my code is the following: #Compute the Jacobian (using SageMath) c=8 x4Sigmoid(x) = c*x^n/(h+x^n) sigjac = jacobian(x4Sigmoid, [n,h]) from scipy.optimize import curve_fit from numpy import inf, power #Define sigmoid function as Python function def sigmoid(x, n, h): return 8*power(x,n)/(h+power(x,n)) def jacfun(x, *args): h,n = args[0] return sigjac(x,h=h,n=n) #Separate x and y values of data x4xData = [val[0] for val in x4ciscoperchRelAbundanceData] x4yData = [val[1] for val in x4ciscoperchRelAbundanceData] #Do the fitting popt, pcov = curve_fit(sigmoid, x4xData, x4yData, p0=[3,4], bounds = ([1, 0], [inf, inf]), jac=jacfun) show(popt) This produces the error message ValueError: too many values to unpack. How do I give SciPy a Jacobian it can use? Or should I try something else?
Q: How to provide a Jacobian to SciPy curve_fit I want to fit a sigmoidal curve to some data. Since SageMath's included find_fit function failed, I'm trying to use scipy.optimize.curve_fit directly. It's not doing a very good job and the outcome is extremely sensitive to the initial guess, often getting stuck on it, so I'm trying to provide a Jacobian in the hope that this will help. What form does the Jacobian function need to take? Right now, my code is the following: #Compute the Jacobian (using SageMath) c=8 x4Sigmoid(x) = c*x^n/(h+x^n) sigjac = jacobian(x4Sigmoid, [n,h]) from scipy.optimize import curve_fit from numpy import inf, power #Define sigmoid function as Python function def sigmoid(x, n, h): return 8*power(x,n)/(h+power(x,n)) def jacfun(x, *args): h,n = args[0] return sigjac(x,h=h,n=n) #Separate x and y values of data x4xData = [val[0] for val in x4ciscoperchRelAbundanceData] x4yData = [val[1] for val in x4ciscoperchRelAbundanceData] #Do the fitting popt, pcov = curve_fit(sigmoid, x4xData, x4yData, p0=[3,4], bounds = ([1, 0], [inf, inf]), jac=jacfun) show(popt) This produces the error message ValueError: too many values to unpack. How do I give SciPy a Jacobian it can use? Or should I try something else?
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:896377", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640431" }
a5fdb3746c0d556175edfd34922138cc4f1e81ed
Stackoverflow Stackexchange Q: Type annotation for classmethod returning instance How should I annotate a @classmethod that returns an instance of cls? Here's a bad example: class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> ???: return cls(bar + "stuff") This returns a Foo but more accurately returns whichever subclass of Foo this is called on, so annotating with -> "Foo" wouldn't be good enough. A: Just for completeness, in Python 3.7 you can use the postponed evaluation of annotations as defined in PEP 563 by importing from __future__ import annotations at the beginning of the file. Then for your code it'd look like from __future__ import annotations class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> Foo: return cls(bar + "stuff") As per the docs, this import will effectively be automatic starting with Python 3.11.
Q: Type annotation for classmethod returning instance How should I annotate a @classmethod that returns an instance of cls? Here's a bad example: class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> ???: return cls(bar + "stuff") This returns a Foo but more accurately returns whichever subclass of Foo this is called on, so annotating with -> "Foo" wouldn't be good enough. A: Just for completeness, in Python 3.7 you can use the postponed evaluation of annotations as defined in PEP 563 by importing from __future__ import annotations at the beginning of the file. Then for your code it'd look like from __future__ import annotations class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> Foo: return cls(bar + "stuff") As per the docs, this import will effectively be automatic starting with Python 3.11. A: The trick is to explicitly add an annotation to the cls parameter, in combination with TypeVar, for generics, and Type, to represent a class rather than the instance itself, like so: from typing import TypeVar, Type # Create a generic variable that can be 'Parent', or any subclass. T = TypeVar('T', bound='Parent') class Parent: def __init__(self, bar: str) -> None: self.bar = bar @classmethod def with_stuff_appended(cls: Type[T], bar: str) -> T: # We annotate 'cls' with a typevar so that we can # type our return type more precisely return cls(bar + "stuff") class Child(Parent): # If you're going to redefine __init__, make sure it # has a signature that's compatible with the Parent's __init__, # since mypy currently doesn't check for that. def child_only(self) -> int: return 3 # Mypy correctly infers that p is of type 'Parent', # and c is of type 'Child'. p = Parent.with_stuff_appended("10") c = Child.with_stuff_appended("20") # We can verify this ourself by using the special 'reveal_type' # function. Be sure to delete these lines before running your # code -- this function is something only mypy understands # (it's meant to help with debugging your types). reveal_type(p) # Revealed type is 'test.Parent*' reveal_type(c) # Revealed type is 'test.Child*' # So, these all typecheck print(p.bar) print(c.bar) print(c.child_only()) Normally, you can leave cls (and self) unannotated, but if you need to refer to the specific subclass, you can add an explicit annotation. Note that this feature is still experimental and may be buggy in some cases. You may also need to use the latest version of mypy cloned from Github, rather then what's available on pypi -- I don't remember if that version supports this feature for classmethods.
stackoverflow
{ "language": "en", "length": 429, "provenance": "stackexchange_0000F.jsonl.gz:896390", "question_score": "88", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640479" }
b6354d51d01ab4fa83e8ff8f8a33d056d297b1a7
Stackoverflow Stackexchange Q: viewChild inside a form does not trigger it from pristine Here's the situation: parent.component.html <form #someForm > <input type="text" name="title" [(ngModel)]="parentVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> child.component.html <div> <input type="number" name="foo" [(ngModel)]="childVar" /> </div> When I change value of 'title' input the submit button gets enabled, but when change the value of 'foo' input nothing happens. How can I render the form dirty from the child component? A: By default, any nested component is not part of the ngForm data structure that Angular creates to track for state. You need to pass the form (via #someForm) into each of the child components. There is an example here: angular2 - validating FormControlName in child component of parent FormGroup
Q: viewChild inside a form does not trigger it from pristine Here's the situation: parent.component.html <form #someForm > <input type="text" name="title" [(ngModel)]="parentVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> child.component.html <div> <input type="number" name="foo" [(ngModel)]="childVar" /> </div> When I change value of 'title' input the submit button gets enabled, but when change the value of 'foo' input nothing happens. How can I render the form dirty from the child component? A: By default, any nested component is not part of the ngForm data structure that Angular creates to track for state. You need to pass the form (via #someForm) into each of the child components. There is an example here: angular2 - validating FormControlName in child component of parent FormGroup A: You can simply create an Event that Emits when the form in the child component got changed. Use the EventEmitter inside ur child component!
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:896420", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640558" }
5654365d33153d14bacc16d2738f55a0f37a4e34
Stackoverflow Stackexchange Q: What is the output of tf.split? So assuming I have this: TensorShape([Dimension(None), Dimension(32)]) And I use tf.split on this tensor _X with the dimension above: _X = tf.split(_X, 128, 0) What is the shape of this new tensor? The output is a list so its hard to know the shape of this new tensor. A: tf.split(X, row = n, column = m) is used to split the data set of the variable into n number of pieces row wise and m numbers of pieces column wise. For example, we have data_set x of size (10,10), then tf.split(x, 2, 0) will break the data_set of x in 2 set of size (5, 10) but if we take tf.split(x, 2, 2), then we will get 4 sets of data of size (5, 5).
Q: What is the output of tf.split? So assuming I have this: TensorShape([Dimension(None), Dimension(32)]) And I use tf.split on this tensor _X with the dimension above: _X = tf.split(_X, 128, 0) What is the shape of this new tensor? The output is a list so its hard to know the shape of this new tensor. A: tf.split(X, row = n, column = m) is used to split the data set of the variable into n number of pieces row wise and m numbers of pieces column wise. For example, we have data_set x of size (10,10), then tf.split(x, 2, 0) will break the data_set of x in 2 set of size (5, 10) but if we take tf.split(x, 2, 2), then we will get 4 sets of data of size (5, 5). A: tf.split() returns the list of tensor objects. You could know shape of each tensor object as follows import tensorflow as tf X = tf.random_uniform([256, 32]); Y = tf.split(X,128,0) Y_shape = tf.shape(Y[1]) sess = tf.Session() X_v,Y_v,Y_shape_v = sess.run([X,Y,Y_shape]) # numpy style print X_v.shape print len(Y_v) print Y_v[100].shape # TF style print len(Y) print Y_shape_v Output : (256, 32) 128 (2, 32) 128 [ 2 32] I hope this helps ! A: The new version of tensorflow defines split function as follows: tf.split( value, num_or_size_splits, axis=0, num=None, name='split' ) however, when I try to run it in R: X = tf$random_uniform(minval=0, maxval=10,shape(256, 32),name = "X"); Y = tf$split(X,num_or_size_splits = 2,axis = 0) it reports error message: Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: Rank-0 tensors are not supported as the num_or_size_splits argument to split. Argument provided: 2.0
stackoverflow
{ "language": "en", "length": 268, "provenance": "stackexchange_0000F.jsonl.gz:896444", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640613" }
b7b86631739bf3704d6fb6c6a9be8a52c27de452
Stackoverflow Stackexchange Q: How to run Angular app on xampp server? I'm working with Angular 2 with php. Before I started PHP with Angular 2. I have done Angular 2 with node.js on server localhost:3000. Now with PHP, how I can configure my Angular 2 app with xampp server so my server code is running on localhost:8080. Please help me on this. A: You can host it on any server by first building the angular project using the command line: ng build --base-href "/football/" --prod This base href will mean that it expects the final server to be something like: localhost:8080/football/. You want to get everything that is made in the dist folder and paste it into your server inside a folder called football.
Q: How to run Angular app on xampp server? I'm working with Angular 2 with php. Before I started PHP with Angular 2. I have done Angular 2 with node.js on server localhost:3000. Now with PHP, how I can configure my Angular 2 app with xampp server so my server code is running on localhost:8080. Please help me on this. A: You can host it on any server by first building the angular project using the command line: ng build --base-href "/football/" --prod This base href will mean that it expects the final server to be something like: localhost:8080/football/. You want to get everything that is made in the dist folder and paste it into your server inside a folder called football. A: Here is my answer. You can write Angular2 app just using Angular2 packages without using node or mamp or xampp and host that app. Ref According to the above reference I created my app using angular 2 - cli after that I made a little change in my root directory index.html file which is: <base href="/"> into <base href="./"> and build my app using: ng build --prod copy dist folder and paste it in my xampp htdocs folder and access the site using: localhost:8080/dist/ output App works A: I think that you are looking something similar to: angular-cli server - how to proxy API requests to another server? Just run your angular 2 application using the CLI, and add the proxy to use the services that are in xampp.
stackoverflow
{ "language": "en", "length": 252, "provenance": "stackexchange_0000F.jsonl.gz:896461", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640670" }
3d4853a361345f59a753b37ecdad66bfc67e10ef
Stackoverflow Stackexchange Q: Ionic - build/run for browser I have a ionic app (current version) that I have built and its now running on my local dev server just fine. I needed to add Strip Payment integration so I included the cordova-stripe-plugin (https://github.com/zyra/cordova-plugin-stripe#module_stripe). I can not test because ionic serve doesn't include the cordova.js, etc. I have looked high and low and can not find any definitive information or guide on how to run/build this app for mobile browser/web/PWA. There is conflicting information. Can you please clarify and provide the command lines to run to build/run and Ionic app that I can deploy to my webserver. Also, what about testing? will I have to rebuild every time I need to make a change or is there a some sort of live reload I can use? Thanks for your help. A: Build for Browser ionic cordova platform add browser ionic cordova build browser --prod For testing on browser just use ionic serve, every time you update code, it will auto rebuild.
Q: Ionic - build/run for browser I have a ionic app (current version) that I have built and its now running on my local dev server just fine. I needed to add Strip Payment integration so I included the cordova-stripe-plugin (https://github.com/zyra/cordova-plugin-stripe#module_stripe). I can not test because ionic serve doesn't include the cordova.js, etc. I have looked high and low and can not find any definitive information or guide on how to run/build this app for mobile browser/web/PWA. There is conflicting information. Can you please clarify and provide the command lines to run to build/run and Ionic app that I can deploy to my webserver. Also, what about testing? will I have to rebuild every time I need to make a change or is there a some sort of live reload I can use? Thanks for your help. A: Build for Browser ionic cordova platform add browser ionic cordova build browser --prod For testing on browser just use ionic serve, every time you update code, it will auto rebuild. A: To build app, ionic cordova build browser To run app, ionic cordova run browser Before run/build run this command on your terminal. npm serve If you are working with a git repository please make sure to get pulls before you start coding and before you commit your code.
stackoverflow
{ "language": "en", "length": 217, "provenance": "stackexchange_0000F.jsonl.gz:896506", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640802" }
7bf7798f5ea44af977c9b5c1d445f950e872a3c2
Stackoverflow Stackexchange Q: search multiple ids in multiple types in elasticsearch I want to fetch documents with ids in specific type. For example right now I have wrote this query in Sense. This query is returning me all the documents with these ids in type product. POST /_search { "query": { "ids" :{ "type" : "product", "values" : ["100005","10002010093"] } } } But what I want here is something like this POST /_search { "query": [ { "ids" :{ "type" : "product", "values" : ["100005","10002010093"] } }, { "ids" :{ "type" : "store", "values" : ["100003","1000201"] } } ] } or POST /_search { "query":{ "ids" :[ { "type" : "product", "values" : ["100005","10002010093"] }, { "type" : "store", "values" : ["100003","1000201"] } ] } } Is there any way to get it done? A: You simply need to use the bool/filter query: POST /_search { "query": { "bool": { "should": [ { "ids": { "type": "product", "values": [ "100005", "10002010093" ] } }, { "ids": { "type": "store", "values": [ "100003", "1000201" ] } } ] } } }
Q: search multiple ids in multiple types in elasticsearch I want to fetch documents with ids in specific type. For example right now I have wrote this query in Sense. This query is returning me all the documents with these ids in type product. POST /_search { "query": { "ids" :{ "type" : "product", "values" : ["100005","10002010093"] } } } But what I want here is something like this POST /_search { "query": [ { "ids" :{ "type" : "product", "values" : ["100005","10002010093"] } }, { "ids" :{ "type" : "store", "values" : ["100003","1000201"] } } ] } or POST /_search { "query":{ "ids" :[ { "type" : "product", "values" : ["100005","10002010093"] }, { "type" : "store", "values" : ["100003","1000201"] } ] } } Is there any way to get it done? A: You simply need to use the bool/filter query: POST /_search { "query": { "bool": { "should": [ { "ids": { "type": "product", "values": [ "100005", "10002010093" ] } }, { "ids": { "type": "store", "values": [ "100003", "1000201" ] } } ] } } }
stackoverflow
{ "language": "en", "length": 178, "provenance": "stackexchange_0000F.jsonl.gz:896518", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640837" }
dbc4be8d0d685af0ae32221ee24da81df140f1d5
Stackoverflow Stackexchange Q: How can I use Realm with Swift 4? I'm trying to run my current project in the new Xcode 9 beta, but when I do so it says Module compiled with Swift 3.1 cannot be imported in Swift 4.0. How can I solve this problem? I'm not using cocoapods. A: As a followup to bdash's item 3 about how to build Realm manually from source, and to answer addzo's question about the xcodebuild error (that I ran into as well): Be sure that the iPhone 6 simulator is set up for your Xcode 9 to avoid that error. I suppose Realm's build scripts must target it. This solved it for me, anyhow.
Q: How can I use Realm with Swift 4? I'm trying to run my current project in the new Xcode 9 beta, but when I do so it says Module compiled with Swift 3.1 cannot be imported in Swift 4.0. How can I solve this problem? I'm not using cocoapods. A: As a followup to bdash's item 3 about how to build Realm manually from source, and to answer addzo's question about the xcodebuild error (that I ran into as well): Be sure that the iPhone 6 simulator is set up for your Xcode 9 to avoid that error. I suppose Realm's build scripts must target it. This solved it for me, anyhow. A: Update: As of v2.10.1, released 2017-09-14, Realm's prebuilt binaries include frameworks built with Xcode 9 for Swift 3.2 and 4.0. It's no longer necessary to build them yourself. The information below remains relevant to anyone looking to use Realm with prerelease versions of Xcode in the future. If you're currently integrating Realm's prebuilt binaries, you'll need to switch to building Realm from source in order to support Swift 3.2 and 4.0, as Realm does not publish prebuilt binaries for prerelease versions of Xcode. You can build Realm from source in one of three ways: * *Using CocoaPods. CocoaPods always builds dependencies from source. *Using Carthage. By default Carthage will attempt to download prebuilt binaries, but will fall back to building from source if the prebuilt binaries are for a different Swift version than the version of Xcode in use. *Build Realm manually from source, and then integrate the built frameworks as you would the prebuilt binaries that Realm provides. You can do this by checking out a release tag from Git: git clone --recursive https://github.com/realm/realm-cocoa.git cd realm-cocoa git checkout v2.10.0 Then run whichever of the following commands corresponds to the platform you care about to build the Realm Swift framework for that platform: REALM_SWIFT_VERSION=4.0 sh build.sh ios-swift REALM_SWIFT_VERSION=4.0 sh build.sh osx-swift REALM_SWIFT_VERSION=4.0 sh build.sh watchos-swift REALM_SWIFT_VERSION=4.0 sh build.sh tvos-swift The built frameworks will be placed in the build directory within the Realm source, where you can then integrate them as you did the prebuilt binaries that Realm provides. These built frameworks should also work with apps using Swift 3.2 due to it using the same compiler as Swift 4.0.
stackoverflow
{ "language": "en", "length": 383, "provenance": "stackexchange_0000F.jsonl.gz:896524", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640852" }
ded7eeef7f9133e17ffb718dc9b017afc64338b5
Stackoverflow Stackexchange Q: Authenticate username/password against IDP using Spring Security SAML I'm aware of how SAML is used for single sign-on (SSO). That is redirection to IDP from SP and getting the user's identity from the SAML response/assertion. My question is: Can I use Spring Security SAML framework to define how to pass username and password as part of a SAML request XML for authentication? Note that I'm not talking about single sign on and just want authentication of username/password programmatically. I am receiving that username/password as part of a web service request (in the header) and the requirement is to validate that username/password against the IDP. Does IDP provide any API or mechanism for authenticating the username/password that I receive as part of web service request? Thanks in advance!
Q: Authenticate username/password against IDP using Spring Security SAML I'm aware of how SAML is used for single sign-on (SSO). That is redirection to IDP from SP and getting the user's identity from the SAML response/assertion. My question is: Can I use Spring Security SAML framework to define how to pass username and password as part of a SAML request XML for authentication? Note that I'm not talking about single sign on and just want authentication of username/password programmatically. I am receiving that username/password as part of a web service request (in the header) and the requirement is to validate that username/password against the IDP. Does IDP provide any API or mechanism for authenticating the username/password that I receive as part of web service request? Thanks in advance!
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:896537", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640889" }
d1d485f903c1f56982f5f92706c70c20abc9ac7a
Stackoverflow Stackexchange Q: AttributeError: module 'cv2.cv2' has no attribute 'cv' I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here: and i am facing following error. C:\Users\MAN\AppData\Local\Programs\Python\Python36\python.exe C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py Traceback (most recent call last): File "C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py", line 11, in font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) AttributeError: module 'cv2.cv2' has no attribute 'cv' Process finished with exit code 1 Is this the Windows issue or it shows only error in Python 3.6 version? for you kind information I am using Python 3.6 in Windows platform. A: font = cv2.cv.CV_FONT_HERSHEY_SIMPLEX I worked on different variable (CV_CAP_PROP_FRAME_WIDTH), and it took me soo long to understand that you also need to remove the "CV_".
Q: AttributeError: module 'cv2.cv2' has no attribute 'cv' I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here: and i am facing following error. C:\Users\MAN\AppData\Local\Programs\Python\Python36\python.exe C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py Traceback (most recent call last): File "C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py", line 11, in font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) AttributeError: module 'cv2.cv2' has no attribute 'cv' Process finished with exit code 1 Is this the Windows issue or it shows only error in Python 3.6 version? for you kind information I am using Python 3.6 in Windows platform. A: font = cv2.cv.CV_FONT_HERSHEY_SIMPLEX I worked on different variable (CV_CAP_PROP_FRAME_WIDTH), and it took me soo long to understand that you also need to remove the "CV_". A: in Opencv3 the cv module is deprecated. So, in line 11 you can initialize the font like following: font = cv2.FONT_HERSHEY_SIMPLEX A: Worked for me with font = cv2.FONT_HERSHEY_SIMPLEX as the best answer suggested.
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:896545", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44640911" }
6222e9c6e490eaa82bd89bf71cbe9e013991962d
Stackoverflow Stackexchange Q: How to mock $_SERVER variables for laravel tests? I'm using the shibboleth apache module for federated single sign-on. It sets the $_SERVER variable with a user's entitlements from active directory. In my laravel application, I use a custom authentication and user provider which leverages these entitlements for resource authorization. My simplified user model has something like this: public function isAdmin() { return Request::server('entitlement') === 'admin'; } However, I can't figure out how to test this because Request::server always returns nothing for that value. public function setUp() { $_SERVER['entitlement'] = 'admin'; parent::setUp(); } public function test_admin_something() { $user = factory(User::class)->create(); $response = $this ->actingAs($user) ->get('/admin/somewhere'); var_dump($_SERVER['entitlement']); // string(5) "admin" var_dump(Request::server('entitlement')); // NULL $response->assertStatus(200); // always fails 403 } I've also tried setUpBeforeClass and checked all of the other server variables which appear to be ignored during testing in lieu of a custom crafted Request object. I also cannot mock the Request façade, per the documentation. A: Digging into the source code reveals an undocumented method withServerVariables public function test_admin_something() { $user = factory(User::class)->create(); $response = $this ->withServerVariables(['entitlement' => 'admin']) ->actingAs($user) ->get('/admin/somewhere'); $response->assertStatus(200); }
Q: How to mock $_SERVER variables for laravel tests? I'm using the shibboleth apache module for federated single sign-on. It sets the $_SERVER variable with a user's entitlements from active directory. In my laravel application, I use a custom authentication and user provider which leverages these entitlements for resource authorization. My simplified user model has something like this: public function isAdmin() { return Request::server('entitlement') === 'admin'; } However, I can't figure out how to test this because Request::server always returns nothing for that value. public function setUp() { $_SERVER['entitlement'] = 'admin'; parent::setUp(); } public function test_admin_something() { $user = factory(User::class)->create(); $response = $this ->actingAs($user) ->get('/admin/somewhere'); var_dump($_SERVER['entitlement']); // string(5) "admin" var_dump(Request::server('entitlement')); // NULL $response->assertStatus(200); // always fails 403 } I've also tried setUpBeforeClass and checked all of the other server variables which appear to be ignored during testing in lieu of a custom crafted Request object. I also cannot mock the Request façade, per the documentation. A: Digging into the source code reveals an undocumented method withServerVariables public function test_admin_something() { $user = factory(User::class)->create(); $response = $this ->withServerVariables(['entitlement' => 'admin']) ->actingAs($user) ->get('/admin/somewhere'); $response->assertStatus(200); }
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:896587", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641045" }
4ac2def20bc310b4ff01040fa92a4b8e42febc9b
Stackoverflow Stackexchange Q: Execute Multiple Asynchronous Route Guards in Order I know angular route guards execute in the specified order when the canActivate function returns a simple boolean, however, what if the guards return type Observable<boolean> or Promise<boolean>? Example in route: { path: 'confirm', canActivate: [AuthGuard, SessionExpiredAuthGuard, CheckoutAuthGuard], component: CheckoutReviewOrderComponent }, SessionExpiredAuthGuard and CheckoutAuthGuard both return type Observable<boolean>. I don't want the CheckoutAuthGuard to be executed before the SessionExpiredAuthGuard is finished retrieving it's data from the asynchronous http request. Is there any way to force these asynchronous guards to execute in order? A: In addition to the answer planet_hunter, I dare to share a little improvement master-guard
Q: Execute Multiple Asynchronous Route Guards in Order I know angular route guards execute in the specified order when the canActivate function returns a simple boolean, however, what if the guards return type Observable<boolean> or Promise<boolean>? Example in route: { path: 'confirm', canActivate: [AuthGuard, SessionExpiredAuthGuard, CheckoutAuthGuard], component: CheckoutReviewOrderComponent }, SessionExpiredAuthGuard and CheckoutAuthGuard both return type Observable<boolean>. I don't want the CheckoutAuthGuard to be executed before the SessionExpiredAuthGuard is finished retrieving it's data from the asynchronous http request. Is there any way to force these asynchronous guards to execute in order? A: In addition to the answer planet_hunter, I dare to share a little improvement master-guard A: Problem First of all, angular doesn't support the feature to call the guards in tandem. So if first guard is asynchronous and is trying to make ajax calls, all the remaining guards will get fired even before completion of the ajax request in guard 1. I faced the similar problem and this is how I solved it - Solution The idea is to create a master guard and let the master guard handle the execution of other guards. The routing configuration in this case, will contain master guard as the only guard. To let master guard know about the guards to be triggered for specific routes, add a data property in Route. The data property is a key value pair that allows us to attach data with the routes. The data can then be accessed in the guards using ActivatedRouteSnapshot parameter of canActivate method in the guard. The solution looks complicated but it will assure proper working of guards once it is integrated in the application. Following example explains this approach - Example 1. Constants Object to map all application guards - export const GUARDS = { GUARD1: "GUARD1", GUARD2: "GUARD2", GUARD3: "GUARD3", GUARD4: "GUARD4", } 2. Application Guard - import { Injectable } from "@angular/core"; import { Guard4DependencyService } from "./guard4dependency"; @Injectable() export class Guard4 implements CanActivate { //A guard with dependency constructor(private _Guard4DependencyService: Guard4DependencyService) {} canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { return new Promise((resolve: Function, reject: Function) => { //logic of guard 4 here if (this._Guard4DependencyService.valid()) { resolve(true); } else { reject(false); } }); } } 3. Routing Configuration - import { Route } from "@angular/router"; import { View1Component } from "./view1"; import { View2Component } from "./view2"; import { MasterGuard, GUARDS } from "./master-guard"; export const routes: Route[] = [ { path: "view1", component: View1Component, //attach master guard here canActivate: [MasterGuard], //this is the data object which will be used by //masteer guard to execute guard1 and guard 2 data: { guards: [ GUARDS.GUARD1, GUARDS.GUARD2 ] } }, { path: "view2", component: View2Component, //attach master guard here canActivate: [MasterGuard], //this is the data object which will be used by //masteer guard to execute guard1, guard 2, guard 3 & guard 4 data: { guards: [ GUARDS.GUARD1, GUARDS.GUARD2, GUARDS.GUARD3, GUARDS.GUARD4 ] } } ]; 4. Master Guard - import { Injectable } from "@angular/core"; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router"; //import all the guards in the application import { Guard1 } from "./guard1"; import { Guard2 } from "./guard2"; import { Guard3 } from "./guard3"; import { Guard4 } from "./guard4"; import { Guard4DependencyService } from "./guard4dependency"; @Injectable() export class MasterGuard implements CanActivate { //you may need to include dependencies of individual guards if specified in guard constructor constructor(private _Guard4DependencyService: Guard4DependencyService) {} private route: ActivatedRouteSnapshot; private state: RouterStateSnapshot; //This method gets triggered when the route is hit public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { this.route = route; this.state = state; if (!route.data) { Promise.resolve(true); return; } //this.route.data.guards is an array of strings set in routing configuration if (!this.route.data.guards || !this.route.data.guards.length) { Promise.resolve(true); return; } return this.executeGuards(); } //Execute the guards sent in the route data private executeGuards(guardIndex: number = 0): Promise<boolean> { return this.activateGuard(this.route.data.guards[guardIndex]) .then(() => { if (guardIndex < this.route.data.guards.length - 1) { return this.executeGuards(guardIndex + 1); } else { return Promise.resolve(true); } }) .catch(() => { return Promise.reject(false); }); } //Create an instance of the guard and fire canActivate method returning a promise private activateGuard(guardKey: string): Promise<boolean> { let guard: Guard1 | Guard2 | Guard3 | Guard4; switch (guardKey) { case GUARDS.GUARD1: guard = new Guard1(); break; case GUARDS.GUARD2: guard = new Guard2(); break; case GUARDS.GUARD3: guard = new Guard3(); break; case GUARDS.GUARD4: guard = new Guard4(this._Guard4DependencyService); break; default: break; } return guard.canActivate(this.route, this.state); } } Challenges One of the challenges in this approach is refactoring of existing routing model. However, it can be done in parts as the changes are non-breaking. I hope this helps. A: With Angular 15's functional guards and the recently upgraded inject function, it's now possible to write an elegant function that executes async guards in order. For example, let's assume that all guards return an Observable<boolean | UrlTree>: interface AsyncGuard extends CanActivate { canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean | UrlTree>; } You could then write a universal ordering function like this: function orderedAsyncGuards( guards: Array<new () => AsyncGuard> ): CanActivateFn { return (route, state) => { // Instantiate all guards. const guardInstances = guards.map(inject) as AsyncGuard[]; // Convert an array into an observable. return from(guardInstances).pipe( // For each guard, fire canActivate and wait for it to complete. concatMap((guard) => guard.canActivate(route, state)), // Don't execute the next guard if the current guard's result is not true. takeWhile((value) => value === true, /* inclusive */ true), // Return the last guard's result. last() ); }; } Then you can use it in the route configuration like this: const ROUTE = { ... canActivate: [orderedAsyncGuards([FirstGuard, SecondGuard])] Here's a working StackBlitz example. A: Here is my solution inspired by @planet_hunter which is fully compatible with Angular 8's CanActivate signature: Multiple canActivate guards all run when first fails
stackoverflow
{ "language": "en", "length": 954, "provenance": "stackexchange_0000F.jsonl.gz:896604", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641092" }
1c55f1f2be4cfe11c2585624241b32a9595ae20d
Stackoverflow Stackexchange Q: Docker not able to use all of Macbook's CPU cores I am currently using a Macbook Pro with i7, which has 8 cores. However, I am not able set the CPU cores to more than 1. When I run docker run --cpus=2 "my-image" I get the following error: docker: Error response from daemon: Range of CPUs is from 0.01 to 1.00, as there are only 1 CPUs available. What am I missing? A: You need to increase the maximum number of CPUs available to containers in the Docker Server. In OS X you can find them in Preferences -> Advanced.
Q: Docker not able to use all of Macbook's CPU cores I am currently using a Macbook Pro with i7, which has 8 cores. However, I am not able set the CPU cores to more than 1. When I run docker run --cpus=2 "my-image" I get the following error: docker: Error response from daemon: Range of CPUs is from 0.01 to 1.00, as there are only 1 CPUs available. What am I missing? A: You need to increase the maximum number of CPUs available to containers in the Docker Server. In OS X you can find them in Preferences -> Advanced. A: If you use Docker Desktop for Mac, you increase from the UI:
stackoverflow
{ "language": "en", "length": 114, "provenance": "stackexchange_0000F.jsonl.gz:896624", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641143" }
de6bde4d7b28fe87abb8d5e5a96463eeb7492dd9
Stackoverflow Stackexchange Q: How to receive an update notification when a user enables 2-step verification? I have created a channel to send my app notifications when a user is updated like so: data = { 'id': channel_id, 'type': 'web_hook', 'address': domain_address, 'kind': 'api#channel', } channel = directory.users().watch(body=data, domain=my_domain, event='update').execute() This successfully sends notifications when I update the user in the Admin SDK GUI. However, when a user takes an action that causes their information to update, such as logging in, changing their password or enabling 2-step verification, I receive no notification. My end goal is to receive a notification when a user enables 2-step verification, i.e. when the isEnrolledIn2Sv attribute changes from False to True. Is there any way of doing this? Thank you! EDIT: The workaround I used was to create a webhook (I used AWS Lambda) to query all users known to have the isEnrolledIn2Sv attribute set to False, and see if any had changed to True. It works! But not ideal, so would love to hear if anyone else knows a cleaner way to do this. A: In addition to 'update', it looks like you want to request 'add' events, as well.
Q: How to receive an update notification when a user enables 2-step verification? I have created a channel to send my app notifications when a user is updated like so: data = { 'id': channel_id, 'type': 'web_hook', 'address': domain_address, 'kind': 'api#channel', } channel = directory.users().watch(body=data, domain=my_domain, event='update').execute() This successfully sends notifications when I update the user in the Admin SDK GUI. However, when a user takes an action that causes their information to update, such as logging in, changing their password or enabling 2-step verification, I receive no notification. My end goal is to receive a notification when a user enables 2-step verification, i.e. when the isEnrolledIn2Sv attribute changes from False to True. Is there any way of doing this? Thank you! EDIT: The workaround I used was to create a webhook (I used AWS Lambda) to query all users known to have the isEnrolledIn2Sv attribute set to False, and see if any had changed to True. It works! But not ideal, so would love to hear if anyone else knows a cleaner way to do this. A: In addition to 'update', it looks like you want to request 'add' events, as well.
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:896633", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641168" }
1fb25001ce241d08ecfd6c2163d24d2f10e90625
Stackoverflow Stackexchange Q: React contenteditable in stateless component I am trying to implement a contenteditable div inside a stateless react component. I keep getting the below warning: warning.js:36 Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional. How do I fix this? Also how do I read contents of div on change? A: As with any React application, browser plugins and extensions that modify the DOM can cause Draft editors to break. Grammar checkers, for instance, may modify the DOM within contentEditable elements, adding styles like underlines and backgrounds. Since React cannot reconcile the DOM if the browser does not match its expectations, the editor state may fail to remain in sync with the DOM. https://github.com/facebook/draft-js/issues/53 A known error. As for reading whats in a div, assign the element an id and.. oDoc = document.getElementById("divelement"); sDefTxt = oDoc.innerHTML;
Q: React contenteditable in stateless component I am trying to implement a contenteditable div inside a stateless react component. I keep getting the below warning: warning.js:36 Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional. How do I fix this? Also how do I read contents of div on change? A: As with any React application, browser plugins and extensions that modify the DOM can cause Draft editors to break. Grammar checkers, for instance, may modify the DOM within contentEditable elements, adding styles like underlines and backgrounds. Since React cannot reconcile the DOM if the browser does not match its expectations, the editor state may fail to remain in sync with the DOM. https://github.com/facebook/draft-js/issues/53 A known error. As for reading whats in a div, assign the element an id and.. oDoc = document.getElementById("divelement"); sDefTxt = oDoc.innerHTML; A: Add suppressContentEditableWarning="true" to contenteditable div. Reference: https://github.com/facebook/draft-js/issues/81 A: Warning: A component is `contentEditable` and contains `children` managed by React Resolved by adding... //... <div suppressContentEditableWarning={true} // <-- Add this className="MyClass" onClick={ ()=> { onEidtHandler() } } onBlur={ ()=> { onSaveHandler() } > Editable content </div> //...
stackoverflow
{ "language": "en", "length": 207, "provenance": "stackexchange_0000F.jsonl.gz:896642", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641201" }
078070122f32eccc51ad066a0284f32c0826f7ca
Stackoverflow Stackexchange Q: npm link, without linking devDependencies It appears that when I run npm link, it will install the project globally, and it seems to install devDependencies with it. Is there a way to run npm link without devDependencies, perhaps with the --only=production flag? A: This is currently not possible with npm link. The problem is, if you install only prod dependencies in that dependency, you're able to link it, but you're not able to develop on that dependency anymore (since missing devDependencies). And vice-versa: If you install devDependencies, you can't link anymore. The solution: A package called npm-local-development at https://github.com/marcj/npm-local-development It basically does the same thing as npm link, but works around the devDependency limitation by setting up a file watcher and syncs file changes automatically in the background, excluding all devDependencies/peerDependencies. * *You install npm-local-development: npm i -g npm-local-development *You create file called .links.json in your root package. *You write every package name with its local relative folder path into it like so { "@shared/core": "../../my-library-repo/packages/core" } *Open a console and run npm-local-development in that root package. Let it run in the background. Disclaimer: I'm the author of this free open-source project.
Q: npm link, without linking devDependencies It appears that when I run npm link, it will install the project globally, and it seems to install devDependencies with it. Is there a way to run npm link without devDependencies, perhaps with the --only=production flag? A: This is currently not possible with npm link. The problem is, if you install only prod dependencies in that dependency, you're able to link it, but you're not able to develop on that dependency anymore (since missing devDependencies). And vice-versa: If you install devDependencies, you can't link anymore. The solution: A package called npm-local-development at https://github.com/marcj/npm-local-development It basically does the same thing as npm link, but works around the devDependency limitation by setting up a file watcher and syncs file changes automatically in the background, excluding all devDependencies/peerDependencies. * *You install npm-local-development: npm i -g npm-local-development *You create file called .links.json in your root package. *You write every package name with its local relative folder path into it like so { "@shared/core": "../../my-library-repo/packages/core" } *Open a console and run npm-local-development in that root package. Let it run in the background. Disclaimer: I'm the author of this free open-source project. A: In npm@4.x or lower When you run npm link in other_module then you will get both dependencies and devDependencies symlinked. The --production flag doesn't change anything, still creates a symlink to the whole directory In npm@5.1.0 They fixed it! If you remove node_modules and then do npm link --only=production, it runs an install before symlinking, and therefore devDependencies folder are indeed excluded. A: A workaround I use is npm pack then point to the packed file in the example
stackoverflow
{ "language": "en", "length": 273, "provenance": "stackexchange_0000F.jsonl.gz:896645", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641207" }
9437df7396319d17b3c135f438583d9164914cf9
Stackoverflow Stackexchange Q: Is there any reason to declare a method virtual without inheritance? Is there any reason to declare a method virtual if a class has no subclasses, and is always used directly? For example: class Foo { public: virtual void DoBar { // Do something here. } } I came across this in some code I was reading, and couldn't find any justification. Thanks! A: Well the essence of virtual keyword is directly related to inheritance. This is an extract from CPP Ref:- Virtual members A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties through references. The syntax for a function to become virtual is to precede its declaration with the virtual keyword So IMHO - the ans to your question is no - it makes no sense - unless the code has changed from initial implementation - and trust me that happens a lot!
Q: Is there any reason to declare a method virtual without inheritance? Is there any reason to declare a method virtual if a class has no subclasses, and is always used directly? For example: class Foo { public: virtual void DoBar { // Do something here. } } I came across this in some code I was reading, and couldn't find any justification. Thanks! A: Well the essence of virtual keyword is directly related to inheritance. This is an extract from CPP Ref:- Virtual members A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties through references. The syntax for a function to become virtual is to precede its declaration with the virtual keyword So IMHO - the ans to your question is no - it makes no sense - unless the code has changed from initial implementation - and trust me that happens a lot! A: It is useful when writing library code to keep the future programmer in mind who may want to extend the class and provide their own behaviour. For example it is common to have a virtual Paint() function or virtual mouse handling functions in GUI libraries. They provide default implementations, but they allow the possibility of extension. A: If that class is meant to be derive from then yes it makes sense. These decisions should be made when deciding the architecture of a program, and defining what can be done with the interfaces. If they do not want this to be derived from then it should not be virtual. If they do want it to be derived from then it should be virtual (and it should also make the destructor virtual).
stackoverflow
{ "language": "en", "length": 287, "provenance": "stackexchange_0000F.jsonl.gz:896675", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641290" }
c8394d567cd9a8d32d6f1052de49140b29f81264
Stackoverflow Stackexchange Q: Google actions not showing cards in test I've created a simple helper in api.ai to tell and added a few intents with responses that link to google actions. When I link my agent to a google project and test it with those intents i get the following errors: expected_inputs[0].input_prompt.rich_initial_prompt: the first element must be a 'simple_response' or a 'structured_response'. and expected_inputs[0].input_prompt.rich_initial_prompt.items[0].basic_card.image: 'accessibility_text' is required. these are both classified as Malformed Response Errors, but I don't really understand seeing as I didn't write any code, simply just used used the UI for api.ai and google projects Any ideas? A: The problem is that the Actions on Google responses still require a text response to be displayed and/or spoken in addition to the card responses. So in the Actions on Google section of the response, you must either set "Use response from the DEFAULT tab as the first response" on: or you must add a Simple Response: When you enter a Basic Card, if you enter an Image URL, you must also enter the Image Accessibility Text:
Q: Google actions not showing cards in test I've created a simple helper in api.ai to tell and added a few intents with responses that link to google actions. When I link my agent to a google project and test it with those intents i get the following errors: expected_inputs[0].input_prompt.rich_initial_prompt: the first element must be a 'simple_response' or a 'structured_response'. and expected_inputs[0].input_prompt.rich_initial_prompt.items[0].basic_card.image: 'accessibility_text' is required. these are both classified as Malformed Response Errors, but I don't really understand seeing as I didn't write any code, simply just used used the UI for api.ai and google projects Any ideas? A: The problem is that the Actions on Google responses still require a text response to be displayed and/or spoken in addition to the card responses. So in the Actions on Google section of the response, you must either set "Use response from the DEFAULT tab as the first response" on: or you must add a Simple Response: When you enter a Basic Card, if you enter an Image URL, you must also enter the Image Accessibility Text:
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:896692", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641336" }
50ca18c7d202695895ef4546e6330c0a8f0026ee
Stackoverflow Stackexchange Q: How to check if Configuration Section exists in .NET Core? How can you check if a configuration section exists in the appsettings.json in .NET Core? Even if a section doesn't exist, the following code will always return an instantiated instance. e.g. var section = this.Configuration.GetSection<TestSection>("testsection"); A: In .Net 6, there is a new extension method for this: ConfigurationExtensions.GetRequiredSection() Throws InvalidOperationException if there is no section with the given key. Further, if you're using the IOptions pattern with AddOptions<TOptions>(), the ValidateOnStart() extension method was also added in .Net 6 to be able to specify that validations should run at startup, instead of only running when the IOptions instance is resolved. With some questionable cleverness you can combine it with GetRequiredSection() to make sure a section actually exist: // Bind MyOptions, and ensure the section is actually defined. services.AddOptions<MyOptions>() .BindConfiguration(nameof(MyOptions)) .Validate<IConfiguration>((_, configuration) => configuration.GetRequiredSection(nameof(MyOptions)) is not null) .ValidateOnStart();
Q: How to check if Configuration Section exists in .NET Core? How can you check if a configuration section exists in the appsettings.json in .NET Core? Even if a section doesn't exist, the following code will always return an instantiated instance. e.g. var section = this.Configuration.GetSection<TestSection>("testsection"); A: In .Net 6, there is a new extension method for this: ConfigurationExtensions.GetRequiredSection() Throws InvalidOperationException if there is no section with the given key. Further, if you're using the IOptions pattern with AddOptions<TOptions>(), the ValidateOnStart() extension method was also added in .Net 6 to be able to specify that validations should run at startup, instead of only running when the IOptions instance is resolved. With some questionable cleverness you can combine it with GetRequiredSection() to make sure a section actually exist: // Bind MyOptions, and ensure the section is actually defined. services.AddOptions<MyOptions>() .BindConfiguration(nameof(MyOptions)) .Validate<IConfiguration>((_, configuration) => configuration.GetRequiredSection(nameof(MyOptions)) is not null) .ValidateOnStart(); A: Since .NET Core 2.0, you can also call the ConfigurationExtensions.Exists extension method to check if a section exists. var section = this.Configuration.GetSection("testsection"); var sectionExists = section.Exists(); Since GetSection(sectionKey) never returns null, you can safely call Exists on its return value. It is also helpful to read this documentation on Configuration in ASP.NET Core. A: Query the children of Configuration and check if there is any with the name "testsection" var sectionExists = Configuration.GetChildren().Any(item => item.Key == "testsection")); This should return true if "testsection" exists, otherwise false.
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:896740", "question_score": "28", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641488" }
2aaa36590c07096ecb96a6b14eebc6036628b4b4
Stackoverflow Stackexchange Q: Invalid code signing entitlements - specifically value 'dns-proxy' for key 'com.apple.developer.networking.networkextension' I am working an existing app on the App Store. The only thing I have to do is update the splash screen and icon. However, when I try to upload iTunes Store I get the error: "Invalid code signing entitlements - specifically value 'dns-proxy' for key 'com.apple.developer.networking.networkextension' in 'Payload/AppName.app/AppName' is not supported." I'm new to building IOS apps - can someone please point in the right direction to fix this? A: I solved this problem by adding the Network Extensions capability, which seems to only appear in Xcode 8.3.3, for all related targets in the Capabilities Tab.
Q: Invalid code signing entitlements - specifically value 'dns-proxy' for key 'com.apple.developer.networking.networkextension' I am working an existing app on the App Store. The only thing I have to do is update the splash screen and icon. However, when I try to upload iTunes Store I get the error: "Invalid code signing entitlements - specifically value 'dns-proxy' for key 'com.apple.developer.networking.networkextension' in 'Payload/AppName.app/AppName' is not supported." I'm new to building IOS apps - can someone please point in the right direction to fix this? A: I solved this problem by adding the Network Extensions capability, which seems to only appear in Xcode 8.3.3, for all related targets in the Capabilities Tab. A: I found the solution. * *Go to the You Apps on Apple Developer. *Go to your Idetifiers (App IDS) and uncheck Network Extensions. *Try again to upload. A: I guess you need to update your developer certificate in your XCode and patch it again.Try to validate it before you upload it.
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:896746", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641511" }
5865076c375d83d4ddaf5e843064e01e46f4bf46
Stackoverflow Stackexchange Q: gitlab ci access to private snippets I have a snippet that I want to use in my gitlab ci across multiple projects. before_script: - curl --header "PRIVATE-TOKEN: xxx" https://gitlab.example.com/api/v4/snippets/1 - bash my_script.sh I tried using the $CI_JOB_TOKEN resulting in a 401. Is there a way to gain access without creating a user token? A: The short answer is NO. CI_JOB_TOKEN variable used for authenticating with the GitLab Container Registry and downloading dependent repositories [1]. You can create personal and project Snippets, with three visibility levels [2], private, internal and public. Private snippets are only visible to the snippet creator, so you need a Personal access token (with api scope!!!, and it's not recommended for CI jobs in public/shared projects. Suggestion: * *Create an Internal snippet *Create a user for CI jobs, with read-only access to project (e.g. ci-bot). *Do CI jobs with ci-bot's Access Token. [1] https://docs.gitlab.com/ee/ci/variables/predefined_variables.html [2] https://docs.gitlab.com/ee/api/snippets.html
Q: gitlab ci access to private snippets I have a snippet that I want to use in my gitlab ci across multiple projects. before_script: - curl --header "PRIVATE-TOKEN: xxx" https://gitlab.example.com/api/v4/snippets/1 - bash my_script.sh I tried using the $CI_JOB_TOKEN resulting in a 401. Is there a way to gain access without creating a user token? A: The short answer is NO. CI_JOB_TOKEN variable used for authenticating with the GitLab Container Registry and downloading dependent repositories [1]. You can create personal and project Snippets, with three visibility levels [2], private, internal and public. Private snippets are only visible to the snippet creator, so you need a Personal access token (with api scope!!!, and it's not recommended for CI jobs in public/shared projects. Suggestion: * *Create an Internal snippet *Create a user for CI jobs, with read-only access to project (e.g. ci-bot). *Do CI jobs with ci-bot's Access Token. [1] https://docs.gitlab.com/ee/ci/variables/predefined_variables.html [2] https://docs.gitlab.com/ee/api/snippets.html
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:896763", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641557" }
5449969b4a28357856ff2fd4e9799f41e00167e1
Stackoverflow Stackexchange Q: render_template in Flask on JS click event I am trying to call a function in Flask by clicking a button. When the button is clicked, the following script runs. JS $("#load_btn").click(function() { $.get("/callback"); } Flask @app.route('/callback') def callback(): print('called') ... # code here that needs to run before rendering callback return render_template('callback.html') The problem here is, called is printed, and GET /callback HTTP/1.1 200 is logged as well, but callback.html is not rendered - the page stays the same. I'm guessing this is probably not the best approach to solving this problem, but if so what is the recommended approach? A: $.get just sends an HTTP request to your server, but doesn't actually do anything anything with the data (in your case, the rendered template) it gets back from the server. Try something like this: $("#load_btn").click(function() { $("html").load("/callback"); } Or if the template you render doesn't contain any <head> tags, only body content, you can do $("#load_btn").click(function() { $("body").load("/callback"); } Or, you can exchange "body" for a specific element to only replace a specific part of the page. If you want the user to be redirected, do this: $("#load_btn").click(function() { window.location = "/callback"; }
Q: render_template in Flask on JS click event I am trying to call a function in Flask by clicking a button. When the button is clicked, the following script runs. JS $("#load_btn").click(function() { $.get("/callback"); } Flask @app.route('/callback') def callback(): print('called') ... # code here that needs to run before rendering callback return render_template('callback.html') The problem here is, called is printed, and GET /callback HTTP/1.1 200 is logged as well, but callback.html is not rendered - the page stays the same. I'm guessing this is probably not the best approach to solving this problem, but if so what is the recommended approach? A: $.get just sends an HTTP request to your server, but doesn't actually do anything anything with the data (in your case, the rendered template) it gets back from the server. Try something like this: $("#load_btn").click(function() { $("html").load("/callback"); } Or if the template you render doesn't contain any <head> tags, only body content, you can do $("#load_btn").click(function() { $("body").load("/callback"); } Or, you can exchange "body" for a specific element to only replace a specific part of the page. If you want the user to be redirected, do this: $("#load_btn").click(function() { window.location = "/callback"; }
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:896773", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641580" }
d47e4f765cc84594f12691f9b6c76f2c2fb241c1
Stackoverflow Stackexchange Q: R + Adding n number of weeks to YYYYWW format I am trying to add 52 weeks to a date variable which is in YYYYWW format. my initial date is 201616 (year 2016 and week 16) and i am trying to add 52 weeks to this date and the expected output is 201715. I tried couple of things but no luck, here is what i tried so far date <- as.Date(as.character(201616), "%Y%W") seq(date, by = "1 week", length.out = 52) I would greatly appreciate your input. Many Thanks for your time! A: The problem is that there are 7 days in week #16 2016. You need to specify a day to convert it to a date that can be used to add days. In the code below %u indicates first day of the week. You can then add 52 weeks to this number. date1 <- as.Date("201616 1", format = "%Y%U %u") format(date1+(52*7), "%Y%U") [1] "201716"
Q: R + Adding n number of weeks to YYYYWW format I am trying to add 52 weeks to a date variable which is in YYYYWW format. my initial date is 201616 (year 2016 and week 16) and i am trying to add 52 weeks to this date and the expected output is 201715. I tried couple of things but no luck, here is what i tried so far date <- as.Date(as.character(201616), "%Y%W") seq(date, by = "1 week", length.out = 52) I would greatly appreciate your input. Many Thanks for your time! A: The problem is that there are 7 days in week #16 2016. You need to specify a day to convert it to a date that can be used to add days. In the code below %u indicates first day of the week. You can then add 52 weeks to this number. date1 <- as.Date("201616 1", format = "%Y%U %u") format(date1+(52*7), "%Y%U") [1] "201716" A: I'm not sure that as.Date can take %Y%W and generate a unique value. It appears to be populating date with the current month and day. If instead we specify a date in the 16th week: date <- as.Date("2016-04-23") and format that in your style format(date, "%Y%W") [1] "201616" we can generate a sequence of 52 values from this newdate_seq <- seq(date, by = "1 week", length.out = 52) and change those to your format too format(newdate_seq, "%Y%W") [1] "201616" "201617" "201618" "201619" "201620" "201621" "201622" "201623" "201624" "201625" "201626" "201627" [13] "201628" "201629" "201630" "201631" "201632" "201633" "201634" "201635" "201636" "201637" "201638" "201639" [25] "201640" "201641" "201642" "201643" "201644" "201645" "201646" "201647" "201648" "201649" "201650" "201651" [37] "201652" "201701" "201702" "201703" "201704" "201705" "201706" "201707" "201708" "201709" "201710" "201711" [49] "201712" "201713" "201714" "201715" which ends where you expect. FYI, for next time, try highlighting what caused you to think there was "no luck" -- what errors did you produce, what results did you produce and how did they differ from what you expect to produce? Simply printing the date variable showed me that it wasn't doing what you expected.
stackoverflow
{ "language": "en", "length": 347, "provenance": "stackexchange_0000F.jsonl.gz:896785", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641616" }
551838020e72ea47d0a304b6af17a3505e0a8334
Stackoverflow Stackexchange Q: why does & (address) of an array print "&" in go Here is the go code package main func main() { var ax [2]int ax[0] = 22 ax[1] = 99 bx := ax cx := &ax fmt.Println(ax) fmt.Println(bx) fmt.Println(cx) fmt.Printf("%p\n", cx) } When I execute it, it gives me the following output PS C:\personal\gospace> ./bin/test [22 99] [22 99] &[22 99] 0xc0420381d0 cx := &ax rightly interpreted cx as pointer. But when I print cx it prints &[22 99] and when I print &ax[0] or %p formatter for cx it rightly prints the address. Why is this behavior? A: Default printing verb fmt.Println uses is %v. While printing it differentiates value vs pointer value, that's why you see & in front of cx. fmt.Println(cx) Next, you specifically tell fmt.Printf to use the verb %p, refer to printing section and it prints base 16 notation, with leading 0x. fmt.Printf("%p\n", cx)
Q: why does & (address) of an array print "&" in go Here is the go code package main func main() { var ax [2]int ax[0] = 22 ax[1] = 99 bx := ax cx := &ax fmt.Println(ax) fmt.Println(bx) fmt.Println(cx) fmt.Printf("%p\n", cx) } When I execute it, it gives me the following output PS C:\personal\gospace> ./bin/test [22 99] [22 99] &[22 99] 0xc0420381d0 cx := &ax rightly interpreted cx as pointer. But when I print cx it prints &[22 99] and when I print &ax[0] or %p formatter for cx it rightly prints the address. Why is this behavior? A: Default printing verb fmt.Println uses is %v. While printing it differentiates value vs pointer value, that's why you see & in front of cx. fmt.Println(cx) Next, you specifically tell fmt.Printf to use the verb %p, refer to printing section and it prints base 16 notation, with leading 0x. fmt.Printf("%p\n", cx)
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:896794", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641643" }
ab4b22e04dcaff9bfb287dd694d1d2f747c6b36b
Stackoverflow Stackexchange Q: What is the purpose of dtplyr and the reason for the warning 'Please library(dtplyr)!'? On loading the latest version of data.table (1.10.4) I get this message: > library(data.table) data.table 1.10.4 ... --------------------------------------------------------------------------------------------------------------------------------------------- data.table + dplyr code now lives in dtplyr. Please library(dtplyr)! --------------------------------------------------------------------------------------------------------------------------------------------- Attaching package: ‘data.table’ The following objects are masked from ‘package:dplyr’: between, first, last The following object is masked from ‘package:purrr’: transpose The message is not very helpful to explain why is it useful to use the dtplyr package. As far as I can see, as long as I avoid the listed conflicts I can use the data.table package normally? In fact, I can't library(dtplyr) without having the package installed, so the message itself does not provide very good instructions in this case. A: The package dtplyr is really performant, it could really speed up the calculation when my dataframe is larger than 10^5 rows. What I did is: library(data.table) library(dplyr) library(dtplyr) Best regards
Q: What is the purpose of dtplyr and the reason for the warning 'Please library(dtplyr)!'? On loading the latest version of data.table (1.10.4) I get this message: > library(data.table) data.table 1.10.4 ... --------------------------------------------------------------------------------------------------------------------------------------------- data.table + dplyr code now lives in dtplyr. Please library(dtplyr)! --------------------------------------------------------------------------------------------------------------------------------------------- Attaching package: ‘data.table’ The following objects are masked from ‘package:dplyr’: between, first, last The following object is masked from ‘package:purrr’: transpose The message is not very helpful to explain why is it useful to use the dtplyr package. As far as I can see, as long as I avoid the listed conflicts I can use the data.table package normally? In fact, I can't library(dtplyr) without having the package installed, so the message itself does not provide very good instructions in this case. A: The package dtplyr is really performant, it could really speed up the calculation when my dataframe is larger than 10^5 rows. What I did is: library(data.table) library(dplyr) library(dtplyr) Best regards
stackoverflow
{ "language": "en", "length": 157, "provenance": "stackexchange_0000F.jsonl.gz:896839", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641789" }
2395f947110fc3b904268c506116277a724184da
Stackoverflow Stackexchange Q: Multithreading in Embedded Systems I am confused about the following: I am hoping to get a job in the field of embedded systems. However, every interview I've had seems to end up with a conversation about threads in C and how to do thread-safe programming My question is how do I go about learning multithreading in embedded systems? Are they the same as POSIX threads? For example, the tasks in FreeRTOS. Are they same thing as pthreads? Can someone give me some tips on what to do and where to start? A: Every OS has it's own threads/task/processes characteristics. Despite the differences, the methods to synchronize, guard and interchange data between those, are roughly the same. If someone knows that you don't know a specific OS, invited you to an interview - he/she probably expects you to answer in general and not to be OS specific. You can solve any problem with POSIX (or any other) tool-set in mind and to mention that migration of the solution to a non-POSIX environment will keep same logic with some minor adaptations.
Q: Multithreading in Embedded Systems I am confused about the following: I am hoping to get a job in the field of embedded systems. However, every interview I've had seems to end up with a conversation about threads in C and how to do thread-safe programming My question is how do I go about learning multithreading in embedded systems? Are they the same as POSIX threads? For example, the tasks in FreeRTOS. Are they same thing as pthreads? Can someone give me some tips on what to do and where to start? A: Every OS has it's own threads/task/processes characteristics. Despite the differences, the methods to synchronize, guard and interchange data between those, are roughly the same. If someone knows that you don't know a specific OS, invited you to an interview - he/she probably expects you to answer in general and not to be OS specific. You can solve any problem with POSIX (or any other) tool-set in mind and to mention that migration of the solution to a non-POSIX environment will keep same logic with some minor adaptations. A: Multithreading concept is almost same everywhere, whether in RTOS or Linux. The difference is in the operational behavior. My question is how do I go about learning multithreading in embedded systems? My suggestion is to first learn and understand the concepts of multithreading by referring some online material, you can practice by writing some simple codes on your desktop running any flavor of Linux. The go for some advanced topics like synchronization mechanism using Semaphore and Mutexes, you will then get to learn about the basic concept of when to use a semaphore and when to use a mutex for thread synchronization. Then move to some Embedded Targets and try out some code using uCOS-II/uCOS-III or FreeRTOS. Are they the same as POSIX threads? No, they are not exactly same, POSIX thread library is a bit advance and is highly portable on different OS. For e.g. a multithread code written on Linux using pthread can also be compiled and executed on Windows with little or no change. On the other hand, a thread implementation on RTOS is different, threads in RTOS are treated as tasks and they start executing only when a call to start the scheduler is made. A: From my own experience trying to find learning resources, I found the the FreeRTOS docs very useful. They have both a reference manual as well as the Mastering the FreeRTOS Kernal doc which includes code snippets and covers topics such as task management, software timers, resource management, and general thread safe programming techniques. I dont think this would be the best place to start out, but once you've familiarized yourself with basics the other answers and comments have mentioned, this could help with the next step of learning by doing.
stackoverflow
{ "language": "en", "length": 471, "provenance": "stackexchange_0000F.jsonl.gz:896850", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641829" }
3143e070fb29e5e6fe804b6a1d0a497257fb4c73
Stackoverflow Stackexchange Q: NSAttributedStringKey giving an unresolved identifier error I'm following an online tutorial to build a magazine type iOS application. I'm attempting to use NSAttributedStringKey but keep getting the error shown below. Any ideas? This is the line of code that is causing the error: let attrs = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font] as [NSAttributedStringKey : Any] A: The code you are trying to use is a new API added in iOS 11. Since you are using Xcode 8 you are not using iOS 11. So you need to use the current (non-beta) API. let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
Q: NSAttributedStringKey giving an unresolved identifier error I'm following an online tutorial to build a magazine type iOS application. I'm attempting to use NSAttributedStringKey but keep getting the error shown below. Any ideas? This is the line of code that is causing the error: let attrs = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font] as [NSAttributedStringKey : Any] A: The code you are trying to use is a new API added in iOS 11. Since you are using Xcode 8 you are not using iOS 11. So you need to use the current (non-beta) API. let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font] A: Swift 4.1 and Xcode 9.3 changes Attributed key value. let strName = "Hello Stackoverflow" let string_to_color2 = "Hello" let attributedString1 = NSMutableAttributedString(string:strName) let range2 = (strName as NSString).range(of: string_to_color2) attributedString1.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: range2) lblTest.attributedText = attributedString1 Hello will be in red color. A: The projects are probably in different versions of Swift. In Swift 4, NSFontAttributeName has been replaced with NSAttributedStringKey.font. as stated here NSFontAttributeName vs NSAttributedStringKey.font Need to confirm whether it will work on versions less than ios11 A: This example works only iOS11. import UIKit class VC: UIViewController { @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var passTxt: UITextField! override func viewDidLoad() { super.viewDidLoad() setupView() } func setupView() { usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) passTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) } } A: Swift 4.x // MARK: - Deal with the empty data set // Add title for empty dataset func title(forEmptyDataSet _: UIScrollView!) -> NSAttributedString! { let str = "Welcome" let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)] return NSAttributedString(string: str, attributes: attrs) } // Add description/subtitle on empty dataset func description(forEmptyDataSet _: UIScrollView!) -> NSAttributedString! { let str = "Tap the button below to add your first grokkleglob." let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)] return NSAttributedString(string: str, attributes: attrs) } // Add your image func image(forEmptyDataSet _: UIScrollView!) -> UIImage! { return UIImage(named: "MYIMAGE") } // Add your button func buttonTitle(forEmptyDataSet _: UIScrollView!, for _: UIControlState) -> NSAttributedString! { let str = "Add Grokkleglob" let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.callout), NSAttributedStringKey.foregroundColor: UIColor.white] return NSAttributedString(string: str, attributes: attrs) } // Add action for button func emptyDataSetDidTapButton(_: UIScrollView!) { let ac = UIAlertController(title: "Button tapped!", message: nil, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Hurray", style: .default, handler: nil)) present(ac, animated: true, completion: nil) } A: You are trying to use an iOS 11 API on a pre-iOS 11 version (likely iOS 10). Surprised that you found a tutorial already using beta features! In the meantime, try this. let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font] and that should work.
stackoverflow
{ "language": "en", "length": 442, "provenance": "stackexchange_0000F.jsonl.gz:896866", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641877" }
547684ff224a0f99c00384fffc3e8f25b45b7c88
Stackoverflow Stackexchange Q: Valgrind Invalid read of size 1 (sscanf) Somehow Valgrind shows an error at the first lines of my program: int main(int argc, char** argv) { int i, r; sscanf(argv[1], "%d", &r); return 0; } Valgrind reports: ==18674== Invalid read of size 1 ==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x400DE3: main (test_b_arbre.c:18) ==18674== Address 0x0 is not stack'd, malloc'd or (recently) free'd ==18674== ==18674== ==18674== Process terminating with default action of signal 11 (SIGSEGV) ==18674== Access not within mapped region at address 0x0 ==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x400DE3: main (test_b_arbre.c:18) I went through some similar questions, but I didn't find how to fix it... How I run the program: valgrind --leak-check=yes --track-origins=yes ./b_arbre 1 2 3 4 5 6 A: You're invoking it with no arguments, so argv[1] is a null pointer. "Fix" it by providing a command line argument. Fix it properly by checking argc and doing something else when it is 1.
Q: Valgrind Invalid read of size 1 (sscanf) Somehow Valgrind shows an error at the first lines of my program: int main(int argc, char** argv) { int i, r; sscanf(argv[1], "%d", &r); return 0; } Valgrind reports: ==18674== Invalid read of size 1 ==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x400DE3: main (test_b_arbre.c:18) ==18674== Address 0x0 is not stack'd, malloc'd or (recently) free'd ==18674== ==18674== ==18674== Process terminating with default action of signal 11 (SIGSEGV) ==18674== Access not within mapped region at address 0x0 ==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so) ==18674== by 0x400DE3: main (test_b_arbre.c:18) I went through some similar questions, but I didn't find how to fix it... How I run the program: valgrind --leak-check=yes --track-origins=yes ./b_arbre 1 2 3 4 5 6 A: You're invoking it with no arguments, so argv[1] is a null pointer. "Fix" it by providing a command line argument. Fix it properly by checking argc and doing something else when it is 1. A: I compiled your exact program on a 64 bit x86_64 Linux (seeing hints of 64 bit libraries in your Valgrind output). The issue doesn't reproduce. I get a warning about the sscanf implicit declaration not being correct, but that is a red herring. I also tried on 64 bit Power PC Linux. Clean Valgrind also. (Of course, the null pointer dereference occurs if the program is called with no arguments, in which case argv[argc] is done; but the issue is described as occurring with arguments.) The problem is likely that the executable being tested doesn't match the source code.
stackoverflow
{ "language": "en", "length": 296, "provenance": "stackexchange_0000F.jsonl.gz:896893", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641971" }
dd9417c9168e96be8687a53460e7712da53444a9
Stackoverflow Stackexchange Q: Reference current file with go:generate is there any way for go:generate to reference the current file? For example, I'd like to do something similar to //go:generate sometool $FILE Thanks A: You can refer current file as follows: //go:generate sometool $GOFILE $GOFILE get expanded to be name of the file processed by go generate.
Q: Reference current file with go:generate is there any way for go:generate to reference the current file? For example, I'd like to do something similar to //go:generate sometool $FILE Thanks A: You can refer current file as follows: //go:generate sometool $GOFILE $GOFILE get expanded to be name of the file processed by go generate.
stackoverflow
{ "language": "en", "length": 54, "provenance": "stackexchange_0000F.jsonl.gz:896901", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44641989" }
9e30e31f5cd371b5db9d9f2a111d59bd4a55e902
Stackoverflow Stackexchange Q: Is there a way to use Docker secrets to read from /run/secrets/redis-pass and set the redis --requirepass flag? Is there a way to use Docker secrets to read from /run/secrets/redis-pass and set the redis --requirepass flag? For example: On a swarm manager set the redis-pass, then use docker stack deploy -c docker-compose-prod.yml appname Here is the working redis service in my docker-compose.yml file. redis: build: ./redis image: redis:3.2.9 volumes: - ./redis/db/:/data/ # Without persistance command: sh -c "redis-server --requirepass XXXXXXXXXX" # With persistance (saves to /data), ref: https://redis.io/topics/persistence # command: sh -c "redis-server --requirepass XXXXXXXXXX --appendonly yes" expose: - "6379" Here is a proposed docker-compose.yml snippet using Docker swarm stacks. version: '3.1' secrets: redis-pass: external: true redis: build: ./redis image: redis:3.2.9 networks: - frontend ports: - "6379" deploy: replicas: 2 update_config: parallelism: 2 delay: 10s restart_policy: condition: on-failure secrets: - redis-pass environment: REDIS_PASS_FILE: /run/secrets/redis-pass A: You can do it this way services: redis: image: redis secrets: - redis_pass environment: REDIS_PASS_FILE: /run/secrets/redis_pass command: [ "bash", "-c", ' docker-entrypoint.sh --requirepass "$$(cat $$REDIS_PASS_FILE)" ' ] like suggested here: * *https://github.com/docker-library/redis/issues/46#issuecomment-335326234 *https://github.com/docker-library/redis/issues/46#issuecomment-364761650
Q: Is there a way to use Docker secrets to read from /run/secrets/redis-pass and set the redis --requirepass flag? Is there a way to use Docker secrets to read from /run/secrets/redis-pass and set the redis --requirepass flag? For example: On a swarm manager set the redis-pass, then use docker stack deploy -c docker-compose-prod.yml appname Here is the working redis service in my docker-compose.yml file. redis: build: ./redis image: redis:3.2.9 volumes: - ./redis/db/:/data/ # Without persistance command: sh -c "redis-server --requirepass XXXXXXXXXX" # With persistance (saves to /data), ref: https://redis.io/topics/persistence # command: sh -c "redis-server --requirepass XXXXXXXXXX --appendonly yes" expose: - "6379" Here is a proposed docker-compose.yml snippet using Docker swarm stacks. version: '3.1' secrets: redis-pass: external: true redis: build: ./redis image: redis:3.2.9 networks: - frontend ports: - "6379" deploy: replicas: 2 update_config: parallelism: 2 delay: 10s restart_policy: condition: on-failure secrets: - redis-pass environment: REDIS_PASS_FILE: /run/secrets/redis-pass A: You can do it this way services: redis: image: redis secrets: - redis_pass environment: REDIS_PASS_FILE: /run/secrets/redis_pass command: [ "bash", "-c", ' docker-entrypoint.sh --requirepass "$$(cat $$REDIS_PASS_FILE)" ' ] like suggested here: * *https://github.com/docker-library/redis/issues/46#issuecomment-335326234 *https://github.com/docker-library/redis/issues/46#issuecomment-364761650 A: Resolved this by following the Docker docs and using entrypoint script. Here is an approach. Define your Docker secret for the redis password On your local dev machine. Create a secrets file, ensure you add a .gitignore entry to not commit secrets to your repo. ./secrets/redis-pass.txt g7VacrULudmwcLnxy23JWyUNZRit7cazG2JekTCc6vccxX2LxLWoHFP8XYLbD4U9 On your swarm leader node. echo "g7VacrULudmwcLnxy23JWyUNZRit7cazG2JekTCc6vccxX2LxLWoHFP8XYLbD4U9" | docker secret create redis-pass - Create a redis config file ./redis/redis.conf Define the requirepass property. requirepass XXXXXXXXXX Update redis Dockerfile Copy the config into the container at build time. ./redis/Dockerfile FROM alpine:3.6 # add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added RUN addgroup -S redis && adduser -S -G redis redis # grab su-exec for easy step-down from root RUN apk add --no-cache 'su-exec>=0.2' ENV REDIS_VERSION 3.2.9 ENV REDIS_DOWNLOAD_URL http://download.redis.io/releases/redis-3.2.9.tar.gz ENV REDIS_DOWNLOAD_SHA 6eaacfa983b287e440d0839ead20c2231749d5d6b78bbe0e0ffa3a890c59ff26 # for redis-sentinel see: http://redis.io/topics/sentinel RUN set -ex; \ \ apk add --no-cache --virtual .build-deps \ coreutils \ gcc \ linux-headers \ make \ musl-dev \ ; \ \ wget -O redis.tar.gz "$REDIS_DOWNLOAD_URL"; \ echo "$REDIS_DOWNLOAD_SHA *redis.tar.gz" | sha256sum -c -; \ mkdir -p /usr/src/redis; \ tar -xzf redis.tar.gz -C /usr/src/redis --strip-components=1; \ rm redis.tar.gz; \ \ # Disable Redis protected mode [1] as it is unnecessary in context # of Docker. Ports are not automatically exposed when running inside # Docker, but rather explicitely by specifying -p / -P. # [1] https://github.com/antirez/redis/commit/edd4d555df57dc84265fdfb4ef59a4678832f6da grep -q '^#define CONFIG_DEFAULT_PROTECTED_MODE 1$' /usr/src/redis/src/server.h; \ sed -ri 's!^(#define CONFIG_DEFAULT_PROTECTED_MODE) 1$!\1 0!' /usr/src/redis/src/server.h; \ grep -q '^#define CONFIG_DEFAULT_PROTECTED_MODE 0$' /usr/src/redis/src/server.h; \ # for future reference, we modify this directly in the source instead of just supplying a default configuration flag because apparently "if you specify any argument to redis-server, [it assumes] you are going to specify everything" # see also https://github.com/docker-library/redis/issues/4#issuecomment-50780840 # (more exactly, this makes sure the default behavior of "save on SIGTERM" stays functional by default) \ make -C /usr/src/redis -j "$(nproc)"; \ make -C /usr/src/redis install; \ \ rm -r /usr/src/redis; \ \ apk del .build-deps RUN mkdir /data && chown redis:redis /data VOLUME /data WORKDIR /data COPY redis.conf /home/redis/ COPY docker-entrypoint.sh /usr/local/bin/ ENTRYPOINT ["docker-entrypoint.sh"] # EXPOSE 6379 # CMD ["redis-server"] Update docker-entrypoint.sh with a sed command. ./redis/docker-entrypoint.sh The sed command will replace value of requirepass property in the redis.conf file with password from the redis-pass secret from /run/secrets/redis-pass. #!/bin/sh set -e # Updated password using sed sed -i "s/requirepass XXXXXXXXXX/requirepass `cat /run/secrets/redis_password`/" /home/redis/redis.conf # first arg is `-f` or `--some-option` # or first arg is `something.conf` if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then set -- redis-server "$@" fi # allow the container to be started with `--user` if [ "$1" = 'redis-server' -a "$(id -u)" = '0' ]; then chown -R redis . exec su-exec redis "$0" "$@" fi exec "$@" Update your docker-compose.yml file ./docker-compose.yml Define compose version of 3.1 version: "3.1" Define secrets secrets: redis-pass: # local dev machine #file: ./secrets/redis-pass.txt # production environment external: true Define redis service. redis: build: ./redis image: redis:3.2.9 command: sh -c 'redis-server /home/redis/redis.conf' expose: - "6379" # networks: # - frontend deploy: replicas: 2 update_config: parallelism: 2 delay: 10s restart_policy: condition: on-failure secrets: - redis-pass tty: true Validate requirepass was updated ➜ blah git:(master) ✗ docker-compose exec redis sh /data # ps -ef PID USER TIME COMMAND 1 root 0:00 sh -c redis-server /home/redis/redis.conf 10 root 0:03 redis-server /home/redis/redis.conf 28 root 0:00 sh 34 root 0:00 ps -ef /data # cat /home/redis/redis.conf requirepass g7VacrULudmwcLnxy23JWyUNZRit7cazG2JekTCc6vccxX2LxLWoHFP8XYLbD4U9 /data # Enjoy!
stackoverflow
{ "language": "en", "length": 759, "provenance": "stackexchange_0000F.jsonl.gz:896928", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642059" }
8cf5a3417ef1fb4b8abd6fafa3b596fc2398fc1c
Stackoverflow Stackexchange Q: Text or legend cut from matplotlib figure on savefig() Say I want to plot a very simple figure with 2-subplot laid out horizontally, and I want to add some text on the right of the second subplot. I am working in Jupyter Notebook, but this shouldn't change anything: import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8, 3)) ax1 = plt.subplot(121) ax1.plot(x,y1) ax2 = plt.subplot(122) ax2.plot(x,y2) ax2.text(1.05,0.7, 'Some text here', horizontalalignment='left', transform=ax2.transAxes) The displayed output is just as I want it: However, when I try to export the figure, the text to the right get cut: plt.savefig(r'C:\mypy\test_graph.png', ext='png'); Using plt.tightlayout(), as suggested here makes the problem worse. How can I best resolve this? A: Adding bbox_inches="tight" to the savefig **kwargs will do it: plt.savefig(r'C:\mypy\test_graph.png', ext='png', bbox_inches="tight") Saved file:
Q: Text or legend cut from matplotlib figure on savefig() Say I want to plot a very simple figure with 2-subplot laid out horizontally, and I want to add some text on the right of the second subplot. I am working in Jupyter Notebook, but this shouldn't change anything: import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8, 3)) ax1 = plt.subplot(121) ax1.plot(x,y1) ax2 = plt.subplot(122) ax2.plot(x,y2) ax2.text(1.05,0.7, 'Some text here', horizontalalignment='left', transform=ax2.transAxes) The displayed output is just as I want it: However, when I try to export the figure, the text to the right get cut: plt.savefig(r'C:\mypy\test_graph.png', ext='png'); Using plt.tightlayout(), as suggested here makes the problem worse. How can I best resolve this? A: Adding bbox_inches="tight" to the savefig **kwargs will do it: plt.savefig(r'C:\mypy\test_graph.png', ext='png', bbox_inches="tight") Saved file: A: Jupyter notebook is by default configured to use its "inline" backend (%matplotlib inline). It displays a saved png version of the figure. During this saving, the option bbox_inches="tight" is used. In order to replicate the figure that you see in the jupyter output, you would need to use this option as well. plt.savefig("output.png", bbox_inches="tight") What this command does is to extend or shrink the area of the saved figure to include all the artists in it. Alternatively, you can shrink the content of the figure, such that there is enough space for the text to fit into the original figure. This can be done with e.g. plt.subplots_adjust(right=0.7) which would mean that the rightmost axes stops at 70% of the figure width.
stackoverflow
{ "language": "en", "length": 249, "provenance": "stackexchange_0000F.jsonl.gz:896934", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642082" }
a7925d7d77d6e7188a36b0c34ea69dfe9b3bf413
Stackoverflow Stackexchange Q: Webpack Hot Module Replacement for KnockoutJS I'm trying to get HMR to work for my knockout application and currently struggling to get HMR to reload whenever I change something inside the viewModel itself, but anything outside the scope will work. Example: //hmr.js require('mymodule'); if(module.hot) module.hot.accept(); // mymodule.js function myViewModel(params) { console.log('this will only be logged once'); // This one doesn't change after saving } console.log('I can get this to be logged multiple times without reload'); module.exports = { viewModel: myViewModel, template: '<div>just some stuff here</div>' }; I'm wondering if I need to do something else to tell HMR to retrigger things inside the viewModel? currently in my main.js file I have ko.applyBindings(new AppViewModel()); which only being fired once and I have ko.components.register() inside my main.js file as well which require in my mymodule file.
Q: Webpack Hot Module Replacement for KnockoutJS I'm trying to get HMR to work for my knockout application and currently struggling to get HMR to reload whenever I change something inside the viewModel itself, but anything outside the scope will work. Example: //hmr.js require('mymodule'); if(module.hot) module.hot.accept(); // mymodule.js function myViewModel(params) { console.log('this will only be logged once'); // This one doesn't change after saving } console.log('I can get this to be logged multiple times without reload'); module.exports = { viewModel: myViewModel, template: '<div>just some stuff here</div>' }; I'm wondering if I need to do something else to tell HMR to retrigger things inside the viewModel? currently in my main.js file I have ko.applyBindings(new AppViewModel()); which only being fired once and I have ko.components.register() inside my main.js file as well which require in my mymodule file.
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:896969", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642166" }
228a2890e59316115330c362dde4f1ec0975d04e
Stackoverflow Stackexchange Q: How to use Bitbucket as a repository in IntelliJ I have tried to add Bitbucket as a repository in IntelliJ (here). However, I came across errors pushing code. I figured out that Bitbucket only allows reading when using access keys. So, I found a plugin that allows IntelliJ to communicate with Bitbucket. But, this plugin has been discontinued. Is there any other way to use Bitbucket with IntelliJ? A: Bitbucket is just Git. IntelliJ supports Git. You are in the wrong section of Bitbucket. You don't want an "Access key" you want to add an SSH key to your user profile. SSH Keys added to your profile can be used for both reads and writes: Use SSH to avoid password prompts when you push code to Bitbucket. To do this: * *Click on your user icon in the bottom left corner, and go to "Bitbucket settings". *Click on "SSH Keys" tab under the "Security" heading of the settings page. *Use the "Add key" button to add your key. For instructions on how to generate an SSH key, see the BitBucket documentation here.
Q: How to use Bitbucket as a repository in IntelliJ I have tried to add Bitbucket as a repository in IntelliJ (here). However, I came across errors pushing code. I figured out that Bitbucket only allows reading when using access keys. So, I found a plugin that allows IntelliJ to communicate with Bitbucket. But, this plugin has been discontinued. Is there any other way to use Bitbucket with IntelliJ? A: Bitbucket is just Git. IntelliJ supports Git. You are in the wrong section of Bitbucket. You don't want an "Access key" you want to add an SSH key to your user profile. SSH Keys added to your profile can be used for both reads and writes: Use SSH to avoid password prompts when you push code to Bitbucket. To do this: * *Click on your user icon in the bottom left corner, and go to "Bitbucket settings". *Click on "SSH Keys" tab under the "Security" heading of the settings page. *Use the "Add key" button to add your key. For instructions on how to generate an SSH key, see the BitBucket documentation here.
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:896978", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642188" }
c900bd790cf14d703eccfae50fe625f05389abc6
Stackoverflow Stackexchange Q: IntelliJ IDEA plugin to fold .conf files? I have a Scala app built with Lift framework. It has a few .conf files. When I open those .conf files in my IntelliJ IDEA Ultimate Fancy Pants Edition, I do not see any buttons to fold those curly braces in those files. Hotkeys do not do it either. Browsed for plugins, none applicable found. Is there any solution to enable code folding in .conf files? Update: Here is an illustration of what would be lovely. Those "-" and "+" icons do not appear in .conf files: A: 2020+ The best option is to install HOCON plugin separately. For now, HOCON file type is not bundled with Scala plugin anymore. P.S. All credits to ghik's comment. Decided to put this into separate answer because I was not able to find the tip at first time.
Q: IntelliJ IDEA plugin to fold .conf files? I have a Scala app built with Lift framework. It has a few .conf files. When I open those .conf files in my IntelliJ IDEA Ultimate Fancy Pants Edition, I do not see any buttons to fold those curly braces in those files. Hotkeys do not do it either. Browsed for plugins, none applicable found. Is there any solution to enable code folding in .conf files? Update: Here is an illustration of what would be lovely. Those "-" and "+" icons do not appear in .conf files: A: 2020+ The best option is to install HOCON plugin separately. For now, HOCON file type is not bundled with Scala plugin anymore. P.S. All credits to ghik's comment. Decided to put this into separate answer because I was not able to find the tip at first time. A: The relevant plugin is the HOCON plugin. To install, click the Get button from the above JetBrains Marketplace link. Or, from within IntelliJ, go to Settings/Preferences (Ctrl+Alt+S for Windows; ⌘+Comma for Mac) and select Plugins, then click Marketplace to search for the plugin and install it. Restart IntelliJ to enable it. To confirm, go back to Settings/Preferences and select Editor > File Types. You should now see HOCON (Human-Optimized Config Object Notation) file types among those listed as "Recognized File Types". Click HOCON and you should see *.conf under "File name patterns". All your .conf files should now appear in IntelliJ with syntax highlighting and code folding. Edited Oct 2020 to remove Scala plugin reference, as it no longer seems to support HOCON files. A: Those .conf files are of HOCON type ("Human-Optimized Config Object Notation"). To enable folding them, you have to force the editor treat them as such. In IntelliJ settings, configure it as illustrated: Preferences->Editor->File Types, and there add filename patterns to HOCON filetype.
stackoverflow
{ "language": "en", "length": 311, "provenance": "stackexchange_0000F.jsonl.gz:897016", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642314" }
882fa4b036a21fd005f1701424b98f806a35e2c8
Stackoverflow Stackexchange Q: DT Fixed Header Frozen on all Tabs of Shiny App R This is an issue with the package DT in R, for Shiny apps. I noticed that with the option fixedHeader = TRUE, the frozen header will appear on all tabs of a Shiny app. Here is an example illustrating the problem. Simply go to "Tab2" and scroll down, and the header from "Tab1" should be visible (unwanted). I would like the header to only appear on "Tab1". library(shiny) library(DT) data("volcano") ui = shinyUI(navbarPage(title = 'Navbar', tabPanel('Table', fluidPage( fluidRow( column(width = 12, DT::dataTableOutput('table')) ) ) ), tabPanel('Tab2', fluidPage( fluidRow( column(width = 4, style = "height:1500px;background-color:#f0f0f5;border-radius:6px 0px 0px 6px; box-shadow:1px 1px 8px #888888") ) ) ) )) server = shinyServer(function(input, output){ output$table <- DT::renderDataTable( volcano, extensions = c('Buttons', 'FixedHeader'), options = list( pageLength = 100, fixedHeader = TRUE ) ) }) runApp(list(ui=ui, server=server), launch.browser = TRUE)
Q: DT Fixed Header Frozen on all Tabs of Shiny App R This is an issue with the package DT in R, for Shiny apps. I noticed that with the option fixedHeader = TRUE, the frozen header will appear on all tabs of a Shiny app. Here is an example illustrating the problem. Simply go to "Tab2" and scroll down, and the header from "Tab1" should be visible (unwanted). I would like the header to only appear on "Tab1". library(shiny) library(DT) data("volcano") ui = shinyUI(navbarPage(title = 'Navbar', tabPanel('Table', fluidPage( fluidRow( column(width = 12, DT::dataTableOutput('table')) ) ) ), tabPanel('Tab2', fluidPage( fluidRow( column(width = 4, style = "height:1500px;background-color:#f0f0f5;border-radius:6px 0px 0px 6px; box-shadow:1px 1px 8px #888888") ) ) ) )) server = shinyServer(function(input, output){ output$table <- DT::renderDataTable( volcano, extensions = c('Buttons', 'FixedHeader'), options = list( pageLength = 100, fixedHeader = TRUE ) ) }) runApp(list(ui=ui, server=server), launch.browser = TRUE)
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:897023", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642337" }
7166591de1cc5d99ac7539025452d0f707bd0b9e
Stackoverflow Stackexchange Q: Tidy way to replicate reshape2 aggregation with tidyverse functions I understand that by design, tidyr does less than reshape2: tidyr never aggregates. Is there a "right" way to replicate reshape2's aggregation, in the sense of better following the tidyverse philosophy? I usually combine a few dplyr verbs and then one from tidyr. I.e.: To replicate dcast(mtcars, gear~cyl, value.var = "disp", sum) gear 4 6 8 1 3 120.1 483.0 4291.4 2 4 821.0 655.2 0.0 3 5 215.4 145.0 652.0 One can do mtcars %>% group_by(gear, cyl) %>% summarise(disp = sum(disp)) %>% spread(cyl, disp) Source: local data frame [3 x 4] Groups: gear [3] gear `4` `6` `8` * <dbl> <dbl> <dbl> <dbl> 1 3 120.1 483.0 4291.4 2 4 821.0 655.2 NA 3 5 215.4 145.0 652.0 I'll appreciate any insight on whether this is an optimal solution, and if it's not, what would be better and why
Q: Tidy way to replicate reshape2 aggregation with tidyverse functions I understand that by design, tidyr does less than reshape2: tidyr never aggregates. Is there a "right" way to replicate reshape2's aggregation, in the sense of better following the tidyverse philosophy? I usually combine a few dplyr verbs and then one from tidyr. I.e.: To replicate dcast(mtcars, gear~cyl, value.var = "disp", sum) gear 4 6 8 1 3 120.1 483.0 4291.4 2 4 821.0 655.2 0.0 3 5 215.4 145.0 652.0 One can do mtcars %>% group_by(gear, cyl) %>% summarise(disp = sum(disp)) %>% spread(cyl, disp) Source: local data frame [3 x 4] Groups: gear [3] gear `4` `6` `8` * <dbl> <dbl> <dbl> <dbl> 1 3 120.1 483.0 4291.4 2 4 821.0 655.2 NA 3 5 215.4 145.0 652.0 I'll appreciate any insight on whether this is an optimal solution, and if it's not, what would be better and why
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:897025", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642339" }
3d57db50015e2fa7027813f31199f6a65b2ec9ab
Stackoverflow Stackexchange Q: Can you convert a string with brackets and array formatting into an array? I am processing a CSV file, and in one of the columns are cells that have the a string in an array format. Here is what accessing those cells looks like: $csv = Import-Csv $filelocation foreach ($line in $csv) { Write-Host $line.ColumnName } Output: [Property=[value1,value2,value3]] [Property=[value1,value2]] ... You can see that each cell outputs a string with an array structure. I want to treat each individual string as an array with Property[0] = value1, etc. Is there a simple way to do this? Otherwise, I assume I will need to use Reg Ex. A: Oh! Sorry...dont see the file content: ,,,,,"[AsymmetricKey=[]]","[AppAddress=[[AddressType=Reply,A‌​ddress=urn:ietf:wg:o‌​auth:2.0:oob]]]","[A‌​ppAuxiliaryId=[]]",,‌​,, Ok...if all file content like this we can do somethisng like: $patch = get-content 'D:\test\testing!.csv' $pl = $patch.Length - 1 for ($i=0 ; $i -le $pl ; $i++) { $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[0] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[1] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[2] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[3] }
Q: Can you convert a string with brackets and array formatting into an array? I am processing a CSV file, and in one of the columns are cells that have the a string in an array format. Here is what accessing those cells looks like: $csv = Import-Csv $filelocation foreach ($line in $csv) { Write-Host $line.ColumnName } Output: [Property=[value1,value2,value3]] [Property=[value1,value2]] ... You can see that each cell outputs a string with an array structure. I want to treat each individual string as an array with Property[0] = value1, etc. Is there a simple way to do this? Otherwise, I assume I will need to use Reg Ex. A: Oh! Sorry...dont see the file content: ,,,,,"[AsymmetricKey=[]]","[AppAddress=[[AddressType=Reply,A‌​ddress=urn:ietf:wg:o‌​auth:2.0:oob]]]","[A‌​ppAuxiliaryId=[]]",,‌​,, Ok...if all file content like this we can do somethisng like: $patch = get-content 'D:\test\testing!.csv' $pl = $patch.Length - 1 for ($i=0 ; $i -le $pl ; $i++) { $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[0] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[1] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[2] $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[3] } A: If you want to search some info, think its can be work (but not sure): $patch = get-content 'D:\test\testing!.csv' $pl = $patch.Length - 1 for ($i=0 ; $i -le $pl ; $i++) { $regex = "urn:ietf:wg:o‌​auth:2.0:o2b" $val = $patch[$i].Replace(",,,,,","").Replace(",,‌​,,","").Replace("Reply,A‌​ddress","Reply.A‌​ddress").Split(",")[1] if ($val.Contains($regex)) { $val } } A: You try to do something like this: $csv = Import-Csv Path:\testing!.csv -Header V1 foreach ($line in $csv) { $obj = New-Object -TypeName PSObject -Property @{ First = $line } #| select First # @{Name='First';Expression={($_.First).Split(";")[1]}} $obj1 = $obj | select -ExpandProperty First $obj1.V1 }
stackoverflow
{ "language": "en", "length": 239, "provenance": "stackexchange_0000F.jsonl.gz:897044", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642388" }
e987eb833f4eb58d9041756bda715a8c630d316d
Stackoverflow Stackexchange Q: Precompiled assets in Rails test environment not used I'm using Rails 5.1.1 and for our rspec feature tests we want would like to use precompiled assets before running all feature tests. (The main reason for this is because capybara-webkit doesn't support javascript es6 features) The assets successfully precompile with RAILS_ENV=test rake assets:precompile however capybara-webkit doesn't appear to use the precompiled assets. config/environment/test.rb looks like this config.assets.prefix = "/assets_test" config.assets.compile = true config.serve_static_assets = true config.assets.js_compressor = Uglifier.new( harmony: true #es6 support ) What do I need to add for test to use the precompiled assets? A: You'll need to set config.assets.compile = false in your test.rb to indicate to Rails that it should only use static (precompiled) assets.
Q: Precompiled assets in Rails test environment not used I'm using Rails 5.1.1 and for our rspec feature tests we want would like to use precompiled assets before running all feature tests. (The main reason for this is because capybara-webkit doesn't support javascript es6 features) The assets successfully precompile with RAILS_ENV=test rake assets:precompile however capybara-webkit doesn't appear to use the precompiled assets. config/environment/test.rb looks like this config.assets.prefix = "/assets_test" config.assets.compile = true config.serve_static_assets = true config.assets.js_compressor = Uglifier.new( harmony: true #es6 support ) What do I need to add for test to use the precompiled assets? A: You'll need to set config.assets.compile = false in your test.rb to indicate to Rails that it should only use static (precompiled) assets.
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:897112", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642590" }
8d5a23691949f3f8e65d287ebbedf1f8cde5a8ae
Stackoverflow Stackexchange Q: Java 8 BasicFileAttributes.creationTime() returning different hour value I have this code snippet using Java 8 to get the Creation Date Time of a specific file: Path path = Paths.get("D:\\SampleFile.txt"); BasicFileAttributes attributes = null; try { attributes = Files.readAttributes(path, BasicFileAttributes.class); System.out.println("Creation Date Time: " + attributes.creationTime()); } catch(IOException ioe) { ioe.printStackTrace(); } The real creation hour of the file I am using as an example differs by 6 hours from the one the above code snippet displays: Real date time: 2017-02-05T10:34:28 This code time: 2017-02-05T16:34:28.247156Z Does anybody know what is the reason of this difference and how to get the correct create date time value ? Thank you in advance! A: The FileTime class assumes UTC as the default time zone for printing. If you want to print it in your system's time zone, you can convert it to a ZonedDateTime like this: attributes.creationTime().toInstant().atZone(ZoneId.systemDefault())
Q: Java 8 BasicFileAttributes.creationTime() returning different hour value I have this code snippet using Java 8 to get the Creation Date Time of a specific file: Path path = Paths.get("D:\\SampleFile.txt"); BasicFileAttributes attributes = null; try { attributes = Files.readAttributes(path, BasicFileAttributes.class); System.out.println("Creation Date Time: " + attributes.creationTime()); } catch(IOException ioe) { ioe.printStackTrace(); } The real creation hour of the file I am using as an example differs by 6 hours from the one the above code snippet displays: Real date time: 2017-02-05T10:34:28 This code time: 2017-02-05T16:34:28.247156Z Does anybody know what is the reason of this difference and how to get the correct create date time value ? Thank you in advance! A: The FileTime class assumes UTC as the default time zone for printing. If you want to print it in your system's time zone, you can convert it to a ZonedDateTime like this: attributes.creationTime().toInstant().atZone(ZoneId.systemDefault()) A: As per FileTime.toString() documentation the value is always presented as UTC time zone: Hence the "Z" at the end. A: As per Oracle doc says: If the file system implementation does not support a time stamp to indicate the time when the file was created then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z). your file system implementation could doesn't support this, I think this is the last modified date.
stackoverflow
{ "language": "en", "length": 225, "provenance": "stackexchange_0000F.jsonl.gz:897125", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642627" }
e5848f68ee4a53e9752bde0fb1d3139bfbe6edad
Stackoverflow Stackexchange Q: How can I intercept some HTTP request fallback to custom file? I use win.loadURL('http://example.com/index.html') to load a page, and I want to intercept this request fallback to custom file like: protocol.interceptStringProtocol('http', (request, callback) => { ... callback({ data: fs.readFileSync(path.normalize(${__dirname}/index.html), 'utf-8') }) }) this will intercept all HTTP requests from this page. How can I do only intercept some HTTP requests?
Q: How can I intercept some HTTP request fallback to custom file? I use win.loadURL('http://example.com/index.html') to load a page, and I want to intercept this request fallback to custom file like: protocol.interceptStringProtocol('http', (request, callback) => { ... callback({ data: fs.readFileSync(path.normalize(${__dirname}/index.html), 'utf-8') }) }) this will intercept all HTTP requests from this page. How can I do only intercept some HTTP requests?
stackoverflow
{ "language": "en", "length": 61, "provenance": "stackexchange_0000F.jsonl.gz:897141", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642688" }
9354374112f44c56bec942e8856aa23bdeb8003b
Stackoverflow Stackexchange Q: How to import component in react native past two folders? Whenever I try to import a component that is two or more folders back I get an issue. Using ../Folder works fine, but if I try to use .../Folder I get a module error. How do I get through the directory? A: If you are trying to import for example index.css, case 1: Same folder import './index.css'; case 2: one dir up import '../index.css'; case 3: two dir up import '../..index.css';
Q: How to import component in react native past two folders? Whenever I try to import a component that is two or more folders back I get an issue. Using ../Folder works fine, but if I try to use .../Folder I get a module error. How do I get through the directory? A: If you are trying to import for example index.css, case 1: Same folder import './index.css'; case 2: one dir up import '../index.css'; case 3: two dir up import '../..index.css'; A: Use ../.. to go up two directories. A: Simply go back by one level using "../" Now for 2 levels and so on append "../" This is for 2 level back. ../../YOUR_PATH/FILE_NAME example: /src/component/form/file1.js If above file need to reach another file in dir parallel to 'component' as in above path i.e. '/src/assets/file.css' so path in file1.js would be as following: ../../assets/file.css
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:897151", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642708" }
08d45b36e13cd8577affc154f224c57816dfd294
Stackoverflow Stackexchange Q: Kotlin: Is local function passed to inlined functions as parameter inlined? When passing a lambda or anonymous function to inlined functions as a parameter, it's quite simple, the code is pasted to the calling position, but when passing a local function as a parameter, the result seems different(shown as below). I wonder if it's inlined? Why or why not? For example: inline fun foo(arg: () -> Int): Int { return arg() } fun bar(): Int { return 0 } fun main(args: Array<String>) { foo(::bar) } And decompiled Java code: public final class InlinedFuncKt { public static final int foo(@NotNull Function0 arg) { Intrinsics.checkParameterIsNotNull(arg, "arg"); return ((Number)arg.invoke()).intValue(); } public static final int bar() { return 0; } public static final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); bar(); } } A: bar() is not declared to be inlined. So why would you expect it to be inlined?! In other words: it would be simply wrong that the signature of method A affects (implicitly) the signature of another method B. Your idea would (somehow) affect "semantics" of bar() - just because you used bar() as argument to another method call.
Q: Kotlin: Is local function passed to inlined functions as parameter inlined? When passing a lambda or anonymous function to inlined functions as a parameter, it's quite simple, the code is pasted to the calling position, but when passing a local function as a parameter, the result seems different(shown as below). I wonder if it's inlined? Why or why not? For example: inline fun foo(arg: () -> Int): Int { return arg() } fun bar(): Int { return 0 } fun main(args: Array<String>) { foo(::bar) } And decompiled Java code: public final class InlinedFuncKt { public static final int foo(@NotNull Function0 arg) { Intrinsics.checkParameterIsNotNull(arg, "arg"); return ((Number)arg.invoke()).intValue(); } public static final int bar() { return 0; } public static final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); bar(); } } A: bar() is not declared to be inlined. So why would you expect it to be inlined?! In other words: it would be simply wrong that the signature of method A affects (implicitly) the signature of another method B. Your idea would (somehow) affect "semantics" of bar() - just because you used bar() as argument to another method call. A: As you can in the decompiled code, kotlin does not inline bar in your case, but it does inline it if it is declared as inline fun bar(). The rule is that lambdas are inlined when they are passed to an inlined function. In all other cases like passing a function reference or a lambda object, no inlining is done.
stackoverflow
{ "language": "en", "length": 250, "provenance": "stackexchange_0000F.jsonl.gz:897191", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642823" }
e366e2bbc46244e2553df8a16873c5e4182a350b
Stackoverflow Stackexchange Q: Did View's draw method can run on background thread in Android? I want to capture screen on background thread.So I use a thread to do this job,like this: private void captureScreen(final Context context) { new Thread(){ @Override public void run() { View view = ((Activity) context).findViewById(android.R.id.content); Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); if (null != bmp) { view.draw(new Canvas(bmp)); stack.push(bmp); } } }.start(); } most time there is no problem, but sometimes this will crash caused by "only original thread can touch this", so make view.draw() run on other thread is right things to do or did you have better method to capture screen on background thread? A: The issue is that you do your code not in UI thread. Android provides several ways to use UI thread: MainActivity.this.runOnUiThread(new Runnable() { public void run() { captureScreen(); } }); or MainActivity.this.myView.post(new Runnable() { public void run() { captureScreen(); } }); and private class BackgroundTask extends AsyncTask<String, Void, Bitmap> { ....... protected void onPostExecute(Bitmap result) { captureScreen(result); } } And you need to refactor your captureScreen(); method to not create new Thread() just do screenshot.
Q: Did View's draw method can run on background thread in Android? I want to capture screen on background thread.So I use a thread to do this job,like this: private void captureScreen(final Context context) { new Thread(){ @Override public void run() { View view = ((Activity) context).findViewById(android.R.id.content); Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); if (null != bmp) { view.draw(new Canvas(bmp)); stack.push(bmp); } } }.start(); } most time there is no problem, but sometimes this will crash caused by "only original thread can touch this", so make view.draw() run on other thread is right things to do or did you have better method to capture screen on background thread? A: The issue is that you do your code not in UI thread. Android provides several ways to use UI thread: MainActivity.this.runOnUiThread(new Runnable() { public void run() { captureScreen(); } }); or MainActivity.this.myView.post(new Runnable() { public void run() { captureScreen(); } }); and private class BackgroundTask extends AsyncTask<String, Void, Bitmap> { ....... protected void onPostExecute(Bitmap result) { captureScreen(result); } } And you need to refactor your captureScreen(); method to not create new Thread() just do screenshot.
stackoverflow
{ "language": "en", "length": 184, "provenance": "stackexchange_0000F.jsonl.gz:897203", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642869" }
f4e5ca766cb5d9934db4354dabbb7d3cdf5f9d55
Stackoverflow Stackexchange Q: React manually fire mouseover event Is there anyway to trigger React's mouseover and mouseenter event? It's possible to fire: ReactDOM.findDOMNode(someNode).focus(); ReactDOM.findDOMNode(someNode).click(); Is there a similar way to fire mouseenter? I need to do a complicated React event with a 3rd party library. A: From @Jonathan's answer in this question: Trigger onmouseover event programmatically in JavaScript This worked for me: function fireEvent(elementId, eventName) { if(document.getElementById(elementId) != null) { if(document.getElementById(elementId).fireEvent) { document.getElementById(elementId).fireEvent('on' + eventName); } else { var evObj = document.createEvent('Events'); evObj.initEvent(eventName, true, false); document.getElementById(elementId).dispatchEvent(evObj); } } } Then you can call it like this: fireEvent(elementId, "mouseover");
Q: React manually fire mouseover event Is there anyway to trigger React's mouseover and mouseenter event? It's possible to fire: ReactDOM.findDOMNode(someNode).focus(); ReactDOM.findDOMNode(someNode).click(); Is there a similar way to fire mouseenter? I need to do a complicated React event with a 3rd party library. A: From @Jonathan's answer in this question: Trigger onmouseover event programmatically in JavaScript This worked for me: function fireEvent(elementId, eventName) { if(document.getElementById(elementId) != null) { if(document.getElementById(elementId).fireEvent) { document.getElementById(elementId).fireEvent('on' + eventName); } else { var evObj = document.createEvent('Events'); evObj.initEvent(eventName, true, false); document.getElementById(elementId).dispatchEvent(evObj); } } } Then you can call it like this: fireEvent(elementId, "mouseover"); A: Have you tried using the React Synthetic Events? Here's an example: class App extends React.Component { onEnter() { console.log('enter'); } onOver() { console.log('over'); } render() { return ( <div style={{ backgroundColor: 'red', padding: '20px' }} onMouseOver={this.onOver}> <h1 onMouseEnter={this.onEnter}>Hello World</h1> </div> ); } } ReactDOM.render(<App/>, document.getElementById('mainContainer')); And here's the jfiddle for the above code.
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:897210", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44642901" }
5816bba55a4ccb4b8738926391fae429405b57fb
Stackoverflow Stackexchange Q: Does Node.js need a job queue? Say I have a express service which sends email: app.post('/send', function(req, res) { sendEmailAsync(req.body).catch(console.error) res.send('ok') }) this works. I'd like to know what's the advantage of introducing a job queue here? like Kue. A: Basically, the point of a queue would simply be to give you more control over their execution. This could be for things like throttling how many you send, giving priority to other actions first, evening out the flow (i.e., if 10000 get sent at the same time, you don't try to send all 10000 at the same time and kill your server). What exactly you use your queue for, and whether it would be of any benefit, depends on your actual situation and use cases. At the end of the day, it's just about controlling the flow.
Q: Does Node.js need a job queue? Say I have a express service which sends email: app.post('/send', function(req, res) { sendEmailAsync(req.body).catch(console.error) res.send('ok') }) this works. I'd like to know what's the advantage of introducing a job queue here? like Kue. A: Basically, the point of a queue would simply be to give you more control over their execution. This could be for things like throttling how many you send, giving priority to other actions first, evening out the flow (i.e., if 10000 get sent at the same time, you don't try to send all 10000 at the same time and kill your server). What exactly you use your queue for, and whether it would be of any benefit, depends on your actual situation and use cases. At the end of the day, it's just about controlling the flow. A: Does Node.js need a job queue? Not generically. A job queue is to solve a specific problem, usually with more to do than a single node.js process can handle at once so you "queue" up things to do and may even dole them out to other processes to handle. You may even have priorities for different types of jobs or want to control the rate at which jobs are executed (suppose you have a rate limit cap you have to remain below on some external server or just don't want to overwhelm some other server). One can also use nodejs clustering to increase the amount of tasks that your node server can handle. So, a queue is about controlling the execution of some CPU or resource intensive task when you have more of it to do than your server can easily execute at once. A queue gives you control over the flow of execution. I don't see any reason for the code you show to use a job queue unless you were doing a lot of these all at once. The specific https://github.com/OptimalBits/bull library or Kue library you mention lists these features on its NPM page: * *Delayed jobs *Distribution of parallel work load *Job event and progress pubsub *Job TTL *Optional retries with backoff *Graceful workers shutdown *Full-text search capabilities *RESTful JSON API *Rich integrated UI *Infinite scrolling *UI progress indication *Job specific logging So, I think it goes without saying that you'd add a queue if you needed some specific queuing features and you'd use the Kue library if it had the best set of features for your particular problem. In case it matters, your code is sending res.send("ok") before it finishes with the async tasks and before you know if it succeeded or not. Sometimes there are reasons for doing that, but sometimes you want to communicate back whether the operation was successful or not (which you are not doing).
stackoverflow
{ "language": "en", "length": 462, "provenance": "stackexchange_0000F.jsonl.gz:897253", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643030" }
8bf941a8111ec7a373b38e4d69034f30d37bd216
Stackoverflow Stackexchange Q: Multiple Knapsack using Dynamic Programming I'm wondering if there is a reasonable way of solving Multiple Knapsack using DP. I get the point in 0-1 Knapsack Problem. The recurrence is quite straightforward, add item/ not add item. dp[item][capacity] = max{ value[item] + dp[item - 1][capacity - weight[item]], dp[item - 1][capacity]} However, I cannot see how to get an recurrence equation for the Multiple Knapsack. Should I extend the recurrence equation to "add item bag 1/ not add item bag 1/ add item bag 2/ not add item bag 2" and so on and so forth? It does not seem a good approach as the number of bags becomes larger and larger.
Q: Multiple Knapsack using Dynamic Programming I'm wondering if there is a reasonable way of solving Multiple Knapsack using DP. I get the point in 0-1 Knapsack Problem. The recurrence is quite straightforward, add item/ not add item. dp[item][capacity] = max{ value[item] + dp[item - 1][capacity - weight[item]], dp[item - 1][capacity]} However, I cannot see how to get an recurrence equation for the Multiple Knapsack. Should I extend the recurrence equation to "add item bag 1/ not add item bag 1/ add item bag 2/ not add item bag 2" and so on and so forth? It does not seem a good approach as the number of bags becomes larger and larger.
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:897257", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643042" }
3ecf16dd8daddd3b1c4e70de9f2d6d02e9bc2769
Stackoverflow Stackexchange Q: Running development server with create-react-app inside of a docker container I am trying to run the create-react-app's development server inside of a docker container and have it recompile and send the changed app code to the client for development purposes, but it isn't picking up the changes from inside of the docker container. (Of course, I have the working directory of the app as a volume for the container.) Is there a way to do make this work? A: Actually, I found an answer here. Apparently create-react-app uses chokidar to watch file changes, and it has a flag CHOKIDAR_USEPOLLING to use polling to watch for file changes instead. So CHOKIDAR_USEPOLLING=true npm start should fix the problem. As for me, I set CHOKIDAR_USEPOLLING=true in my environment variable for the docker container and just started the container.
Q: Running development server with create-react-app inside of a docker container I am trying to run the create-react-app's development server inside of a docker container and have it recompile and send the changed app code to the client for development purposes, but it isn't picking up the changes from inside of the docker container. (Of course, I have the working directory of the app as a volume for the container.) Is there a way to do make this work? A: Actually, I found an answer here. Apparently create-react-app uses chokidar to watch file changes, and it has a flag CHOKIDAR_USEPOLLING to use polling to watch for file changes instead. So CHOKIDAR_USEPOLLING=true npm start should fix the problem. As for me, I set CHOKIDAR_USEPOLLING=true in my environment variable for the docker container and just started the container. A: Polling, suggested in the other answer, will cause much higher CPU usage and drain your battery quickly. You should not need CHOKIDAR_USEPOLLING=true since file system events should be propagated to the container. Since recently this should work even if your host machine runs Windows: https://docs.docker.com/docker-for-windows/release-notes/#docker-desktop-community-2200 (search for "inotify"). However, when using Docker for Mac, this mechanism seems to be failing sometimes: https://github.com/docker/for-mac/issues/2417#issuecomment-462432314 Restarting the Docker daemon helps in my case. A: If your changes are not being picked up, it is probably a problem with the file watching mechanism. A workaround for this issue is to configure polling. You can do that globally as explained by @Javascriptonian, but you can do this also locally via the webpack configuration. This has the benefit of specifying ignored folders (e.g. node_modules) which slow down the watching process (and lead to high CPU usage) when using polling. In your webpack configuration, add the following configuration: devServer: { watchOptions: { poll: true, // or use an integer for a check every x milliseconds, e.g. poll: 1000 ignored: /node_modules/ // otherwise it takes a lot of time to refresh } } source: documentation webpack watchOptions If you are having the same issue with nodemon in a back-end Node.js project, you can use the --legacy-watch flag (short -L) which starts polling too. npm exec nodemon -- --legacy-watch --watch src src/main.js or in package.json: "scripts": { "serve": "nodemon --legacy-watch --watch src src/main.js" } documentation: nodemon legacy watch A: If you use linux then you don't need to use CHOKIDAR_USEPOLLING=true A: With react-script v5.0.0 onward the command is WATCHPACK_POLLING=true instead of CHOKIDAR_USEPOLLING=true A: Clear Answer for react-script v5.0.0 onward 1- Create a .env file in the root directory of the project 2- Add the WATCHPACK_POLLING=true to the .env file 3- build new image 4- run new container 5- verify that the changes being detected. Or you can just add WATCHPACK_POLLING=true to your script for making the container like this docker run --name my-app -it --rm -v $(pwd)/src:/app/src -p 3000:3000 -e WATCHPACK_POLLING=true myapp A: In my case, I was running the docker run command in a Git bash command line (on Windows) and the hot reloading was not working. Using react-script v5.0.0, setting WATCHPACK_POLLING=true in the .env file and running the docker run command in PowerShell worked. docker run -it --rm -v ${PWD}:/app -v /app/node_modules -p 3000:3000 -e CHOKIDAR_USEPOLLING=true myapp
stackoverflow
{ "language": "en", "length": 527, "provenance": "stackexchange_0000F.jsonl.gz:897258", "question_score": "21", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643045" }
12a3b9c9e1bf74e7ac0d04324f798bb57859f407
Stackoverflow Stackexchange Q: PayPal payment integration for REACT NATIVE with latest lib android + ios Can any body provide a swipe solution with latest react-native PayPal library ? I have spent a week but not getting a proper solution. There are many old and incomplete solution on net but not a proper and complete solution for new developers. Resources : https://www.npmjs.com/package/react-native-paypal https://github.com/MattFoley/react-native-paypal https://github.com/sharafat/sample-code-php A: As Danial suggested above, if you do not want your app do be dependant on third party react native libraries then try integrating paypal with a WebView wrapper. Here is how I did it Integrating Paypal in your react native app
Q: PayPal payment integration for REACT NATIVE with latest lib android + ios Can any body provide a swipe solution with latest react-native PayPal library ? I have spent a week but not getting a proper solution. There are many old and incomplete solution on net but not a proper and complete solution for new developers. Resources : https://www.npmjs.com/package/react-native-paypal https://github.com/MattFoley/react-native-paypal https://github.com/sharafat/sample-code-php A: As Danial suggested above, if you do not want your app do be dependant on third party react native libraries then try integrating paypal with a WebView wrapper. Here is how I did it Integrating Paypal in your react native app A: Unfortunately, there isn't a single repo that is up to date and maintains by the community as far as I know. That's why your options are limited. Utilize PayPal APIs PayPal has various APIs for different use cases that you can pick up without worrying about the SDK itself. They give you lots of those functionalities, sure it might not be smooth as the SDK itself, but it can solve your problem, nicely. In case you are developing for both mobile and the web, you can use your APIs for both of them. Becuase they do not depend on the specific platform. Solution My solution for this is pretty straightforward. Do not use the PayPal SDK if you don't want to mess with Native functionality and not exactly sure why you need it. PayPal has a various set of APIs that you can use on your server side or client side without touching the native code. Here I give you a simple scenario that using ExpressCheckout APIs and handle on the server side. For all below steps, you can use PHP, Node or any other server-side languages. I only briefly tell you the steps and the rest are on you! 1. Create an access token for your transaction. Follow below link for details. https://developer.paypal.com/docs/integration/direct/make-your-first-call 2. Create a payment transaction. You need to pass your payment details such as currency and total amount. In this step, you can pass your 'return_url' and cancel_url too. Make sure to attach your order id or order code to both of them, so you can track the orders when either of them triggered and change your order status accordingly. https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/advanced-payments-api/create-express-checkout-payments/ 3. Send the payment URL to React Native and load it by WebView. In this Step, you can use the WebView component in React Native and load the PayPal URL inside. Later for checking whether the payment is done, you can either use a throttling function or use other alternatives such as WebSocket. The goal here is to know whether the transaction is done or canceled. When the payment is done. get rid of the WebView and redirect the user to thank you page and any other things you need to do after the user payment is done. There might be more elegant ways to do this, but I believe for simple scenarios (or even more!) this is sufficient. A: Screenshot attached link= https://www.npmjs.com/package/react-native-paypal-lib Use this Library for React Native Application It's very simple to implements.follow these steps for implementation.
stackoverflow
{ "language": "en", "length": 519, "provenance": "stackexchange_0000F.jsonl.gz:897274", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643092" }
f1b8e64d8f638c22cfd5f70407fac45b810a2277
Stackoverflow Stackexchange Q: How to include XML comments files in Swagger in ASP.NET Core I need Swagger generate API documentation include UI to test operations. When use ASP.NET in my project, deps XML files are generated, everything is OK, look like this: But when I use ASP.NET Core in my project, deps XML files are not generated. It just generates my project comments XML file, look like this: And when I deploy my project to IIS, the project XML not in deploy files list. A: I use this way to register XML file: foreach (var filePath in System.IO.Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)), "*.xml")) { try { c.IncludeXmlComments(filePath); } catch (Exception e) { Console.WriteLine(e); } }
Q: How to include XML comments files in Swagger in ASP.NET Core I need Swagger generate API documentation include UI to test operations. When use ASP.NET in my project, deps XML files are generated, everything is OK, look like this: But when I use ASP.NET Core in my project, deps XML files are not generated. It just generates my project comments XML file, look like this: And when I deploy my project to IIS, the project XML not in deploy files list. A: I use this way to register XML file: foreach (var filePath in System.IO.Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)), "*.xml")) { try { c.IncludeXmlComments(filePath); } catch (Exception e) { Console.WriteLine(e); } } A: Microsoft themselves have documentation for this question available here, I found it quite helpful. In short, the following changes are required: Startup.cs, ConfigureServices() services.AddSwaggerGen(c => { ... c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml")); }); {project_name}.csproj <PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> <NoWarn>$(NoWarn);1591</NoWarn> </PropertyGroup> A: For .Net Core 3.1 and NuGet xml files I add this to project file: <Project> <!-- Here is you other csproj code --> <Target Name="_ResolveCopyLocalNuGetPackageXmls" AfterTargets="ResolveReferences"> <ItemGroup> <ReferenceCopyLocalPaths Include="@(ReferenceCopyLocalPaths->'%(RootDir)%(Directory)%(Filename).xml')" Condition="'%(ReferenceCopyLocalPaths.NuGetPackageId)' != '' and Exists('%(RootDir)%(Directory)%(Filename).xml')" /> </ItemGroup> </Target> </Project> P.S. This is modified code from https://github.com/ctaggart/SourceLink#known-issues (2.8.3 version) A: For .Net Core 2 upto 3.1 versions it's slightly different, for those who come across it using a newer version you would create your private void ConfigureSwagger(IServiceCollection services) constructor, add the reference to swagger services.AddSwaggerGen(c => { c.SwaggerDoc(/*populate with your info */); then define a new parameter which will be the path for your swagger XML documentation: var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml"); c.IncludeXmlComments(filePath);. It should look something like this: private void ConfigureSwagger(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "YourApiName", Description = "Your Api Description.", TermsOfService = "None", Contact = new Contact {Name = "Contact Title", Email = "contactemailaddress@domain.com", Url = ""} }); var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml"); c.IncludeXmlComments(filePath); }); } For this to work, you need to ensure that the build's Output has the documentation file checked (see red arrow) and the path set appropriately. I've noticed that you can strip the pre-filled path and just use bin\YourApiName.xml, just like below: Update: If these changes aren't working as expected, please check the configuration. In the example, the config is set to Debug. If you're running from a different environment (env) you may need to check whether these setting apply to that env. Update 2: Since the release of OpenAPI I thought I'd update my example (below) to show a more accurate reference to this specification which should follow something similar to: services.AddSwaggerGen(o => { o.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API Name", Description = "Your API Description", Version = "v1", TermsOfService = null, Contact = new OpenApiContact { // Check for optional parameters }, License = new OpenApiLicense { // Optional Example // Name = "Proprietary", // Url = new Uri("https://someURLToLicenseInfo.com") } }); }); A: The Microsoft documentation here suggests using a DocumentationFile tag in your csproj file. Just make sure you have the correct build for your deployment (Release/Debug): <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DocumentationFile>bin\Release\netcoreapp2.0\APIProject.xml</DocumentationFile> </PropertyGroup> I just used this in practice (with the tweaks below) and it works well: <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DocumentationFile>bin\Release\$(TargetFramework)\$(MSBuildProjectName).xml</DocumentationFile> <NoWarn>1701;1702;1705;1591</NoWarn> </PropertyGroup> A: Enable "XML documentation file" checkbox for each project you depend on to generate their files on build. It could be done at project's properties Build tab. To include all XML files on deploy, add this target to the published project's csproj file: <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish"> <ItemGroup> <DocFile Include="bin\*\*\*.xml" /> </ItemGroup> <Copy SourceFiles="@(DocFile)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" /> </Target> This will copy all XML files from bin folder and nested subfolders (like bin\Release\netcoreapp1.1\) to publish dir. Of course you can customize that target. A: In .net core 3.1,Please follow the below steps: Go to Startup.cs Page and add the below code public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title="Book Store API", Version="v1", Description="This is an educational site"}); var xfile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xpath = Path.Combine(AppContext.BaseDirectory,xfile); c.IncludeXmlComments(xpath); }); services.AddControllers(); } After that go to Properties of the project and click on the XML Documentation File option and save it.
stackoverflow
{ "language": "en", "length": 687, "provenance": "stackexchange_0000F.jsonl.gz:897292", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643151" }
d518d52b0669ca92ac9743142136299e882bcd05
Stackoverflow Stackexchange Q: Target BeforeBuild doesn't work in csproj I'm trying to use the target event "BeforeBuild" in .csproj (vs2017), but it's not working. Someone would know what is wrong: <Project DefaultTargets="BeforeBuild" Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <Target Name="BeforeBuild"> <Message Text="Test123"></Message> </Target> </Project> The expected result is a message: Test123 on output. []s A: BeforeBuild dosen't working in csproj That because Before/AfterTarget in csproj gets overridden by SDKs target file. if you're using the new Sdk attribute on the Project element, it's not possible to put a target definition after the default .targets import. This can lead to targets that people put in their project files unexpectedly not running, with no indication why unless you examine the log file and see the message that the target has been overridden. dsplaisted have filed Microsoft/msbuild#1680 for this issue. As a workaround, you can do the following: <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> <PreBuildEvent /> </PropertyGroup> <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> <Target Name="BeforeBuild"> <Message Text="Test123"></Message> </Target> Or: <Target Name="test" BeforeTargets="Build"> <Message Text="Test123" /> </Target>
Q: Target BeforeBuild doesn't work in csproj I'm trying to use the target event "BeforeBuild" in .csproj (vs2017), but it's not working. Someone would know what is wrong: <Project DefaultTargets="BeforeBuild" Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <Target Name="BeforeBuild"> <Message Text="Test123"></Message> </Target> </Project> The expected result is a message: Test123 on output. []s A: BeforeBuild dosen't working in csproj That because Before/AfterTarget in csproj gets overridden by SDKs target file. if you're using the new Sdk attribute on the Project element, it's not possible to put a target definition after the default .targets import. This can lead to targets that people put in their project files unexpectedly not running, with no indication why unless you examine the log file and see the message that the target has been overridden. dsplaisted have filed Microsoft/msbuild#1680 for this issue. As a workaround, you can do the following: <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> <PreBuildEvent /> </PropertyGroup> <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> <Target Name="BeforeBuild"> <Message Text="Test123"></Message> </Target> Or: <Target Name="test" BeforeTargets="Build"> <Message Text="Test123" /> </Target> A: From the official docs: Warning Be sure to use different names than the predefined targets listed in the table in the previous section (for example, we named the custom build target here CustomAfterBuild, not AfterBuild), since those predefined targets are overridden by the SDK import which also defines them. You don't see the import of the target file that overrides those targets, but it is implicitly added to the end of the project file when you use the Sdk attribute method of referencing an SDK.
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:897329", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643288" }
6d47e41d735b8f6e881b886a93dd2686be7c9a84
Stackoverflow Stackexchange Q: How to make Sqoop to work with two different versions of oracle jdbc driver I am to use Sqoop to work with two versions of oracle. For each version of the oracle, we need a specific version of oracle jdbc driver jar to talk with oracle. I put the two oracle jdbc jars into $SQOOP_HOME/lib, which will lead to classpath loading issue(sqoop works well for one oracle, but doesn't work for the other oracle) I would ask if there is a way to specify the jdbc jar instead of loading it from $SQOOP_HOME/lib (which is the default behavior) when I kick off the sqoop command to load data into oracle.
Q: How to make Sqoop to work with two different versions of oracle jdbc driver I am to use Sqoop to work with two versions of oracle. For each version of the oracle, we need a specific version of oracle jdbc driver jar to talk with oracle. I put the two oracle jdbc jars into $SQOOP_HOME/lib, which will lead to classpath loading issue(sqoop works well for one oracle, but doesn't work for the other oracle) I would ask if there is a way to specify the jdbc jar instead of loading it from $SQOOP_HOME/lib (which is the default behavior) when I kick off the sqoop command to load data into oracle.
stackoverflow
{ "language": "en", "length": 111, "provenance": "stackexchange_0000F.jsonl.gz:897332", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643297" }
ca241f6db790ec5bd647e379f961393247a545e0
Stackoverflow Stackexchange Q: Code splitting `import` breaks Jest tests I'm using the code splitting feature of webpack, but it seems that jest doesn't recognize the import() function: import('myModule').then(function (myModule) { ^^^^^^ SyntaxError: Unexpected token import I don't have any special setup. My npm test script is simply run jest "test": "jest" How can I make it work? I'm using the latest version of jest 20.0.4 and babel-jest 20.0.3 A: Oh I just found the answer. Simply install this plugin: https://github.com/airbnb/babel-plugin-dynamic-import-node and add it to the .babelrc file: { ... "env": { "test": { "plugins": ["dynamic-import-node"] } } }
Q: Code splitting `import` breaks Jest tests I'm using the code splitting feature of webpack, but it seems that jest doesn't recognize the import() function: import('myModule').then(function (myModule) { ^^^^^^ SyntaxError: Unexpected token import I don't have any special setup. My npm test script is simply run jest "test": "jest" How can I make it work? I'm using the latest version of jest 20.0.4 and babel-jest 20.0.3 A: Oh I just found the answer. Simply install this plugin: https://github.com/airbnb/babel-plugin-dynamic-import-node and add it to the .babelrc file: { ... "env": { "test": { "plugins": ["dynamic-import-node"] } } }
stackoverflow
{ "language": "en", "length": 96, "provenance": "stackexchange_0000F.jsonl.gz:897348", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643340" }
ddbc43fcd3e256cd14eaca88ce336d7cf19757d3
Stackoverflow Stackexchange Q: Django - 'sqlclear' equivalent in Django > 1.9 In Django 1.10.6, I made a model, and ran python manage.py makemigrations and python manage.py migrate, it created a table in MySQL DB. Later I came to know that the table was not required. I searched and found an answer here. But that was for the versions before 1.9. In Django 1.9 sqlclear has been removed. Now my doubt is, how can I drop a table from the DB using Django, for versions greater than 1.9? Is there any sqlclear equivalent in versions greater than 1.9? Kindly help. A: 1. Delete your Model for the Table or comment it out totally 2. python manage.py makemigrations 3. python manage.migrate hope it helps
Q: Django - 'sqlclear' equivalent in Django > 1.9 In Django 1.10.6, I made a model, and ran python manage.py makemigrations and python manage.py migrate, it created a table in MySQL DB. Later I came to know that the table was not required. I searched and found an answer here. But that was for the versions before 1.9. In Django 1.9 sqlclear has been removed. Now my doubt is, how can I drop a table from the DB using Django, for versions greater than 1.9? Is there any sqlclear equivalent in versions greater than 1.9? Kindly help. A: 1. Delete your Model for the Table or comment it out totally 2. python manage.py makemigrations 3. python manage.migrate hope it helps
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:897365", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643383" }
4fbca71ad28e09a0a694b68362878f68a107257f
Stackoverflow Stackexchange Q: RequiresPermission annotations with "allOf" in Kotlin In Kotlin, I'd like to add a method annotation that's equivalent to this RequiresPermission annotation in Java, indicating that multiple permissions are required: @RequiresPermission(allOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) public Location getLocation() { // ... } How can I write this annotation in Kotlin? A: You can pass in an array of items as an annotation parameter with arrayOf: @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)) fun getLocation(): Location { // ... } You can actually get to this solution by just pasting your Java code into a Kotlin file Android Studio as well. Update: since Kotlin 1.2, you can use an array literal syntax as well: @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION]) fun getLocation(): Location { // ... }
Q: RequiresPermission annotations with "allOf" in Kotlin In Kotlin, I'd like to add a method annotation that's equivalent to this RequiresPermission annotation in Java, indicating that multiple permissions are required: @RequiresPermission(allOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) public Location getLocation() { // ... } How can I write this annotation in Kotlin? A: You can pass in an array of items as an annotation parameter with arrayOf: @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)) fun getLocation(): Location { // ... } You can actually get to this solution by just pasting your Java code into a Kotlin file Android Studio as well. Update: since Kotlin 1.2, you can use an array literal syntax as well: @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION]) fun getLocation(): Location { // ... }
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:897373", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643402" }
a84dc8a4c68305257ac001c8f4f9e2b72ee5416b
Stackoverflow Stackexchange Q: Selectively deleting images uploaded to Azure blob (Django/Python project) In a Django (Python) project, I'm using Azure blobs to store photos uploaded by users. The code simply goes something like this: from azure.storage.blob import BlobService blob_service = BlobService(account_name=accountName, account_key=accountKey) blob_service.put_blob( 'pictures', name, # including folder content_str, # image as stream x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control ='public, max-age=3600, s-maxage=86400' ) My question is: what's the equivalent method to delete an uploaded photo in my particular scenario? I'm writing a task to periodically clean up my data models, and so want to get rid of images associated to them as well. A: You should be able to use: blob_service.delete_blob(container_name, blob_name) You can also delete an entire container: blob_service.delete_container(container_name) There are a few extra parameters which will be helpful to you if you're trying to delete snapshots, deal with leases, etc. Note that put_blob() is defined in blockblobservice.py, while delete_blob() is defined in baseblobservice.py (deletes are going to be the same, whether page, block, or append blob).
Q: Selectively deleting images uploaded to Azure blob (Django/Python project) In a Django (Python) project, I'm using Azure blobs to store photos uploaded by users. The code simply goes something like this: from azure.storage.blob import BlobService blob_service = BlobService(account_name=accountName, account_key=accountKey) blob_service.put_blob( 'pictures', name, # including folder content_str, # image as stream x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control ='public, max-age=3600, s-maxage=86400' ) My question is: what's the equivalent method to delete an uploaded photo in my particular scenario? I'm writing a task to periodically clean up my data models, and so want to get rid of images associated to them as well. A: You should be able to use: blob_service.delete_blob(container_name, blob_name) You can also delete an entire container: blob_service.delete_container(container_name) There are a few extra parameters which will be helpful to you if you're trying to delete snapshots, deal with leases, etc. Note that put_blob() is defined in blockblobservice.py, while delete_blob() is defined in baseblobservice.py (deletes are going to be the same, whether page, block, or append blob).
stackoverflow
{ "language": "en", "length": 163, "provenance": "stackexchange_0000F.jsonl.gz:897380", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643421" }
065d671c8259b506fc3bb9af8763c56c876e45f4
Stackoverflow Stackexchange Q: Unable to connect to Google Container Engine I've updated gcloud to the latest version (159.0.0) I created a Google Container Engine node, and then followed the instructions in the prompt. gcloud container clusters get-credentials prod --zone us-west1-b --project myproject Fetching cluster endpoint and auth data. kubeconfig entry generated for prod kubectl proxy Unable to connect to the server: error executing access token command "/Users/me/Code/google-cloud-sdk/bin/gcloud ": exit status Any idea why is it not able to connect? A: You can try to run to see if the config was generated correctly: kubectl config view I had a similar issue when trying to run kubectl commands on a new Kubernetes cluster just created on Google Cloud Platform. The solution for my case was to activate Google Application Default Credentials. You can find a link below on how to activate it. Basically, you need to set an environmental variable to the path of the .json with the credentials from GCP GOOGLE_APPLICATION_CREDENTIALS -> c:\...\..\..Credentials.json exported from Google Cloud https://developers.google.com/identity/protocols/application-default-credentials I found this solution on a kuberenetes github issue: https://github.com/kubernetes/kubernetes/issues/30617 PS: make sure you have also set the environmental variables for: %HOME% to %USERPROFILE% %KUBECONFIG% to %USERPROFILE%
Q: Unable to connect to Google Container Engine I've updated gcloud to the latest version (159.0.0) I created a Google Container Engine node, and then followed the instructions in the prompt. gcloud container clusters get-credentials prod --zone us-west1-b --project myproject Fetching cluster endpoint and auth data. kubeconfig entry generated for prod kubectl proxy Unable to connect to the server: error executing access token command "/Users/me/Code/google-cloud-sdk/bin/gcloud ": exit status Any idea why is it not able to connect? A: You can try to run to see if the config was generated correctly: kubectl config view I had a similar issue when trying to run kubectl commands on a new Kubernetes cluster just created on Google Cloud Platform. The solution for my case was to activate Google Application Default Credentials. You can find a link below on how to activate it. Basically, you need to set an environmental variable to the path of the .json with the credentials from GCP GOOGLE_APPLICATION_CREDENTIALS -> c:\...\..\..Credentials.json exported from Google Cloud https://developers.google.com/identity/protocols/application-default-credentials I found this solution on a kuberenetes github issue: https://github.com/kubernetes/kubernetes/issues/30617 PS: make sure you have also set the environmental variables for: %HOME% to %USERPROFILE% %KUBECONFIG% to %USERPROFILE% A: It looks like the default auth plugin for GKE might be buggy on windows. kubectl is trying to run gcloud to get a token to authenticate to your cluster. If you run kubectl config view you can see the command it tried to run, and run it yourself to see if/why it fails. As Alexandru said, a workaround is to use Google Application Default Credentials. Actually, gcloud container has built in support for doing this, which you can toggle by setting a property: gcloud config set container/use_application_default_credentials true or set environment variable %CLOUDSDK_CONTAINER_USE_APPLICATION_DEFAULT_CREDENTIALS% to true. A: Using GKE, update the credentials from the "Kubernetes Engine/Cluster" management worked for me. The cluster line provides "Connect" button that copy the credentials commands into console. And this refresh the used token. And then kubectl works again. Why my token expired? well, i suppose GCP token are not eternal. So, the button plays the same command automatically that : gcloud container clusters get-credentials your-cluster ... Bruno
stackoverflow
{ "language": "en", "length": 356, "provenance": "stackexchange_0000F.jsonl.gz:897391", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643444" }
1ca91b222f5a154f7b994dc271c06d2aa5cf28a7
Stackoverflow Stackexchange Q: Google Analytics HTTP status -1 when sending hit(s) by request [GAIBatchingDispatcher didSendHits:response:data:error:] id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker]; [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_action" action:@"button_press" label:@"play" value:nil] build]]; When I send the event, I get log: 2017-06-20 11:30:00.541 Right-iOS[28240:626691] INFO: GoogleAnalytics 3.17 -[GAIBatchingDispatcher didSendHits:response:data:error:] (GAIBatchingDispatcher.m:226): Hit(s) dispatched: HTTP status -1
Q: Google Analytics HTTP status -1 when sending hit(s) by request [GAIBatchingDispatcher didSendHits:response:data:error:] id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker]; [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_action" action:@"button_press" label:@"play" value:nil] build]]; When I send the event, I get log: 2017-06-20 11:30:00.541 Right-iOS[28240:626691] INFO: GoogleAnalytics 3.17 -[GAIBatchingDispatcher didSendHits:response:data:error:] (GAIBatchingDispatcher.m:226): Hit(s) dispatched: HTTP status -1
stackoverflow
{ "language": "en", "length": 48, "provenance": "stackexchange_0000F.jsonl.gz:897392", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643448" }
def8d82fde116fe6d6f820f2f7ce295254ff47a3
Stackoverflow Stackexchange Q: React Native [TextInput]: How to change scroll position of multiline TextInput? When my multiple InputText started a new line the scroll position will not scroll to bottom automatically resulting texts from new line not be visible. How to make my multiline InputText to autoscroll to the bottom every time a newline created?
Q: React Native [TextInput]: How to change scroll position of multiline TextInput? When my multiple InputText started a new line the scroll position will not scroll to bottom automatically resulting texts from new line not be visible. How to make my multiline InputText to autoscroll to the bottom every time a newline created?
stackoverflow
{ "language": "en", "length": 53, "provenance": "stackexchange_0000F.jsonl.gz:897412", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643502" }
9c099a170baf295dc9f996fc28472c47cafe0097
Stackoverflow Stackexchange Q: Cannot access external service in Kubernetes AWS I have already made a Kubernetes 1.5 cluster which is running in AWS using KOPS. I have many nodes in there with various instance type such as t2.medium, m3.medium, c4.large and c4.xlarge. But sometimes my Kubernetes pods running on t2.medium, m3.medium, c4.large cannot access external service like Amazon Relational Database Service (RDS), Elasticsearch and external SMS service. For RDS i got an error message PG::ConnectionBad and for others i got timeout. Does the problem come from AWS node instance or from Kubernetes pods? Because i never get an error if using c4.xlarge and up. If the problem come from my AWS instance, why that happened? Thank you
Q: Cannot access external service in Kubernetes AWS I have already made a Kubernetes 1.5 cluster which is running in AWS using KOPS. I have many nodes in there with various instance type such as t2.medium, m3.medium, c4.large and c4.xlarge. But sometimes my Kubernetes pods running on t2.medium, m3.medium, c4.large cannot access external service like Amazon Relational Database Service (RDS), Elasticsearch and external SMS service. For RDS i got an error message PG::ConnectionBad and for others i got timeout. Does the problem come from AWS node instance or from Kubernetes pods? Because i never get an error if using c4.xlarge and up. If the problem come from my AWS instance, why that happened? Thank you
stackoverflow
{ "language": "en", "length": 115, "provenance": "stackexchange_0000F.jsonl.gz:897422", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643527" }
fea74d8ac8da090e61bd0548587c9a8f39f9bfb8
Stackoverflow Stackexchange Q: how to get the last value from a RDD? I want to get the last value of RDD, this my code: val rdd=sc.parallelize(0 to 10,1) val last=rdd.sortBy(x=>{x},false,1).first() println(last) It's so inefficient,anyone has better way?Thanks! A: You can use max function if you are looking to get a last value after sorting rdd.max() Or you can use top function rdd.top(1)
Q: how to get the last value from a RDD? I want to get the last value of RDD, this my code: val rdd=sc.parallelize(0 to 10,1) val last=rdd.sortBy(x=>{x},false,1).first() println(last) It's so inefficient,anyone has better way?Thanks! A: You can use max function if you are looking to get a last value after sorting rdd.max() Or you can use top function rdd.top(1)
stackoverflow
{ "language": "en", "length": 60, "provenance": "stackexchange_0000F.jsonl.gz:897424", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643538" }
73864fce32a27ceaead4812a254aa1884db5d920
Stackoverflow Stackexchange Q: SonarLint Eclipse plugin - purpose of "Issue Locations" and "Rule Description" views I just downloaded the SonarLint Eclipse plugin and successfully launched an analysis on my projet after configuring my SonarQube server. The "SonarLint Report" and "SonarLint On-The-Fly" are correctly populated. However, the "SonarQube Issue Locations" and "SonarQube Rule Description" views remain empty. Why that? What are they supposed to display? I didn't find an answer on the plugin's documentation. A: If you initially open the SonarQube Issue Locations or SonarQube Rule Description Eclipse views on their own (for instance via Quick Access), they will appear empty as you have described in your answer. Instead, you should navigate to the SonarLint On-The-Fly view, select an issue and right-click on it. Then select either Rule description or Issue locations, as shown in the following screenshot: From that point onwards just selecting a different issue will automatically refresh the data in the SonarQube Issue Locations orSonarQube Rule Description views.
Q: SonarLint Eclipse plugin - purpose of "Issue Locations" and "Rule Description" views I just downloaded the SonarLint Eclipse plugin and successfully launched an analysis on my projet after configuring my SonarQube server. The "SonarLint Report" and "SonarLint On-The-Fly" are correctly populated. However, the "SonarQube Issue Locations" and "SonarQube Rule Description" views remain empty. Why that? What are they supposed to display? I didn't find an answer on the plugin's documentation. A: If you initially open the SonarQube Issue Locations or SonarQube Rule Description Eclipse views on their own (for instance via Quick Access), they will appear empty as you have described in your answer. Instead, you should navigate to the SonarLint On-The-Fly view, select an issue and right-click on it. Then select either Rule description or Issue locations, as shown in the following screenshot: From that point onwards just selecting a different issue will automatically refresh the data in the SonarQube Issue Locations orSonarQube Rule Description views.
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:897459", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643643" }
31d99d08708823dc3aa86ad45fa4ec34531c6227
Stackoverflow Stackexchange Q: Android Realm: how to search string is either null or empty I have a very quick question. How to get all records where the particular field (String type) is not null and empty. Currently, I do: String nullStr = null; //temporary null string to pass it to realm. RealmResults<Feedback> feedbacks = realm.where(Feedback.class) .notEqualTo("Comment", nullStr) .notEqualTo("Comment", "") .findAll(); Is this the only way to get record that is not null and empty? How about if the Comment contains only spaces? Is there a way to get record where the field is not null and not contain white-spaces? Thanks A: realm.where(Feedback.class) .isNull("Comment") .or() .equalTo("Comment", "") .findAll(); And if you want the inverse of this, use not().beginGroup()./*query here*/.endGroup()
Q: Android Realm: how to search string is either null or empty I have a very quick question. How to get all records where the particular field (String type) is not null and empty. Currently, I do: String nullStr = null; //temporary null string to pass it to realm. RealmResults<Feedback> feedbacks = realm.where(Feedback.class) .notEqualTo("Comment", nullStr) .notEqualTo("Comment", "") .findAll(); Is this the only way to get record that is not null and empty? How about if the Comment contains only spaces? Is there a way to get record where the field is not null and not contain white-spaces? Thanks A: realm.where(Feedback.class) .isNull("Comment") .or() .equalTo("Comment", "") .findAll(); And if you want the inverse of this, use not().beginGroup()./*query here*/.endGroup()
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:897462", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643649" }
beb2ec958312d05e25b70ca6c940a025f3a36d1c
Stackoverflow Stackexchange Q: How to parse a list of named ES6/ES2015 exports from a module? I want to parse the text content of a javascript file for export statements and extract a list of named exports from the module. Why? I'm looking to extend import-js's Meteor environment to understand local packages and the main hold-up seems to be being able to parse and identify the named exports of each package. The existing implementation identifies the package name, path and isopack so I can easily get the path to the mainModule of each package. I just need help parsing that file for export statements. A: You can use babylon to generate a JavaScript AST of an input file, and then check the top level for ExportDefaultDeclaration, ExportNamedDeclaration, and ExportAllDeclaration. Given the following example: export default test; export { foo as bar, baz }; export let lol = "okay then"; // also var, const export * from 'import-js'; Babylon 7 generates this AST: You can use this list of various supported syntaxes for export and use the explorer to see what Babylon is expected to generate, and then you can use the resulting JSON to get the parsed information you need.
Q: How to parse a list of named ES6/ES2015 exports from a module? I want to parse the text content of a javascript file for export statements and extract a list of named exports from the module. Why? I'm looking to extend import-js's Meteor environment to understand local packages and the main hold-up seems to be being able to parse and identify the named exports of each package. The existing implementation identifies the package name, path and isopack so I can easily get the path to the mainModule of each package. I just need help parsing that file for export statements. A: You can use babylon to generate a JavaScript AST of an input file, and then check the top level for ExportDefaultDeclaration, ExportNamedDeclaration, and ExportAllDeclaration. Given the following example: export default test; export { foo as bar, baz }; export let lol = "okay then"; // also var, const export * from 'import-js'; Babylon 7 generates this AST: You can use this list of various supported syntaxes for export and use the explorer to see what Babylon is expected to generate, and then you can use the resulting JSON to get the parsed information you need.
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:897468", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643664" }
7eea1b0f57491085adeaa9697be6c435037ccac5
Stackoverflow Stackexchange Q: How can I clean up my local branches if they are deleted from GIT repo How can I delete all my local branches if they are deleted from GIT repo. Is there any command for that ? . I dont want to it one by one by the command git branch -D/-d branch-name . A: Remove information on branches that were deleted on origin When branches get deleted on origin, your local repository won't take notice of that. You'll still have your locally cached versions of those branches (which is actually good) but git branch -a will still list them as remote branches. You can clean up that information locally like this: git remote prune origin Your local copies of deleted branches are not removed by this. The same effect is achieved by using git fetch --prune You could also set that as a default.
Q: How can I clean up my local branches if they are deleted from GIT repo How can I delete all my local branches if they are deleted from GIT repo. Is there any command for that ? . I dont want to it one by one by the command git branch -D/-d branch-name . A: Remove information on branches that were deleted on origin When branches get deleted on origin, your local repository won't take notice of that. You'll still have your locally cached versions of those branches (which is actually good) but git branch -a will still list them as remote branches. You can clean up that information locally like this: git remote prune origin Your local copies of deleted branches are not removed by this. The same effect is achieved by using git fetch --prune You could also set that as a default. A: To delete (or "prune") local branches that are not in the repo git remote prune origin prune Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>". With --dry-run option, report what branches will be pruned, but do no actually prune them. A: It sounds like you are asking for a way to delete your own branch named train if there was an origin/train at one point and there is no longer an origin/train now. This is (a) somewhat dangerous and (b) difficult to do (because there is nothing built in to remember that "there was an origin/train"), but if you redefine the problem a bit, it's much less difficult. It remains dangerous. It means you are telling your software to automatically destroy information whether or not that loses information you did not want destroyed. For instance, you may have put a lot of work in the last day or two into your train and then someone deletes the upstream origin/train not realizing that you are working on it. Now you tell your Git to delete your train without ever giving you a chance to restore origin/train, and you lose the work you just did. (You can get your work back, through the HEAD reflog, but it's not a very good plan—which is why I call this "somewhat dangerous".) To see ways to delete branches that have lost their upstreams (e.g., after running git remote prune origin or git fetch --prune origin), see Remove local branches no longer on remote. A: Just for reference if someone looking in this page later Quiet good amount of details on the same DevConnect Page Command which we can use for fully merged local branches is git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d
stackoverflow
{ "language": "en", "length": 459, "provenance": "stackexchange_0000F.jsonl.gz:897479", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643712" }
9728eac3e26b6f7bbc828e7c2eb84df521e287bd
Stackoverflow Stackexchange Q: React Webpack - Error: Module is not a loader (must have normal or pitch function) My webpack.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs ], output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", publicPath: 'http://localhost:3000/assets/bundles/', // Tell django to use this URL to load packages and not use STATIC_URL + bundle_name }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // don't reload if there is an error new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader?presets[]=react'], }, // to transform JSX into JS ], }, resolve: { modules: ['node_modules', 'bower_components'], extensions: ['.js', '.jsx'] }, } Error: Error: Module 'C:\Workspace\PyCharmProjects\ProjectPearl\node_modules\react-hot-loader\index.js' is not a loader (must have normal or pitch function) Looks like some got working (https://github.com/webpack/webpack/issues/3180) by adding -loader extension for modules, however for me it still doesn't resolve. Please assist. A: The usage is react-hot-loader/webpack loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=react'], Look at some example usages here http://gaearon.github.io/react-hot-loader/getstarted/
Q: React Webpack - Error: Module is not a loader (must have normal or pitch function) My webpack.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs ], output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", publicPath: 'http://localhost:3000/assets/bundles/', // Tell django to use this URL to load packages and not use STATIC_URL + bundle_name }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // don't reload if there is an error new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader?presets[]=react'], }, // to transform JSX into JS ], }, resolve: { modules: ['node_modules', 'bower_components'], extensions: ['.js', '.jsx'] }, } Error: Error: Module 'C:\Workspace\PyCharmProjects\ProjectPearl\node_modules\react-hot-loader\index.js' is not a loader (must have normal or pitch function) Looks like some got working (https://github.com/webpack/webpack/issues/3180) by adding -loader extension for modules, however for me it still doesn't resolve. Please assist. A: The usage is react-hot-loader/webpack loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=react'], Look at some example usages here http://gaearon.github.io/react-hot-loader/getstarted/ A: The issue may arise because of mismatched version of react-hot-loader dependent libraries. To ensure you have all react-hot-loader related dependencies configured correctly in package.json run following command. * *npm install (if you have already installed all dependencies then this is not required) *npm remove --save-dev react-hot-loader *npm install --save react-hot-loader@<specific-version> in my case specific-version was 1.3.1
stackoverflow
{ "language": "en", "length": 238, "provenance": "stackexchange_0000F.jsonl.gz:897486", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643738" }
44b4ac06f68a35a203a0d75c9e9aeb525f1c5dd4
Stackoverflow Stackexchange Q: How can I write multi-line code in the Terminal use python? How can I write multi-line code in the python REPL? : aircraftdeMacBook-Pro:~ ldl$ python Python 2.7.10 (default, Jul 30 2016, 19:40:32) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> such as a sample example: i = 0 while i < 10: i += 1 print i In the terminal I don't know hot to line feed in the python shell: I tested the Control+Enter, and Shift+Enter, and Command+Enter, they all wrong: >>> while i < 10: ... print i File "<stdin>", line 2 print i ^ IndentationError: expected an indented block A: There comes out: IndentationError: expected an indented block So, when use the while loop, the next line should have the indented block(press Tab key). >>> i = 0 >>> while i < 10: ... i += 1 ... print i ... 1 2 3 4 5 6 7 8 9 10 >>>
Q: How can I write multi-line code in the Terminal use python? How can I write multi-line code in the python REPL? : aircraftdeMacBook-Pro:~ ldl$ python Python 2.7.10 (default, Jul 30 2016, 19:40:32) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> such as a sample example: i = 0 while i < 10: i += 1 print i In the terminal I don't know hot to line feed in the python shell: I tested the Control+Enter, and Shift+Enter, and Command+Enter, they all wrong: >>> while i < 10: ... print i File "<stdin>", line 2 print i ^ IndentationError: expected an indented block A: There comes out: IndentationError: expected an indented block So, when use the while loop, the next line should have the indented block(press Tab key). >>> i = 0 >>> while i < 10: ... i += 1 ... print i ... 1 2 3 4 5 6 7 8 9 10 >>> A: Just copy the code and past it in the terminal, and press return. This code works perfect if you do that: i = 0 .. .. while i < 10: .. i += 1 .. print(i) .. 1 2 3 4 5 6 7 8 9 10 A: Utilize the python3 - <<'EOF' command. For instance: python3 - <<'EOF' a=7 b=5 print(a+b) EOF 12 A: You can add a trailing backslash. For example, if I want to print a 1: >>> print 1 1 >>> print \ ... 1 1 >>> If you write a \, Python will prompt you with ... (continuation lines) to enter code in the next line, so to say. To resolve IndentationError: expected an indented block, put the next line after while loop in an indented block (press Tab key). So, the following works: >>> i=0 >>> while i < 10: ... i+=1 ... print i ... 1 2 3 4 5 6 7 8 9 10 A: Python automatically detects code blocks in sections like for-next, while, etc. Just put a ':' <-- Colon symbol after some code. Then the next line will have a continuation symbol ('...') in front of it instead of the prompt ('>>>') Remember to press a tab to indent the code that you want to execute in the block. That will indent the line and tell Python that the code that follows is a part of the block.
stackoverflow
{ "language": "en", "length": 407, "provenance": "stackexchange_0000F.jsonl.gz:897499", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643775" }
070c1abd3a9a939dfb511377597258fc64472c80
Stackoverflow Stackexchange Q: Jython 2.7 with Java 1.8 - Import custom jar I'm using jython 2.7 with java, with the objective of creating a python wrapper around my jar file (let's call it myJar.jar) Here's my python file: import sys sys.path.append('/pathTo/myJar.jar') from java.lang import Math #this works from java.io import File # this works` from com.myPackage.classes import myClass print('trying to import myClass') I run the following command to execute this code: java -jar ~/pathTo/jython.jar jyTest.py I get an importError stating: ImportError: No module named myPackage aside from using sys.path.append(), I've also tried: java -jar ~/pathTo/jython.jar -Dpython.path=/pathTo/myJar.jar jyTest.py and java -cp ~/pathTo/jython.jar:~/pathTo/myJar.jar jyTest.py and java -classpath ~/pathTo/myJar.jar -jar ~/pathTo/jython.jar jyTest.py I also tried using java -cp by exporting myJar.jar to $CLASSPATH. None of the above approaches worked. Please note that if I do not add the line from com.myPackage.classes import myClass, I can see the print statement being executed, therefore, my jython.jar is working as expected. I installed jython 2.7 Standalone package, as per the instructions given on: https://wiki.python.org/jython/InstallationInstructions ...therefore I only have jython.jar How should I make myJar.jar visible to my python file ? Thanks
Q: Jython 2.7 with Java 1.8 - Import custom jar I'm using jython 2.7 with java, with the objective of creating a python wrapper around my jar file (let's call it myJar.jar) Here's my python file: import sys sys.path.append('/pathTo/myJar.jar') from java.lang import Math #this works from java.io import File # this works` from com.myPackage.classes import myClass print('trying to import myClass') I run the following command to execute this code: java -jar ~/pathTo/jython.jar jyTest.py I get an importError stating: ImportError: No module named myPackage aside from using sys.path.append(), I've also tried: java -jar ~/pathTo/jython.jar -Dpython.path=/pathTo/myJar.jar jyTest.py and java -cp ~/pathTo/jython.jar:~/pathTo/myJar.jar jyTest.py and java -classpath ~/pathTo/myJar.jar -jar ~/pathTo/jython.jar jyTest.py I also tried using java -cp by exporting myJar.jar to $CLASSPATH. None of the above approaches worked. Please note that if I do not add the line from com.myPackage.classes import myClass, I can see the print statement being executed, therefore, my jython.jar is working as expected. I installed jython 2.7 Standalone package, as per the instructions given on: https://wiki.python.org/jython/InstallationInstructions ...therefore I only have jython.jar How should I make myJar.jar visible to my python file ? Thanks
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:897505", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643795" }
f6bc131cda2bb5f15f39c9daf978974fed76459f
Stackoverflow Stackexchange Q: CoreML Model Compile Error compiling model trained in keras with Embedding layer as first layer I've trained a simple model in keras and its first layer is an Embedding layer as below: I converted the model to .mlmodel but when I try to compile the code in Xcode I get this error: /mlkitc: compiler error: Inner product layer: dense_1: Product of input's C,H,W (32,1,1) must be equal to the input channels (16000) Could it be a problem with the conversion?
Q: CoreML Model Compile Error compiling model trained in keras with Embedding layer as first layer I've trained a simple model in keras and its first layer is an Embedding layer as below: I converted the model to .mlmodel but when I try to compile the code in Xcode I get this error: /mlkitc: compiler error: Inner product layer: dense_1: Product of input's C,H,W (32,1,1) must be equal to the input channels (16000) Could it be a problem with the conversion?
stackoverflow
{ "language": "en", "length": 81, "provenance": "stackexchange_0000F.jsonl.gz:897519", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643838" }
3d7a5a0d4f54e34b7e6ad5f0f8783cb47340f44c
Stackoverflow Stackexchange Q: Firebase Notification not working in background I need help. Firebase Notifications is Not Working in Background. This is My Code: @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "FROM:" + remoteMessage.getFrom()); sharedPreference = getSharedPreferences(Global.SECURETRADE, 0); UID = sharedPreference.getString(Global.ID, ""); Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)`enter code here`; NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notificationBuilder.setSmallIcon(R.mipmap.small_secure_trade_app_icon); } else { notificationBuilder.setSmallIcon(R.drawable.small_secure_trade_app_icon); } notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.securetrade_icon)); notificationBuilder.setContentTitle(remoteMessage.getData().get("title")); notificationBuilder.setContentText(remoteMessage.getData().get("body")); notificationBuilder.setAutoCancel(true); notificationBuilder.setSound(defaultSoundUri); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); } } A: when app is in background or killed you have to use data payload for notification. Firebase onMessageReceived not called when app in background
Q: Firebase Notification not working in background I need help. Firebase Notifications is Not Working in Background. This is My Code: @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "FROM:" + remoteMessage.getFrom()); sharedPreference = getSharedPreferences(Global.SECURETRADE, 0); UID = sharedPreference.getString(Global.ID, ""); Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)`enter code here`; NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notificationBuilder.setSmallIcon(R.mipmap.small_secure_trade_app_icon); } else { notificationBuilder.setSmallIcon(R.drawable.small_secure_trade_app_icon); } notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.securetrade_icon)); notificationBuilder.setContentTitle(remoteMessage.getData().get("title")); notificationBuilder.setContentText(remoteMessage.getData().get("body")); notificationBuilder.setAutoCancel(true); notificationBuilder.setSound(defaultSoundUri); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); } } A: when app is in background or killed you have to use data payload for notification. Firebase onMessageReceived not called when app in background A: Just remove 'notification' section from the json you sent through push notification. Simply sent the 'data' section, onMessageReceived will work as normal A: Yes, Firebase will not call the onMessageReceived() when the app is in background unless you make the notification request body changes from yoour server code. Checkout this answer https://stackoverflow.com/a/40083727/4620609 A: Are you sending data-messages (not notification-messages) ? notification-messages don't call onMessageReceived() Use notification messages when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want to process the messages on your client app. Read more here: https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages PS: FCM Web Console always sends notification-messages If you are sending a data-messages, and onMessageReceived() is not called... then it's a different problem. It might even be a problem of that specific device. See Push notifications using FCM not received when app is killed android A: when app running in background onMessageReceive will not work offline message coming to launcher activity just copy this peace of code in your launcher activity and check it. it will work. Bundle bundle = getIntent().getExtras(); if (bundle != null) { Logger.info(TAG, "FIRE BASE OFF LINE NOTIFICATIONS COMING TO THIS BLOCK--->"); JSONObject json = new JSONObject(); Set<String> keys = bundle.keySet(); for (String key : keys) { Logger.info(TAG, "json object--->" + key + "---values--" + JSONObject.wrap(bundle.get(key))); } } and your payload should be like this { "notification": { "title": "Your Title", "text": "Your Text", "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter }, "data": { "keyname": "any value " //you can get this data as extras in your activity and this data is optional }, "to" : "to_id(firebase refreshedToken)" } reference
stackoverflow
{ "language": "en", "length": 375, "provenance": "stackexchange_0000F.jsonl.gz:897530", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643866" }
cff5ea1f1e609d87bd89ecc6df5e05d3efa824aa
Stackoverflow Stackexchange Q: How can I copy the contents of a firebase storage bucket from one project to another? I'm using firebase storage to store profile pictures. I've created two projects: MyApp and MyApp-Dev. I can easily download the json data from the MyApp database and upload it to MyApp-Dev database. Is there a way to do something similar to transfer the images from one project to another? Without the user's profile pictures it makes testing MyApp-Dev quite difficult. A: If you have the Google Cloud SDK installed you can use the gsutil command. Install GCP SDK gsutil doc And you could move the information between buckets. Example: gsutil -m cp -r gs://<bucket-myapp-name> gs://<bucket-myapp-dev-name> -m to run in parallel. This can significantly improve performance if you are performing operations on a large number of files over a reasonably fast network connection cp copy -r recursive
Q: How can I copy the contents of a firebase storage bucket from one project to another? I'm using firebase storage to store profile pictures. I've created two projects: MyApp and MyApp-Dev. I can easily download the json data from the MyApp database and upload it to MyApp-Dev database. Is there a way to do something similar to transfer the images from one project to another? Without the user's profile pictures it makes testing MyApp-Dev quite difficult. A: If you have the Google Cloud SDK installed you can use the gsutil command. Install GCP SDK gsutil doc And you could move the information between buckets. Example: gsutil -m cp -r gs://<bucket-myapp-name> gs://<bucket-myapp-dev-name> -m to run in parallel. This can significantly improve performance if you are performing operations on a large number of files over a reasonably fast network connection cp copy -r recursive A: I did copy bucket A to be stored in the root of bucket B, gsutil -m cp -r gs://<bucket-a>/* gs://<bucket-B>
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:897547", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643908" }
11e747ec881690e829f48e64d7db2bdbe3cb34dd
Stackoverflow Stackexchange Q: How to create UISplitViewController programmatically in Swift Is there anyone who can help me to explain how to make UISpliterController programmatically in Swift. In my application I want to apply the supporting feature of iphone device and ipad. If the app is running on iphone then use single controler but if the application is running on ipad then use UISpliterController with existing ViewController. I have tried it but it always produce blackscreen Here is my code. if UIDevice.current.userInterfaceIdiom == .pad { let spliterVC = UISplitViewController() let homeNavControler = mainStoryboard.instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController let secondVC = mainStoryboard.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController spliterVC.viewControllers = [homeNavControler,secondVC] appdelegate.window?.rootViewController = spliterVC } A: if you want do it with navigationController, then try it: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() var splitViewController = UISplitViewController() var homeViewController = HomeViewController() var secondViewController = SecondViewController() var homeNavigationController = UINavigationController(rootViewController:homeViewController) var secondNavigationController = UINavigationController(rootViewController:secondViewController) splitViewController.viewControllers = [homeNavigationController,secondNavigationController] self.window!.rootViewController = splitViewController self.window!.makeKeyAndVisible() return true } else { // use single controller for iPhone and return that controller } }
Q: How to create UISplitViewController programmatically in Swift Is there anyone who can help me to explain how to make UISpliterController programmatically in Swift. In my application I want to apply the supporting feature of iphone device and ipad. If the app is running on iphone then use single controler but if the application is running on ipad then use UISpliterController with existing ViewController. I have tried it but it always produce blackscreen Here is my code. if UIDevice.current.userInterfaceIdiom == .pad { let spliterVC = UISplitViewController() let homeNavControler = mainStoryboard.instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController let secondVC = mainStoryboard.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController spliterVC.viewControllers = [homeNavControler,secondVC] appdelegate.window?.rootViewController = spliterVC } A: if you want do it with navigationController, then try it: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() var splitViewController = UISplitViewController() var homeViewController = HomeViewController() var secondViewController = SecondViewController() var homeNavigationController = UINavigationController(rootViewController:homeViewController) var secondNavigationController = UINavigationController(rootViewController:secondViewController) splitViewController.viewControllers = [homeNavigationController,secondNavigationController] self.window!.rootViewController = splitViewController self.window!.makeKeyAndVisible() return true } else { // use single controller for iPhone and return that controller } }
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:897552", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643920" }
e5f3e2aceda496f194797fb754927f92a9ec9b5b
Stackoverflow Stackexchange Q: Use DocumentTermMatrix in R with 'dictionary' parameter I want to use R for text classification. I use DocumentTermMatrix to return the matrix of word: library(tm) crude <- "japan korea usa uk albania azerbaijan" corps <- Corpus(VectorSource(crude)) dtm <- DocumentTermMatrix(corps) inspect(dtm) words <- c("australia", "korea", "uganda", "japan", "argentina", "turkey") test <- DocumentTermMatrix(corps, control=list(dictionary = words)) inspect(test) The first inspect(dtm) work as expected with result: Terms Docs albania azerbaijan japan korea usa 1 1 1 1 1 1 But the second inspect(test) show this result: Terms Docs argentina australia japan korea turkey uganda 1 0 1 0 1 0 0 While the expected result is: Terms Docs argentina australia japan korea turkey uganda 1 0 0 1 1 0 0 Is it a bug or I use it the wrong way ? A: Corpus() seems to have a bug when indexing word frequency. Use VCorpus() instead, this will give you the expected result.
Q: Use DocumentTermMatrix in R with 'dictionary' parameter I want to use R for text classification. I use DocumentTermMatrix to return the matrix of word: library(tm) crude <- "japan korea usa uk albania azerbaijan" corps <- Corpus(VectorSource(crude)) dtm <- DocumentTermMatrix(corps) inspect(dtm) words <- c("australia", "korea", "uganda", "japan", "argentina", "turkey") test <- DocumentTermMatrix(corps, control=list(dictionary = words)) inspect(test) The first inspect(dtm) work as expected with result: Terms Docs albania azerbaijan japan korea usa 1 1 1 1 1 1 But the second inspect(test) show this result: Terms Docs argentina australia japan korea turkey uganda 1 0 1 0 1 0 0 While the expected result is: Terms Docs argentina australia japan korea turkey uganda 1 0 0 1 1 0 0 Is it a bug or I use it the wrong way ? A: Corpus() seems to have a bug when indexing word frequency. Use VCorpus() instead, this will give you the expected result.
stackoverflow
{ "language": "en", "length": 152, "provenance": "stackexchange_0000F.jsonl.gz:897572", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643961" }
37439af0a44e5770727b08985eddfc3c9d2bbcbc
Stackoverflow Stackexchange Q: react native stuck after bundle: Done copying assets My react-native run-ios --device stuck after displaying this line. simulator does not stuck. I tried `rm -rf $TMPDIR/react-* && watchman watch-del-all && rm -rf ios/build/ModuleCache/* && rm -rf node_modules/ && npm cache clean && npm i`. No luck. bundle: Done writing bundle output bundle: Copying 84 asset files bundle: Done copying assets + [[ ! -n false ]] Same on using xcode build. Xcode says running 2 of 4 custom shell scripts and report navigator displays bundle: Done writing bundle output bundle: Copying 84 asset files bundle: Done copying assets + [[ ! -n false ]] Any suggestion? react-native: 0.44.0
Q: react native stuck after bundle: Done copying assets My react-native run-ios --device stuck after displaying this line. simulator does not stuck. I tried `rm -rf $TMPDIR/react-* && watchman watch-del-all && rm -rf ios/build/ModuleCache/* && rm -rf node_modules/ && npm cache clean && npm i`. No luck. bundle: Done writing bundle output bundle: Copying 84 asset files bundle: Done copying assets + [[ ! -n false ]] Same on using xcode build. Xcode says running 2 of 4 custom shell scripts and report navigator displays bundle: Done writing bundle output bundle: Copying 84 asset files bundle: Done copying assets + [[ ! -n false ]] Any suggestion? react-native: 0.44.0
stackoverflow
{ "language": "en", "length": 109, "provenance": "stackexchange_0000F.jsonl.gz:897584", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44643998" }
0e1491df743b0d0e12fe2a0dadd24b51f58c2215
Stackoverflow Stackexchange Q: What's is the difference between required_with and required_with_all laravel validation I already tried have a look at https://laravel.com/docs/5.4/validation but still , i don't really get what's is the difference between : required_with_all and required_without Anyone can explain to me in detail what's the difference ? A: required_with: The field under validation must be present and not empty only if any of the other specified fields are present. required_with_all: The field under validation must be present and not empty only if all of the other specified fields are present. Note: Check bold text above. For more detail see Laravel docs
Q: What's is the difference between required_with and required_with_all laravel validation I already tried have a look at https://laravel.com/docs/5.4/validation but still , i don't really get what's is the difference between : required_with_all and required_without Anyone can explain to me in detail what's the difference ? A: required_with: The field under validation must be present and not empty only if any of the other specified fields are present. required_with_all: The field under validation must be present and not empty only if all of the other specified fields are present. Note: Check bold text above. For more detail see Laravel docs A: required_with_all : Laravel Doc: The field under validation must be present only if all of the other specified fields are present. required_without_all : Laravel Doc: The field under validation must be present and not empty only when all of the other specified fields are not present. Example: $rules = array( 'facebook_id' => 'required_without_all:twitter_id,instagram_id', 'twitter_id' => 'required_without_all:facebook_id,instagram_id', 'instagram_id' => 'required_without_all:facebook_id,twitter_id', ); $validator = Validator::make(Input::all(), $rules); required_with: Laravel Doc: The field under validation must be present only if any of the other specified fields are present. Example: $rules = array( 'sell' => 'required_without:rent', 'rent' => 'required_without:sell', 'price' => 'required_with:sell|numeric|min:0', );
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:897592", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644016" }
873d81e4d759617dccf66a9c188f773edb38cf5e
Stackoverflow Stackexchange Q: Server side rendering using Angular4(Angular Universal) I am working on an Angular4 webpack project to which I wanted to add AngularUniversal to make server side rendering possible.But most tutorials are using angular cli.I want to integrate Universal with webpack.I tried following this tutorial with no luck.Can someone please help. A: Angular universal is only used for angular 2.x. Angular 4.x you need to use platform server.Examples are as follows: For angular 2.X.X : AngularClass's seed project using express/universal https://github.com/angular/universal-starter For angular 4.X.X Use angular platform server https://github.com/ng-seed/universal There are few other examples also: * *https://github.com/hs950559/ng4-univ *https://github.com/designcourse/angular-seo learn step by step implementation here
Q: Server side rendering using Angular4(Angular Universal) I am working on an Angular4 webpack project to which I wanted to add AngularUniversal to make server side rendering possible.But most tutorials are using angular cli.I want to integrate Universal with webpack.I tried following this tutorial with no luck.Can someone please help. A: Angular universal is only used for angular 2.x. Angular 4.x you need to use platform server.Examples are as follows: For angular 2.X.X : AngularClass's seed project using express/universal https://github.com/angular/universal-starter For angular 4.X.X Use angular platform server https://github.com/ng-seed/universal There are few other examples also: * *https://github.com/hs950559/ng4-univ *https://github.com/designcourse/angular-seo learn step by step implementation here A: The example that is mentioned in given tutorial is using the example mentioned in Angular Resources section. They have recently updated their docs and have not yet provided the detailed documentation to implement @angular/universal. This used to be the page you are looking for but it had some issues mentioned here. May be that's why they removed it and have decided to rewrite it. A: This Angular Universal is only for Angular 2. If you want to start from scratch you can use this Angular 4 Universal Seed which has all features like: * *Angular 4 *WebPack *dev/prod modes *SCSS compilation *i18n, SEO, and TSLint/codelyzer *lazy loading, config, cache Or if you already had Angular 4 project running you can Integrate Universal by doing following settings in your code: Install these packages: npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save npm install express @types/express --save-dev Add this in your app.module.ts file import { BrowserModule } from '@angular/platform-browser'; BrowserModule.withServerTransition({ appId: 'my-app-id' // withServerTransition is available only in Angular 4 }), Create following files src/uni/app.server.ts import { NgModule } from '@angular/core'; import { APP_BASE_HREF } from '@angular/common'; import { ServerModule } from '@angular/platform-server'; import { AppComponent } from '../app/app'; import { AppModule } from '../app/app.module'; import 'reflect-metadata'; import 'zone.js'; @NgModule({ imports: [ ServerModule, AppModule ], bootstrap: [ AppComponent ], providers: [ {provide: APP_BASE_HREF, useValue: '/'} ] }) export class AppServerModule { } src/uni/server-uni.ts import 'zone.js/dist/zone-node'; import 'zone.js'; import 'reflect-metadata'; import { enableProdMode } from '@angular/core'; import { AppServerModuleNgFactory } from '../../aot/src/uni/app.server.ngfactory'; import * as express from 'express'; import { ngUniversalEngine } from './universal-engine'; enableProdMode(); const server = express(); // set our angular engine as the handler for html files, so it will be used to render them. server.engine('html', ngUniversalEngine({ bootstrap: [AppServerModuleNgFactory] })); // set default view directory server.set('views', 'src'); // handle requests for routes in the app. ngExpressEngine does the rendering. server.get(['/', '/dashboard', '/heroes', '/detail/:id'], (req:any, res:any) => { res.render('index.html', {req}); }); // handle requests for static files server.get(['/*.js', '/*.css'], (req:any, res:any, next:any) => { let fileName: string = req.originalUrl; console.log(fileName); let root = fileName.startsWith('/node_modules/') ? '.' : 'src'; res.sendFile(fileName, { root: root }, function (err:any) { if (err) { next(err); } }); }); // start the server server.listen(3200, () => { console.log('listening on port 3200...'); }); src/uni/universal-engine.ts import * as fs from 'fs'; import { renderModuleFactory } from '@angular/platform-server'; const templateCache = {}; // cache for page templates const outputCache = {}; // cache for rendered pages export function ngUniversalEngine(setupOptions: any) { return function (filePath: string, options: { req: Request }, callback: (err: Error, html: string) => void) { let url: string = options.req.url; let html: string = outputCache[url]; if (html) { // return already-built page for this url console.log('from cache: ' + url); callback(null, html); return; } console.log('building: ' + url); if (!templateCache[filePath]) { let file = fs.readFileSync(filePath); templateCache[filePath] = file.toString(); } // render the page via angular platform-server let appModuleFactory = setupOptions.bootstrap[0]; renderModuleFactory(appModuleFactory, { document: templateCache[filePath], url: url }).then(str => { outputCache[url] = str; callback(null, str); }); }; } Add below configuration in your tsconfig.ts file which I assume located in root dir { "compilerOptions": { "baseUrl": "", "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2016", "dom"], "moduleResolution": "node", "outDir": "./dist/out-tsc", "sourceMap": true, "target": "es5", "module": "commonjs", "types": ["node"], "typeRoots": [ "node_modules/@types" ] }, "files": [ "src/uni/app.server.ts", "src/uni/server-uni.ts" ], "angularCompilerOptions": { "genDir": "aot", "entryModule": "./src/app/app.module#AppModule", "skipMetadataEmit": true }, "exclude": [ "test.ts", "**/*.spec.ts" ] } Atlast your webpack.config.uni.js in root dir const ngtools = require('@ngtools/webpack'); const webpack = require('webpack'); const path = require('path'); const ExtractTextWebpackPlugin = require("extract-text-webpack-plugin"); module.exports = { devtool: 'source-map', entry: { main: ['./src/uni/app.server.ts', './src/uni/server-uni.ts'] }, resolve: { extensions: ['.ts', '.js'] }, target: 'node', output: { path: path.join(__dirname, "dist"), filename: 'server.js' }, plugins: [ new ngtools.AotPlugin({ tsConfigPath: './tsconfig.json' }) ], module: { rules: [ { test: /\.(scss|html|png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, use: 'raw-loader' }, { test: /\.ts$/, loader: require.resolve('@ngtools/webpack') }, { test: /\.(png|jpg|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url?limit=512&&name=[path][name].[ext]?[hash]' }, { test: /\.scss$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "sass-loader" // compiles Sass to CSS }] } ] } } Add below scripts in you package.json file: "ngc-build": "ngc -p ./tsconfig.json", // To generate ngFactory file "build:uni": "webpack --config webpack.config.uni.js", "serve:uni": "node dist/server.js", There are certain things that we should keep in mind: * *window, document, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work. You do have some options given in this link if you truly need some of this functionality. A: You can find an Angular 4 tutorial on server-side rendering with Webpack on this blog. Features: * *it is built upon Angular 4 *it does not depend on Angular CLI *it builds upon Webpack *the blog provides a step by step instruction in three phases: * *phase 1: Run a Server Side Rendered Hello World Page on a Docker Container (I am providing a pre-installed Docker image for your convenience, but the instructions should work on your own Angular environment) *phase 2: Create a new functional Link on the main Page *phase 3 (optional): Dynamically insert a WordPress Blog POST via RESTful API The end result can be viewed easily on a Docker host like follows: (dockerhost)$ docker run -it -p 8002:8000 oveits/angular_hello_world:centos bash (container)# git clone https://github.com/oveits/ng-universal-demo (container)# cd ng-universal-demo (container)# npm i (container)# npm run start I have chosen port 8002 above, since I am running other examples on ports 8000 and 8001 already; If the docker host is running on Virtualbox, you might need a port mapping from 8002 of the Virtualbox host to 8002 of the Virtualbox VM. On a browser, navigate to http://localhost:8002/blog. You will see the content of a blog post that is downloaded from the Wordpress API. With right-click->view source you will see the HTML content. This demonstrates that this is a server-side rendered page. P.S.: Like the tutorial you have tried out, the tutorial is based on a Git project that originally has been created by Rob Wormald, but with this fork by FrozenPandaz, I have found a version that is upgraded to Angular 4 and has worked better with Webpack (see the appendix of the blog for more details).
stackoverflow
{ "language": "en", "length": 1142, "provenance": "stackexchange_0000F.jsonl.gz:897617", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644097" }
1699a0c017cbe487afd5c3b60f13c12d8832b639
Stackoverflow Stackexchange Q: PSVersion is not recognized After installing powershell, i tried running PSVersionTable.PSVersion and PSVersionTable to check the version, however i get the following error: I did install WMF-4.0 and the .NET framework versions before installing WMF-v5 Most posts point me to make sure i have .NET and WMF-4.0 installed and i cant seem to find anything else. Note I am Using windows 7 A: You need to enter $PsVersionTable. It is a built in variable and you access variables via $.
Q: PSVersion is not recognized After installing powershell, i tried running PSVersionTable.PSVersion and PSVersionTable to check the version, however i get the following error: I did install WMF-4.0 and the .NET framework versions before installing WMF-v5 Most posts point me to make sure i have .NET and WMF-4.0 installed and i cant seem to find anything else. Note I am Using windows 7 A: You need to enter $PsVersionTable. It is a built in variable and you access variables via $. A: The correct way to get the version is $PSVersionTable. It's a variable, not a call to anything.
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:897671", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644284" }
26415ac310eb71aa5184c04a3fc8ace6f2913d03
Stackoverflow Stackexchange Q: How to create a custom plugin in Javascript for hybrid mobile application? How to create a custom plugin in Javascript for hybrid mobile application and Use the same plugin in Hybrid Mobile Application. How to write Cordova Plugins – Ionic and the Mobile Web. If anyone knows the same then please add your answer with proper steps.
Q: How to create a custom plugin in Javascript for hybrid mobile application? How to create a custom plugin in Javascript for hybrid mobile application and Use the same plugin in Hybrid Mobile Application. How to write Cordova Plugins – Ionic and the Mobile Web. If anyone knows the same then please add your answer with proper steps.
stackoverflow
{ "language": "en", "length": 58, "provenance": "stackexchange_0000F.jsonl.gz:897672", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644287" }
81b844c7c08de5ea29ad4ff76bcb4599ed68b188
Stackoverflow Stackexchange Q: PHP : How to change page title of PDF in browser I have codes here to view pdf file in browser but I can't find how to change the page title and the title bar. Is this possible to customize title? $file = "additionalInfo_content/QXp6dk3ZB1.pdf"; $fp = fopen($file, "r") ; $myFileName = 'test'; header("Cache-Control: maxage=1"); header("Pragma: public"); header("Content-type: application/pdf"); header("Content-Disposition: inline; filename=".$myFileName.""); header("Content-Description: PHP Generated Data"); header("Content-Transfer-Encoding: binary"); header('Content-Length:' . filesize($file)); ob_clean(); flush(); while (!feof($fp)) { $buff = fread($fp, 1024); print $buff; } exit; The page title show's what the last string in my URL which is the QXp6dk3ZB1.pdf as well the title bar. I want to change it on what my desire title A: The title is normally changed using the HTML <title> element. When viewing a file that is not HTML, it just displays the filename, or the internal PDF meta-title, if available. You would have to alter the meta data of your file before sending it to the browser. Among other methods, there's this one: http://php.net/manual/en/function.pdf-set-info.php
Q: PHP : How to change page title of PDF in browser I have codes here to view pdf file in browser but I can't find how to change the page title and the title bar. Is this possible to customize title? $file = "additionalInfo_content/QXp6dk3ZB1.pdf"; $fp = fopen($file, "r") ; $myFileName = 'test'; header("Cache-Control: maxage=1"); header("Pragma: public"); header("Content-type: application/pdf"); header("Content-Disposition: inline; filename=".$myFileName.""); header("Content-Description: PHP Generated Data"); header("Content-Transfer-Encoding: binary"); header('Content-Length:' . filesize($file)); ob_clean(); flush(); while (!feof($fp)) { $buff = fread($fp, 1024); print $buff; } exit; The page title show's what the last string in my URL which is the QXp6dk3ZB1.pdf as well the title bar. I want to change it on what my desire title A: The title is normally changed using the HTML <title> element. When viewing a file that is not HTML, it just displays the filename, or the internal PDF meta-title, if available. You would have to alter the meta data of your file before sending it to the browser. Among other methods, there's this one: http://php.net/manual/en/function.pdf-set-info.php A: You can control the window title that displays when loading a pdf through php by using your htaccess file Rewrite rules to hide the php processing file. Example using the htaccess RewriteRule ^uploads/([^/]+)/([^/]+)/([^/]+)(/)?$ /file.php?source=$1&file=$2&name=$3 [NC,L,QSA] * *If your url were "https://example.com/uploads/files/QXp6dk3ZB1/myfilename.pdf", then you can pull your file QXp6dk3ZB1.pdf but have the clean filename "myfilename.pdf" show in the browser window.
stackoverflow
{ "language": "en", "length": 229, "provenance": "stackexchange_0000F.jsonl.gz:897694", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644360" }
afd987afc317297e5b9587755737188b9c619346
Stackoverflow Stackexchange Q: CMake - tracing and debugging targets dependencies I have a rather complicated CMakeLists.txt file with multiple add_subdirectory's, add_custom_command's, and add_custom_target's. I don't modify any source files. However some binary targets are always rebuilt and it takes valuable time. I have to debug this issue, or write new a CMakeLists.txt file from scratch. Is there a way to get from CMake information about why it rebuilds a particular target at build time? For example, GNU Make has the --debug command line option: Considering target file 'foo.exe'. Prerequisite 'bar.cpp' is newer than target 'foo.exe'. Must remake target 'foo.exe' Maybe CMake has something similar? There are --debug and --trace options, but they seem to be handled at configure time and are not able to say something at build time. CMake has the --graphviz option for that, but it shows only binary targets. No interface, alias, and added dependencies support. There are appropriate tickets in the official tracker: * *Interface libraries and --graphviz *Alias libraries and --graphviz *'add_dependencies' and --graphviz
Q: CMake - tracing and debugging targets dependencies I have a rather complicated CMakeLists.txt file with multiple add_subdirectory's, add_custom_command's, and add_custom_target's. I don't modify any source files. However some binary targets are always rebuilt and it takes valuable time. I have to debug this issue, or write new a CMakeLists.txt file from scratch. Is there a way to get from CMake information about why it rebuilds a particular target at build time? For example, GNU Make has the --debug command line option: Considering target file 'foo.exe'. Prerequisite 'bar.cpp' is newer than target 'foo.exe'. Must remake target 'foo.exe' Maybe CMake has something similar? There are --debug and --trace options, but they seem to be handled at configure time and are not able to say something at build time. CMake has the --graphviz option for that, but it shows only binary targets. No interface, alias, and added dependencies support. There are appropriate tickets in the official tracker: * *Interface libraries and --graphviz *Alias libraries and --graphviz *'add_dependencies' and --graphviz
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:897712", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644427" }
f07dbbb91c46818b5f480db8b3d32834adc0ae3d
Stackoverflow Stackexchange Q: How to get previous page url in codeigniter I need privously visited page url in a variable and to find it inside a controller. is there any way to find it?please help me.By using following code redirect($this->agent->referrer()); i can redirected to the previous page .but I need this inside a variable to check. A: It may be helpful $url= $_SERVER['HTTP_REFERER'];
Q: How to get previous page url in codeigniter I need privously visited page url in a variable and to find it inside a controller. is there any way to find it?please help me.By using following code redirect($this->agent->referrer()); i can redirected to the previous page .but I need this inside a variable to check. A: It may be helpful $url= $_SERVER['HTTP_REFERER']; A: try this: $this->load->library('user_agent'); if ($this->agent->is_referral()) { $refer = $this->agent->referrer(); } In this way you load user_agent library, check if there is a referral url and then store It into a variable to use It after A: use global $_SERVER['HTTP_REFERER']; but its not trusted php website say that https://www.php.net/manual/en/reserved.variables.server.php The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:897714", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644429" }
290ca28a206ce4d9c78736e6db6144e1cc380846
Stackoverflow Stackexchange Q: How to delete amazon cognito user? I want to delete cognito user using my nodejs application. Example cognitoUser.deleteUser (err, result) -> if err reject err resolve result when i try to delete cognito user error throws as follows Error: User is not authenticated cognitoUser.deleteUser is used by an authenticated user to delete himself but i want to delete all users using super user Please give me some idea to solve this problem. A: You can use the main aws javascript SDK and call the adminDeleteUser operation. It is an authenticated operation and it will require developer credentials for you to call it. https://github.com/aws/aws-sdk-js/blob/master/apis/cognito-idp-2016-04-18.normal.json#L100 var aws = require('aws-sdk'); var CognitoIdentityServiceProvider = aws.CognitoIdentityServiceProvider; var client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: 'us-east-1' }); //now you can call adminDeleteUser on the client object
Q: How to delete amazon cognito user? I want to delete cognito user using my nodejs application. Example cognitoUser.deleteUser (err, result) -> if err reject err resolve result when i try to delete cognito user error throws as follows Error: User is not authenticated cognitoUser.deleteUser is used by an authenticated user to delete himself but i want to delete all users using super user Please give me some idea to solve this problem. A: You can use the main aws javascript SDK and call the adminDeleteUser operation. It is an authenticated operation and it will require developer credentials for you to call it. https://github.com/aws/aws-sdk-js/blob/master/apis/cognito-idp-2016-04-18.normal.json#L100 var aws = require('aws-sdk'); var CognitoIdentityServiceProvider = aws.CognitoIdentityServiceProvider; var client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: 'us-east-1' }); //now you can call adminDeleteUser on the client object A: You can do from AWS-CLI aws cognito-idp admin-delete-user --user-pool-id ${user pool id} --username ${username usually email here}
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:897719", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644444" }
57a30776ee9796dc7aa3f60032c94aab474b9355
Stackoverflow Stackexchange Q: MaskEdittext Cursor issue I am using MaskEdittext text for formatting a number in US Format (123) 456-7890.I am facing one issue when I type number in edittext and place a cursor on ediittext it will be appeared like this here is the screen: here is my xml code: <com.sample.activities.MaskedEditText android:id="@+id/edttextlogin" android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/register_rectange1" android:hint="@string/phone_number" android:imeOptions="actionNext" android:inputType="phone" android:nextFocusDown="@+id/edttextpinnumber" android:paddingLeft="10dp" android:typeface="monospace" android:singleLine="true" android:cursorVisible="false" android:textSize="@dimen/edittextsize_sub" android:textColorHint="@color/hint_color_light" android:textColor="@color/main_header" maskededittext:mask="(***) ***-*********" /> I am using this dependency: compile 'ru.egslava:MaskedEditText:1.0.5' A: You can get readymade library for mask edittext. https://github.com/pinball83/Masked-Edittext
Q: MaskEdittext Cursor issue I am using MaskEdittext text for formatting a number in US Format (123) 456-7890.I am facing one issue when I type number in edittext and place a cursor on ediittext it will be appeared like this here is the screen: here is my xml code: <com.sample.activities.MaskedEditText android:id="@+id/edttextlogin" android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/register_rectange1" android:hint="@string/phone_number" android:imeOptions="actionNext" android:inputType="phone" android:nextFocusDown="@+id/edttextpinnumber" android:paddingLeft="10dp" android:typeface="monospace" android:singleLine="true" android:cursorVisible="false" android:textSize="@dimen/edittextsize_sub" android:textColorHint="@color/hint_color_light" android:textColor="@color/main_header" maskededittext:mask="(***) ***-*********" /> I am using this dependency: compile 'ru.egslava:MaskedEditText:1.0.5' A: You can get readymade library for mask edittext. https://github.com/pinball83/Masked-Edittext
stackoverflow
{ "language": "en", "length": 85, "provenance": "stackexchange_0000F.jsonl.gz:897743", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644518" }
78cc5280db72b53296f441415a9ed74cc9c6575e
Stackoverflow Stackexchange Q: Django FilteredSelectMultiple not rendering on page I am currently using Django version 1.11.2 and would like to use the FilteredSelectMultiple widget outside of the admin page. This is my forms.py: class TBDAuthGroupManageForm(forms.Form): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) def __init__(self, parents=None, *args, **kwargs): super(TBDAuthGroupManageForm, self).__init__(*args, **kwargs) This is my views.py: class TBDAuthGroupManageView(DetailView): model = TBDAuthGroup template_name = 'perms/tbdauthgroup_manage.html' def get_context_data(self, **kwargs): context = super(TBDAuthGroupManageView, self).get_context_data(**kwargs) context['form'] = TBDAuthGroupManageForm() return context And this is my template: {% extends "base.html" %} {% load static %} {% block css %} {{ form.media }} <script type="text/javascript" src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> {% endblock %} {% block content %} {{ form }} {% endblock %} However when I render it in the page, I only get this: and not this: I would love to know what I'm doing wrong and how I could fix this so my form looks like the admin form. A: {% block content %} {{ form.media }} <form> {{ form.permissions }} </form> {% endblock %} try this in your template
Q: Django FilteredSelectMultiple not rendering on page I am currently using Django version 1.11.2 and would like to use the FilteredSelectMultiple widget outside of the admin page. This is my forms.py: class TBDAuthGroupManageForm(forms.Form): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) def __init__(self, parents=None, *args, **kwargs): super(TBDAuthGroupManageForm, self).__init__(*args, **kwargs) This is my views.py: class TBDAuthGroupManageView(DetailView): model = TBDAuthGroup template_name = 'perms/tbdauthgroup_manage.html' def get_context_data(self, **kwargs): context = super(TBDAuthGroupManageView, self).get_context_data(**kwargs) context['form'] = TBDAuthGroupManageForm() return context And this is my template: {% extends "base.html" %} {% load static %} {% block css %} {{ form.media }} <script type="text/javascript" src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> {% endblock %} {% block content %} {{ form }} {% endblock %} However when I render it in the page, I only get this: and not this: I would love to know what I'm doing wrong and how I could fix this so my form looks like the admin form. A: {% block content %} {{ form.media }} <form> {{ form.permissions }} </form> {% endblock %} try this in your template
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:897745", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644521" }
53d09d2b58e5353d0169f3b84ba0e1b659a1693a
Stackoverflow Stackexchange Q: ggplot2: change the background color of one of the legend elements I would like to change the background color for one legend element but not the rest. For example, using the built in R dataset ToothGrowth ggplot(ToothGrowth, aes(x=dose,y=len,colour=supp)) + geom_point() Rather than change the color of the dots themselves, I want to change the background color of the box in the legend from grey to another color for only one of the legend elements. For instance change the background of VC but not OJ. A: This is kind of a hack because you use the {magick} package but it gives the desired output: library(ggplot2) library(magick) fig <- image_graph(width = 1000, height = 500, res = 96) ggplot(ToothGrowth, aes(x=dose,y=len,colour=supp)) + geom_point() dev.off() fig %>% image_fill("lightblue", point = "+950+220", fuzz = 5) image_fill() is the equivalent of the paint bucket in MSPaint
Q: ggplot2: change the background color of one of the legend elements I would like to change the background color for one legend element but not the rest. For example, using the built in R dataset ToothGrowth ggplot(ToothGrowth, aes(x=dose,y=len,colour=supp)) + geom_point() Rather than change the color of the dots themselves, I want to change the background color of the box in the legend from grey to another color for only one of the legend elements. For instance change the background of VC but not OJ. A: This is kind of a hack because you use the {magick} package but it gives the desired output: library(ggplot2) library(magick) fig <- image_graph(width = 1000, height = 500, res = 96) ggplot(ToothGrowth, aes(x=dose,y=len,colour=supp)) + geom_point() dev.off() fig %>% image_fill("lightblue", point = "+950+220", fuzz = 5) image_fill() is the equivalent of the paint bucket in MSPaint
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:897794", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644675" }
b30042a0665afcfeba9bac88fe738e18af8c5971
Stackoverflow Stackexchange Q: How to describe destructured object arguments in JSDoc If I have a JavaScript function taking an object as a parameter, I can describe expected properties of the object with JSDoc like this: /** * @param bar * @param bar.baz {number} * @param bar.qux {number} */ function foo(bar) { return bar.baz + bar.qux; } How do I describe these properties if I define my function with ECMAScript 6 destructuring, not giving the real parameter object a name at all? const foo = ({ baz, qux }) => baz + qux; A: It turns out JSDoc does support destructing via making up a placeholder name. It is lacking in official documentation. http://usejsdoc.org/tags-param.html#parameters-with-properties /** * @param {Object} param - this is object param * @param {number} param.baz - this is property param * @param {number} param.qux - this is property param */ const foo = ({ baz, qux }) => baz + qux;
Q: How to describe destructured object arguments in JSDoc If I have a JavaScript function taking an object as a parameter, I can describe expected properties of the object with JSDoc like this: /** * @param bar * @param bar.baz {number} * @param bar.qux {number} */ function foo(bar) { return bar.baz + bar.qux; } How do I describe these properties if I define my function with ECMAScript 6 destructuring, not giving the real parameter object a name at all? const foo = ({ baz, qux }) => baz + qux; A: It turns out JSDoc does support destructing via making up a placeholder name. It is lacking in official documentation. http://usejsdoc.org/tags-param.html#parameters-with-properties /** * @param {Object} param - this is object param * @param {number} param.baz - this is property param * @param {number} param.qux - this is property param */ const foo = ({ baz, qux }) => baz + qux; A: I had the same question too. Now I am using Visual Code Studi, its plugin does something like this (this is suitable for me): /** * @param {} {a * @param {} b * @param {} c} * @param {} {d} */ const aaa = ({a,b,c},{d}) => { }
stackoverflow
{ "language": "en", "length": 201, "provenance": "stackexchange_0000F.jsonl.gz:897814", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644750" }
bb85c1a2ee6b0407a25c69cb2e705dd69edd4855
Stackoverflow Stackexchange Q: react native: How to set Image defaultSource on Android react native: How to set Image defaultSource on Android. I have read the React native 1.58 document. I found the Image props defaultSource supported iOS only. I need to set the default Image when the network Image load error. I used to write the code like this: { ImageUrl? <Image style={styles.docimg} source={{uri: ImageUrl}}/> : <Image style={styles.docimg} source={require('../../../resource/default.png')}/> } Now there is a problem. When the URL is a string type, but it isn't a correct network Image. As the URL is true then the Image will show nothing. I saw the Image props onError maybe solve my issue. I need to set the placeholder Image. A: Work for me <ImageBackground style={{ width: 100, height: 100, marginRight: 20, borderRadius: 10, }} source={ require('../../assets/images/Spinner.gif') //Indicator }> <Image style={{ width: 100, height: 100, marginRight: 20, borderRadius: 10, }} source={{ uri: `//Image U want To Show` }} /> </ImageBackground>
Q: react native: How to set Image defaultSource on Android react native: How to set Image defaultSource on Android. I have read the React native 1.58 document. I found the Image props defaultSource supported iOS only. I need to set the default Image when the network Image load error. I used to write the code like this: { ImageUrl? <Image style={styles.docimg} source={{uri: ImageUrl}}/> : <Image style={styles.docimg} source={require('../../../resource/default.png')}/> } Now there is a problem. When the URL is a string type, but it isn't a correct network Image. As the URL is true then the Image will show nothing. I saw the Image props onError maybe solve my issue. I need to set the placeholder Image. A: Work for me <ImageBackground style={{ width: 100, height: 100, marginRight: 20, borderRadius: 10, }} source={ require('../../assets/images/Spinner.gif') //Indicator }> <Image style={{ width: 100, height: 100, marginRight: 20, borderRadius: 10, }} source={{ uri: `//Image U want To Show` }} /> </ImageBackground> A: const [error, setError]=setState(false); return(){ <Image onError={(error) => { setError(true); }} source={ error ? require("../../assets/images/defaultImage.png") : { uri: imageUrl } } /> } This will show the default image if your network image fails to load or gives an error 404. A: I have tried using @Ravi Raj's answer but seems not related to failure on loading image. Beside the answer will make the image keep flashing between the default and actual image. ( The error that @vzhen met ) Therefore I have developed based on his answer and generated this component. See if this suits you ;) progressive-image.js - Component <ProgressiveImage/> import React, { Component } from 'react'; import { Image } from 'react-native'; export default class ProgressiveImage extends Component { state = { showDefault: true, error: false }; render() { var image = this.state.showDefault ? require('loading.png') : ( this.state.error ? require('error.png') : { uri: this.props.uri } ); return ( <Image style={this.props.style} source={image} onLoadEnd={() => this.setState({showDefault: false})} onError={() => this.setState({error: true})} resizeMode={this.props.resizeMode}/> ); } } Then import and call the component like this: import ProgressiveImage from './progressive-image'; <ProgressiveImage style={{width: 100, height: 100}} uri={'http://abc.def/ghi.jpg'} resizeMode='contain'/> Hope this answer can help you ;) A: You just try this and hope it works... // initially showDefault will be false var icon = this.state.showDefault ? require('../../../resource/default.png') : {uri: ImageUrl}; return( <Image style={styles.docimg} source={icon} onLoadStart={() => this.setState({showDefault: true})} onLoad={() => this.setState({showDefault: false})} /> ) Setting showDefault = false in onLoad() should not trigger url fetch again since images are cached by default in android and IOS. A: According to the docs, the defaultSource prop is ignored on Android on Debug builds, so if you are looking for a placeholder while the actual source is loading -- not in case of errors -- make sure to test on release mode before implementing workarounds to load it only because of debug mode. "Note: On Android, the default source prop is ignored on debug builds." A: defaultSource doesn't work on android... Please follow the method bellow to fix it: Dont forget to import View, ImageBackground, & Image class MyComponent extends Component { constructor() { this.state = { isImageLoading: true, } } render() { <View> <ImageBackground source={{ uri: this.state.isImageLoading ? YOUR_DEFAULT_IMAGE : null }} > <Image source={{ uri: YOUR_IMAGE }} onLoad={() => this.setState({ isImageLoading: false })} /> </ImageBackground> </View> } }
stackoverflow
{ "language": "en", "length": 538, "provenance": "stackexchange_0000F.jsonl.gz:897817", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644755" }
93822c86a0bc03282aa6515b2121fc4b538d5608
Stackoverflow Stackexchange Q: How to get source code of a class constructor in Javascript I'd like to get source code of class constructor. For normal functions, toString() can show source code of itself. But constructor's toString() shows the entire class' source code. I have a demo here: class TestClass { constructor() { console.log('constructor'); } hello() { console.log('hello'); } } console.log(' ----- hello -----') console.log(TestClass.prototype.hello.toString()) console.log(' ----- constructor -----') console.log(TestClass.prototype.constructor.toString())
Q: How to get source code of a class constructor in Javascript I'd like to get source code of class constructor. For normal functions, toString() can show source code of itself. But constructor's toString() shows the entire class' source code. I have a demo here: class TestClass { constructor() { console.log('constructor'); } hello() { console.log('hello'); } } console.log(' ----- hello -----') console.log(TestClass.prototype.hello.toString()) console.log(' ----- constructor -----') console.log(TestClass.prototype.constructor.toString())
stackoverflow
{ "language": "en", "length": 67, "provenance": "stackexchange_0000F.jsonl.gz:897818", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644767" }
f4b03a9f93f960a9d9d4a12f8dceb1294212ef90
Stackoverflow Stackexchange Q: Which method is called when back to previous view via navigation controller? I used navigation controller in my app. Back button is working fine, when it is tapped previous view is appearing. I need to know, in previous view, which method is getting called while appearing. Any assistance would be appreciated. A: When you go back the following methods will be called: Notifies the view controller that its view is about to be added to a view hierarchy. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } Notifies the view controller that its view was added to a view hierarchy. override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) }
Q: Which method is called when back to previous view via navigation controller? I used navigation controller in my app. Back button is working fine, when it is tapped previous view is appearing. I need to know, in previous view, which method is getting called while appearing. Any assistance would be appreciated. A: When you go back the following methods will be called: Notifies the view controller that its view is about to be added to a view hierarchy. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } Notifies the view controller that its view was added to a view hierarchy. override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } A: When your previous view is appearing, viewWillAppear(:) and viewDidAppear(:) called every time while view is appearing. A: When a view controller reappears * *It will call viewWillAppear(_:) .. also you can define other view appearing methods like viewDidAppear(_:) *it will not call viewDidLoad() Please check the Apple Document in detail to understand the View Controller Lifecycle https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:897865", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644916" }
ffa774d76b8b984d2b0a03d90dd0443fedbd984e
Stackoverflow Stackexchange Q: Any New Column is Null value in Entity Framework I am adding a new column to exiting database table with values, but when I used the entity framework model, the column data value return Null, however its has a real value in database. How solve this problem? A: If you are using LINQ for data retrieval: Double click and open edmx -> right click and select update from database -> select refresh tab and select your table and click ok. The above will update your dbcontext file. If you are using stored procedure, you will have to update the complex type of your stored procedure
Q: Any New Column is Null value in Entity Framework I am adding a new column to exiting database table with values, but when I used the entity framework model, the column data value return Null, however its has a real value in database. How solve this problem? A: If you are using LINQ for data retrieval: Double click and open edmx -> right click and select update from database -> select refresh tab and select your table and click ok. The above will update your dbcontext file. If you are using stored procedure, you will have to update the complex type of your stored procedure A: The most likely explanation for your problem is that you did not COMMIT the changes you made to the database. Not the changes to the schema but the table updates. EF is returning NULL values because you did not commit your changes so the actual field values are ... NULL !
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:897871", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644934" }
8613857a093afa649b12c5d20a3cb9fb09e31175
Stackoverflow Stackexchange Q: binning data via DecisionTreeClassifier sklearn? suppose I have a data set: X y 20 0 22 0 24 1 27 0 30 1 40 1 20 0 ... I try to discretize X into few bins by minimizing the entropy. so I did the following: clf = tree.DecisionTreeClassifier(criterion = 'entropy',max_depth = 4) clf.fit(X.values.reshape(-1,1),y.values) threshold = clf.tree_.threshold[clf.tree_.threshold>-2] threshold = np.sort(threshold) 'threshold' should give the splitting points, is this a correct way of binning data? any suggestions? A: first, what you did is correct. There are many ways to bin your data: * *based on the values of the column (like: dividing the column for 10 equal groups between min and max of the column value). *based on the distribution of the column values, for example it's could be 10 groups based on the deciles of the column (better to use pandas.qcut for that) *based on the target, like you did. I found this blog relevant to you and I think your method for finding the best splits works just fine https://towardsdatascience.com/discretisation-using-decision-trees-21910483fa4b
Q: binning data via DecisionTreeClassifier sklearn? suppose I have a data set: X y 20 0 22 0 24 1 27 0 30 1 40 1 20 0 ... I try to discretize X into few bins by minimizing the entropy. so I did the following: clf = tree.DecisionTreeClassifier(criterion = 'entropy',max_depth = 4) clf.fit(X.values.reshape(-1,1),y.values) threshold = clf.tree_.threshold[clf.tree_.threshold>-2] threshold = np.sort(threshold) 'threshold' should give the splitting points, is this a correct way of binning data? any suggestions? A: first, what you did is correct. There are many ways to bin your data: * *based on the values of the column (like: dividing the column for 10 equal groups between min and max of the column value). *based on the distribution of the column values, for example it's could be 10 groups based on the deciles of the column (better to use pandas.qcut for that) *based on the target, like you did. I found this blog relevant to you and I think your method for finding the best splits works just fine https://towardsdatascience.com/discretisation-using-decision-trees-21910483fa4b
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:897873", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644945" }
6f75d902ec06853788c7e16e1257ec55f732bb2b
Stackoverflow Stackexchange Q: Is there any way to auto format ( AStyle ) while typing code in Code::Blocks? I always format code in Code::Blocks using Source Code Formatter (AStyle) plugin. I need to press short-cut keys or right click to mouse to apply formatting. Is there any better way to format code without pressing any keys or mouse clicks? Thanks !!
Q: Is there any way to auto format ( AStyle ) while typing code in Code::Blocks? I always format code in Code::Blocks using Source Code Formatter (AStyle) plugin. I need to press short-cut keys or right click to mouse to apply formatting. Is there any better way to format code without pressing any keys or mouse clicks? Thanks !!
stackoverflow
{ "language": "en", "length": 59, "provenance": "stackexchange_0000F.jsonl.gz:897874", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44644950" }