text
stringlengths 0
13M
|
---|
Title: Use Guice multibindings with assisted inject for the set members
Tags: java;scala;guice
Question: I have a class ```PluginManager``` which accepts a ```Set<Plugin>``` using the Guice multi-bindings feature. However, the ```PluginManager``` has some runtime information that needs to be passed to the ```Plugin``` constructor.
This seems to be a perfect use-case for Guice assisted injection i.e. my ```PluginManager``` would have ```Set<PluginFactory>``` injected, where the runtime information is provided to each factory, resulting in the required ```Plugin``` instances.
I don't know the syntax to use in the ```Module``` however. The multibinder ```addBinding``` does not seem to have any facility to connect the result of ```FactoryModuleBuilder```.
I can create my own custom Factory implementations and multibind that obviously, but is there a way to combine multibinder with assisted inject?
Here is the accepted answer: I think this gives you an example to do exactly what you want. Please note that scala's multibinder has a pending pull request that allows you to create the set binder in multiple places.
```object Test {
trait Plugin {
def name(): String
}
object Plugin {
trait Factory[+T <: Plugin] {
def newPlugin(name: String): T
}
}
case class MyPlugin @Inject() (@Assisted name: String) extends Plugin
case class OtherPlugin @Inject() (@Assisted name: String) extends Plugin
class PluginManager @Inject() (pluginFactories: Set[Plugin.Factory[Plugin]]) {
for (factory <- pluginFactories) {
println(factory.newPlugin("assisted injection"))
}
}
def main(args: Array[String]): Unit = {
val injector = Guice.createInjector(new ScalaModule {
override def configure(): Unit = {
val plugins = ScalaMultibinder.newSetBinder[Plugin.Factory[Plugin]](binder)
plugins.addBinding().to[Plugin.Factory[MyPlugin]]
plugins.addBinding().to[Plugin.Factory[OtherPlugin]]
bindFactory[Plugin, MyPlugin, Plugin.Factory[MyPlugin]]()
bindFactory[Plugin, OtherPlugin, Plugin.Factory[OtherPlugin]]()
bind[PluginManager].asEagerSingleton()
}
def bindFactory[I: Manifest, C <: I : Manifest, F: Manifest](): Unit = {
import net.codingwell.scalaguice._
install(new FactoryModuleBuilder()
.implement(typeLiteral[I], typeLiteral[C])
.build(typeLiteral[F]))
}
})
}
}
```
You can do a bunch of things depending on the style you want. For example you could make a generic addPlugin method (when a newer version of scala-guice is released) like this:
```val injector = Guice.createInjector(new ScalaModule {
override def configure(): Unit = {
bindPlugin[MyPlugin]()
bindPlugin[OtherPlugin]()
bind[PluginManager].asEagerSingleton()
}
def bindPlugin[T <: Plugin : Manifest](): Unit = {
val plugins = ScalaMultibinder.newSetBinder[Plugin.Factory[T]](binder)
plugins.addBinding().to[Plugin.Factory[T]]
bindFactory[Plugin, T, Plugin.Factory[T]]()
}
def bindFactory[I: Manifest, C <: I : Manifest, F: Manifest](): Unit = {
import net.codingwell.scalaguice._
install(new FactoryModuleBuilder()
.implement(typeLiteral[I], typeLiteral[C])
.build(typeLiteral[F]))
}
})
```
Comment for this answer: I know it does! =) I wrote the pull request =).
Comment for this answer: Thank you, I was close to this but didn't have a generic type on my Factory trait, and so Guice was telling me I couldn't bind each plugin because it had already been bound. This worked perfectly!
Comment for this answer: BTW, I did run into the issue you mentioned with scala-guice and Multibinder (https://github.com/codingwell/scala-guice/issues/29) but the code in your referenced pull request fixed it. Thanks!
|
Title: Donut shape related to concentric circles in QGIS
Tags: pyqgis
Question: I would like to get an area between 10 miles and 20 miles from the center of counties. To do that, I wrote the code and got the following image. But, as you can see, there are some empty points, as the processing of "difference" clip the original 10 miles areas. I would like to get a donut shape.
Any idea?
```# Get centers of counties related to budgets
result = processing.run("native:meancoordinates", {
'INPUT': mem_layer,
'WEIGHT':None,
'UID':'fips_budgets',
'OUTPUT':'memory:'})
center = result['OUTPUT']
# Get buffers related to center from 10 miles
result = processing.run("native:buffer", {
'INPUT': center,
'DISTANCE':0.144985991,
'SEGMENTS':5,
'END_CAP_STYLE':0,
'JOIN_STYLE':0,
'MITER_LIMIT':2,
'DISSOLVE':False,
'OUTPUT':'memory:'})
buffer = result['OUTPUT']
# Get buffers related to center from 20 miles
result = processing.run("native:buffer", {
'INPUT': center,
'DISTANCE':0.289971982,
'SEGMENTS':5,
'END_CAP_STYLE':0,
'JOIN_STYLE':0,
'MITER_LIMIT':2,
'DISSOLVE':False,
'OUTPUT':'memory:'})
buffer2 = result['OUTPUT']
# Get 20-10 miles areas
result = processing.run("native:difference", {
'INPUT': buffer2,
'OVERLAY': buffer,
'OUTPUT':'memory:'})
buffer3 = result['OUTPUT']
QgsProject.instance().addMapLayer(buffer3)
```
I can get the result.
Actually, each center point has an ID (fips)[picture 2]. I would like to pass this information to the donut layer because I would like to define counties related to the center of the county. To do this, I am planning to use "intersection" such as the following code. Then, I would like to get information "This centered county (A) may affect the following counties (B, C, D) within the donut area". But, I could not get this information like [picture 3] because of the lack of the information.
```Donuts = vl
# Get intersection of buffer and counties
result = processing.run("native:intersection", {
'INPUT': Donuts,
'OVERLAY': mem_layer,
'INPUT_FIELDS':[],
'OVERLAY_FIELDS':[],
'OVERLAY_FIELDS_PREFIX':'',
'OUTPUT':'memory:'})
intersection = result['OUTPUT']
QgsProject.instance().addMapLayer(intersection)
```
Here is the accepted answer: You can access the individual point geometries using getFeatures then use the methods of the geometry to buffer twice and then difference:
```#List the point layer fields
layer = iface.activeLayer()
layerfields = [f for f in layer.fields()]
#Create a memory layer and add the same fields (partly from https://anitagraser.com/pyqgis-101-introduction-to-qgis-python-programming-for-non-programmers/pyqgis101-creating-editing-a-new-vector-layer/)
vl = QgsVectorLayer("Polygon?crs={}&index=yes".format(layer.crs().authid()), "Donuts", "memory")
pr = vl.dataProvider()
fieldlist = []
for f in layerfields:
newfield = QgsField(name=f.name(), type=f.type())
fieldlist.append(newfield)
pr.addAttributes(fieldlist)
vl.updateFields()
#Iterate over each point, buffer*2, difference, add geometry and attributes
for f in layer.getFeatures():
geom = f.geometry()
buff1 = geom.buffer(1000,5) #Small buffer
buff2 = geom.buffer(1500,5) #Bigger buffer
donut = buff2.difference(buff1) #Difference between them
#Add the new donut polygon feature
newfeature = QgsFeature()
newfeature.setGeometry(donut)
newfeature.setAttributes(f.attributes())
pr.addFeature(newfeature)
QgsProject.instance().addMapLayer(vl)
```
|
Title: GStreamer: cannot put pipeline to play
Tags: opencv;video;gstreamer
Question: this is a command what I run in the terminal,```rosrun ros_exploration ros_exploration```after that, I got an unexpected error as below.it should be mentioning that the note,```GStreamer: cannot put pipeline to play```probably is the key point of this problem. unfortunately, I don't know how do I fix it.
```0:00:04.442429649 3130 0x2071c90 ERROR omx gstomx.c:3249:plugin_init: Failed to load configuration file: Valid key file could not be found in search dirs (searched in: /home/htf/.config:/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg:/usr/local/etc/xdg as per GST_OMX_CONFIG_DIR environment variable, the xdg user config directory (or XDG_CONFIG_HOME) and the system config directory (or XDG_CONFIG_DIRS)
0:00:04.990602557 3078 0x7fd5a8002e70 ERROR GST_PIPELINE grammar.y:816:priv_gst_parse_yyparse: no element "Video"
(ros_exploration:3078): GStreamer-CRITICAL **: gst_element_make_from_uri: assertion 'gst_uri_is_valid (uri)' failed
0:00:04.990762618 3078 0x7fd5a8002e70 ERROR GST_PIPELINE grammar.y:971:priv_gst_parse_yyparse: no source element for URI "/18_09_11-11:44:53-PCL.avi"
GStreamer Plugin: Embedded video playback halted; module filesink0 reported: Could not open file "Video/18_09_11-11:44:53-PCL.avi" for writing.
GStreamer Plugin: Embedded video playback halted; module filesink0 reported: GStreamer error: state change failed and some element failed to post a proper error message with the reason for the failure.
OpenCV Error: Unspecified error (GStreamer: cannot put pipeline to play
) in CvVideoWriter_GStreamer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16open, file /home/htf/Downloads/opencv-667.385.0637/modules/highgui/src/cap_gstreamer.cpp, line 1528
Qt has caught an exception thrown from an event handler. Throwing
exceptions from an event handler is not supported in Qt. You must
reimplement QApplication181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16notify() and catch all exceptions there.
terminate called after throwing an instance of 'cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16xception'
what(): /home/htf/Downloads/opencv-667.385.0637/modules/highgui/src/cap_gstreamer.cpp:1528: error: (-2) GStreamer: cannot put pipeline to play
in function CvVideoWriter_GStreamer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16open
Aborted (core dumped)
```
If you have ever used GStreamer or met the relevant problems and solutions, little clues would be appreciated.
here is a part of relevant codes,
PCL_VideoWriter.open(FileName.toAscii().data(),CV_FOURCC('M','P','2','V'),FPS,cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Size(640,480));
// MainTimer->start(viewer_thr->loop_time);
``` if(SLAM_IMG_Capture_flag == 1)
{
FileName.clear();
FileName = "Video/"+CurrDateText+"-"+CurrTimeText+"-SLAM"+".avi";
```
I tried to recompile OpenCV-2.4.13. here are my commands,```cmake cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local/opencv-2.4.13 -D WITH_FFMPEG=ON ..```& ```make```&
````sudo make install`
```
. Then I got this,
``` Video I/O:
-- DC1394 1.x: NO
-- DC1394 2.x: YES (ver 2.2.1)
-- FFMPEG: YES
-- avcodec: YES (ver 58.18.100)
-- avformat: YES (ver 58.12.100)
-- avutil: YES (ver 56.14.100)
-- swscale: YES (ver 5.1.100)
-- avresample: YES (ver 1.0.1)
-- GStreamer:
-- base: YES (ver 667.385.0637)
-- video: YES (ver 667.385.0637)
-- app: YES (ver 667.385.0637)
-- riff: YES (ver 667.385.0637)
-- pbutils: YES (ver 667.385.0637)
```
however, the error is that ```error: ‘CV_CAP_FFMPEG’ was not declared in this scope``` or ```error: ‘CAP_FFMPEG’ is not a member of ‘cv’``` still exists.
Here is the accepted answer: From what i see you are trying to open a video file not a gstreamer pipe. For this case using FFMPEG interface of opencv might be more useful. ```VideoWriter``` class has an overload function for it:
```bool cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16VideoWriter181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16open ( const String & filename,
int apiPreference,
int fourcc,
double fps,
Size frameSize,
bool isColor = true
)
```
You may use it like:
```PCL_VideoWriter.open(FileName.toAscii().data(),CAP_FFMPEG,CV_FOURCC('M','P','2','V'),FPS,cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Size(640,480));
// MainTimer->start(viewer_thr->loop_time);
```
Also, is the video in correct path i.e "Video/18_09_11-11:44:53-PCL.avi"?
Comment for this answer: Sorry, I confused VideoCapture and VideoWriter. Now I updated the answer. Could you try the overloaded `open` function with `CAP_FFMPEG` parameter instead of the original.
Comment for this answer: `CAP_FFMPEG` _is_ the parameter. you can use it directly, or with namespace `cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16P_FFMPEG`. Hopefully, you have FFMPEG installed in your system and OpenCV is compiled with FFMPEG flags turned on.
Comment for this answer: I guess it's the same in 2.4. One possibility is that you are missing FFMPEG in your OpenCv build. You might need to re-build OpenCv with FFMPEG flags enabled.
Comment for this answer: @HanJingyu could you try again after enabling avresample? You need to install `libavresample-dev` package (`sudo apt-get install libavresample-dev`)
Comment for this answer: I said that because FFMPEG requires all sub-requirements to work properly. Is your initial code (without CAP_FFMPEG ) also not working?
Comment for this answer: @HanJingyu sorry, I forgot this thread. From what I read recompiling OpenCv doesn't affect your results, hopefully you recompiled your application after recompiling OpenCv. I don't think other commands are necessary, we want to disable gstreamer and use FFMPEG instead.
Comment for this answer: I also posted the relevant codes. I have never used the GStreamer, so the question is what should I type in the terminal after installed successfully if launching GStreamer.@Alper Kucukkomurler
Comment for this answer: to be honest, codes related to video capturing was written by one of a classmate, So I also not sure whether the generated video on the correct path. I was guessing the video should be saved in home/Videos(ubuntu).@Alper Kucukkomurler
Comment for this answer: if possible, could you tell me what the CAP_FFMPEG parameter should be? sorry, I got confused with all of this project.@Alper Kucukkomurler
Comment for this answer: However, I am using OpenCV-2.4.13. so cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16P_FFMPEG is not a member of "cv" namespace.@ Alper Kucukkomurler
Comment for this answer: because I am using OpenCV-2.4.13, I tried to rewrite a suitable format of cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16P_FFMPEG. but ‘CV_CAP_FFMPEG’ was not declared in this scope. so if possible, could you tell me what is the proper format of cv181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 FFMPEG under 2.4.13? Besides, I also tried to use OpenCV-3.4.0. unfortunately, most part of this project is based on OpenCV-2.4.13. so it's very difficult for me to update a new version.
Comment for this answer: I have already followed your clues and updated the descriptions of my problem as you can see above.@Alper Kucukkomurler. thank you for your patience.
Comment for this answer: I did followed what you said, but it doesn't make sense.@ Alper Kucukkomurler
Comment for this answer: NO, without these words, the code could be compiled smoothly. However, when typing some commands to launch the file, I will get an unexpected error as above.@Alper Kucukkomurler
Comment for this answer: here is the corresponding project posted on GitHub
https://github.com/TengFeiHan0/AFOA-SLAM/blob/master/ros_exploration/src/captureviewer.cpp
Comment for this answer: have you found a solution to this problem? if you have more ideas, please feel free to contact me. thanks a lot.@Alper Kucukkomurler
Comment for this answer: before typing rosrun ros_exploration ros_exploration, do I need to enter some other commands related to GStreamer?just as this document said,https://gstreamer.freedesktop.org/documentation/tools/gst-launch.html
@Alper Kucukkomurler
|
Title: Command not found after installing successfully via pip
Tags: python;youtube;pip
Question: I just downloaded ```youtube-dl``` via pip as follows:
```sukhvir@SN:~$ sudo pip install youtube-dl
Downloading/unpacking youtube-dl
Downloading youtube_dl-2015.06.25-py2.py3-none-any.whl (965kB): 965kB downloaded
Installing collected packages: youtube-dl
Successfully installed youtube-dl
Cleaning up...
```
then when i try to run it, the following error shows up:
```sukhvir@SN:~$ youtube-dl https://www.youtube.com/watch?v=QcIy9NiNbmo
-bash: youtube-dl: command not found
```
Can you please help as to why this is happening and how can i rectify this issue ?
Comment: It's a python module so maybe try running it inside the python shell?
Comment: its funny .. i am able to run it if i install it using easy_install .. but not if I do it using pip
Here is the accepted answer: I know it is a bit old, but I ran in the same problem.
The solution is simple: you installed it with 'sudo' rights,
so if you run it with ```sudo youtube-dl``` will start without problem (as module).
To avoid this, you could install ```pip install --user youtube-dl```
|
Title: Unit test computed property on an Ember controller
Tags: unit-testing;ember.js;ember-cli;qunit;ember-qunit
Question: The code from my controllers/cart.js:
```export default Ember.Controller.extend({
cartTotal: Ember.computed('[email protected]', function() {
return this.model.reduce(function(subTotal, product) {
var total = subTotal + product.get('subTotal');
return total;
}, 0);
})
)};
```
This computed property loops over all the elements in the model, adding all the values of the ```subTotal``` property, returning a ```cart total```.
cart-test.js
```import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:cart', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
var controller = this.subject();
assert.ok(controller);
});
test('cartTotal function exists', function(assert) {
var controller = this.subject();
assert.equal(controller.get('cartTotal'), 30, 'The cart total function exists');
});
```
The test fails with ```TypeError: Cannot read property 'reduce' of null``` because it obviously doesn't have a model to loop over.
How can I mock the dependencies of the ```cartTotal``` computed property to make the test pass?
Thanks!
Comment: Can you add the rest of your test's code?
Comment: done. edited the post
Here is the accepted answer: Something along these lines maybe?
```import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
var products = [
Ember.Object.create({ name: 'shoe', subTotal: 10 }),
Ember.Object.create({ name: 'shirt', subTotal: 20 })];
var model = Ember.ArrayProxy.create({
content: Ember.A(products)
});
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject();
}
});
test('cartTotal', function(assert) {
this.controller.set('model', model);
assert.equal(this.controller.get('cartTotal'), 30, 'The cart total function exists');
});
```
Comment for this answer: Yeah, I just pulled examples from different sources and don't have an actual ember-cli app to test stuff in so I don't know why importing the model doesn't work. Oh well.
Comment for this answer: yes! With a little difference: instead of `Product.create` we could not even import our model and instead use `Ember.Object.create`
In fact with the `Product.create` I got errors. It worked with Ember.Object.create.
If you make the changes to your answer I shall mark it as the correct one.
Thanks a lot for your help!
Comment for this answer: it was importing. it failed with an error to use `store.createRecord` instead of `Product.create`.
Here is another answer: One way to deal with this would be to stub the model in the ```beforeEach``` hook:
```var sampleModel = [ // sample data that follows your actual model structure ]
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject(); // allows you to access it in the tests without having to redefine it each time
this.controller.set('model', sampleModel);
}
});
```
Comment for this answer: Oups, used an object instead of an array x.x
Comment for this answer: Thanks. I've edited my first post with the result I got from trying this out. I have a feeling I may not be doing it correctly, but I feel like I got closer.
Comment for this answer: Your answer was going down the right path though :)
|
Title: Custom Field Alerts in TFS 2012
Tags: tfs-alerts
Question: I added a custom field (Product Owner) in ```TFS```. Since I wanted a drop down of valid ```TFS``` users, I copied the setup of the Assigned To control ```(String, Dimension, ALLOWEXISTINGVALUE, VALIDUSER)```. I want to be able to set up an alert that says:
```Product Owner = [Me]
```
but equals is not an available option in the operator drop down list. When I try to set up an alert my only options for this field are ```Changes, Changes From, Changes To```.
Suggestions?
Thanks,
Troy
Here is the accepted answer: • In the Eventing system, there are two types of fields: core fields and non-core fields. When building the alert definition, you can only use Changes, Changes From and Changes To for certain core fields. In the Alerts Explorer Alert Definition, there are different operators depending on whether the field is a core field or not. Core fields will have =, <> and other equality operators along with Changes, Changes From and Changes To. All other fields only have the change-based operators.
Core fields that are part of every work item type are listed below:
- Activated By
- Activated Date
- Area Path
- Assigned To
- Attached File Count
- Authorized As
- Changed By
- Changed Date
- Created By
- Created Date
- Description
- ID
- Iteration Path
- PortfolioProject
- Reason
- State
- Title
- Work Item Type
All other fields are in the non-core field category.
When there is a change in the system, the Eventing system creates an XML message to represent that change. To reduce data volume and processing overhead, the XML message contains the values for the core fields and the values for any field that changed. It does not contain any non-core fields that did not change.
Sorry, this seems not possible here.
Maybe some others have some dirty tricks, I would love to know : )
Thank you!
Evgeniya
Here is another answer: Has anyone found a work around for this? I don't see why I can't use the variable "[Me]" for a custom field, cmon Microsoft. I'd guess maybe use a hidden field that does a check for this or something along those lines
Comment for this answer: found a MSDN thread : [Not getting the "=" in Alerts explorer](https://social.msdn.microsoft.com/Forums/en-US/b6f2ed98-6f66-4b86-bc95-1d7123cac1ba/not-getting-the-in-alerts-explorer?forum=tfspowertools)
|
Title: How to monitor the features called in after scenario and after feature hooks?
Tags: karate
Question: I am calling a feature file after-feature hook .
It is mentioned in the readme that
```# one limitation of afterScenario and afterFeature is that any feature steps involved will NOT appear
```
So how to check whether anything has failed in the feature file called in after-feature hook?
One possibility is to use karate.log file , but is there any other way to generate reports for it?
Here is the accepted answer: There is no other way, print to the log.
You can also create a feature file just to test this feature being called and debug that using the Karate UI.
It may be a better idea to use the yet undocumented Java hook, see this example MandatoryTagHook
|
Title: Stata regression with conditions on dummies and variable values
Tags: regression;stata;dummy-variable;multiple-conditions;two-way
Question: I'm trying to create a regression that would include a polynomial (let's say 2nd order) of ```year``` on a certain interval of ```year``` (say 1 to 70) and a number of dummies for certain values of ```year``` (say for every ```year``` between 45 and 60).
If I didn't have the restriction for dummies, I believe the commands would be:
```gen year2=year^2
regress y year year2 i.year if inrange(year,1,70)
```
I can't make the dummies manually, there will be more than 15 of them in the end). Could anybody help me, please?
If I then want to plot the estimated function without the dummies, why do these two bring different things?
```twoway function _b[_cons] +_b[year]*x + _b[year2]*x^2, range(1 70)
twoway function _b[_cons] +_b[year]*year + _b[year2]*year^2, range(1 70)
```
The way I understood it, ```_b[_cons]```, ```_b[year]``` and ```_b[year2]``` call previously calculated coefficients for the corresponding independent variables and then multiplies it with them. Why does it bring different results then if ```x``` should be the same thing as ```year``` in this case?
Comment: I assumed both my questions arised from my unfamiliarity with Stata and may be easy to answer by people who have some experience with it. As such, could you please tell me which important features is it missing? Claiming it is a duplicate to my previous question suggests you haven't even read it.
Comment: You need to act on the advice given in your previous question please.
Comment: Possible duplicate of [how to make a flexible polynomial regression in Stata?](https://stackoverflow.com/questions/50213871/how-to-make-a-flexible-polynomial-regression-in-stata)
Comment: `twoway function` is unusual. It always plots in terms of a generic x-axis variable which it calls `x` and which is used regardless of whether any variable in the data is called (or abbreviates to) `x`. Referring to `x` in the syntax is needed for the command to make sense in most cases. It's not illegal not to mention `x` as for example `twoway function 2` has to be legal to show a horizontal line value 2 over the range 0 to 1, but specifying in terms of some other variable usually produces nonsense, or not what you want.
Comment: I've edited it out personal comments and padding, which don't help your question. For example, there is no queue you can jump by being under time pressure, as if no one else was! Claims of urgency are usually counter-productive.
Comment: Please don't snap at the people who are willing to help you. @PearlySpencer clearly did read your previous question and made fair comment on it. It's not a good question for the reasons given.
Here is another answer: I am not sure why Pearly is giving you such a hard time, I think this may be what you're looking for, but let me know if it is something different:
One thing to note, I am using a dataset that comes preloaded with Stata and this is usually a nice way to make a MVCE like Nick was saying in your other post.
```clear
sysuse gnp96
/* variables: gnp, date (quarterly) */
gen year = year(dofq(date)) // get yearly variable
gen year2=year^2 // get the square of the yearly variable
tab year if inrange(year,1970,1975), gen(yr) // generate dummy variables
// the dummy varibales generated have null values for years not
// in the specified range, so we're going to fill those in
foreach v of varlist yr* {
replace `v' = 0 if `v' == .
}
// here's your regression
regress gnp year year2 yr* if inrange(year,1967,1990)
```
Now, the yr* are your dummy variables and the * is a wildcard calling all variables named like yr[something]
This gives you the range for the dummy variables and the range for the year variables.
As to your question on using x vs year, I am only hypothesizing, but I think that when you use x it is continuous since Stata isn't looking at your variables, but instead just at the x axis whereas your year variable is discrete (a bunch of integers) so it looks more like a step function. More information can be found using the command ```help twoway function```
Comment for this answer: Sure it is okay to be a beginner. I was one too. And all volunteers on here, i am certain they want to help. But they cannot do so effectively and on a regular basis if they have to guess what each question is asking, re-write the OPs' questions for clarity, provide a MVCE and so on.
Comment for this answer: On the first and last paragraphs, please see my comments on the main question.
Comment for this answer: I read that blog post too, and much of the commentary on it as well. FWIW, I don't think that has anything to do with a difficult and time-consuming question being too difficult and time-consuming to be worth my detailed effort. SO is not a help-line in which every question is entitled to an answer. We can choose what to ignore! Also, I put effort here not just into answering questions but also in trying to be clear on why it is difficult or even impossible to answer a question. Any implication that I should be infinitely obliging is not one that I can achieve.
Comment for this answer: @NickCox https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/
it's okay to be a beginner here, I couldn't answer the linked question, but this one was completely different and understandable even if it was not formatted wonderfully
|
Title: Check which element is above other
Tags: javascript;overlapping
Question: Say I have two boxes overlapping (fiddle)
```<html>
<body>
<div class="box">element 1</div>
<div class="box" style="left: 20px; top: 10px; background-color: red;">element 2</div>
<style>
.box {
background-color: green;
position: absolute;
width: 100px;
height: 100px;
border: 1px sold red;
}
</style>
</body>
</html>
```
Is there a way to tell which box is above the other in vanilla javascript? I only care about what the user visually perceives as above.
Something like below
```isAbove(el1, el2) // false
isAbove(el2, el1) // true
```
Comment: Above means what? Higher z-index?
Comment: I know, your question was unclear hence why it did not get attention in the last 6 hours. The deleted answer thought it meant x, y position.
Comment: Note, `heght` should be `height` at CSS at question and linked jsfiddle
Comment: conceptually, you'd want to find their first common parent and then determine which comes first by declaration
Comment: @epascarello it means visually being above another. The question is how to check that. Checking by z-index doesn't work in the example above.
Comment: It seems to me that your view is driving your model. Unless you're trying to inject something into a page over which you have no control, I can't see why you'd need to know this.
Here is another answer: Simply get those elements zIndex and compare them
Here is another answer: about the only way i can think of to tell is to get the dom paths of the elements involved and check which one comes first by declaration; this should give you an idea in the absence of z-index which element would naturally be shown 'on top' of the other.
```function getAncestors(ele) {
var ancestors = [ele];
while(ele.parentElement) { // walk all parents and get ancestor list
ele = ele.parentElement;
ancestors.push(ele);
}
return ancestors.reverse(); // flip list so it starts with root
}
function declaredBefore(ele1,ele2) {
var a1 = getAncestors(ele1);
var a2 = getAncestors(ele2);
for(var i=0;i<a1.length;i++) { // check path, starting from root
if(a1[i] !== a2[i]) { // at first divergent path
var testNodes = a1[i-1].childNodes; // get children of common ancestor
for(var j=0;j<testNodes.length;j++) { // check them for first disparate ancestor
if(testNodes[j] === a1[i]) { return true; } // ele1 is first
if(testNodes[j] === a2[i]) { return false; } // ele2 is first
}
}
}
return undefined; // could not determine who was first
}
function isAbove(ele1, ele2) {
// rudimentary z-index check for eles sharing a parent
if(ele1.parentNode === ele2.parentNode) {
var z1 = ele1.style.zIndex;
var z2 = ele2.style.zIndex;
if(z1 !== undefined && z2 !== undefined) { // if both have z-index, test that
return z1 > z2;
}
}
return declaredBefore(ele2, ele1); // if 2 is declared before 1, 1 is on top
}
```
this solution is far from bulletproof, but it should at least let you know which element is declared last, accounting for dom tree hierarchy. it also does not compare zIndex unless the elements share a parent, although you could probably modify that to check zIndex hierarchy of parents as well.
Comment for this answer: whatever appears last in document order is rendered on top; in the absence of z-index, elements are in z-order based on their document tree position, respecting heirarchy. you can get around this with css (flexbox is a good example, you can change the item order which presumably change the internal z-order). my example tests whichever is declared _last_, which should by default be 'on top' in terms of rendering.
Comment for this answer: This assumes though that an element following another, is rendered first. Is this how all browsers act?
|
Title: How to chain animation in android to the same view?
Tags: android;animation;view;chaining;chained
Question: I got some text views and I want to make the buzz effect of MSN.
My plan is:
take the view, let say 10dip to the left,
take it back to its start position
after that take it 10dip up
then back
down back
left... and so on.
My point is, I have some sequence of movements that I want to set to one view and that needs to execute one after another.
How can I do that?
Here is the accepted answer: Use an AnimationSet:
```AnimationSet set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(100);
set.addAnimation(animation);
animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
);
animation.setDuration(500);
set.addAnimation(animation);
view.startAnimation( set );
```
Comment for this answer: This answer is not correct. Animations will launch simulatneously.
Comment for this answer: Can you at least modify it? It's really confusing.
Comment for this answer: I agree, this answer is just wrong. But I can't delete it as it has been accepted... @Lukap, please un-accept it.
Comment for this answer: I can't delete it neither as it has been accepted... @Lukap, please un-accept it and ping me.
Comment for this answer: This is indeed perfectly usable:
`
animDown.duration = 100;
animUp.duration = 300;
animUp.startOffset = animDown.duration;
val set = AnimationSet(true);
set.addAnimation(animDown);
set.addAnimation(animUp);
view.startAnimation(set);`
Comment for this answer: Just tried AnimationSet and doesn't chain animation. They are executed at the same time. This answer is wrong.
Comment for this answer: AnimationSet performs animations asynchronously. To achieve the desired effect, you need to use AnimationSet.setStartOffset() in the second animation
Comment for this answer: What??? This is wrong, animationSet animates its child animations together. "AnimationSet: Represents a group of Animations that should be played together."
Here is another answer: I have the beginnings of an sdk 15 compatible class that can be used to build complex animation chains hope it helps someone. You should be able to follow the design pattern to add your own methods. If you do please comment them here and I will update the answer, Cheers!
```package com.stuartclark45.magicmatt.util;
import java.util.LinkedList;
import java.util.List;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.view.View;
/**
* Used to build complex animations for a view. Example usage bellow makes view move out to the
* right whilst rotating 45 degrees, then move out to the left.
*
* {@code
* int rotateDuration = 200;
* int rotation = 45;
* new AnimationBuilder(view)
* .translationX(100, rotateDuration)
* .rotateTo(rotation, rotateDuration)
* .then()
* .translationX(-200, rotateDuration)
* .start();
* }
*
* @author Stuart Clark
*/
public class AnimationBuilder {
private View view;
private List<Animator> setsList;
private List<Animator> buildingList;
public AnimationBuilder(View view) {
this.view = view;
this.setsList = new LinkedList<>();
this.buildingList = new LinkedList<>();
}
public AnimationBuilder rotateTo(float deg, long duration) {
buildingList.add(ObjectAnimator.ofFloat(view, "rotation", deg).setDuration(duration));
return this;
}
public AnimationBuilder translationX(int deltaX, long duration) {
buildingList.add(ObjectAnimator.ofFloat(view, "translationX", deltaX).setDuration(duration));
return this;
}
public AnimationBuilder translationY(int deltaX, long duration) {
buildingList.add(ObjectAnimator.ofFloat(view, "translationY", deltaX).setDuration(duration));
return this;
}
public AnimationBuilder then() {
createAniSet();
// Reset the building list
buildingList = new LinkedList<>();
return this;
}
public void start() {
createAniSet();
AnimatorSet metaSet = new AnimatorSet();
metaSet.playSequentially(setsList);
metaSet.start();
}
private void createAniSet() {
AnimatorSet aniSet = new AnimatorSet();
aniSet.playTogether(buildingList);
setsList.add(aniSet);
}
}
```
Here is another answer: You probably mean AnimatorSet (not AnimationSet). As written in documentation:
```
This class plays a set of ```Animator``` objects in the specified order. Animations can be set up to play together, in sequence, or after a specified delay.
There are two different approaches to adding animations to a AnimatorSet: either the ```playTogether()``` or ```playSequentially()``` methods can be called to add a set of animations all at once, or the ```play(Animator)``` can be used in conjunction with methods in the ```Builder``` class to add animations one by one.
```
Animation which moves ```view``` by ```-100px``` for ```700ms``` and then disappears during ```300ms```:
```final View view = findViewById(R.id.my_view);
final Animator translationAnimator = ObjectAnimator
.ofFloat(view, View.TRANSLATION_Y, 0f, -100f)
.setDuration(700);
final Animator alphaAnimator = ObjectAnimator
.ofFloat(view, View.ALPHA, 1f, 0f)
.setDuration(300);
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(
translationAnimator,
alphaAnimator
);
animatorSet.start()
```
Comment for this answer: Don't forget `animatorSet.start()`
|
Title: ufw firewall rules are somehow autogenerated
Tags: networking;ufw;microk8s
Question: I try to create the following ufw rules:
```ufw default deny
ufw allow 51820/udp comment 'wireguard port'
ufw allow 22/tcp comment 'ssh'
ufw enable
```
but somehow i get alot of different rules as well:
```To Action From
-- ------ ----
[---]
Anywhere on vxlan.calico ALLOW Anywhere
Anywhere on cali+ ALLOW Anywhere
Anywhere ALLOW OUT Anywhere on vxlan.calico
Anywhere ALLOW OUT Anywhere on cali+
Anywhere (v6) ALLOW OUT Anywhere (v6) on vxlan.calico
Anywhere (v6) ALLOW OUT Anywhere (v6) on cali+
```
Background information: I installed microk8s ( a mini kubernetes) which installs calico as network.
I rly want to secure my server and avoid open ports to my kubernetes so that it is only reachable via the wireguard vpn.
Can someone help me avoiding this auto created ufw rules?
thanks ;)
Here is another answer: Some packages check for installed firewall and update the specific config even if the firewall is not enabled.
UFW is itself not the firewall, it is a firewall management system (like ```firewalld``` and some others). It keeps the config in ```/etc/ufw``` in two parts. First is the applications, which contains what an application needs from the firewall if it will be allowed. Second are the scripts with the actual configuration if the firewall is enabled.
I don't know the ```microk8s``` package in detail, but I think it finds ```ufw``` installed and writes the needed config in one of the rules files in ```/etc/ufw``` to make sure it is activated on enabling the firewall. Check the rules files for the words ```vxlan.calico``` and ```cali+``` and you will find the base ```iptables``` command which configure the iptables firewall. Or check the ```microk8s``` package install scripts in ```/var/lib/dpkg/info``` to see what it does with ```ufw```.
It's the same I do in case I write a package which needs some firewall config.
|
Title: How to move one folder back in Putty
Tags: putty
Question: I'm new to Putty and I have installed this on Windows.
I need to move one folder back (one folder upper) from current directory.
I tried ```cd..``` and ```cd...``` but didn't work out.
So how to move one folder back from this directory to an upper folder ?
Here is the accepted answer: if you want to go to an upper directory use this command :
```cd ..
```
|
Title: Run SAP GUI script in the background (not visible)
Tags: sap-gui
Question: I am writing a code using SAP GUI Scripting API to automate some tasks in the SAP GUI for Windows, but I need to hide the screens.
Is there such thing as a ```visible = false``` option?
If there is not, how can I do it?
Context: the SAP GUI Scripting API is called from VBA in Microsoft Outlook but is valid for any language automating SAP GUI via SAP GUI Scripting API.
Comment: not clear, what are you want from SAP, just read the data from it thro RFC, or trying to insert/update some SAP data?
Comment: did you try to use WScript.Shell?
Comment: Insert data, fill fields
Comment: I did not, would it be possible?
Here is another answer: You can connect to your server through ```OpenConnection``` or ```OpenConnectionByConnectionString``` using ```/INPLACE``` at the end of the connection string.
Resuming... Instead of use something like ```conn = scripting_engine.Children( 0 )```, try to use something like:
```conn = scripting_engine.OpenConnection( 'MYSAPCONNECTION /INPLACE' )
session = conn.Children( 0 )
```
By the away... See more at this link.
Here is another answer: Thank you all.
I figured it out, just needed to add
```.findById("wnd[0]").iconify
```
Thanks again
Comment for this answer: Does anyone know how can I apply this command "findById("wnd[0]").iconify" to the pop-ups windows?
I tried changing wnd[0] for wnd[1] but it did not work
Comment for this answer: Apologies for the late comment, if you didn't figure it out I think you may have to use `Application.SendKeys("{ENTER}")` from VBA. This will click the "Enter" key. However, this will only work when the popup window is activated.
Here is another answer: from my expirience, I know two options of running SAP script, the first one is using WScript.Shell, I know that there is too much information against this method, try to search about it
```Sub test()
Dim Wsh
Set Wsh = CreateObject("WScript.Shell").Run("C:\Users\USERNAME\Desktop\Script1.vbs")
End Sub
```
this method is allow to launch applications in your PC, e.g.:
```Sub test2()
Dim Wsh As Object
Set Wsh = CreateObject("WScript.Shell").Exec("calc.exe")
End Sub
```
the second one of running script, is the launch the code from script in MS office without *.vbs file, as in example bellow
```Option Explicit
Public SapGuiAuto As Object
Public ApplicationSAP As Object
Public Connection As Object
Public Session As Object
Sub start()
Set SapGuiAuto = GetObject("SAPGUI")
Set ApplicationSAP = SapGuiAuto.GetScriptingEngine
Set Connection = ApplicationSAP.Children(0)
Set Session = Connection.Children(0)
Session.findById("wnd[0]").maximize ' max main SAP window
Session.findById("wnd[0]/tbar[0]/okcd").Text = "/n" & "IW33" 'Transaction code
Session.findById("wnd[0]").sendVKey 0 'start transaction
End Sub
```
I hope it will help you in further searching of the required information
Comment for this answer: @levys Maybe I'm wrong, but when you use scripts, you will hardly be able to turn off screen updating for the SAP window. But you can use other methods of updating the SAP data. without using the SAP window, e.g. connection to SAP using RFC BAPI Call, but in this case you need to know functional module which is behind transaction-code. the second method which is might help you, is the using of GuiXT.
Comment for this answer: I think I was not clear enough.
I have a code in Outlook VBA and it is working just fine.
It automates a SAP process.
The thing is: I want SAP Screen to be updated in the end of the process, and NOT while the process is running.
It would be something similar to Application.ScreenUpdate = False in VBA
Here is another answer: You can automate Outlook from any application without displaying Outlook UI. See How to automate Outlook from another program for more information.
Also you may find the Using Automation to Send a Microsoft Outlook Message article helpful.
Comment for this answer: @levys That isn't particularly clear in your question, made more apparent by the fact that this answer exists. Perhaps you could edit your question to be more clear?
Comment for this answer: Not quite what I expected... It is SAP that I don't want to display. Outlook is fine
Comment for this answer: I think I was not clear enough. I have a code in Outlook VBA and it is working just fine. It automates a SAP process. The thing is: I want SAP Screen to be updated in the end of the process, and NOT while the process is running. It would be something similar to Application.ScreenUpdate = False in VBA
Here is another answer: You could try the following: session.TestToolMode = 1
Regards,
ScriptMan
|
Title: GDC installation error
Tags: gcc;d
Question: I wanted to install GDC at my FreeBSD Desktop, so I followed this:
https://wiki.dlang.org/GDC/Installation/Generic
I typed those at my tcsh terminal:
```vmware@localhost:~ % sudo mkdir -p gdc/dev
vmware@localhost:~ % sudo cp Downloads/gcc-7.3.0.tar.xz gdc
vmware@localhost:~ % cd gdc
vmware@localhost:~/gdc % sudo tar -xvf gcc-7.3.0.tar.xz
vmware@localhost:~/gdc % sudo git clone https://github.com/D-Programming-GDC/GDC.git dev
vmware@localhost:~/gdc % cd dev
vmware@localhost:~/gdc/dev % sudo git checkout gdc-7
vmware@localhost:~/gdc/dev % sudo ./setup-gcc.sh ../gcc-7.3.0
vmware@localhost:~/gdc/dev % sudo mkdir ../objdir
vmware@localhost:~/gdc/dev % cd ../objdir
```
these didn't made any errors.
but when I typed this,
```vmware@localhost:~/gdc/objdir % sudo ../gcc-7.3.0/configure --enable-languages=d --disable-bootstrap --prefix=/usr/local/share/gdc --with-bugurl="http://bugzilla.gdcproject.org" --enable-checking=yes
```
terminal said:
```configure: error: GDC is required to build d
```
why is this happening?
Here is another answer: GDC has been updated to now use the D frontend (v2.081.1). See https://github.com/D-Programming-GDC/GDC/commit/1c2972f44660d64173202a7f111bd915a578700c. This means a GDC bootstrap compiler will be needed to build GDC.
After discussing this with some of the GDC developers, this is my understanding of their strategy:
```stable``` and ```gdc-x-stable``` branches will continue to use the C++ frontend, so they will not require a GDC bootstrap compiler.
```master``` and ```gdc-x``` branches will use the D frontend, so will require a GDC bootstrap compiler
So, I believe the procedure would be
build a bootstrap compiler from ```gdc-x-stable``` branch
Use the bootstrap compiler from (1) to build ```gdc-x``` branch
Perhaps use the resulting GDC compiler from (2) to build the ```gdc-x``` branch again.
|
Title: Add Target Not Working Swift 3 - UIButton inside a UIStackView
Tags: ios;uiview;uibutton;swift3
Question: I am trying to add a UIButton to a stackview programatically which is a part of custom UIView class. The issue is if I try to add a target with the selector from the Custom UIView class, the selector is never fired on tapping the button. But if i give it a selector from my UIViewController it works fine.
Can someone tell me what I am doing wrong here ?
```self.isUserInteractionEnabled = false;
self.translatesAutoresizingMaskIntoConstraints = false;
self.layer.borderWidth = 1.0;
self.layer.borderColor = UIColor.black.cgColor;
self.expandCollapseButton = UIButton(frame: CGRect.zero);
self.expandCollapseButton!.addTarget(self, action: #selector(OMLiquidActionButton.expandButtonActionHandler(sender:)), for: .touchUpInside);
self.mainContainer = UIStackView(frame:CGRect.zero);
self.mainContainer?.isUserInteractionEnabled = true;
self.mainContainer?.axis = .vertical;
self.mainContainer?.distribution = .equalSpacing;
//Add the maincontainer/stackview to the parentview
//add the view to the container
self.mainContainer?.addArrangedSubview(self.expandCollapseButton!);
self.parentView?.addSubview(self.mainContainer!);
```
Please Note: Constraints are already defined for the view programatically and button exists as the topmost view.
Comment: Thanks for the suggesting it but it has nothing to do with the UIResponder class. I am not able to understand why I am not able to register a selector in same UIView class.
Comment: parentView = superView. Main Container = StackView. I already changed the as suggested above but still the problem exists
Comment: Why are you not using `addArrangedSubview`?
Comment: The view hierarchy is related to the responder chain. When you set it up in the view controller are you adding it to a stack view in this weird way?
Comment: Could you post a little more code? Which class is your code snipped from? Why is `isUserInteractionEnabled = false`? Why is the frame of the mainContainer set to zero?
|
Title: Configuring multiple mouse settings
Tags: xorg;mouse;bluetooth;etc
Question: I am a left-handed thinkpad user and have grown used to using the trackpoint in its default right-handed configuration. When I use my bluetooth mouse, however, I would like the buttons to have a left-handed layout. In 11.04 (Natty) I can configure this manually using xinput, but I would like to have it applied automatically when the mouse is connected. I have followed the xorg documentation by creating /etc/X11/xorg.conf/99-ms500mouse.conf and placing the following into it:
```Section "InputClass"
Identifier "Microsoft Bluetooth Mouse 5000 button remap"
MatchProduct "Microsoft Bluetooth Notebook Mouse 5000"
MatchDevicePath "/dev/input/event*"
Option "ButtonMapping" "3 2 1 4 5 0 0 0 0 0 0 0"
EndSection
```
This seems to work initially (GDM seems to be using it correctly), but when I log in and start my X session, the buttons are mysteriously reverted:
```
$ xinput get-button-map "Microsoft Bluetooth Notebook Mouse 5000"
1 2 3 4 5 6 7 8 9 10 11 12
```
The following is my /var/log/Xorg.0.log:
```[ 276.648] (II) config/udev: Adding input device Microsoft Bluetooth Notebook Mouse 5000 (/dev/input/mouse1)
[ 276.648] (II) No input driver/identifier specified (ignoring)
[ 276.649] (II) config/udev: Adding input device Microsoft Bluetooth Notebook Mouse 5000 (/dev/input/event14)
[ 276.649] (**) Microsoft Bluetooth Notebook Mouse 5000: Applying InputClass "evdev pointer catchall"
[ 276.649] (**) Microsoft Bluetooth Notebook Mouse 5000: Applying InputClass "Microsoft Bluetooth Mouse 5000 button remap"
[ 276.649] (II) Using input driver 'evdev' for 'Microsoft Bluetooth Notebook Mouse 5000'
[ 276.649] (II) Loading /usr/lib/xorg/modules/input/evdev_drv.so
[ 276.649] (**) Microsoft Bluetooth Notebook Mouse 5000: always reports core events
[ 276.649] (**) Microsoft Bluetooth Notebook Mouse 5000: Device: "/dev/input/event14"
[ 276.670] (**) Microsoft Bluetooth Notebook Mouse 5000: ButtonMapping '3 2 1 4 5 0 0 0 0 0 0 0'
[ 276.670] (--) Microsoft Bluetooth Notebook Mouse 5000: Found 8 mouse buttons
[ 276.670] (--) Microsoft Bluetooth Notebook Mouse 5000: Found scroll wheel(s)
[ 276.670] (--) Microsoft Bluetooth Notebook Mouse 5000: Found relative axes
[ 276.670] (--) Microsoft Bluetooth Notebook Mouse 5000: Found x and y relative axes
[ 276.670] (--) Microsoft Bluetooth Notebook Mouse 5000: Found absolute axes
[ 276.670] (II) evdev-grail: failed to open grail, no gesture support
[ 276.670] (II) Microsoft Bluetooth Notebook Mouse 5000: Configuring as mouse
[ 276.670] (II) Microsoft Bluetooth Notebook Mouse 5000: Adding scrollwheel support
[ 276.670] (**) Microsoft Bluetooth Notebook Mouse 5000: YAxisMapping: buttons 4 and 5
[ 276.670] (**) Microsoft Bluetooth Notebook Mouse 5000: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
[ 276.670] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-2/4-2:1.0/bluetooth/hci0/hci0:11/input14/event14"
[ 276.670] (II) XINPUT: Adding extended input device "Microsoft Bluetooth Notebook Mouse 5000" (type: MOUSE)
[ 276.670] (II) Microsoft Bluetooth Notebook Mouse 5000: initialized for relative axes.
[ 276.670] (WW) Microsoft Bluetooth Notebook Mouse 5000: ignoring absolute axes.
[ 276.670] (**) Microsoft Bluetooth Notebook Mouse 5000: (accel) keeping acceleration scheme 1
[ 276.670] (**) Microsoft Bluetooth Notebook Mouse 5000: (accel) acceleration profile 0
[ 276.671] (**) Microsoft Bluetooth Notebook Mouse 5000: (accel) acceleration factor: 2.000
[ 276.671] (**) Microsoft Bluetooth Notebook Mouse 5000: (accel) acceleration threshold: 4
```
As you can see, it appears to apply the button mapping I want (that is, swap buttons 3 and 1 and disable all others), but once the session starts this is gone. How do I make sure these settings stick?
Thanks a lot!
Here is another answer: Found the problem. gnome-settings-daemon is overriding the settings I give the mouse with the system-wide settings (which are set to right-handed). The only way to avoid this behavior is to fire up gconf-editor and find the key:
```/apps/gnome_settings_daemon/plugins/mouse/active
```
And unset it. This will prevent it from overriding the settings specified in an xorg.conf (or fragment file in etc/X11/xorg.conf.d/).
|
Title: What are elasticsearch node network stats?
Tags: elasticsearch
Question: When I get node stat in es with curl, the response is ;
```curl -XGET 'http://localhost:9200/_nodes/stats/network?human&pretty'
{
"cluster_name" : "elasticsearch",
"nodes" : {
"XpAeeHs6Q7WxycqJBOShfA" : {
"timestamp" : 1411385146836,
"name" : "Ape-X",
"transport_address" : "inet380-562-5705:9300]",
"host" : "test",
"ip" : [ "inet380-562-5705:9300]", "NONE" ],
"network" : {
"tcp" : {
"active_opens" : 93920,
"passive_opens" : 39,
"curr_estab" : 62,
"in_segs" : 7053825,
"out_segs" : 4536915,
"retrans_segs" : 4948,
"estab_resets" : 1572,
"attempt_fails" : 523,
"in_errs" : 708,
"out_rsts" : 48488
}
}
}
}
}
```
I checked it with "netstat -anlp" command. There was not any connection to 9200 or 9500 ports. However "curr_estab" is 62. Does "curr_estab" show current established network? I looked in documentation for parameters "active_opens", "passive_opens" and "curr_estab" but I couldn't find any. What these parameters represents in elasticsearch?
Here is another answer: ```
Active and Passive OPENs
TCP/IP is based on the client/server model of operation, and TCP connection setup is based on the existence of these roles as well. The client and server each prepare for the connection by performing an OPEN operation. However, there are two different kinds of OPEN:
Active OPEN: A client process using TCP takes the “active role” and initiates the connection by actually sending a TCP message to start the connection (a SYN message).
Passive OPEN: A server process designed to use TCP, however, takes a more “laid-back” approach. It performs a passive OPEN by contacting TCP and saying “I am here, and I am waiting for clients that may wish to talk to me to send me a message on the following port number”. The OPEN is called passive because aside from indicating that the process is listening, the server process does nothing.
A passive OPEN can in fact specify that the server is waiting for an active OPEN from a specific client, though not all TCP/IP APIs support this capability. More commonly, a server process is willing to accept connections from all comers. Such a passive OPEN is said to be unspecified.
```
|
Title: Highcharts - Cannot load external data with JSON / No PHP
Tags: javascript;json;csv;highcharts
Question: I'm playing around with HighCharts / HighStocks and am trying to automatically pass data from my reporting software into the charts, without using a PHP file, but I can't quite figure out how to get my syntax right.
Quite bluntly, I think this is out of my league. I'm not a AJAX/Javascript/JSON coder. My skills lie elsewhere, and after going through and reading about 40 pages of threads here, I'm hoping someone can help me out.
Obviously the example works fine when I use it locally, but when I try and change the source data in the get JSON line, I just get an empty page / no chart. I've been banging my head against a wall with this for quite a while now, but not having any luck.
HTML Code:
```<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'Container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'This is the header'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="../js/highstock.js"></script>
<script src="../js/modules/exporting.js"></script>
<div id="Container" style="height: 500px; min-width: 500px;"></div>
<p>Testing</p>
</body>
</html>
```
As far as I can see, this is the line that I need to change:
```$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
```
On my local server, I can use the following link to extract data from reporting tool (which reads from SQL database).
```//localserver/query=ZZZ
```
and this outputs as:
```[{f1:"[[1338732000000,29119.439],"},
{f1:"[1338818400000,30367.229],"},
{f1:"[1338904800000,29221.893],"},
{f1:"[1339336800000,29640.756]]"}]
```
Or I can pass it out as such:
```[[1338732000000,29119.439],
[1338818400000,30367.229],
[1338904800000,29221.893],
[1338991200000,31075.204],
[1339077600000,29449.717],
[1339336800000,29640.756]]
```
I appreciate the data format(s) above are slighly different to what is expected by HighCharts.
My questions are:
a) Is it possible to populate the highchart via data on demand from local server without using a PHP file?
Everything is on the same/local server. Reporting software has a web element, that queries a SQL database, and returns the data set.
Basically I want to replace this:
```$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
```
With this:
```$.getJSON('http://localserver/query=ZZZ', function(data) {
```
Reason being that reporting software allows users to change dates, variables (e.g. Country) etc, and then I'd want that to update the chart.
b) Can I parse/translate the data in JavaScript inside the html?
I think half the problem I am having is getting the reporting software and Highcharts Javascript to handshake. I've tried the local csv example from their site, but I can't get that to work at all, and can't find a full html/javascript example anywhere.
Thanks in advance!
Comment: You are using jsonp instead of json.
Here is another answer:
Yes you can use JSON generated from an SQL query to populate Highcharts. They key here is to initialize the chart inside the .getJSON callback function and loop through the JSON data to add the points to the chart.
Here's some sample code to hopefully get you started:
```<script type="text/javascript">
var chart = null;
function createChart() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
},
xAxis: {
type: 'datetime',
title: {
text: 'Time'
}
},
yAxis: {
title: {
text: 'Some data'
}
},
series: [{
data: [],
name: 'some data',
type: 'line'
}],
});
}
$(document).ready(function() {
// Fetch JSON...
$.getJSON('http://localhost/script.php', function(res, textStatus, jqXHR) {
if (res.success) {
// Populate the chart...
var points = [];
$.each(res.points, function(i, val) {
points.push({ x : val.x, y : val.y });
});
createChart();
chart.series[0].setData(points);
}
});
});
</script>
```
|
Title: Lightning - CSP and Client Side Callout
Tags: visualforce;lightning-apps
Question: I was reviewing lightning document, it seems the framework is currently limited to make callout only through apex, I understand this is done for security reasons, I feel its a big limitation while we compare with VF and other framework for adoption, it will also result in un-necessary server side code written and compatibility problem with existing projects like ForceTk, etc is a problem, Is there any plan to relax this restriction in future?
Here is the accepted answer: I feel the same pain as you do and asked already a similar question which is answered by Doug here
Lightning: is direct API access on the roadmap?
As to my knowledge this is still up to date and therefore not sure, if or when this constraint might be relaxed.
Comment for this answer: Thanks!, so for short term there is no clear roadmap
Comment for this answer: My guess: for short term it will stay as it is.
Comment for this answer: the performance reason given is vague though, since the client code executes on browser side.
Here is another answer: It's now possible to call external API using Javascript from within Salesforce Lightning.
Start by going to Setup → CSP Trusted Sites and adding your trusted site.
Which in this example is: https://api.postcodes.io/
Then use an approach like this:
```({
postcodeSearch : function(component, postcode) {
var url = 'https://api.postcodes.io/postcodes/' + postcode;
this.makeAjaxRequest(component, url);
},
callAjax : function(method, url, async, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(component) {
if (xmlhttp.readyState == 4 ) {
callback.call(this, xmlhttp);
}
};
xmlhttp.open(method, url, async);
xmlhttp.send();
},
makeAjaxRequest : function(component, url) {
this.callAjax("GET", url, true,
function(xmlhttp){
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
else if (xmlhttp.status == 400) {
console.log("makeAjaxRequest: 400 Error");
}else {
console.log("makeAjaxRequest: Error");
}
}
);
}
})
```
Comment for this answer: this doesn't work for me. I still get `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://wwwcie.ups.com/rest/XAV. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).` even with adding my site to CSP.
Comment for this answer: @TylerZika the error message says you are missing CORS which can be set via `Setup > CORS > New > Enter an orgin URL pattern`
|
Title: How to obtain the direct link to a YouTube video file
Tags: youtube;download
Question: I'm trying to figure out where to find the actual FLV video YouTube files. I've found several tutorials on the Internet, but none that work. So if anyone knows, that'd be much appreciated.
Comment: I haven't tried it, but try this: [http://stackoverflow.com/a/17305321/994031](http://stackoverflow.com/a/17305321/994031)
Comment: Try this http://youtube.2tera.com/
Here is another answer: You cannot directly obtain a source of the video from YouTube. There are many websites that allow you to download videos from YouTube in various formats such as an FLV format. An application like JDownloader works great for YouTube videos and many more!
Comment for this answer: If there is no way to obtain these sources, than how do applications such as JDownloader do it?
Comment for this answer: @THexi Well, manually it is not really feasible to do, though if you know any programming take a look at something like this: http://www.sajithmr.me/download-youtube-videos-using-php-code
Here is another answer: VLC may serve.
From The Best Hidden Features of VLC:
```
Find a video on YouTube and copy the URL from the address bar.
In VLC, head to Media > Open Network Stream.
Paste the YouTube link in the box and click Play.
Under Tools, click Codec Information.
In the box that says Location, right-click the block of text and click Select All. Copy this text to your clipboard.
Go back to your browser and paste the link in the address bar. This will open the source file directly on YouTube's servers.
Right-click the video as it plays and select Save Video As.
```
That'll give you an ```mp4``` file. VLC can also convert some file formats.
Comment for this answer: I need the direct link so I can import my videos in my apps without importing the interface. The URL you get from VLC is apparently temporary and get changed. So, I couldn't use this information to get the actual url for the video.
Comment for this answer: Doesn't seem to work anymore. Video is not loading.
Comment for this answer: Still works for me.
|
Title: Will water introduced in a large tube connected to a small tube force water upward
Tags: pressure;water
Question: Will water introduced in a large tube connected to a small tube force water upward as a self starting siphon. I am thinking of a 3"pvc pipe 6" long sealed with only a 3/8 tube coming out of it will create excess pressure 3" pushing the water up the 3/8" tube 2 feet
Here is another answer: No, the water will be at the same level in both tubes. Hydrostatic pressure depends only on the height of the liquid and not the area of the tube. Remember that pressure is force per unit area. The weight of liquid in the thin tube is less than that of the liquid in the thick tube. By a factor of 8. But the area of the tube is also smaller by a factor of 8. So the two pressures are equal for equal heights.
|
Title: Is there an easy convertor between dpkg --print-architecture and uname -m for generic scp?
Tags: printing;cpu;scp;cp
Question: I want to copy files that relevant to my machines (x86_64 / aarch64) from remote machines.
I want to use: ```scp user@host:*$(uname)* .``` to copy both wheels and .deb files, e.g.:
name-x.y.z-cp36-cp36m-linux_x86_64.whl
name_x.y.z_amd64.deb
Now, using ```$(uname -m)``` will yield ```x86_64``` which matches the wheel, and using ```$(dpkg --print-architecture) will yield ```amd64` which matches the .deb
Locally, I use
```find . | grep -E "$(uname -m)|$(dpkg --print-architecture)" | xargs -I{} cp -u {} dst/
```
to find and copy - but I'm not sure how to move this into scp.
My current attempt is stuck with:
```scp user@host:dst/[*$(uname -m)*][*$(dpkg --print-architecture)*]
```
which finds nothing.
Comment: As I understand it, you want to grab *all* the files which **has** your print architecture in the filename ?
Here is another answer: After looking a bit - I found that this answer can help me.
Using ```rsync``` I was able to copy exactly what I wanted:
```py_version=$(python -V | cut -d' ' -f2 | tr -d ".")
rsync -am --include="*$(dpkg --print-architecture)*" --include="*${py_version:0:2}*$(uname -m)*" --exclude="*" user@host:dst .
```
Explanation:
```py_version=$(python -V | cut -d' ' -f2 | tr -d ".")``` gets me the 2 first version digits (e.g. 3.6.9 -> 36) which will help me pinpoint the wheel
```--include="*$(dpkg --print-architecture)*"``` will pinpoint the .deb
```--include="*${py_version:0:2}*$(uname -m)*"``` will pinpoint the wheel using architecture + python version
```--exclude="*"``` will remove everything else
|
Title: ERROR RecyclerView: No adapter attached; skipping layout en Android Studio
Tags: android-studio;firebase;android-layout;recyclerview
Question: antes de nada comentaros que soy novato en programación, y estoy realizando mi proyecto de fin de grado superior, estoy implementando un chat con Firebase, y he conseguido llegar hasta el punto de tener las vistas creadas, con dos fragment con RecyclerView donde se visualizan los usuarios y las conversaciones realizadas, y luego una vista de la conversación.
Ya consigo seleccionar un usuario y mandar un mensaje, quedando guardado en firebase, el problema me surge a la hora de mostrar los mensajes en la vista, me dá el error del encabezado.
La aplicación no se sale, ni da ninguna excepción, simplemente graba el mensaje pero no lo muestra en la actividad.
ESTRUCTURA DE FIREBASE:
os adjunto mi código:
activity_message.xml
```<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MessageActivity"
android:background="@drawable/backgroundbienvenida">
<android.support.design.widget.AppBarLayout
android:id="@+id/bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/MenuStyle">
<ImageView
android:id="@+id/imagenchat"
android:layout_width="60dp"
android:layout_height="60dp"
app:srcCompat="@drawable/btnchatsprinpress"
android:contentDescription="@string/image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/username"
android:layout_marginLeft="25dp"
android:text="username"
android:textColor="#ffff"
android:textStyle="bold"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/bar_layout"
android:layout_above="@+id/bottom"
/>
<RelativeLayout
android:layout_width="match_parent"
android:padding="5dp"
android:id="@+id/bottom"
android:background="#CDCDCD"
android:layout_alignParentBottom="true"
android:layout_height="60dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:id="@+id/text_send"
android:background="@drawable/fondoeditextchatenviar"
android:hint="Escribe un Mensaje..."
android:textColor="@color/colorPrimaryDark"
android:paddingLeft="50dp"
android:paddingEnd="45dp"
android:paddingBottom="6dp"
android:layout_toLeftOf="@+id/btn_send"
android:layout_centerVertical="true"/>
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="@+id/btn_send"
android:background="@drawable/btnchatenviaranima"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</RelativeLayout>
```
CLASS Chat
```public class Chat {
private String sender;
private String receiver;
private String message;
public Chat(){}
public Chat(String sender, String receiver, String message) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
```
ADAPTADOR
```package com.example.luism.cordobasuma.Adaptadores;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.luism.cordobasuma.Chat;
import com.example.luism.cordobasuma.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends
RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<Chat> mChat;
FirebaseUser fuser;
public MessageAdapter (Context mContext,List<Chat> mChat){
this.mChat = mChat;
this.mContext = mContext;
}
@NonNull
@Override
public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup
parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view =
LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent,
false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
}
@Override
public int getItemCount() {return mChat.size();}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public ViewHolder (View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
}
}
@Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
```
ACTIVITY MENSAJE
```package com.example.luism.cordobasuma;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.luism.cordobasuma.Adaptadores.MessageAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MessageActivity extends AppCompatActivity {
TextView username;
FirebaseUser fuser;
DatabaseReference reference;
ImageButton btn_send;
EditText text_send;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
//LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(getApplicationContext());
//linearLayoutManager.setStackFromEnd(true);
//recyclerView.setLayoutManager(linearLayoutManager);
//recyclerView.setAdapter(messageAdapter);
username = (TextView) findViewById(R.id.username);
btn_send = (ImageButton) findViewById(R.id.btn_send);
text_send = (EditText) findViewById(R.id.text_send);
intent = getIntent();
final String userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = text_send.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(),userid,msg);
}else {
Toast.makeText(MessageActivity.this,"No puede enviar un
mensaje vacío",Toast.LENGTH_LONG).show();
}
text_send.setText("");
}
});
reference =
FirebaseDatabase.getInstance().getReference("Usuarios").child(userid);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Usuario user = dataSnapshot.getValue(Usuario.class);
username.setText(user.getUsuario());
readMessages(fuser.getUid(),userid);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message) {
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("remitente",sender);
hashMap.put("receptor",receiver);
hashMap.put("mensaje",message);
reference.child("Chats").push().setValue(hashMap);
}
private void readMessages (final String myid, final String userid) {
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver() !=null && chat.getReceiver().equals(myid) && chat.getSender() !=null && chat.getSender().equals(userid) ||
chat.getReceiver() !=null && chat.getReceiver().equals(userid) && chat.getSender() !=null && chat.getSender().equals(myid)) {
mchat.add(chat);
}
MessageAdapter messageAdapter = new MessageAdapter(MessageActivity.this,mchat);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setAdapter(messageAdapter);
recyclerView.setLayoutManager(linearLayoutManager);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
```
ERROR:
```2019-04-24 01:56:46.880 1604-1604/com.example.luism.cordobasuma
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@34ddeca
2019-04-24 01:56:47.464 1604-1604/com.example.luism.cordobasuma E/RecyclerView: No adapter attached; skipping layout
2019-04-24 01:56:55.874 1604-1604/com.example.luism.cordobasuma W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@2c59f01
2019-04-24 01:56:56.228 1604-1604/com.example.luism.cordobasuma E/RecyclerView: No adapter attached; skipping layout
2019-04-24 01:56:56.406 1604-1604/com.example.luism.cordobasuma E/RecyclerView: No adapter attached; skipping layout
2019-04-24 01:56:56.447 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.447 1604-1629/com.example.luism.cordobasuma I/ism.cordobasum: Background concurrent copying GC freed 26716(1689KB) AllocSpace objects, 4(208KB) LOS objects, 49% free, 3MB/6MB, paused 860us total 285.248ms
2019-04-24 01:56:56.447 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.447 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.453 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.453 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.454 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.456 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.456 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.456 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.458 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.458 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.458 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.459 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.459 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.460 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.461 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.462 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.462 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.464 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.465 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.465 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.466 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.467 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.467 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.468 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.470 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.472 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.485 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.485 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.485 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.494 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.495 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.495 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.496 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.496 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.496 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.497 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.500 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.500 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.502 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.502 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.503 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.509 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.509 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.509 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.510 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.511 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.511 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.512 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.512 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.513 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.514 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.514 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.514 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.516 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.516 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.517 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.517 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.518 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.518 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.520 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.521 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.521 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.524 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.524 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.525 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.528 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.528 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for remitente found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.528 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for mensaje found on class com.example.luism.cordobasuma.Chat
2019-04-24 01:56:56.529 1604-1604/com.example.luism.cordobasuma W/ClassMapper: No setter/field for receptor found on class com.example.luism.cordobasuma.Chat
```
Gracias por vuestra ayuda```introducir el código aquí```
Comment: dentro de readmessages pone un breakpoint en el array y fijate si se va llenando con la data, puede que los parametros que le mandas en el readmessage no encuentren ningun valor en firebase por eso no te trae nada
Comment: Eso era Gastón, no encontraba los datos. Muchas Gracias
|
Title: My application skips AsyncTask.execute() and crashes
Tags: java;android;android-asynctask
Question: here is my onCreate method the problem is that the app shows the toast "Finish ! " but it dosen't execute ```li.execute(Email,Password);``` and it crashes. that's it
I want the app to do what's inside ```li.execute(Email,Password);``` first.
PS : loginBackgroundWorker is a class that extends ```AsyncTask<String,String,String>``` and it has ```onPreExecute()``` and ```doInBackground()``` and ```onPostExecute()``` methods.
The app dosen't show any errors or warnings but it crashes in the emulator.
here is the code :
```protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
li = new loginBackgroundWorker(LoginActivity.this);
//loginBackgroundWorker is a class that extends AsyncTask
EditTextEmail =(EditText) findViewById(R.id.emailField);
EditTextPassword =(EditText) findViewById(R.id.passwordField);
loginButton = (CardView) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Email = EditTextEmail.getText().toString().trim();
Password = EditTextPassword.getText().toString().trim();
li.execute(Email,Password);
Toast.makeText(LoginActivity.this,"Finish !",Toast.LENGTH_LONG).show();
}
});
}
```
here is AsyncTask Class (I don't think that what is inside those functions is important for you)
```public class loginBackgroundWorker extends AsyncTask<String,String,String> {
Context context;
public String email;
public String password;
public static final String login_url="http://(779)418-1253/login.php";
public loginBackgroundWorker(Context context) {
this.context = context;
}
@Override
public void onPreExecute() {
//Toast.makeText(context,"preExecute",Toast.LENGTH_LONG).show();
}
@Override
public String doInBackground(String... params) {
try {
email = params[0];
password = params[1];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onPostExecute(String result) {
Toast.makeText(context,"Onpost",Toast.LENGTH_LONG).show();
String r=result.trim();
Boolean aBoolean = true;
if (result.equals("1"))
{
Toast.makeText(context,"Bien Connecté",Toast.LENGTH_LONG).show();
aBoolean = false;
}
else if (result.equals(""))
r = "Login ou mot de passe incorrect";
if (aBoolean)
{
Toast.makeText(context,r,Toast.LENGTH_LONG).show();
}
}
}
```
here is the StackTrace
``` --------- beginning of crash
05-26 14:56:24.023 14756-14756/com.example.zaariou.blacklist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zaariou.blacklist, PID: 14756
java.lang.IllegalStateException: Cannot execute task: the task is already running.
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:593)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at com.example.zaariou.blacklist.LoginActivity$1.onClick(LoginActivity.java:58)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
```
Comment: OK I will show the whole AsyncTask Class
Comment: OK I posted my stacktrace now
Comment: I click the button the first time it shows toast "finish !", when I click it the second time it crashes.
Comment: Show your `AsyncTask` and stacktrade dude
Comment: And what's your exception stacktrace?
Comment: `Cannot execute task: the task is already running.` You're start the task elsewhere or you're probably clicking the button multiple times
Here is another answer: Instance of ```AsyncTask``` can only run once.
If you want to reuse your ```AsyncTask``` you must initialize new instance of your ```loginBackgroundWorker``` and run it.
Move your ```loginBackgroundWorker``` initialization to your ```OnClickListener.onClick``` handle
Comment for this answer: When I did that it crashes after multiple clicks and here is my Stacktrace it shows this error at each click
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f811727d2e0
and crashes after that
`--------- beginning of crash
05-26 15:27:05.137 (779)418-1253/com.example.zaariou.blacklist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zaariou.blacklist, PID: 20334
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference`
|
Title: how to access multiple sites from an external computer using scotch box 2
Tags: vagrant;vagrantfile
Question: I am running vagrant scotch box 2.0, I have added multiple domains to the box.
I have added the ip to my hosts file
```845.888.9417 site1.local
845.888.9417 site2.local
```
The domains are working from local machine.
What I am wanting to do is allow access to these sites from another computer on the network
I had added a port forward to vagrant file, and this works in a single domain environment.
but is there a way to somehow tie the domains in such a way that from an external computer they can access both domains, by simply adding a different port number , or some other way to get both sites to work externally?
I am not sure if this is relevant or not, but right now I am running scotch box on a mac, but I need the solution to also work on a windows system.
here is my vagrant file
```# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "scotch/box"
config.vm.network "private_network", ip: "845.888.9417"
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.hostname = "scotchbox"
config.vm.synced_folder "/Users/acc/Documents/vagrant/site1", "/var/www/site1.local/public",id:"1", :mount_options => ["dmode=777", "fmode=666"]
config.vm.synced_folder "/Users/acc/Documents/vagrant/site2", "/var/www/site2.local/public",id:"2", :mount_options => ["dmode=777", "fmode=666"]
config.vm.provision "shell", inline: <<-SHELL
## Only thing you probably really care about is right here
DOMAINS=("site1.local" "site2.local")
## Loop through all sites
for ((i=0; i < ${#DOMAINS[@]}; i++)); do
## Current Domain
DOMAIN=${DOMAINS[$i]}
echo "Creating directory for $DOMAIN..."
mkdir -p /var/www/$DOMAIN/public
echo "Creating vhost config for $DOMAIN..."
sudo cp /etc/apache2/sites-available/scotchbox.local.conf /etc/apache2/sites-available/$DOMAIN.conf
echo "Updating vhost config for $DOMAIN..."
sudo sed -i s,scotchbox.local,$DOMAIN,g /etc/apache2/sites-available/$DOMAIN.conf
sudo sed -i s,/var/www/public,/var/www/$DOMAIN/public,g /etc/apache2/sites-available/$DOMAIN.conf
echo "Enabling $DOMAIN. Will probably tell you to restart Apache..."
sudo a2ensite $DOMAIN.conf
echo "So let's restart apache..."
sudo service apache2 restart
done
SHELL
# Optional NFS. Make sure to remove other synced_folder line too
#config.vm.synced_folder ".", "/var/www", :nfs => { :mount_options => ["dmode=777","fmode=666"] }
end
```
Here is another answer: The answer is that the additional domains need to go on different ports, then works
```# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "scotch/box"
config.vm.network "private_network", ip: "845.888.9417"
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 81, host: 8081
config.vm.network "forwarded_port", guest: 82, host: 8082
config.vm.hostname = "scotchbox"
config.vm.synced_folder "/Users/acc/Documents/vagrant/main", "/var/www/public",id:"3", :mount_options => ["dmode=777", "fmode=666"]
config.vm.synced_folder "/Users/acc/Documents/vagrant/site1", "/var/www/site1.local/public",id:"1", :mount_options => ["dmode=777", "fmode=666"]
config.vm.synced_folder "/Users/acc/Documents/vagrant/site2", "/var/www/site2.local/public",id:"2", :mount_options => ["dmode=777", "fmode=666"]
config.vm.provision "shell", inline: <<-SHELL
## Only thing you probably really care about is right here
DOMAINS=("site1.local" "site2.local")
IPS=("81" "82")
## Loop through all sites
for ((i=0; i < ${#DOMAINS[@]}; i++)); do
## Current Domain
DOMAIN=${DOMAINS[$i]}
MYIP=${IPS[$i]}
echo "Creating directory for $DOMAIN..."
mkdir -p /var/www/$DOMAIN/public
echo "Creating vhost config for $DOMAIN..."
sudo cp /etc/apache2/sites-available/scotchbox.local.conf /etc/apache2/sites-available/$DOMAIN.conf
echo "Updating vhost config for $DOMAIN..."
sudo sed -i s,scotchbox.local,$DOMAIN,g /etc/apache2/sites-available/$DOMAIN.conf
sudo sed -i s,/var/www/public,/var/www/$DOMAIN/public,g /etc/apache2/sites-available/$DOMAIN.conf
sudo sed -i s,80,$MYIP,g /etc/apache2/sites-available/$DOMAIN.conf
sudo sed -i s,'<VirtualHost',"Listen $MYIP \\n<VirtualHost",g /etc/apache2/sites-available/$DOMAIN.conf
echo "Enabling $DOMAIN. Will probably tell you to restart Apache..."
sudo a2ensite $DOMAIN.conf
echo "So let's restart apache..."
sudo service apache2 restart
done
SHELL
# Optional NFS. Make sure to remove other synced_folder line too
#config.vm.synced_folder ".", "/var/www", :nfs => { :mount_options => ["dmode=777","fmode=666"] }
end
```
|
Title: Sending input to the blocking stream of PHP ssh
Tags: php;ssh;stream;blocking
Question: I have similar situation as the following question
SSH2 change a user password
The only difference is my action is "scp", I want to send ssh command through PHP to send the files to remote machine using scp command (I know php itself has method to achieve this, but for some reason, I skip that method).
```Code is as follows
//run specified cmd with stream reading and writing
function runCMDAdvance($cmd){
if (strpos($cmd,'scp') !== false) {
//reply machine when ask for password in file transfer
$confirmPass = $this->password."\n".$this->password."\n";
if (!($stream = ssh2_exec($this->conn, $cmd )))
{
echo "fail: unable to execute command\n";
fclose($stream);
return ERROR_SSH_EXEC_COMM;
}
fwrite($stream,$confirmPass); //>>Actually I want to pass the password information by writing to the stream, but turn out that it does not work
stream_set_blocking($stream, true);
}
}
```
When I try to write the password information after the stream set blocking, the php execution code will stuck. (I guess the reason will be the remote machine is waiting for the password information but php does not able to give them, so it just keep waiting and jam the php running thread.)
I have read through the above question but can't seem to get the right direction to achieve this, is there any ideas on this??
Again, thanks all for the help!
Referring to neubert's answer, using phpseclib still not work...
```//$cmd is $cmd = 'scp '.$scpPath.' root@'.$ip.':/root';
function runCMDAdvance($cmd, $tVal){
if (strstr($cmd,"scp")!==FALSE){
if((include('Net/SSH2.php')) && (include('Net/SCP.php'))){
//set ssh timeout value
$this->setTimeoutVar($tVal);
$ssh = new Net_SSH2($this->host);
if (!$ssh->login($this->username, $this->password)){
echo "Bad Login";
return false;
}
$ssh->write($cmd."\n");
$ssh->read(' password:');
$ssh->write($this->password."\n");
}
}
else{
echo "Wrong command used, please check your code";
return false;
}
}
```
My solution to deal with SSH read and write stream
```//run any specified cmd using ssh
//parameter:
//cmd>>running command
//tVal>>command run timeout
//return:terminal stdout
function runCMDAdvance($sshIP, $cmd, $tVal,$tarIP){
$ssh = new Net_SSH2($sshIP);
if (!$ssh->login($this->username, $this->password)){
echo "Bad Login";
return false;
}
//set timeout for running ssh command, should be done after the ssh object has been initialized
$ssh->setTimeout($tVal);
//scp action detected
if (strstr($cmd,"scp")!==FALSE){
//if this is the first time to do the ssh, connect with "yes" for answering
if ($ssh->write($cmd)){
//store the output of the text message given by the router
$ssh_stdout = $ssh->read();
//echo $ssh_stdout."|||";
if (strstr($ssh_stdout,'trusted ')!==FALSE){
$ssh->write("y\n");
//and ask password
$ssh->read(' :password');
}
//deal with known host situation
elseif (strstr($ssh_stdout,'ssh-keygen ')!==FALSE){
$ssh->write('ssh-keygen -f '.'/root/.ssh/known_hosts -R '.$tarIP."\n");
$ssh->write($cmd);
$ssh->read(' :password');
$ssh->write($this->password."\n");
return true;
}
//deal with still connecting situation
elseif (strstr($ssh_stdout,'Are you sure you want to continue connecting')!==FALSE){
$ssh->write("yes\n");
$ssh->read(' :password');
$ssh->write($this->password."\n");
return true;
}
$ssh->write($this->password."\n");
$returnRead = $ssh->read();
$ssh->disconnect();
return true;
}//end of inner inner if
}//end of scp if (deal with scp)
else{//if not scp action,just normal action,simply execute the command
//exec will not return anything if the command is not run successfully
$res = $ssh->exec($cmd);
$ssh->disconnect();
return $res;
}
}
```
Here is the accepted answer: Here's how you could do it with phpseclib, a pure PHP SSH2 implementation:
```<?php
include('Net/SSH2.php');
define('NET_SSH2_LOGGING', 3);
$ssh = new Net_SSH2('www.website1.com');
$ssh->login('username', 'password');
$ssh->write("ssh [email protected]\n");
$ssh->read(' password:');
$ssh->write("password\n");
$ssh->setTimeout(0.5);
echo $ssh->read();
```
Comment for this answer: Thanks for the method, but I have tried, still hang my script as before, don't know which part went wrong...
Comment for this answer: Hi neubert, sorry for late reply, I have finally figured it out, this is my program mistake, not related to the code, I can now do the read and write stream successfully using phpseclib, I will post the working code later this week, thanks all for the great help especially neubert!
Comment for this answer: I've updated my code to add `decine('NET_SSH2_LOGGING', 3)`. This'll output the raw unencrypted SSH packets that are being sent to and fro. If you could post that that'd be great. Thanks!
Here is another answer: ```scp``` (as well as ```ssh```) do not expect a password but from the standard input, but from the console (as in ```tty```), and this is a Good Thing. Storing your password anywhere such as some PHP code compromises the very purpose of ssh.
Instead you should create a RSA authentication key. Here is a simple how-to.
Once you are done, change your command line as follows:
```scp -i /path/to/your/rsa.private.key
```
Make sure to store this private key in a "secure" location. It must be accessible from your PHP script, but no one else. In particular do not make it accessible from a URL.
|
Title: Return results from asyncio.get_event_loop
Tags: python-3.x;python-requests;python-asyncio
Question: I'm new to using the asyncio module. I have the following code that is querying a service to return IDs. How do I set a variable to return the results from the 'findIntersectingFeatures' function?
Also, how can I have the print statements execute after run_in_executor has finished. They are currently printing immediately after the first iteration.
```import json, requests, time
import asyncio
startTime = time.clock()
out_json = "UML10kmbuffer.json"
intersections = []
def findIntersectingFeatures(coordinate):
coordinates = '{"rings":' + str(coordinate) + '}'
forestCoverURL = 'http://server1.ags.com/server/rest/services/Forest_Cover/MapServer/0/query'
params = {'f': 'json', 'where': "1=1", 'outFields': '*', 'geometry': coordinates, 'geometryType': 'esriGeometryPolygon', 'returnIdsOnly': 'true'}
r = requests.post(forestCoverURL, data = params, verify=False)
response = json.loads(r.content)
if response['objectIds'] != None:
intersections.append(response['objectIds'])
return intersections
with open(out_json, "r") as f_in:
for line in f_in:
json_res = json.loads(line)
coordinates = []
# Get features
feat_json = json_res["features"]
for item in feat_json:
coordinates.append(item["geometry"]["rings"])
loop = asyncio.get_event_loop()
for coordinate in coordinates:
loop.run_in_executor(None, findIntersectingFeatures, coordinate)
print("Intersecting Features: " + str(intersections))
endTime = time.clock()
elapsedTime =(endTime - startTime) / 60
print("Elapsed Time: " + str(elapsedTime))
```
Here is the accepted answer: To use asyncio, you shouldn't just get the event loop, you must also run it. You can use ```run_until_complete``` to run a coroutine to completion. Since you need to run many coroutines in parallel, you can use ```asyncio.gather``` to combine them into a single parallel task:
```coroutines = []
for coordinate in coordinates:
coroutines.append(loop.run_in_executor(
None, findIntersectingFeatures, coordinate))
intersections = loop.run_until_complete(asyncio.gather(*coroutines))
```
```
Also, how can I have the print statements execute after ```run_in_executor``` has finished.
```
You can ```await``` the call to ```run_in_executor``` and place your ```print``` after it:
```def find_features(coordinate):
inter = await loop.run_in_executor(None, findInterestingFeatures, coordinate)
print('found', inter)
return inter
# in the for loop, replace coroutines.append(loop.run_in_executor(...))
# with coroutines.append(find_features(coordinate)).
```
|
Title: How do I print output in a certain way
Tags: c#;linq;token;cc
Question: I have written this code using LINQ query
``` static public void BracesRule(String input)
{
//Regex for Braces
string BracesRegex = @"\{|\}";
Dictionary<string, string> dictionaryofBraces = new Dictionary<string, string>()
{
//{"String", StringRegex},
//{"Integer", IntegerRegex },
//{"Comment", CommentRegex},
//{"Keyword", KeywordRegex},
//{"Datatype", DataTypeRegex },
//{"Not included in language", WordRegex },
//{"Identifier", IdentifierRegex },
//{"Parenthesis", ParenthesisRegex },
{"Brace", BracesRegex },
//{"Square Bracket", ArrayBracketRegex },
//{"Puncuation Mark", PuncuationRegex },
//{"Relational Expression", RelationalExpressionRegex },
//{"Arithmetic Operator", ArthimeticOperatorRegex },
//{"Whitespace", WhitespaceRegex }
};
var matches = dictionaryofBraces.SelectMany(a => Regex.Matches(input, a.Value)
.Cast<Match>()
.Select(b =>
new
{
Index = b.Index,
Value = b.Value,
Token = a.Key
}))
.OrderBy(a => a.Index).ToList();
for (int i = 0; i < matches.Count; i++)
{
if (i + 1 < matches.Count)
{
int firstEndPos = (matches[i].Index + matches[i].Value.Length);
if (firstEndPos > matches[(i + 1)].Index)
{
matches.RemoveAt(i + 1);
i--;
}
}
}
foreach (var match in matches)
{
Console.WriteLine(match);
}
}
```
it's output is something like this
{Index=0, Value= {, Token=Brace}
But I want Output be like
{ BRACE
Comment: This is a tokenizer. Lexical Analyser
Input: {}
Output: {Index=0, Value= {, Token=Brace}
{Index=1, Value= }, Token=Brace}
But I want Output be like
Output: { Brace
} Brace
Comment: I have tried a lot. i'm still learning LINQ query. So not much into it! Sorry! Could use help!
Comment: Could you elaborate a littble bit more on your problem? Can you supply an example of your input? Which part exactly do you want to change (and how)? The output?
Comment: This is your code, but you can't change the output formatting?
Here is the accepted answer: One possibility would be to modify the anonymous object - create the string from the ```Key```(=Brace) and the ```Value```(={ or }):
```string input = "ali{}";
//Regex for Braces
string BracesRegex = @"\{|\}";
Dictionary<string, string> dictionaryofBraces = new Dictionary<string, string>()
{
{"Brace", BracesRegex }
};
var matches = dictionaryofBraces.SelectMany(a => Regex.Matches(input, a.Value)
.Cast<Match>()
.Select(b => String.Format("{0} {1}", b.Value, a.Key.ToUpper())))
.OrderBy(a => a).ToList();
foreach (var match in matches)
{
Console.WriteLine(match);
}
```
The output is as desired:
```{ BRACE
} BRACE
```
Comment for this answer: Glad that the answer helped.
|
Title: Observing complex data structures in real time in JavaFX
Tags: java;javafx;javafx-8
Question: Im trying to make a GUI layer to monitor the state in an underlying application. The data Im monitoring is sort of a trading application with the following data structure representing different markets represented and a stript down JSON version for readability.
```{
markets: [{id: 1, runners:[{id:a, prices: [{price:10, level: 1}...]}...]},
{id: 2, runners:[{id:a, prices: [{price:10, level: 1}...]}...]},
{id: 3, runners:[{id:a, prices: [{price:10, level: 1}...]}...]}]
}
```
What makes this hard for me is the following:
I represent ```markets``` as an ```ObservableMap``` and display in a ```ListView``` listing all the ids for different markets. Whenever ```markets``` get updated the ```ListView```. However the tricky part is given some market id gets selected in the ```ListView``` I want to display all the runners and tier prices for the selected market and update the prices seen as they gets updated in the background. What I dont understand is how this is done in JavaFX.
```
My question is if there are any examples online like this where you
first see a list of things and then make a selection and only see the
updates for this selection or could someone make suggestions how this
use case is handled in JavaFX since it feels to be a standard case.
```
Comment: `yourListView.getSelectionModel().getSelectedItems()` returns a ObservableList. You can observe the selection using a `ListChangeListener`.
Comment: This is a rather broad question. Can you break this down and ask a specific question for aspects you are stuck with, one at a time? Are you able to write some code that simply monitors a single market? Once you have that, are you able to write code that displays the result of monitoring that in real time? Can you then add code that enables you to change the market being monitored, and then tie that to the selection in the list view? Each of these is basically a completely different aspect of what you are asking.
Here is the accepted answer: As I said in the comment, you can observe the selection of your ListView. A short example how you do that:
```public class Test
{
public Test()
{
ListView<Object> myListView = new ListView<>();
myListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
myListView.getSelectionModel().getSelectedItems().addListener(this181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16onSelectionChange);
}
private void onSelectionChange(ListChangeListener.Change<? extends Object> change)
{
// Use the complete List to Update everything you need:
List<? extends Object> selection = change.getList(); // List of all selected Items
// OR use the Change to only update the Things that have been changed:
while (change.next())
{
if (change.wasPermutated())
{
for (int i = change.getFrom(); i < change.getTo(); i++)
{
//permutate
}
}
else if (change.wasUpdated())
{
//update item
}
else
{
for (Object removedItem : change.getRemoved())
{
// perform remove action
}
for (Object addedItem : change.getAddedSubList())
{
// perform add action
}
}
}
}
}
```
In my Example the Items in the ListView are just Objects. You can change that to whatever Type you're using.
|
Title: CSS gradient and background-image above gradient
Tags: css;background-image;gradient
Question: My question is this: How can i make my 2 background images appear to the right and left above a CSS gradient. I'm working on a Joomla website using the JA Elastica template (modifying the default CSS).
In my current CSS if i put the "background: url('images')" above the gradient, then it shows the images but not the gradient and if i put it below the gradient it shows the gradient but not the images.
The code i'm currently using is this:
```body#bd {
background-image: linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
background-image: -o-linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
background-image: -moz-linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
background-image: -webkit-linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
background-image: -ms-linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.02, rgb(142,210,46)),
color-stop(0.51, rgb(171,252,74)),
color-stop(0.76, rgb(206,255,104)));
background:
url('https://dl.dropbox.com/u/6512758/onebeat.ro/right.png') no-repeat top right,
url('https://dl.dropbox.com/u/6512758/onebeat.ro/left.png') no-repeat top left;
}
```
Here is the accepted answer: Everything needs to be on the same background-image property otherwise the previous background statement will be replaced by the next one. For example:
```background-image: url('https://dl.dropbox.com/u/6512758/onebeat.ro/right.png') no-repeat top right, linear-gradient(bottom, rgb(142,210,46) 2%, rgb(171,252,74) 51%, rgb(206,255,104) 76%);
```
Check here for more examples:
How do I combine a background-image and CSS3 gradient on the same element?
Comment for this answer: Thanks for the link, i'll look it up
|
Title: Polygon Chain - Conversion to non-crossing while preserving shape?
Tags: c++;c;geometry;computational-geometry
Question: I have polygon chains similar to the following...
...given the chain in the image, how would I go about calculating a chain that defines the same shape but without crossing paths?
Specifically, in the case of the image's input chain, the result I want looks like this:
A1,
A2,
Intersect between A2 and A3,
Intersect between A3 and A4,
A4,
A5,
Intersect between A3 and A4,
A3,
Intersect between A3 and A2,
A6
I'm looking for an algorithm to accomplish this for any chain, but I'm not sure what I'm trying to do is even called, which makes searching for a solution tricky.
If there's a name for what I'm trying to do it would be of great help to know it.
Thank you for any assistance!
Comment: Your question is not very clear. Can you please provide a figure for what you expect the output to be? Also what exactly is meant by _same shape_? Shape does not seem well defined for paths...
Comment: @Moron, but I listed the *exact* output I'm looking for - the image I linked to gives the output I listed context.
Comment: Thanks for the edit Nick! I should have known I could just embed the image.
Comment: @Moron, "Also what exactly is meant by same shape?" - The best way I can explain it is, if you played "connect the dots" with the results chain you'd draw the exact same shape. You'd just be connecting the dots such that your pen never crossed a line it had already drawn (although it could stop at a single point more than once).
Here is the accepted answer: Here's a simple algorithm:
```for each line segment in the chain:
Identify any segments which cross this segment
If crossings > 0
Follow the branch to the right, if this doesn't lead back to the
current intersection follow the branch to the left
go to the next line segment
```
If following a branch doesn't lead back to that intersection before getting to the end of the chain that means you have skipped a loop, so you need to choose the other branch.
For your example, running this algorithm would produce
```Start at segment A1-A2
No intersections, goto next
Segment A2-A3
Intersection A2-A3/A6-A5 choose right path and store the current intersection somewhere
Segment A6-A5
Intersection A6-A5/A4-A3 choose right path and store intersection
Segment A3-A4
A4-A5
A5-A6
Back at intersection A6-A5/A4-A3, go right again to be back on A4-A3
A3-A2
Back at intersection A2-A3/A6-A5, go right again
Finish
```
Comment for this answer: great visual explanation! Would +2 if I could.
Comment for this answer: @Monte You're right, it looks like it's possible for the algorithm to return to a previous path. If it does this however it must be the case that there is more than one bad intersection (else the other path would be traversable), so a record can be made of which intersections you've already tried, eg http://img526.imageshack.us/img526/3117/path.png
Comment for this answer: But wouldn't that break down if the intersects got complicated? As in this image: http://imgur.com/hBLwz.jpg
|
Title: Excel showing error message when typing "- do -"?
Tags: microsoft-excel;worksheet-function
Question: Why Microsoft Excel Show an Error Message when typing "--do--"? It show an message "Your Formulae is incomplete".
Here is the accepted answer: Start your text with a single quote ' if you want to enter what Excel might think is a formula, because it contains numbers or is a mathematical expression.
The message box does say "If you are not trying to enter a formula, avoid using an equal sign, a minus sign, or precede it with a single quotation mark"
Here is another answer: When you hit the first "-" it thinks you want to do a subtraction operation and tries to put a formula in the cell. If you first format the cell as text and then type that in you'll be fine.
|
Title: How to make a JSON object out of getAllResponseHeaders method
Tags: javascript;json;google-chrome;google-chrome-extension;xmlhttprequest
Question: I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the ```getAllResponseHeaders``` method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message ```SyntaxError: Unexpected token D in JSON at position 0 at main```.
Here is the code I am using to do this so far:
```xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
allResponseHeaders = xmlhttp.getAllResponseHeaders();
}
};
xmlhttp.send();
var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;
```
When I put an alert immediately after the ```allResponseHeaders = xmlhttp.getAllResponseHeaders();``` call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the ```Unexpected token D``` part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.
EDIT: I would like my JSON object to look something like this:
```{
"headers": {
"Date": "June 20, 2016",
"Content-Type": "charset=UTF/8",
...
}
}
```
Comment: JSON.parse() isn't going to work on a string that doesn't contain JSON...that's like asking why parseFloat() doesn't work on the string "hello".
Comment: What is your desired output format, specifically? Please [edit] your question to show an example. Also, you might want to add `console.log(allResponseHeaders)` immediately after assigning the value to that variable, so that you can see what format it is in (I think it should be one header per line separated by carriage returns).
Comment: Is there anyway to convert it to a JSON string?
Comment: I edited to show you what the ideal json format should be, and yes it is giving me each field separated by a line
Here is the accepted answer: See https://msdn.microsoft.com/en-us/library/ms536428(v=vs.85).aspx. The return headers are a crlf delimited string where each line contains key values separated by a colon. You will probably have to adjust the code below to account for whitespace.
```var arr = allResponseHeaders.split('\r\n');
var headers = arr.reduce(function (acc, current, i){
var parts = current.split(': ');
acc[parts[0]] = parts[1];
return acc;
}, {});
```
Comment for this answer: The first item of the return value is incorrect.
{
"": undefined
connection: "Keep-Alive"
content-length: "306"
content-type: "text/html; charset=UTF-8"
date: "Wed, 21 Oct 2020 07:42:37 GMT"
keep-alive: "timeout=5, max=94"
server: "Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.2.26"
x-powered-by: "PHP/7.2.26"
}
Here is another answer: I use the following function to extract all response headers as JS object using ```getAllResponseHeaders()```:
```function getResponseHeaderMap(xhr) {
const headers = {};
xhr.getAllResponseHeaders()
.trim()
.split(/[\r\n]+/)
.map(value => value.split(/: /))
.forEach(keyValue => {
headers[keyValue[0].trim()] = keyValue[1].trim();
});
return headers;
}
```
Here is another answer: Simplified version of the accepted answer and fixed issue reported by ```@Emrah Tuncel``` :
```
The first item of the return value is incorrect. { "": undefined }
```
```// ES6:
const headers = request.getAllResponseHeaders().trim().split('\r\n').reduce((acc, current) => {
const [x,v] = current.split(': ');
return Object.assign(acc, { [x] : v });
}, {});
```
Here is another answer: You should put ```JSON.parse``` logic inside the callback ```onreadystatechange```, since Ajax is an asynchronous call and ```allResponseHeaders``` may not be initialized when you use it right after sending the http request.
|
Title: How to get AST only of main function using clang
Tags: c++;clang;abstract-syntax-tree;control-flow-graph
Question: I want to get AST of main function in source file (assuming there is one) to build control flow graph out of it. I found code that generates and traverse AST here: https://shaharmike.com/cpp/libclang/.
But the problem is it goes into all included files. I also find this topic: Clang AST visitor, avoid traversing include files. But it seems that in clang10 some changes were made and suggested solution don't work now. Or maybe there is some other way to get AST for build control flow graph? Only requirement - it must work C++ source code.
Comment: I want to build control flow graph for C++ code. But, becuase of task itself in my studies, I can't use already implement in any ways CFG builder (clang already has one). So, I thought that right way is to get part of AST with info about what is written and on what line it written in sourse file. And because of the task itself in university, the ultimate goal in not to create CFG builder that can cover anything, but create a program which can create CFG for simple programs and get a grasp on how it can be done.
Comment: Going into included files is necessary due to macros, which are not part of the final AST. Unless you want preprocessor AST? What exactly are you trying to achieve?
Here is another answer: Reading the documentation teaches me that ```clang_visitChildren``` only goes "into" whatever it is pointing to if you return ```CXChildVisit_Recurse```. So your visit function should inspect the cursor kind and return ```CXChildVisit_Continue``` until it reaches a function definition where the name equals ```main```. What it does with ```main``` is up to you, but I suggest returning ```CXChildVisit_Break```.
Here is another answer: So, thanks to Botje and this post(https://www.phototalks.idv.tw/academic/?p=1932) I find the solution. Not the best code in any means, but it works. I hope it'll help others.
```#include <iostream>
#include <clang-c/Index.h>
#include <string.h>
using namespace std;
ostream& operator<<(ostream& stream, const CXString& str)
{
stream << clang_getCString(str);
clang_disposeString(str);
return stream;
}
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string getCursorKindName( CXCursorKind cursorKind )
{
CXString kindName = clang_getCursorKindSpelling( cursorKind );
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string result = clang_getCString( kindName );
clang_disposeString( kindName );
return result;
}
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string getCursorSpelling( CXCursor cursor )
{
CXString cursorSpelling = clang_getCursorSpelling( cursor );
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string result = clang_getCString( cursorSpelling );
clang_disposeString( cursorSpelling );
return result;
}
CXChildVisitResult visitor1( CXCursor cursor, CXCursor /* parent */, CXClientData clientData )
{
CXSourceLocation location = clang_getCursorLocation( cursor );
unsigned int locationstring =0;
clang_getSpellingLocation ( location, NULL, &locationstring, NULL,NULL);
if( clang_Location_isFromMainFile( location ) == 0 )
return CXChildVisit_Continue;
CXCursorKind kind = clang_getCursorKind(cursor);
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string str2 ("main");
CXCursorKind cursorKind = clang_getCursorKind( cursor );
unsigned int curLevel = *( reinterpret_cast<unsigned int*>( clientData ) );
unsigned int nextLevel = curLevel + 1;
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string( curLevel, '-' ) << " " << getCursorKindName(
cursorKind ) << " (" << getCursorSpelling( cursor ) << ") ";
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << locationstring ;
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << endl;
clang_visitChildren( cursor,
visitor1,
&nextLevel );
return CXChildVisit_Continue;
}
CXChildVisitResult visitor( CXCursor cursor, CXCursor /* parent */, CXClientData clientData )
{
CXSourceLocation location = clang_getCursorLocation( cursor );
if( clang_Location_isFromMainFile( location ) == 0 )
return CXChildVisit_Continue;
CXCursorKind kind = clang_getCursorKind(cursor);
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string str2 ("main");
CXCursorKind cursorKind = clang_getCursorKind( cursor );
unsigned int curLevel = *( reinterpret_cast<unsigned int*>( clientData ) );
unsigned int nextLevel = curLevel + 1;
if (!((str2.compare(getCursorSpelling(cursor)))))
{
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16string( curLevel, '-' ) << " " << getCursorKindName(
cursorKind ) << " (" << getCursorSpelling( cursor ) << ")\n";
clang_visitChildren( cursor,
visitor1,
&nextLevel );
return CXChildVisit_Continue;
}
else
{
return CXChildVisit_Continue;
}
}
int main()
{
CXIndex index = clang_createIndex(0, 0);
CXTranslationUnit unit = clang_parseTranslationUnit(
index,
<source_file_name>, nullptr, 0,
nullptr, 0,
CXTranslationUnit_None);
CXCursor cursor = clang_getTranslationUnitCursor(unit);
unsigned int treeLevel = 0;
clang_visitChildren( cursor, visitor, &treeLevel );
clang_disposeTranslationUnit(unit);
clang_disposeIndex(index);
}
```
|
Title: null pointer exception parsing json using GSON Android
Tags: android;eclipse;json;android-asynctask;gson
Question: I'm calling a web service which gets the data from the database and outputs the following JSON :
```{"eventId":"1","eventTitle":"opening ceremony","eventCategory":"store","eventSubCategory":"clothing","eventDescription":"This is an event description of some kid for the first event","eventDate":"13/05/2012","eventTime":"14:52","eventAddress":"49 somerset road","eventCity":"southsea","eventCountry":"UK","eventWebsite":"www.nxtldn.com","eventEmail":"[email protected]","eventPhone":"07757491567","eventKeywords":"clothes, street, wear, heart, love"},{"eventId":"2","eventTitle":"cupcakes","eventCategory":"Store","eventSubCategory":"food","eventDescription":"This is an event description of some kid for the second event","eventDate":"17/05/2012","eventTime":"11:22","eventAddress":"12 cleveleys road","eventCity":"london","eventCountry":"UK","eventWebsite":"www.ashshort.com","eventEmail":"[email protected]","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]
```
which I append (I have tested to see if the JSON is valid using http://jsonlint.com/):
```{"Events":[{"eventId":"1","eventTitle":"opening ceremony","eventCategory":"store","eventSubCategory":"clothing","eventDescription":"This is an event description of some kid for the first event","eventDate":"13/05/2012","eventTime":"14:52","eventAddress":"49 somerset road","eventCity":"southsea","eventCountry":"UK","eventWebsite":"www.nxtldn.com","eventEmail":"[email protected]","eventPhone":"07757491567","eventKeywords":"clothes, street, wear, heart, love"},{"eventId":"2","eventTitle":"cupcakes","eventCategory":"Store","eventSubCategory":"food","eventDescription":"This is an event description of some kid for the second event","eventDate":"17/05/2012","eventTime":"11:22","eventAddress":"12 cleveleys road","eventCity":"london","eventCountry":"UK","eventWebsite":"www.ashshort.com","eventEmail":"[email protected]","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]}
```
I'm calling it using an AsyncTask
```public class EventSync extends AsyncTask<String, Integer, EventsList> {
EventsList elist1 = new EventsList();
@Override
protected EventsList doInBackground(String... urls) {
String tempurl = urls[0];
String output = "";
InputStream is = null;
StringBuilder sb = new StringBuilder();
EventsList list = new EventsList();
try
{
URL url = new URL(tempurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
output = sb.toString();
String json = "{\"Events\":" + output + "}";
System.out.println(json);
Gson gson = new Gson();
// When debugging this is the line I believe it fails on, It points to a bit of memory but the list is empty.
EventsList jsonlist = gson.fromJson(json, EventsList.class);
return jsonlist;
}
@Override
protected void onPostExecute(EventsList list)
{
System.out.println("in on post");
for (Event event : list.getEvents())
{
System.out.println(event.getEventId());
}
}}
```
```public class EventsList {
public EventsList(){
}
private List<Event> events;
public List<Event> getEvents()
{
return events;
}
public void setEventsList(List<Event> events)
{
this.events = events;
}}
```
```public class Event {
private String eventId;
private String eventTitle;
private String eventCategory;
private String eventSubCategory;
private String eventDescription;
private String eventDate;
private String eventTime;
private String eventAddress;
private String eventCity;
private String eventCountry;
private String eventWebsite;
private String eventEmail;
private String eventPhone;
private String eventKeywords;
public Event()
{
}
// ALL GETS AND SETS
```
At the moment I'm just trying to test it to see if it will return before I use a custom adapter to populate a listview. But unfortunate I am getting the following error:
```11-10 23:37:08.315: E/AndroidRuntime(5592): FATAL EXCEPTION: main
11-10 23:37:08.315: E/AndroidRuntime(5592): java.lang.NullPointerException
11-10 23:37:08.315: E/AndroidRuntime(5592): at com.nxtldn.trill.EventSync.onPostExecute(EventSync.java:71)
11-10 23:37:08.315: E/AndroidRuntime(5592): at com.nxtldn.trill.EventSync.onPostExecute(EventSync.java:1)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.os.AsyncTask.finish(AsyncTask.java:631)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.os.Looper.loop(Looper.java:137)
11-10 23:37:08.315: E/AndroidRuntime(5592): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-10 23:37:08.315: E/AndroidRuntime(5592): at java.lang.reflect.Method.invokeNative(Native Method)
11-10 23:37:08.315: E/AndroidRuntime(5592): at java.lang.reflect.Method.invoke(Method.java:511)
11-10 23:37:08.315: E/AndroidRuntime(5592): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-10 23:37:08.315: E/AndroidRuntime(5592): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-10 23:37:08.315: E/AndroidRuntime(5592): at dalvik.system.NativeStart.main(Native Method)
```
I new to android so I'm not sure if there is a better way of doing this or what the correct way is.
Is it down the the structure of my JSON why the GSON wont accept and returns null pointers?
Many thanks in advance to anyone that can help :)
Here is the accepted answer: I found it was due to me adding "/n" to my string builder, creating the new line and chopping off the final } of the json. Thanks everyone
Here is another answer: In EventsList you are expecting a List(Collection) of events but the JSON you append is actually an Object: "{\"Events\":" + output + "}"; Perhaps you wanted it to look like this:
```"{\"Events\":[" + output + "]}";
```
This puts your single event into an array of potential events. Your use case is confusing, I'm not sure why you want to put a single JSON object into an array but perhaps there are more details I'm missing.
Comment for this answer: Sorry, the first JSON output is missing a square bracket which was removed when copying to SOF. If you could please place your attention to the second JSON, it is a JSON Object of Events which holds a JSON Array of JSON Objects. Am i correct in say that? Which I am then trying to convert using GSON into my two seperate Classes.
Comment for this answer: Try calling it "events" instead of "Events"
Here is another answer: Try changing
```EventsList jsonlist = gson.fromJson(json, EventsList.class);
```
to
```Event[] jsonlist = gson.fromJson(json, Event[].class);
```
This is assuming that you have used an array of type Event (shown above in your example) in your webservice to create this json. I think the current problem is that your json string does not match up to the class EventList therefore returning null. Ensure that the Event class in your service and android project match.
|
Title: Can't Disable Intel Turboboost via InsydeH2O BIOS
Tags: 16.04;bios;turbo-boost
Question: According to this post
Cannot change Intel turbo boost (/sys/devices/system/cpu/intel_pstate/no_turbo/ not accessible)
I followed the steps. And it seems like I have to disable Turboboost at BIOS because I faced the same problem as him, but my BIOS doesn't have an option to disable it (InsydeH2O BIOS). I have to disable it because I want to test the FLOPs via PAPI.
So I would like to ask if there are alternative ways to disable it?
Comment: I'm sorry. I did `echo "1" | sudo tee sys/devices/system/cpu/intel_pstate/no_turbo` and it worked properly. Maybe it's because of gedit because I got the same error as him on gedit. But when I checked via `grep MHz /proc/cpuinfo`, it seems that CPU freq scaling is still enabled. How can I stop this feature temporarily to run PAPI's FLOPs testing program. My CPU is Intel® Core™ i7-4700MQ CPU @ 2.40GHz w/ 4 cores and 8 threads.
Comment: It didn't work, even if I restarted. CPU clocks are still variant, but nearly closed to each other (about 2400). PAPI still cannot detect stable clock.
Comment: Yes, but the person on the link you gave was interpreting the meaning of turbo enabled or disabled backwards. In his case, it was already disabled in the BIOS. Could you please add some of the similar information to your question. And what is your processor model?
Comment: Set all CPUs to use the performance frequency scaling governor. However note that the CPU itself can still backoff its own frequency under very low load conditions, but the response time to a stable CPU frequency will be the fastest in performance mode. Do: `sudo su` then `for file in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo "performance" > $file; done` then check it `cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor` then `exit`.
Comment: Well, that would be PAPI's problem. Modern CPUs vary the clock frequency. If your BIOS has the option, then try disabling Intel Speedstep.
|
Title: Area 51 Share buttons are outdated
Tags: bug;area51
Question: The share button for Twitter on Area 51 looks dated, and none of the buttons are retina display optimized. An itch to scratch would be to switch the "t" to a bird and/or retinize those images.
Comment: Not really a bug, unless the sharing itself is broken. Since the Area 51 code base is "frozen", I doubt this will be ever done though, as they are only fixing critical bugs.
Here is the accepted answer: Apparently, Area 51 hasn't have an update for a very long time here.
It would be nice to see an more up-to-date version of the logos for the social communities. Twitter definitely needs to change to its newer logo and probably other sites, like Gmail and other now unrecognizeable sites. Hopefully, a mod comes with a big status-completed and finishes this before it becomes a 2016 resolution.
|
Title: How to print all words of a for loop in one line
Tags: python;python-3.x;formatting
Question: I have following set of data.
```set = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]
```
I want my output to look like:
```John: m(23) m(45)
Maria: f(17)
Stacy: f(19) f(21)
```
Right now my output looks like this with the following code.
Output:
```John: m (23)
Maria: f (17)
John: m (45)
Stacy: f (19)
Stacy: f (21)
```
Code:
```for ind in set:
i = ind[0]
if i == "john":
print("John:"," ", str(ind[1]), "({0}) ".format(str(ind[2])))
elif i == "maria":
print("Maria:"," ", str(ind[1]), "({0}) ".format(str(ind[2])))
elif i == "stacy":
print("Stacy:", " ", str(ind[1]), "({0}) ".format(str(ind[2])))
```
Comment: Your `set` is a list of tuples. And you shouldn't give variables names of [built-in functions](https://docs.python.org/3/library/functions.html).
Here is another answer: You should first collect the data for each person, and then you can print for each person, one at a time like:
Code:
```data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]
# collect per person, except Mary. We don't like Mary
as_dict = {}
for datum in data:
as_dict.setdefault(datum[0], []).append(datum)
# print each person, except Mary. We don't like Mary.
for name, items in as_dict.items():
if name in set('john stacy maria'.split()):
msg = '{}: '.format(name) + ' '.join('{} ({})'.format(i[1], i[2])
for i in items)
print(msg)
```
Results:
```john: m (23) m (45)
mary: f (32)
stacy: f (19) f (21)
maria: f (17)
```
Comment for this answer: I need to compare if the first index of my data matches with given name, ie, i = datum[0], if i == "john" then do this... as seen in the output i don't want mary to be printed
Comment for this answer: I have very large data. Among them I only I want John, Stacy, Maria to be printed.
Comment for this answer: Then simply exclude `mary`. `if name != 'mary'`
Comment for this answer: Do you expect me to be chasing changing requirements? I answered the question as presented. I frankly saw your stacked if as a naive implementation, not a requirement.
Here is another answer: Here's a different approach in which you collect the names of all person from your input list, then you collect and combine all information associated with each person and finally you print these information:
```inSet = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]
# Get names of people
nameSet = sorted(set([info[0] for info in inSet]))
# Get all info associated with each of these people
displayInfo = [ " ".join(["".join([info[1], '(' + str(info[2]) + ')']) for info in inSet if name==info[0]]) for name in nameSet]
# Print these information, after capitalizing first letter of each name.
for info in zip(map(str.title,nameSet),displayInfo):
print(": ".join(info))
```
Output:
```John: m(23) m(45)
Maria: f(17)
Mary: f(32)
Stacy: f(19) f(21)
```
Here is another answer: Try this (it only prints for john, maria and stacy):
```data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]
permitted_names = ['john', 'maria', 'stacy']
output = {}
for name, gender, age in data:
if name not in permitted_names:
pass
elif name not in output:
output[name] = '{0}({1})'.format(gender, age)
else:
output[name] += ' {0}({1})'.format(gender, age)
for name, value in output.items():
print("{0}: {1}".format(name, value))
```
Output:
```john: m(23) m(45)
maria: f(17)
stacy: f(19) f(21)
```
Here is another answer: You can use python's ```defaultdict``` for this:
```In [37]: from collections import defaultdict
In [38]: data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
...: ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]
In [39]: d = defaultdict(list)
In [40]: for name, *rest in data:
...: d[name].append(rest)
In [41]: for name, value in d.items():
...: if name in ('john', 'maria', 'stacy'):
...: strvalues = (' {}({})'.format(a, b) for a, b in value)
...: print('{}: {}'.format(name, ''.join(strvalues)))
john: m(23) m(45)
maria: f(17)
stacy: f(19) f(21)
```
Comment for this answer: I am not allowed to import any library.
|
Title: mysql like query with check of values in comma separated data
Tags: mysql
Question: I have a table with data like this
```+-------+---------------------+------------------------------------------------+--------------------+
| id | name | movieyears | length(movieyears) |
+-------+---------------------+------------------------------------------------+--------------------+
| 85530 | Nargis Fakhri | [2011,2013,2014] | 16 |
| 26683 | Nawazuddin Siddiqui | [1999,2006,2007,2009,2010,2012,2013,2014,2015] | 46 |
| 14508 | Aditi Rao Hydari | [2009,2011,2012,2013,2014] | 26 |
+-------+---------------------+------------------------------------------------+--------------------+
```
Challenge is to find the rows for which the actors were only active in past 4 years and not in any other years, so essentially a good query should return only the first row of 'Nargis Fakhri' and not of any other actor, I know about Find_In_set but that's to find if actor existed for one particular year.
Comment: Don't store multiple values in a single column.
Comment: 1. See normalization. That's all.
Comment: I wish i could, I am out of option here, and Yes i do know normalization, I am just not in state to do so.
Here is the accepted answer: The solution would be quite as ugly as the table design...
```select
id, name
from
TheTable
where
movieyears <> '[]' and
replace(replace(replace(replace(replace(movieyears, '2011', ''), '2012', ''), '2013', ''), '2014', ''), ',', '') = '[]'
```
Comment for this answer: an ugly code needs an ugly mate, couldn't agree more :)
Here is another answer: As a note, your years seem to be ordered. If this is the case:
```select t.*
from tablewithdata t
where substring_index(movieyears, ',', 1) >= '2011';
```
|
Title: How to call widget section from another file in Flutter
Tags: flutter;flutter-layout
Question: i have Method and Widget section defined in main.dart and my code works fine,
i created new file method.dart and used all methods in that file and imported methods in my main file and it worked,
but my issue is how i can call Widget section from another file in main.dart.
main.dart:
```
how to call following widget from another file:
```
```Widget buttonSection = Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(color, Icons.call, 'CALL'),
_buildButtonColumn(color, Icons.near_me, 'ROUTE'),
_buildButtonColumn(color, Icons.share, 'SHARE'),
],
),
);
```
```
following method can be called from another file:
```
```Column _buildButtonColumn(Color color, IconData icon, String label) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
```
```
Using it in material function:
```
```return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter layout demo'),
),
body: ListView(
children: [
Image.asset(
'images/lake.jpg',
width: 600,
height: 240,
fit: BoxFit.cover,
),
buttonSection,
],
),
),
);
```
Comment: how to use widget of file1.dart in main.dart
Comment: please give one simple example if you can.
Comment: You can call them by using a class and object in file.
Comment: I can't understood. Can you share all code with proper description?
Here is the accepted answer: To use your buttonSection widget from any file whether it is main.dart file or any other dart file you have to write the buttonSection widget out of any class and globally.
So you can have the access of that particular widget. If you are creating it inside a Stateful or Stateless class then you will not be able to access the buttonSection widget.
So create a dart file and add the following widget out of all class and define globally.
```Widget buttonSection = Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(color, Icons.call, 'CALL'),
_buildButtonColumn(color, Icons.near_me, 'ROUTE'),
_buildButtonColumn(color, Icons.share, 'SHARE'),
],
),
);
```
Then to access it anywhere import the dart file containing buttonSection widget and you can use it like,
```@override
Widget build(BuildContext context) {
return buttonSection;
}
```
Also, keep in mind that your widget/variable/function name should not start with "_" to globally access it from another dart files.
Comment for this answer: Thankyou all clear but, what do you mean by define it out of all class ?
Comment for this answer: if i just copy and paste your code for buttonsection in empty file file1.dart without app body or main function or without stateless widget, will it work if i call it in main.dart? or i need to define everything as well again and again.
Comment for this answer: i want minimal code in file1.dart i want only buttonsection in it. is it possibly
Comment for this answer: Out of all means, you cannot define the widget inside any Stateful or Stateless widget. otherwise its scope will be limited to the respective Stateful or Stateless class and you will not be able to access it from other dart files directly.
Comment for this answer: You can access your buttonSection widget. But, if you are talking about _buildButtonColumn() widget inside it. Then it is not possible to access it. You have to define them.
Comment for this answer: What you can do is define your whole buttonSection widget with its all child in a new file then you can access that whole widget in as many files as you want.
Comment for this answer: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203980/discussion-between-jay-mungara-and-fayakon).
|
Title: n8n Hubspot Trigger node authentication failing
Tags: docker;hubspot;scopes;n8n
Question: I'm setting up the Hubspot trigger node in n8n.
I'm working on localhost through docker & using ngrok so I have a https URL for the OAuth callback. When I try to connect to my Hubspot developer account I get the error:
Couldn’t complete the connection
Insufficient scopes were provided. Please contact the app developer.
I have selected all scopes in my developer app & in my private app used via the Hubspot parent account.
Does anyone have any idea what could be the cause of this?
Thanks
|
Title: apollo-link-state: How to specify object type parameter on typeDefs less state link?
Tags: javascript;graphql;apollo-client
Question: I am creating my ```stateLink``` without providing a schema like this:
```const stateLink = withClientState({
cache,
resolvers,
defaults
})
```
I have a mutation that take an Object as parameter:
```MY_MUTATION = gql`mutation myMutation($product: Product) {...}`
```
Since there is no ```typeDefs``` (no ```Product``` object type), and there is no type checking anyway, how can I specify that the ```$product``` argument is an object and not a scalar type ?
Comment: No you don't get the point. What is here `gql(...)` is not JS, but GraphQL Query Language. I got my answer. With apollo-link-state there is no type checking. So you can put whatever you want there , `Product`, `Int` or whatever, as long as the argument works well with your resolver's code.
Comment: OK, good to know.
Comment: I am not sure to unserstand what exactly you are trying to achieve. To who/what do you want to specify the type to? If you are expecting type-checking, you should be using a type-checking tool like flow, typescript or even another language than JS because JS is not typed.
Comment: I do get the point :) I use apollo client and server with typescript and use graphql code generator to generate typescript types from my schema and queries. This way I get type checking at compile time
|
Title: How do you log to Firebug from an extension?
Tags: debugging;firefox;logging;console;firebug
Question: I'm writing an extension for Firefox, and I need to log some data to Firebug's console. Within the scope of my addon, "console" is undefined, and "window.content.console" is also undefined. So how do I log to the console?
Here is the accepted answer: Since you're not writing Javascript that executes within a window, ```console``` is not defined.
So you need to reference the Firebug extension first:
```Firebug.Console.log(str);
```
Comment for this answer: Oopch, `Firebug` is undefined!
Comment for this answer: try this
Application.console.log("Hello from my Firefox Extension!");
Comment for this answer: @TahaJahangir, just turn your Firebug on for current page and press f5 ;)
Comment for this answer: I have Firebug installed but it seems you can no longer do this. `Firebug` is `undefined`.
Here is another answer: There are contexts in which even the Firebug object is unknown, like if you're trying to call it from a sidebar... in which case you have to go all the way back to the original window to get the firebug object:
``` var Firebug = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow).Firebug;
```
You can then from within your sidebar call Firebug like so:
```Firebug.Console.log("foo");
```
This is documented here: https://developer.mozilla.org/en/Code_snippets/Sidebar
Here is another answer: To log to the console from inside a firefox extension’s javascript:
Application.console.log("Hello from my Firefox Extension!");
Here is another answer: If in your extension you have access to the content Window object, you can unwrap it, and call the console methods directly:
```window.wrappedJSObject.console.log('something important');
```
Comment for this answer: window.wrappedJSObject is undefined
Here is another answer: As far as I know you can only do that if you are creating a JetPack Add-on. Normal debugging is done with Venkman from Mozilla at http://www.mozilla.org/projects/venkman/
Here is another answer: Firebug console is associated with a particular page, so it wouldn't be very convenient even if you managed to log messages there. Did you try Chromebug? I didn't use it, but I would expect to find a similar console for extensions to use there.
You could also use the regular Error Console, although you won't get all the niceties Firebug's console provides. You could install Console^2 https://addons.mozilla.org/en-US/firefox/addon/1815 to make using the Error Console a little less painful.
|
Title: React-Chart.js : How do I increase the space between the legends and chart?
Tags: javascript;reactjs;chart.js;react-chartjs
Question: There are a couple of questions that run along the same lines as mine. However, these questions focus on simply chart.js. I have a similar problem but on react-chart.js. How do I increase the space between the legend and chart? I have used ```padding``` but it only increases the space between the legends. Not quite what I wanted. Below is my doughnut chart component.
``` <div className="dougnut-chart-container">
<Doughnut
className="doughnut-chart"
data={
{
labels: ["a", "b", "c", "d", "e", "f"],
datasets: [
{
label: "Title",
data: [12821, 34581, 21587, 38452, 34831, 48312],
backgroundColor: [
'rgb(61, 85, 69)',
'rgb(115, 71, 71)',
'rgb(166, 178, 174)',
'rgb(209, 191, 169)',
'rgb(66, 63, 62)',
'rgb(43, 43, 43)',
]
}
],
}
}
options={
{
plugins: {
legend: {
labels: {
color: "white",
font: {
size: 12
},
padding: 10,
},
position: "left",
title: {
display: true,
text: "Title",
color: "grey",
padding: 10
}
}
},
elements: {
arc: {
borderWidth: 0
}
},
responsive: true,
maintainAspectRatio: true,
}
}
/>
</div>
```
What my chart looks like:
Here is the accepted answer: This answer suggested by @LeeLenalee works for me. But for those who are confused and wants to see this integrated in their components, here is what I did:
```<div className="dougnut-chart-container">
<Doughnut
className="doughnut-chart"
data={
{
labels: ["label_1", "label_2", "label_3", "label_4", "label_5", "label_6"],
datasets: [
{
label: "Title",
data: [12821, 34581, 21587, 38452, 34831, 48312],
backgroundColor: [
'rgb(61, 85, 69)',
'rgb(115, 71, 71)',
'rgb(166, 178, 174)',
'rgb(209, 191, 169)',
'rgb(66, 63, 62)',
'rgb(43, 43, 43)',
]
}
],
}
}
options={
{
plugins: {
legend: {
labels: {
color: "white",
font: {
size: 12
},
padding: 10,
},
title: {
display: true,
text: "A Longer Title To Occupy Space",
color: "grey",
padding: {
bottom: 10
},
font: {
size: 13
}
},
position: "left"
},
// this is the id that is specified below
legendDistance: {
padding: 130 // dictates the space
}
},
elements: {
arc: {
borderWidth: 0
}
},
responsive: true,
maintainAspectRatio: true,
}
}
plugins={
[
{
id: 'legendDistance',
beforeInit(chart, args, opts) {
// Get reference to the original fit function
const originalFit = chart.legend.fit;
// Override the fit function
chart.legend.fit = function fit() {
// Call original function and bind scope in order to use `this` correctly inside it
originalFit.bind(chart.legend)();
// Specify what you want to change, whether the height or width
this.width += opts.padding || 0;
}
}
}
]
}
/>
</div>
```
This is the result: result
Take note: You need to reload your page to see the changes.
Here is another answer: for react you can try this code ->
```const legendMargin = {
id: "legendMargin",
beforeInit: function (chart) {
const fitValue = chart.legend.fit;
chart.legend.fit = function fit() {
fitValue.bind(chart.legend)();
return (this.height += 40);
};
}
};
```
then just need to pass ```legendMargin``` as a props like this way
```<Bar options={options} data={data} plugins={[legendMargin]} />```
Comment for this answer: This wont work, the legend is on the side of the chart so the height does not affect its distance to the chart
Here is another answer: You can write a custom plugin as showed by this answer, but instead of adding some extra space to the height you will need to add some extra spacing to the width of the legend boxes:
```var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
}]
},
options: {
plugins: {
legend: {
position: 'left'
},
legendDistance: {
padding: 50
}
}
},
plugins: [{
id: 'legendDistance',
beforeInit(chart, args, opts) {
// Get reference to the original fit function
const originalFit = chart.legend.fit;
// Override the fit function
chart.legend.fit = function fit() {
// Call original function and bind scope in order to use `this` correctly inside it
originalFit.bind(chart.legend)();
// Change the height as suggested in another answers
this.width += opts.padding || 0;
}
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
```<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>```
|
Title: How to get files from multiple directories using fs or async methods?
Tags: javascript;node.js;fs;async.js
Question: I am trying to write logic where i can get files information from each directory , How can i achieve that using ```async``` or any ```fs``` method. I am passing ```fileInfo``` and ```filePath``` to function ```compareDates``` for further implementation. With below code i dont see any results.
controller.js
```var cron = require('cron-job');
var fs = require('fs');
var path = require('path');
var async = require('async');
var directories = ['./logs/dit', './logs/st','./logs/uat']
function cronJob() {
directories.forEach(function(dir){
var files = fs.readdirSync(dir);
async.eachSeries(files, function(file, callback) {
var filePath = path.join(dirPath, file);
var fileInfo = {};
fs.stat(filePath, function(err, stats) {
if (err) {
console.info("File doesn't");
} else {
fileInfo.fileDate = stats.birthtime;
fileInfo.filename = file;
compareDates(fileInfo,filePath);
console.log(fileInfo);
}
});
});
})
}
cronJob();
```
Error
```throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
```
Comment: i see that error in console when it invoke `var files = fs.readdirSync(dir);`
Comment: no I am not , any better way to get this done
Comment: What's the actual error message? And where did you find that line of code?
Comment: That's weird. Are you sure you're not using `fs.readdir`?
Here is another answer: This function will return an array of file paths for all files inside a directory. It recursively loops through all folders and subfolders within the specified dir and ignores empty folders.
```var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
```
Usage:
```walk(directory, function(err, results) {
// throw error if something is wrong
if (err) throw err;
results.forEach(function(path) {
// do stuff with the path
});
});
```
Note that the function will return paths relative to ```/``` or ```C:\```; if you want your directories to be relative to the location of your server/app.js file, you'll need to slice off the length of ```__dirname``` from the beginning of each path.
You can then use ```fs.stat``` on each of the files to get the information you need to pass to your function.
Using your code, it would be like:
```var directories = ['/logs/dit', '/logs/st','/logs/uat'];
directories.forEach(function(directory){
walk(directory, function(listOfFiles) {
listOfFiles.forEach(function(file) {
fs.stat(file, function(err, stats) {
if (err) throw err;
var fileDate = stats.birthtime;
var filename = file;
compareDates(filename, filePath);
});
});
});
});
```
Apologies in advance if my code is a bit messy. Some things you could do :
use a ```for``` loop instead of ```forEach``` if you need to keep
count of files.
repurpose ```walk``` and utilize the ```fs.stat``` call thats being made in there.
Hope this helps :)
Comment for this answer: i am getting error `at Array.forEach (native)
at cronJob (C:\Users`
Comment for this answer: `
ReferenceError: walk is not defined
at C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serverfiles\cronJobs.js:
10:6
at Array.forEach (native)
at C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serverfiles\cronJobs.js:
9:14
at Array.forEach (native)
at cronJob (C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serverfiles\cro
nJobs.js:7:13)
at Object. (C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serv
erfiles\cronJobs.js:42:1)`
Comment for this answer: i fixed that `filename` period
Comment for this answer: ok i added that and see `TypeError: listOfFiles.forEach is not a function
at C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serverfiles\cronJobs.
34:21
at C:\Users\sh529u\WebstormProjects\Ulog-0\ulog\app\serverfiles\cronJobs.`
Comment for this answer: could you paste the error stack? You might have to normalize the paths before doing any computations on them if you are running on an OS other than linux (i.e. windows)
There was also a period in `var filename = file` (assuming you copied and pasted the code)
Comment for this answer: You have to define the walk function. Copy the walk function and paste it ABOVE your `cron` function.
Also, you should use backticks ```` for the stacks. helps with readability :)
Comment for this answer: That's really odd, since `listOfFiles` is an array of strings... You can try using a for loop to iterate through the items instead.
`for (i = 0; i < listOfFiles.length; i++){
//code goes here
}`. If you can, use a console log and JSON.stringify listOfFiles to see its output. that should help you understand what you need to do to loop through those items or figure out where the problem is.
|
Title: CV linear regression KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported
Tags: python;cross-validation
Question: I trying to compare the linear regression R squared with the gradient boosting’s one using k-fold cross-validation, a procedure that consists in splitting the data k times into train and validation sets and for each split, the model is trained and tested
```## call model
model = linear_model.LinearRegression()
## K fold validation
scores = []
cv = model_selection.KFold(n_splits=5, shuffle=True)
fig = plt.figure()
i = 1
for train, test in cv.split(X_train, y_train):
prediction = model.fit(X_train[train],
y_train[train]).predict(X_train[test])
true = y_train[test]
score = metrics.r2_score(true, prediction)
scores.append(score)
plt.scatter(prediction, true, lw=2, alpha=0.3,
label='Fold %d (R2 = %0.2f)' % (i,score))
i = i+1
plt.plot([min(y_train),max(y_train)], [min(y_train),max(y_train)],
linestyle='--', lw=2, color='black')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('K-Fold Validation')
plt.legend()
plt.show()
```
But I'm not able to avoid:
KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Int64Index([ 6, 9, 13, 32, 40,\n ...\n 4221, 4223, 4224, 4226, 4233],\n dtype='int64', length=679
Comment: Yes, I hope, I did:X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=1234, stratify=df['q
'])
Comment: It doesnt work for me because X, y are panda arrays
Comment: Are you sure your X_train and y_train have the same number of samples and same row indexes?
Comment: Please look at this [link](https://stackoverflow.com/questions/60459218/pandas-passing-list-likes-to-loc-or-with-any-missing-labels-is-no-longer-su). Try using .iloc to access the rows
|
Title: How to send POST request from Android to Elasticsearch
Tags: android;json;elasticsearch;android-volley
Question: I have an app, where the 'Feedback' entered by the user is stored as JSONObject. How do I send this JSONObject to elasticsearch?
Below is the code I have tried:
``` void sendFeedback() {
String url = "http://localhost:9200/trial_feedback_index2/trial_feedback_type2 ";
/* "trial_feedback_index2" is my index and "trial_feedback_type2" is my type, where I want to store the data, in elasticsearch.*/
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
// Log.d("Error.Response", response);
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("Feedback", feedbackQAJsonObjOuter.toString());
return params;
}
};
queue.add(postRequest);
// add it to the RequestQueue
}
```
How do I make it work?
Thanks!
Comment: `http://localhost:9200/` will not work. That needs to be the external IP of your server, but you've given localhost of your Android device, not running Elasticsearch
Comment: What is the problem? What errors did you get? It's difficult trying to help someone when you don't know what's their exact problem
Here is another answer: You can use ```HashMap``` to store your data and then convert it to ```JSONObject```. After that pass that ```JSONObject``` to request:
```HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("feedbackKey","value");
JSONObject jsonObject = new JSONObject(hashMap);
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>()
{.....
..... Your other code
```
|
Title: #Value error using custom function in Excel
Tags: excel;function;add-in;user-defined-functions;vba
Question: I'm getting a #VALUE error when I try to call my custom function. All it is supposed to do is a bit of math. Does anyone see what could be wrong here?
I copied this one off the internet:
Source:
http://www.engineerexcel.com/linear-interpolation-vba-function-in-excel/
```
```Function LININTERP(x, xvalues, yvalues)
'x and y values must be in ascending order from top to bottom.
'x must be within the range of available data.
x1 = Application.WorksheetFunction.Index(xvalues, Application.WorksheetFunction.Match(x, xvalues, 1))
x2 = Application.WorksheetFunction.Index(xvalues, Application.WorksheetFunction.Match(x, xvalues, 1) + 1)
y1 = Application.WorksheetFunction.Index(yvalues, Application.WorksheetFunction.Match(x, xvalues, 1))
y2 = Application.WorksheetFunction.Index(yvalues, Application.WorksheetFunction.Match(x, xvalues, 1) + 1)
LININTERP = y1 + (y2–y1) * (x–x1) / (x2–x1)
End Function
```
This is a simplified version I made thinking that the worksheet function calls may be causing the error:
```Function LININTERP(x, x1, x2, y1, y2)
LININTERP = y1 + (y2–y1) * (x–x1) / (x2–x1)
End Function
```
my test data in an unrelated workbook:
(All formatted as "General")
```A1: 633
A2: 634
B1: 14.968
B2: 15.024
C1 (my x): 633.6
```
Just plugging the actual math into a cell works as expected. Calling the function throws the #VALUE error.
My function is saved in a module in a workbook that I have saved and added to Excel as an Add-In.
Comment: btw, those `(y2–y1)`, etc **should** have autocorrected to `(y2 - y1)` if the VBE had recognized the maths operation.
Comment: Also with Option Explicit you get a compile error (variable not defined)
Comment: Your `-` are not actual minus, code 150 vs code 45. highlight each and replace it with an actually typed `-`
Here is the accepted answer: My sampling of your formula and data threw an error on the hyphens not being interpreted as 'minus signs'. In fact, they come up as unicode 8211. Retyping them, declaring the vars as variants and removing the ```...WorksheetFunction...``` fixed the problem.
```Function LININTERP(x, xvalues, yvalues)
Dim x1 As Variant, x2 As Variant, y1 As Variant, y2 As Variant
'x and y values must be in ascending order from top to bottom.
'x must be within the range of available data.
x1 = Application.Index(xvalues, Application.Match(x, xvalues, 1))
x2 = Application.Index(xvalues, Application.Match(x, xvalues, 1) + 1)
y1 = Application.Index(yvalues, Application.Match(x, xvalues, 1))
y2 = Application.Index(yvalues, Application.Match(x, xvalues, 1) + 1)
LININTERP = y1 + (y2 - y1) * (x - x1) / (x2 - x1)
End Function
```
Moral of the story: Don't trust everything you find on the internet.
Comment for this answer: btw² - Removing WorksheetFunction and passing the returned value back to a variant allows you to check for errors like `If IsError(x1) Then`. Keeping WorksheetFunction removes this ability for error-handling.
|
Title: XSD for complex XML structure
Tags: xml;xsd;xml-parsing;xsd-validation
Question: I have a rather complex XML structure I am trying to validate and I can't seem to come up with a XSD structure that would allow me to express the following:
```<foo fooAttribute1="..." fooAttribute2="..." ...>
<bar1 id="1" ... />
<bar1 id="2" ... />
<bar2 id="1" ... />
<bar2 id="2" ... />
<![MyFormattedTextGoesHere[foo text goes here]]>
</foo>
```
So, I want to have a ```foo``` which can contain
attributes
0..* ```bar1``` elements
0..* ```bar2``` elements
formatted text (e.g. starting with ```<![MyFormattedTextGoesHere[``` and ending with ```]]>```
On a related note: can I also validate attribute values like so:
```<xml someAttribute=$... />``` (has to start with a ```$```)?
What I currently have is
```<xs:element name="foo" minOccurs="0" maxOccurs="unbounded">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="bar1" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" form="unqualified" type="xs:string" />
<xs:attribute name="..." form="unqualified" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="bar2" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" form="unqualified" type="xs:string" />
<xs:attribute name="..." form="unqualified" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="fooAttribute1" form="unqualified" type="xs:string"/>
<xs:attribute name="fooAttribute2" form="unqualified" type="xs:string"/>
<xs:attribute name="..." form="unqualified" type="xs:string" />
<!-- accept/validate text here? -->
</xs:complexType>
<!-- or here? -->
</xs:element>
```
Comment: Edited my question to show my current XSD structure. I tried to add simpleContent but couldn't mix it with the child elements `bar1`, `bar2`, I think
Here is the accepted answer: The XML above is not well-formed because of ```<!``` followed by general text. What is meant here may be a CDATA section, like so:
```<?xml version="1.0" encoding="UTF-8"?>
<foo fooAttribute1="$..." fooAttribute2="..." >
<bar1 id="1" />
<bar1 id="2" />
<bar2 id="1" />
<bar2 id="2" />
<![CDATA[MyFormattedTextGoesHere[foo text goes here]]>
</foo>
```
A good starting point for a schema against which the above XML is valid is this:
```<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:simpleType name="beginswithdollar">
<xs:restriction base="xs:string">
<xs:pattern value="\$.*"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="foo">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="bar1" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence/>
<xs:attribute name="id" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="bar2" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence/>
<xs:attribute name="id" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="fooAttribute1" type="beginswithdollar"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
</xs:element>
</xs:schema>
```
A few things are not supported by XML Schema though:
Whether text is in CDATA sections or not is not visible by XML Schema. CDATA sections are used to avoid escaping special characters.
Complex types can be mixed-content or not. If mixed-content, it can not be controlled where the text appears or what its type is: it could also appear before or between ```bar*``` elements.
Attributes can be allowed with no restriction with ```xs:anyAttribute```, but it is not possible to restrict their type in general. In the above schema, for example, the attribute ```fooAttribute1``` must start with a dollar, while any other attributes are allowed with no restriction.
If XML Schema 1.1 is supported, there is also the ```assert``` feature that allows to express user-defined constraints. This may be a way to further restrict validity of instances in a tailored way beyond what other XML Schema components can do.
Comment for this answer: Thanks so far; one more question, though: Is there a way to check if there is a CDATA section present?
Comment for this answer: @vonludi No, as far as XSD is concerned it is irrelevant whether the text is in a CDATA section or not (just as it is irrelevant if `E` is written as `E`)
|
Title: Error while using shell script to copy lines to a file using cygwin
Tags: shell;cygwin
Question: I am trying to copy few lines to another file .bashrc using shell script and cygwin terminal.The lines are :
```echo "export DEVENVHOME=${DEVENVHOME:-$workarea/devenv.x}" >> .bashrc
```
I am writing command :
``` workarea="/home/WORKAREA" sh script1.sh
```
But the output on .bashrc is :
``` export DEVENVHOME=workarea/devenv.x
```
But i want the copy line
``` export DEVENVHOME=${DEVENVHOME:-$workarea/devenv.x}
```
in .bashrc where $workarea should be replaced by the workarea provided as argument on cygwin terminal.
Here is the accepted answer: Single quotes suppress substitution.
```echo '...' >> ...
```
Comment for this answer: Your `.bashrc` is not interactive with your current shell environment since it is loaded when your session starts, so it won't pick up variables set later. You would also need to specify the `$workarea` variable in your `.bashrc` as well in order for this to work as intended, or if you do want it to interact with your current shell environment, you would need to use some form of `eval` -- for instance if I want to load my user's .bashrc settings in my root shell, I would use `eval "$(cat /home/username/.bashrc)"`. Experiment around with `eval` a bit, and you can get what you're looking for.
Comment for this answer: I wrote accordingly, But now the $workarea variable is also not being replaced by argument provided through cygwin terminal.
|
Title: F6 key not working in NetBeans 7.4
Tags: netbeans;netbeans-7;netbeans-7.4
Question: I am using NetBeans IDE 7.4 to code my programs. The problem of it is that, the F6 key is not working. That means the program is not running when F6 is pressed. Nothing is happening when F6 is pressed.
I use a Lenovo G500 laptop. My OS is Windows 8. Now I use HP G62 notebook. Its OS is Windows 7. It too has the same problem.
How can I solve this issue ?
Comment: @a_horse_with_no_name Yes. The same things can be run on other machines by pressing F6.
Comment: Did you define a main project? And does that main project have a default main class?
Here is the accepted answer: Many newer laptops have reprogrammed the Function keys up top to be something different than F1-F12. So to make the F6 key work in NetBeans, use the 'fn' ket with it. That is 'fn+F6'. It will work for you.
|
Title: Select and use raster layer from python
Tags: pyqgis;qgis-plugins;pyqt4
Question: I'm a developer but this is the first experience with python and QGIS Plugin, I want make a plug-in for Remote Sensing Index.
I have followed this basic tutorial https://www.youtube.com/watch?v=ZI3yzAVCK_0 and in this moment I have one dropdown with layer selection.
I correctly loaded the layer but I want see only the raster layer with multiple band for raster calculation, is it possible to filter it?
After at item selection from the dropdown list, load the band in other dropdown list for right association (green, blue, red, RedEdge ,Near IR).
Is it possible to make? What is the class prop to read?
This is almost the UI
Here is the accepted answer: Hopefully the following will help get you started, I've added comments to try and explain how it works.
Essentially, you can use a QgsMapLayerComboBox to filter out all layers loaded in QGIS and only have it list the multiband rasters. You can then define a function which will read the selected layer and populate the combo boxes for the bands (note that I only added the standard red, green and blue bands):
```def raster_bands(self):
# Read current item in raster layer combobox
rlayer = self.dockwidget.mMapLayerComboBox.currentText()
# Match name of current item with layer in table of contents
selected_rlayer = QgsMapLayerRegistry.instance().mapLayersByName(rlayer)[0]
# Clear band combo boxes
self.dockwidget.red_comboBox.clear()
self.dockwidget.green_comboBox.clear()
self.dockwidget.blue_comboBox.clear()
# Add band numbers to associated combo boxes
self.dockwidget.red_comboBox.addItem(str(selected_rlayer.renderer().redBand()))
self.dockwidget.green_comboBox.addItem(str(selected_rlayer.renderer().greenBand()))
self.dockwidget.blue_comboBox.addItem(str(selected_rlayer.renderer().blueBand()))
# Set first filter for QgsMapLayerComboBox to only populate with raster layers
self.dockwidget.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.RasterLayer)
# Create an empty list
rlayer_list = []
# Loop through all loaded layers in table of contents
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
# If layer is a raster and it is not a multiband type
if layer.type() == 1 and layer.renderer().type() != "multibandcolor":
# Add to list
rlayer_list.append(layer)
# Set second filter to only populate with multiband rasters
self.dockwidget.mMapLayerComboBox.setExceptedLayerList(rlayer_list)
# Run function on startup
raster_bands(self)
# When raster selection is changed, update combo boxes
self.dockwidget.mMapLayerComboBox.currentIndexChanged.connect(raster_bands)
```
Result:
Comment for this answer: Thanks Joseph! you're so kind!
Tomorrow morning i try , but i think are all in necessary for me ;)
Comment for this answer: @AntonioFeliziani - Most welcome, hope it will be helpful. Edited the post slightly to remove a couple of unnecessary lines :)
Comment for this answer: Thanks Joseph Sorry i try tu use QgsMapLayerRegistry but not work, i have serch in the net, and i have undestand not worl with PyQt4 core...
I try to add "from qgis.core import QgsMapLayerRegistry" but i use PyCharm with QtCreator for the UI and i think is not possible call this class.
Are other method?
Comment for this answer: sorry i dotn have make the tag "mention" @Joseph
Comment for this answer: @AntonioFeliziani - Apologies for the late reply, holidays ;). Perhaps your issue might be related to [this](http://gis.stackexchange.com/questions/199169/how-can-i-trigger-a-qgis-plugin-event-from-map-refresh/199265#199265) where you need to change a line in the header file of your plugin?
|
Title: Using map and lambda to count frequency in a dictionary
Tags: python;dictionary;lambda
Question: So the task is rather simple. Read in a string and store each character and its frequency in a dictionary then return the dictionary. I did it rather easily with a for loop.
```def getInputFreq():
txt = input('Enter a string value: ')
d = dict()
for c in txt:
d[c] = d.get(c,0) + 1
return d
```
The issue is that I need to rewrite this statement using a map and lambda.
I've tried a few things, early attempts returned empty dictionaries ( code has been lost in the attempts ).
My latest attempt was ( in place of the for loop in above )
``` d = map((lambda x: (d.get(x,0)+1)),txt)
```
which returns a map object address.
Any suggestions?
Comment: This is an odd requirement, in my opinion. `map` returns an iterable with as many elements as the iterable you pass it. But your dictionary will usually be far smaller than your `txt` string. So it's very awkward to try to get a dictionary out of `map`'s return value.
Comment: Why not use `collections.Counter()`?
Comment: ok, try `d = list(map((lambda x: (d.get(x,0)+1)),txt))`. But that won't work
Comment: Yea, this is part of a bigger project but the map and lambda constraint was thrown in there.
Comment: @Jean-FrançoisFabre, This returns a list of 1s.
Comment: –1 for arbitrary restrictions
Comment: Why the `map` and `lambda` constraint, I assume it's for school?
Here is the accepted answer: First, in python 3, you have to force list iteration on ```map```
Then, your approach won't work, you'll get all ones or zeroes, because the expression doesn't accumulate the counts.
You could use ```str.count``` in a lambda, and map the tuples to a dictionary, that works:
```txt = "hello"
d = dict(map(lambda x : (x, txt.count(x)), set(txt)))
```
result:
```{'e': 1, 'l': 2, 'h': 1, 'o': 1}
```
But once again, ```collections.Counter``` is the preferred way to do that.
Comment for this answer: Even if the input contains no duplicate letters, this is still inefficient. `.count` is O(N), and you're calling it N times, for a total of O(N^2). By comparison, `Counter` is O(N). But still, this is a fairly concise way to satisfy OP's strange requirements, so +1.
Comment for this answer: how about `list(map(lambda x: x, [])) or dict(Counter('hello'))`, meeting the requirements to use map and lambda ;)
Comment for this answer: counting duplicate letters only once can also be achieved by casting to `set` first. Like: `d = dict(map(lambda x : (x, txt.count(x)), set(txt)))`
Comment for this answer: @Chris_Rands That's hustling.. xD
|
Title: Will this Observable create a memory leak?
Tags: rxjs;rxjs5
Question: Will this Observable create a memory leak?
becuase every time you run it, it will keep the initial select stream open?!?!
```return this.store.select(store => store.appDb.appBaseUrl)
.mergeMap(url => {
return this.http.get(url)
.debug('received ' + url)
.map(res => res.json())
})
```
and if so, will adding a take(1) fix it?
```return this.store.select(store => store.appDb.appBaseUrl)
.take(1) // <--------------- stop after 1?
.mergeMap(url => {
return this.http.get(url)
.debug('received ' + url)
.map(res => res.json())
})
```
tx Sean
Here is the accepted answer: Simply having an hot observable ```this.store.select``` does not immediately imply that you have a memory leak. It is your task to store a reference to your subscription on that observable and dispose of it when done.
I find it helpful to annotate my streams with ```.take(X)``` as the last thing i do when i know how many elements i expect because this will make the stream dispose automatically after emitting the expected amount.
```return this.store.select(store => store.appDb.appBaseUrl)
.mergeMap(url => this.http.get(url)
.debug('received ' + url)
.map(res => res.json())
)
.take(1)
```
Comment for this answer: I see, well the subscription is managed by the effects library.. but I do call this action multiple times..
|
Title: toomanyrequests: Rate exceeded ONLY when using Docker pull from ECR
Tags: docker;amazon-ecr
Question: I am using the ECR Public Gallery to pull some images in a CI pipeline which runs frequently. I get this error from time to time, but what bothers me is that it only happens when using ```docker```. When I use ```podman``` to pull the images, it never complains about any quota limits.
```# docker pull public.ecr.aws/docker/library/alpine:latest
latest: Pulling from docker/library/alpine
toomanyrequests: Rate exceeded
```
And even sometimes, this error appears at the end of the pull:
```# docker-compose pull
Pulling nginx ...
Pulling haproxy ...
Pulling haproxy ... pulling from docker/library/haproxy
Pulling nginx ... pulling from docker/library/nginx
Pulling nginx ... pulling fs layer
Pulling nginx ... pulling fs layer
Pulling nginx ... pulling fs layer
Pulling nginx ... pulling fs layer
Pulling nginx ... pulling fs layer
Pulling nginx ... pulling fs layer
Pulling nginx ... waiting
Pulling nginx ... waiting
Pulling nginx ... waiting
Pulling nginx ... downloading (100.0%)
Pulling nginx ... verifying checksum
Pulling nginx ... download complete
Pulling nginx ... downloading (1.0%)
Pulling nginx ... downloading (1.0%)
...
Pulling nginx ... extracting (94.1%)
Pulling nginx ... extracting (100.0%)
Pulling nginx ... pull complete
Pulling nginx ... extracting (100.0%)
Pulling nginx ... extracting (100.0%)
Pulling nginx ... pull complete
Pulling nginx ... extracting (100.0%)
Pulling nginx ... extracting (100.0%)
Pulling nginx ... pull complete
Pulling nginx ... extracting (100.0%)
Pulling nginx ... extracting (100.0%)
Pulling nginx ... pull complete
Pulling nginx ... extracting (100.0%)
Pulling nginx ... extracting (100.0%)
Pulling nginx ... pull complete
Pulling nginx ... digest: sha256:2bcabc23b45489fb08...
Pulling nginx ... status: downloaded newer image fo...
Pulling nginx ... done
ERROR: for haproxy toomanyrequests: Rate exceeded
ERROR: toomanyrequests: Rate exceeded
```
Then, I went ahead and created a public registry under my account thinking that I would have better control over these limits and I pushed all the images I needed:
```docker pull public.ecr.aws/<my_repo_id>/alpine:latest```
But I ran into the same problem.
I thought that since it's under my account, I could change the Rate limits, but when on the quotas management in AWS UI I bumped into:
```Rate of unauthenticated image pulls``` -> ```1``` and it's "Not adjustable"
Which is also what the docs say: https://docs.aws.amazon.com/AmazonECR/latest/public/public-service-quotas.html
This triggers several questions:
What does that ```1``` mean? 1 pull per second?
Why does it apply only when I use docker and not with podman?
How can I change this quota?
Comment: Did you login with `docker login`?
Comment: No, I want it to be a public registry without login.
Here is another answer: "Rate of unauthenticated image pull" is per second (verified with AWS support).
It looks like you're pulling two images with your docker-compose so that is why you're getting this error.
Podman probably doesn't do this concurrently I'm guessing (I don't use podman).
Your best bet would be to use either a private registry with authenticated requests and/or the pull-through cache.
Comment for this answer: Thanks for your answer. I have created a registry using `registry:2` container image on a private VM. It doesn't have pull limits but it has other disadvantages vs other public registries.
|
Title: Wildcard find and replace XML: Cannot specify replacement value
Tags: sql;sql-server;xml;sql-server-2008;xquery
Question: In the following, XML schema which exemplifies that production data that I wish to modify, I'm simply trying to find ANY value of "Billy" and replace it with "Peter". The reason for the wildcard is we have to do this with a lot of values and a lot of tables with XML columns, and once I get this working, I can easily wrap it up in a cursor.
```DECLARE @tbXML TABLE ( ID INT , ParameterValue XML )
declare @oldval nvarchar(max) = 'Billy'
declare @newval nvarchar(max) = 'Peter'
INSERT INTO @tbXML VALUES ( 1, '<USER>Billy</USER>' )
INSERT INTO @tbXML VALUES ( 2, '<USER>John</USER>' )
INSERT INTO @tbXML VALUES ( 3, '<USER>David</USER>' )
INSERT INTO @tbXML VALUES ( 4, '<USER>Nick</USER>' )
SELECT 'before', *
FROM @tbXML
WHILE EXISTS ( SELECT 1 FROM @tbXML WHERE ParameterValue.exist('/User[(text()[1])eq sql:variable("@oldval")]')=1)
BEGIN
UPDATE @tbXML
SET ParameterValue.modify('replace value of (/User[(text()[1]) eq sql:variable("@oldval")] with sql:variable("@newval")')
WHERE ParameterValue.exist('/User[(text()[1])eq sql:variable("@oldval")]')=1
END
SELECT *
FROM @tbXML
```
But what I get is:
```XQuery [@tbXML.ParameterValue.modify()]: ")" was expected.
```
Either I'm stupidly missing a ```")"``` somewhere (Tried lots of permutations, same error), or there is something more wrong with my approach. Would appreciate a nudge in the right direction, thanks!
Here is the accepted answer: You don't need the WHILE or the WHERE. Just do this:
```SELECT 'before', *
FROM @tbXML;
UPDATE @tbXML
SET ParameterValue.modify('replace value of (/USER[. = sql:variable("@oldval")]/text())[1]
with sql:variable("@newval")');
SELECT *
FROM @tbXML;
```
|
Title: Post method with Requests
Tags: python;python-requests
Question: I'm trying to make a simple post method with the ```requests``` module, like this :
``` s=requests.Session()
s.post(link,data=payload)
```
In order to do it properly, the payload is an id from the page itself, and it's generated in every access to the page.
So I need to get the data from the page and then proceed the request.
The problem when you accessed the page is that a new id will be generated.
So if we do this:
``` s=requests.Session()
payload=get_payload(s.get(link).text)
s.post(link,data=payload)
```
It will not work because when you acceded the page with ```s.get``` the right id is generated, but when you go for the post request, a new id will be generated so you'll be using an old one.
Is there any way to get the data from the page right before the post request?
Something like:
``` s.post(link,data=get_data(s.get(link))
```
Here is the accepted answer: When you do a post (or get) request, the page will generate another id and send it back to you. There is no way of sending data to the page while it is being generated because you need to receive a response first to process the data on the page and once you have received the response, the server will create a new id for you the next time you view the page.
See https://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/images/HTTP.png for a simple example image of a HTTP Request
Comment for this answer: ok there is any way after i receive the response to get that id from the page before sending the request ?
Comment for this answer: found this : `r = requests.post(url, data=json.dumps(payload))`
maybe json is the solution ?
Comment for this answer: @Bilal Xenon Mellah What do you want to know?
Comment for this answer: @FreeSteampowresGames json won't get you past the HTTP protocol barrier. If you have access to the site, you could modify it to remember the last stored id and then your initial idea would work. Just wondering, what is the end goal of the post request. You seem to want to send data to the server that the server already knows...
Here is another answer: In general, there is no way to do this. The server's response is potentially affected by the data you send, so it can't be available before you have sent the data. To persist this kind of information across requests, the server would usually set a cookie for you to send with each subsequent request - but using a ```requests.Session``` will handle that for you automatically. It is possible that you need to set the cookie yourself based on the first response, but cookies are a key/value pair, and you only appear to have the value. To find the key, and more generally to find out if this is what the server expects you to do, requires specific knowledge of the site you are working with - if this is a documented API, the documentation would be a good place to start. Otherwise you might need to look at what the website itself does - most browsers allow you to look at the cookies that are set for that site, and some (possibly via extensions) will let you look through the HTTP headers that are sent and received.
Comment for this answer: there is a way , for example :
https://github.com/davidyen1124/Facebot/
get all the data needed to fill the payload with : fb_dtsg , wwwupp ,csid,tids , ids
but i didn't figure it out how he does that
Comment for this answer: found this : `r = requests.post(url, data=json.dumps(payload))`
maybe json is the solution ?
|
Title: Should I use a EAV model or not in laravel?
Tags: php;mysql;laravel;database-design;entity-attribute-value
Question: I am building a app and I have in my app around 20 categories and each category has some custom fields. So a user picks a category and fills in the custom fields. After that I need to store the values in DB. Can you suggest what would be the best approach to do it. Also I need to be able to filter on this custom fields - like a advanced filter and a performance is a key too.
Should I just make for each category a separate table with their custom fields in such case?
Thank you for help
Dany
Comment: thank you @JohnJoseph for the answer and where would you store the selected values for the custom fields in 3 table custom_fields_values?
Comment: I'll only roughly answer the last question as the rest are too broad and non specific. category should be a table and category_custom_fields should be another, with the custom fields table storing a category ID to link them together. Ask questions for the other issues as and when you come to them once your database model is designed.
Here is the accepted answer: There are two options that I can think of.
1) Create a JSON field called something like attributes in your category table. And then store basically an array of Key Values in it. That will present some challenges when querying on attributes though. I know there are ways around it but i've never needed it so I do not know.
2) Create a Category Attributes table in your DB that goes something like this
```cat_id - int
key - varchar
value - varchar
Composite Index Unique on [cat_id, key,value ]
```
Then create a Category Attribute model in laravel and define a hasmany relationship where Category has many Category Attributes
then querying your categories would go something like this
```$categories = Category181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16whereHas('CategoryAttributes', function ($query) {
$query->where('key', '=', 'color');
$query->where('value','=', 'blue');
})->get();```
Here is another answer: The benefits and drawbacks of implementing an Entity-Attribute-Value (EAV) model in a relational database are the same with Laravel as they are with almost every other framework or language. I don't see that using Laravel really has anything to do with the question.
If your use case needs the flexibility of EAV, and you are prepared for the additional complexity (by an order of magnitude) and prepared for a big performance hit... if those aren't breakers, then use the EAV model.
But if you don't require any of the benefits of EAV, then by all means, avoid the drawbacks.
|
Title: Why does gedit (Text Editor) switch to read only, and how can I undo it without reloading?
Tags: 18.04;gedit;read-only
Question: So, I have been using the gedit text editor for years, often with multiple files open at a time in tabs.
Today, I find that my two gedit sessions and all the files open in them are suddenly all in "[read only]" mode and won't let me edit the files I was editing earlier with that same loading of the program (but a couple of days ago, and the computer has been put to sleep and awakened a few times since).
I'm still logged in as my usual account, the files are owned by that account and the owner (me) has permissions to edit them.
Opening new files in a new gedit window also results in them being loaded read-only.
I have looked through the various menus I could find and see nothing that seems relevant.
None of what I have done is new to my experience, and I have used gedit for years in this sort of way without ever having seen this happen to me. What's it caused by and how could I get the files back to editable short of closing and reloading them?
Comment: Is your disk mounted read-only? See https://github.com/waltinator/pathlld.git - Bash script to answer "Why can't I read/write that file?"
Comment: What happened before this issue
Comment: @GeorgeUdosen Before this I have been using the computer about as usual. Firefox, gedit, compiling and running my OpenFrameworks C++ projects, running system updates, viewing PDFs. My file manager is PCManFM. The unusual things would be whatever the updates were (since an update is always something new, though I didn't pay attention this time), backing up my source code to an external drive by dragging files in PCManFM (I do remember pressing the Eject Media icon for it in PCManFM before closing the lid to sleep).
Comment: @waltinator I noticed after posting this last night that yes, it wasn't just gedit - the whole file system was in read only. My first symptom may actually have been GIMP, which I loaded and noticed it freaking out about not being able to make a temp file, but GIMP has done that before without being unable to save files, so I just thought it was GIMP.
Here is the accepted answer: After posting this last night, I noticed that gedit (Text Editor) was NOT to blame. The whole file system had been set to read-only somehow, so gedit was just behaving correctly.
Why the filesystem was read-only suddenly, I don't know. Could be my hard drive is dying, so I'll try to test for that.
Update: After running some analysis of the disk, there were some logical errors but no physical errors. Correcting the logical errors and restarting cleared up the problem, though I still don't know what the cause was. It clearly was not gedit, though.
Comment for this answer: Please remember to click the grey check mark next to your answer later on. This will let other users know it is the correct solution.
Comment for this answer: Well done for letting us know!
|
Title: how to add custom metrics to spark mlib evaluator?
Tags: scala;apache-spark
Question: The spark version is 2.3.1.
```Spark-Mlib``` library provide a ```BinaryClassificationEvaluator``` (BinaryClassificationEvaluator.scala) class to evaluate the algorithm, and also can be used to gird search. But it only suppose two metrics
``` val metric = $(metricName) match {
case "areaUnderROC" => metrics.areaUnderROC()
case "areaUnderPR" => metrics.areaUnderPR()
//what i want todo
case "areUnderXX"=> myCustomMetric()
}
```
I try to add more, but ```BinaryClassificationEvaluator``` have some members that are set to ```private```, so i can't just extends it. Here are the code that can't be viewed outside the package:
```SchemaUtils.checkColumnTypes(schema, $(rawPredictionCol), Seq(DoubleType, new VectorUDT))
SchemaUtils.checkNumericType(schema, $(labelCol))
```
These code do some type check, so if i remove it, it would workaround. But, It seems unsafe and ugly. So, is there another way to do it? any help would be appreciated!
Here is another answer: You can use MulticlassMetrics. It provides more metrics. As an example using a DataFrame with your labels and predictions:
```+---------+----------+
|label |prediction|
+---------+-----+----+
| 1.0 | 0.0 |
| 0.0 | 0.0 |
+---------+----------+
```
You must pivot your dataframe for the label field
```val metrics = df.select("prediction", labelName)
.as[(Double, Double)]
.rdd
val multim = new MulticlassMetrics(metrics)
val labels = multim.labels
val accuracy = multim.accuracy
println("Summary Statistics")
println(s"Accuracy = $accuracy")
labels.foreach { l =>
println(s"Precision($l) = " + multim.precision(l))
}
// Recall by label
labels.foreach { l =>
println(s"Recall($l) = " + multim.recall(l))
}
// False positive rate by label
labels.foreach { l =>
println(s"FPR($l) = " + multim.falsePositiveRate(l))
}
```
There are more metrics you can see in https://spark.apache.org/docs/2.2.0/mllib-evaluation-metrics.html
Depending of what kind of metrics you need maybe you should deal with the dataframe with the dataframe. For example, if you want to compute your confusion matrix, you can proceed pivoting over the "prediction" column like:
```df.groupBy("label").
pivot("prediction", range)
.count()
.na.fill(0.0)
.orderBy("label)
.show()
```
Comment for this answer: thanks. this works if i only want to measure the model result. But what i want to do is implement an evalluator which can pipeline with the original workflow(in order to gird search and something else), so this may not work.
|
Title: Routing resources/paths with :path_prefix and :name_prefix
Tags: ruby-on-rails;routes
Question: I have the following route definied:
```map.resources :addresses, :path_prefix => ':site', :name_prefix => 's_'
```
I've had no problem correcting my scaffolding links for "Show" and "New". But I am getting a failure to generate error when attempting to use:
```edit_s_address_path(address) or edit_s_address
```
rake routes shows that this is the proper path. I'm perplexed. Thanks in advance.
Comment: What version of rails is this? and can you show some code where you are trying to ref the route from? (like a snippet of a view or controller)
Here is another answer: Shouldn't you use ```s_edit_address_path(address)```? According to the Rails Guide on routing, the ```name_prefix``` comes at the start of the route name.
Comment for this answer: That's what I thought, too. But I get an undefined method name using the name prefix at the beginning. rake routes shows that 'edit' and 'new' prefix everything.
|
Title: Unable to import babel-plugins/presets in production for transform
Tags: reactjs;meteor;babeljs
Question: I am using babel in production to transform jsx strings into html, for the purpose of rendering email bodies via string templates.
```import {transform} from '@babel/core';
const {code} = transform(template, {plugins: ['@babel/plugin-transform-react-jsx']});
```
I have ```@babel/core``` and ```@babel/plugin-transform-react-jsx``` in my dependencies. The code works on development but on production it fails saying, 'Can not find module ```@babel/plugin-transform-react-jsx```'. Can someone help me debug/understand the underlying issue here?
I tried adding a deliberate ```import '@babel/plugin-transform-react-jsx';``` but to no avail.
Sample code for the same: https://codesandbox.io/s/cool-euler-v21z3
Can it be a deployment issue? The complete error logs:
```Exception while invoking method 'template.getComponentFunctions' Error: Cannot find module '@babel/plugin-transform-react-jsx' from '/built_app/programs/server'
316-762-1581] at Function.module.exports [as sync] (/built_app/programs/server/npm/node_modules/resolve/lib/sync.js:58:15)
316-762-1581] at resolveStandardizedName (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:101:31)
316-762-1581] at resolvePlugin (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:54:10)
316-762-1581] at loadPlugin (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:62:20)
316-762-1581] at createDescriptor (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
316-762-1581] at /built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:109:50
316-762-1581] at Array.map (<anonymous>)
316-762-1581] at createDescriptors (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
316-762-1581] at createPluginDescriptors (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:105:10)
316-762-1581] at /built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:63:53
316-762-1581] at cachedFunction (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/caching.js:62:27)
316-762-1581] at cachedFunction.next (<anonymous>)
316-762-1581] at evaluateSync (/built_app/programs/server/npm/node_modules/gensync/index.js:244:28)
316-762-1581] at sync (/built_app/programs/server/npm/node_modules/gensync/index.js:84:14)
316-762-1581] at plugins (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:28:77)
316-762-1581] at mergeChainOpts (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-chain.js:319:26)
```
Here is another answer: While I was unable to figure out the reason and solve it properly, I was able to work around by using ```@babel/standalone```.
|
Title: Convert from console to string for return
Tags: c#;excel
Question: I am attempting to convert my output from the console to a return type of string, what am I missing? Under return I get an error that says, "returns void, a return keyword must not be followed by an object expression." And when I take the return off, it gives me the same thing for the string sInput.
``` static void Main(string[] args)
{
var excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\Documents\Mail.xlsx");
Worksheet worksheet = workbook.Worksheets[1];
var MailNumbers = worksheet.UsedRange;
string sInput;
foreach (Range row in MailNumbers.Rows)
{
sInput = row.Cells[2, 8].Text + " " + row.Cells[2, 4].Text + " " + row.Cells[2, 5].Text + " " + row.Cells[2, 6].Text + " " + row.Cells[2, 3].Text + " " + row.Cells[2, 7].Text;
};
return sInput;
excel.Quit();
}
```
Hopefully Im overlooking something simple.
Thanks!
Comment: You mean other than ignoring the fact that `main` is documented (and declared in your code) as `void`, which means it can't possibly return a value?
Comment: I tried to change void to string. And I got an error under Main, "Not all code paths return a value."
|
Title: Table pagination not work
Tags: jquery;jquery-plugins;pagination
Question: I use two jQuery plugins: quickSearch and tablePagination
When I type text into the input box, pagination doesn't work :(
This is my code:
```<html><head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.quicksearch.pack.js"></script>
<script type="text/javascript" src="/js/jquery.tablePagination.js"></script>
<script>
var options = {rowsPerPage : 2,}
$('#admin_table').tablePagination(options);
$('table#admin_table tbody tr').quicksearch({
position: 'before',
attached: '#admin_table',
labelText: 'Search'
});
</script>
</head>
<body>
<table id="admin_table" class="admin_table">
<tbody>
<tr><td>test</td><td>test11</td></tr>
<tr><td>te</td><td>tt11</td></tr>
<tr><td>te4t</td><td>tes211</td></tr>
<tr><td>tes45t</td><td>te234st11</td></tr>
<tr><td>te67st</td><td>te123st11</td></tr>
</body>
</html>
```
How can I do pagination if I type text into the search input?
Comment: btw. you are missing the type attribute from one of your script tags. After `var options = {...}` you should add a semi-colon. and you are missing the closing `` and `` tags
Here is the accepted answer: Try this fixed version. Your main problem probably is that you didn't wrap your initialization code into the ```$(document).ready(function() { ... });``` block. By not doing that you have multiple potential error sources. Code gets executed before quicksearch and or tablepagination are fully load and/or gets executed before the table itself is visible in the dom as it gets rendered after the javascript
```<html><head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.quicksearch.pack.js"></script>
<script type="text/javascript" src="/js/jquery.tablePagination.js"></script>
<script type="text/javascript">
var options = {rowsPerPage : 2,};
$(document).ready(function() {
$('table#admin_table').tablePagination(options);
$('table#admin_table > tbody > tr').quicksearch({
position: 'before',
attached: '#admin_table',
labelText: 'Search'
});
});
</script>
</head>
<body>
<table id="admin_table" class="admin_table">
<tbody>
<tr><td>test</td><td>test11</td></tr>
<tr><td>te</td><td>tt11</td></tr>
<tr><td>te4t</td><td>tes211</td></tr>
<tr><td>tes45t</td><td>te234st11</td></tr>
<tr><td>te67st</td><td>te123st11</td></tr>
</tbody>
</table>
</body>
</html>
```
|
Title: What is the safest logging framework for a web application using existing libraries?
Tags: java;logging;frameworks
Question: I need to decide on a logging framework for a new web application running in containers (Tomcat, JBoss...). This application references java libraries using different logging frameworks.
My reading indicates that some logging frameworks do not work well in container because of classloader issues. I am also reading that this is not an issue anymore. The situation is confusing. What is the status?
It seems like using SLF4J and redirecting to Log4J + using bridges to SLF4J for referenced Java libraries (when necessary) is the safe solution.
Which logging framework should I use for my web application and remain on the safe side?
Comment: Can you use the logging framework which comes with the container or the logging framework which come with Java?
Comment: Given your requirements I would use SLF4J but I have only used Apache Karaf lately. ;)
Comment: The application can be deployed in different containers. Otherwise, I have no restrictions except those mentioned in the question.
Here is the accepted answer: After digging the subject deeper, I can conclude the following:
The classloader issues are mostly reported around the Jakarta Common Logging (JCL) interface.
In order to tackle the multiple logging frameworks used in different Java libraries, a logging interface such as SLF4J or JCL is necessary.
SLF4J is a safe solution for web applications running in containers. It is preferable to accessing the logger provided by the container regarding portability issues.
I have summarized my findings in a blog post.
Comment for this answer: Sounds about right. One caveat is that some libraries may be using JBoss Logging, which is yet another logging facade - Hibernate 4 is a notable example. JBoss Logging tries to autodetect a logging provider; if you are using log4j or Logback, it will find and use those. However, if you are using SLF4J and some other provider (eg Gossip, AVSL), then JBoss Logging won't find it, and will use java.util.logging.
Here is another answer: You can (and should) deploy your own logging libraries with your web application. There is no guarantee what logging system will be supported on a server, nor how it will be configured. By providing your own, you can tailor it to your applications needs.
So unless you get to specify and manage the application server, ship what you want to use with your application.
|
Title: Axios requests in a loop after previous completes
Tags: javascript;axios;httprequest;synchronous
Question: The application I am building involves sending video frames to the server for processing. I am using Axios to send a POST request to the server. I intend to send about 3-5 frames(POST request) per second. I need to send one after the previous request completes because the next request has data in the request body which depends on the response of the previous request.
I tried running it in a loop but that won't do because the next one starts before the previous one completed. In the current code, I have something like this -
```const fun = () => {
axios.post(url,data)
.then((res) => {
// process the response and modify data accordingly
// for the next request
})
.finally(() => fun());
};
```
This way I am able to achieve the requests to be one after another continuously. But I am unable to control the number of requests that are being sent per second. Is there any way I can limit the number of requests per second to be say at max 5?
Additional Info: I am using this for a web app where I need to send webcam video frames(as data URI) to the server for image processing and the result back to the client after it. I am looking to limit the number of requests to reduce the internet data consumed by my application and hence would like to send at the max 5 requests per second(preferably evenly distributed). If there's a better way that Axios POST requests for this purpose, please do suggest :)
Comment: Have you looked at Bottleneck? https://www.npmjs.com/package/bottleneck
Comment: Just my 2 cents, this sounds like a great case of using websockets, if they're supported by the backend.
Comment: @Ak47 the advantage of websockets is that you can send data back and forward without constant handshaking which is usually required for each post/get request. Once you open the websocket channel streaming the data is really straightforward and it costs less for the backend to handle websocket data than continuous post requests.
Comment: @VladimirBogomolov I know I can use websockets. Just wondering if my method has any disdavantages or flaws? I am using python and flask in the backend, so websockets is probably supported
Here is the accepted answer: An amazing library called Bottleneck can come to your aid here. You can limit the number of request per second to any number you want using the following code:
```const Bottleneck = require("bottleneck");
const axios = require('axios');
const limiter = new Bottleneck({
maxConcurrent: 1,
minTime: 200
});
for(let index = 0; index < 20; index++){
limiter.schedule(() => postFrame({some: 'data'}))
.then(result => {
console.log('Request response:', result)
})
.catch(err => {
console.log(err)
})
}
const postFrame = data => {
return new Promise((resolve, reject) => {
axios.post('https://httpstat.us/200', data)
.then(r => resolve(r.data))
.catch(e => reject(e))
});
}
```
By manipulating the limiter
```const limiter = new Bottleneck({
maxConcurrent: 1,
minTime: 200
});
```
You can get your axios request to fire at any rate with any concurrency.
For instance to limit the number of request per second to 3, you would set ```minTime``` to ```333```. Stands to reason, if you want to limit it to 5 per second, it would have to be set to ```200```.
Please refer the the Bottleneck documentation here: https://www.npmjs.com/package/bottleneck
Comment for this answer: @Ak47 Not off the top of my head. That's something I will think about, but in the meantime, let me point out that I use this exact code to post records from a file line by line using axios. I send out 4 requests per second. Some files contain literally millions of lines and this sucker works like a charm every time on pretty pedestrian hardware. So if your concern specifically is that it will end up using too much resources, I would argue you'd probably be all right. It has the nifty `limiter.stop()` function to arbitrarily kill the execution.
Comment for this answer: @Ak47 Very interesting observation. Are you running your process in a browser? I do disclaim any experience using Bottlenck in a browser as my stuff runs on a Node server.
Comment for this answer: Thanks...This looks like it will work in my case. I will try it out
Comment for this answer: I tried the library but it doesn't work for infinite loops. In my case, I have to keep the request running till client makes it stop. It seems that the library is queuing up all the request from the start itself and stopping so as to achieve minTime for each request. I think it would be demanding if I wanted to keep it running for long time since all queue gets queued from start itself. Is there a way I can just schedule 5 request per second and loop it infinitely without maintaining queue as this library seems to do?
Comment for this answer: It seems to run up to hundreds of thousands in loop but starts lagging if I increasing looping any more. It probably means it is consuming resources. Although my usecase suffices in much less number of loops but I was just wondering if there's a way to handle a case where the requests needed to be kept going indefinitely. I will look if there's a way to achieve what I described above. Thanks for the help :)
Comment for this answer: yes, I am using it in my react app in browser.
|
Title: Node.js - wait for process.exit() to execute after earlier code is finished
Tags: javascript;node.js;asynchronous;callback;fs
Question: In my node.js application I want to write some data to a logfile when the server is shutdown (thus when CTRL+C has been done in the cmd). The problem is that the ```process.exit()``` is called before the writing to the file is finished. I tried using a ```callback``` and jQuery ```$.Deferred.resolve()```, but to no avail: probably because the file-write is async but I'd like to keep it asynchronous.
The callback code:
```if (process.platform === "win32"){
var rl = readLine.createInterface ({
input: process.stdin,
output: process.stdout
});
rl.on ("SIGINT", function (){
process.emit ("SIGINT");
});
}
process.on ("SIGINT", function(){
var stopServer = function() {
//this happens way too early, the logger.log has not written it's data yet
process.exit();
};
var logServerStop = function(callback) {
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("");
callback();
};
logServerStop(stopServer);
});
```
And the ```logger.log``` code:
```var fs = require('fs');
var filename = './output/logs/logfile.txt';
exports.log = function(data, addDate){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();
if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');
fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}
});
};
```
I'd also like to keep the log-function as it is (so I wouldn't like having to add a callback-function parameter, I'd like my problem to be handled in the callback code. Thanks in advance.
Edit 1
```process.on ("SIGINT", function(){
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("", false, function(){
process.exit();
});
});
```
And the ```logger.log``` changes:
```exports.log = function(data, addDate, callback){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();
if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');
fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}
});
if(typeof(callback)=='function'){ callback(); }
};
```
Comment: Why avoid a callback function to your `log` method? It's the simplest solution. It doesn't mean you have to use it every time.
Comment: Can you show that attempt, please? Where exactly did you add the `fn()` call, and how did you modify your sigint handler?
Comment: You'll need to put it in the asynchronous `open`/`write` callbacks of course, otherwise it's equivalent to what you've done before!
Comment: I tried adding a callback parameter to the `log` method, but for some reason the callback would never be called. The logger wrote the data to the logfile as intended, but `process.exit()` never happened. I tried adding the line "if(typeof(fn)=='function'){ fn(); }" to the end of my `log` method, which fixed the issue of the `process.exit()` not happening but the file-write did not happen again.
Comment: I edited my post with the changes you requested to see.
Comment: Thank you! I didn't think it through that much, the `write` and `open` functions are indeed async so I should have put that line there. I was thinking that I just want to callback as soon as the `log` function finished but as the other 2 are async, the log function finished before the others in it had finished.
Here is another answer: Please see the edits to the log function.
``` exports.log = function(data, addDate, callback){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();
if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');
fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
//execute call back here.
if(typeof callback === 'function'){
callback(e);
}
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
//execute call back here.
if(typeof callback === 'function'){
callback(err);
}
});
}
});
};
```
In callback you can pass your error as first parameter, then when you call logger.log you can do this as below:
```process.on ("SIGINT", function(){
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("", false, function(e){
if(e){
//Handle error here.
}
process.exit();
});
});
```
Comment for this answer: Please follow the edits. if you are editing your log function you can call your callback after you write your log file.
Comment for this answer: I'm afraid your suggestion didn't fix it
Comment for this answer: Thank you for your effort, but the above response already helped me out with the same idea! :) (also - in your suggestion I wouldn't really want the `err` as parameter for my callback). Thanks though!
|
Title: Visual Studio VB.net error to debug
Tags: vb.net;visual-studio-2010
Question: I am working in a solution for a while using Vb.net in Visual Studio, when I try to run debug (F5) I get the following error:
"Error while trying to run project: Unable to start debugging.
The process has been terminated.
Refresh the process list before attempting another attach."
I am not sure what is the issue, but I guess something with Visual Studio, because I restored a backup from my solution that it was working perfectly, and I got the same error (image below). Can you help me please??
Thanks!!!
Comment: Have you turned it off, then back on again?
Comment: Hello, Yes I tried that but it didn't work..... Any suggestions? I guess is something with the database maybe... I have another project that doesnt use a SQL database (it uses only a .txt file) and debug is starting normally.... I don't know...
Comment: any suggestions? I tried to install visual studio again, but the error persisted. Thanks!
Comment: I know this is ancient, but I am experiencing the same issue. Did you ever get it working?
|
Title: Quality option not working in cordova camera plugin
Tags: windows;cordova
Question: I have a mobile application that allows uploading images either via camera or choosing it from a photo library. While uploading the user is prompted if he or she wants a high quality image to be uploaded or not. If yes, quality option is set to 100 else set to 50. This seems to work fine for android and ios builds but not for windows build. Even after selecting the high quality option, the image uploaded has low quality.Is there something that I'm missing? A plugin that might need to be added specific to windows to make stuff work?
Please help.
I've included a part of the code snippet:
.factory('$Camera', function ($q, $crypt, $settings) {
```return {
getPicture: function () {
var q = $q.defer();
var options = {
quality: $settings.getValue('uploadHighQualityImage') ? 100 : 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.CAMERA,
targetWidth: 500,
targetHeight: 500
};
navigator.camera.getPicture(function (result) {
// Put the options
q.resolve(result);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
},
```
Comment: @VaheTshitoyan Added. Have a look.
Comment: Including some code would certainly help. Try providing a [Minimal working example](https://stackoverflow.com/help/mcve)
|
Title: Cakephp AppError file under Lib folder not getting included
Tags: php;cakephp
Question: I am using cakephp 2.2
I have created a class AppError under app/Lib folder.
when i am including it under bootstrap file I am not able to use its function.
It seem it is not included
I used
App181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16uses('AppError','Lib')
Any help will b appreciated
Here is the accepted answer: App/lib directory is mostly used to override all the core functionality of cakePHP (refer here), you can create a component and use it in your case.
Thanks :)
Comment for this answer: Thanks for the reply.... It is working fine now... It was included but not showing any effect.... After doing changes in core.php it start working
|
Title: distributed architecture and data replication
Tags: architecture;orientdb;distributed
Question: I'm looking to implement a very simple distributed architecture; 2 Masters node on 2 workstations ; A fedora workstation and another fedora VM hosted on a Windows computer.
I followed the installation procedure;
copy the directory of the "databases" to the second station.
start of first instance
start of the second instance
The instances start correctly.
But a change on one side is not reflected on the other.
I don't see what I could have forgotten...
Here is another answer: this requires enabling, in the config/orientdb-server-config.xml file, the OHazelcastPlugin in each OrientDB.
The nodeName parameter is added with the node name and the enabled is set to true
```<handler class="...OHazelcastPlugin">
<parameters>
<parameter value="node01" name="nodeName"/>
<parameter value="true"> name="enabled"/>
...
</parameters>
</handler>
```
Also change, in the listener section, the port-range of the binary protocol to 2424-2430
In addition to configuring the config/hazelcast.xml file, disabling multicast and adding the tcp-ip section
```<network>
...
<join>
<multicast enabled="false">
....
</multicast>
<tcp-ip enabled="true">
<member>IPnode01:2434</member>
<member>IPnode02:2434</member>
</tcp-ip>
```
With the above, you run the first node and later the second, so that the latter is synchronized with what the first has.
|
Title: Calling Python function from Cython function
Tags: python;c;arrays;cython
Question: I'm trying to create a Cython function that depends on a Python function. The arguments of this Python function include a float and an array (I'm using Numpy arrays). I tried to follow this example Python/Cython/C and callbacks, calling a Python function from C using Cython but my code segfaults when is trying to access the array passed to the Python function.
I have to make a callback function since I cannot pass a Python function to the C function directly.
Below is a minimal example (my code is more complex than this example but the problem is the same)
example.py:
```import numpy as np
from example_cython import my_function
def python_fun(x, x_arr):
"""
Add x to the elements of x_arr
"""
x_arr += x
return 0.0
A = np.arange(3.)
B = np.ones(3, dtype=np.float)
n = 3
x = 2.
# Call the C function using the Python one
my_function(A, B, n, x, python_fun)
```
example.c
```#include<stdio.h>
// Add x to the elements of *a and then add the elements of *a to *b
void C_fun(double * a, double * b, int n, double x,
double (*f) (double, double *)
) {
printf("a: %f b: %f x: %f\n", a[0], b[0], x);
// Update array a
f(x, a);
for(int i=0; i<n; i++) b[i] += a[i];
}
```
example.h
```void C_fun(double * a, double * b, int n, double x,
double (*f) (double, double *)
);
```
example_cython.pyx
```# Function prototype for the C function
ctypedef double (*cfunction)(double x, double * y)
cdef object f
cdef extern from "example.h":
void C_fun(double * a, double * b, int n, double x,
double (*f) (double, double *)
)
cdef double cfunction_cb(double x, double [:] y):
global f
result = f(x, y)
return result
# This function calls the f function (a Python f) that updates *a and then sums
# the elements of *a into *b
def my_function(double [:] a, double [:] b, int n, double x, pythonf):
global f
f = pythonf
C_fun(&a[0], &b[0], n, x, <cfunction> cfunction_cb)
```
setup.py
```from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
extension_src = ["example_cython.pyx", "example.c"]
extensions = [
Extension("example_cython", extension_src)
]
setup(
ext_modules=cythonize(extensions),
)
```
Compiling the Cython module works, and I can access the C function and print the array contents, but when the function calls the array, it has the problem
```a: 0.000000 b: 1.000000 x: 2.000000
[1] 791 segmentation fault (core dumped) python example.py
```
Comment: @ead that gives me an error: `Cannot convert 'double *' to Python object`
Comment: in `cdef double cfunction_cb(double x, double [:] y)`, `double [:]` is a typed memory view, what you want to use in the signature is a `double *`
Comment: If you use more than one callback simultaniously, using runtime generated closures is a better solution, see https://stackoverflow.com/a/51054667/5769463
Comment: which is better than segfault in my optinion - because now you see what you are doing wrong.
Comment: Your problem is: you use ` cfunction_cb` which let the compiler cast the types no matter what, you should use `&cfunction_cb` instead - in this case compiler would check the types and you could see the type-mismatch.
|
Title: Could not load file or assembly 'Newtonsoft.Json, Version=217-749-8138, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' with google api
Tags: c#;json;dll;json.net
Question: In my project i used the library Newtonsoft.Json version 11.0.2, and i need use Google.Api and Google.Core, but when install this two library i receive the next error:
```
System.IO.FileLoadException: 'Could not load file or assembly
'Newtonsoft.Json, Version=217-749-8138, Culture=neutral,
PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
located assembly's manifest definition does not match the assembly
reference. (Exception from HRESULT: 0x80131040)'
```
The error is because Google.Core use the version of newtonsoft.json 12.0.3 and in my project i have the version 11.0.2.
When made the build in output i can see the next error:
```
NU1605: Detected package downgrade: Newtonsoft.Json from 12.0.3 to
11.0.2. Reference the package directly from the project to select a different version. MyProject -> Google.Apis.Oauth2.v2 51.243.225.559 ->
Google.Apis.Auth 1.48.0 -> Google.Apis.Core 1.48.0 -> Newtonsoft.Json
(>= 12.0.3) MyProject -> Newtonsoft.Json (>= 11.0.2)
```
How should to fix this error?
Comment: I try this, but, the web desn't work.
I can solved this error make this, but i receive another error when loading web. My code it have incompatibility with new version.
Comment: thanks @Ralf and dogyear for their answers. The problem is I have a lot of code and i want to find another solution for not touch or touch the minimal as possible code.
Any idea for solved this?
I see myself correcting a lot of code ): -_- ;)
Comment: @Ralf is correct. You should change all of your references to 12.0.3 since that's what is needed to run those Google Nuget packages. Since it's resulting in your code being incompatible with the new version you'll need to fix your code. If your code can't work with the new version then your code can't work with the Google packages. So you just gotta update and fix your code. No way around that.
Comment: Do what the error message tells you to do. You should reference in all project the Newtonsoft.Json package you want to use or is at least needed (presumably at least 12.0.3). That will overide the dependencies of the other referenced packages in that projects.
Comment: There is no easy way. When using nuget packages you need to always have an eye on their dependencies. Json.Net is a typical candidate here. Many nuget packages have that as dependencies and then in different versions. If you just let it go a more or less random version (presumably a wrong one) of that will lastly end up in your output folder. You need to check the package dependencies. Find the version that all packages can live with and reference that one from your project.
Here is another answer: Can you try updating the package to the latest version in your project? Try remove all the references of the Newtonsoft.Json (11.0.2) from your project and install the latest update from Nuget. Hope that works.
|
Title: Regex for whole numbers or numbers with quarter decimal
Tags: regex;validation
Question: I need a regex that only allows for whole numbers or numbers with a quarter decimal.
So far I have this, however this code ```/[^.]+\.25|[^.]+\.50|[^.]+\.75|[^.]+\.00/``` forces user to type a number with a decimal. I'm looking for something more flexible.
Valid
```0
0.
.25
.5
.75
3
1.
```
1.00
5.0
4.25
8.50
8.75
Invalid
```1.2
.3
.
empty space
```
Comment: @revo Doesn't match `1.00`.
Comment: melpomene you are right, I did not account for 1.00 which would be valid. Thanks for your efforts revo and melpomene.
Comment: Try `^(?!\.?$)\d*\.?(?:[27]5|5?0?)?$`. See live demo here https://regex101.com/r/Nw5Amy/1
Comment: @melpomene I don't see it in samples or there is no explicit rule for it and I'm not supposed to read the regex from OP and find the rules. But if that's the case, it's just a matter of adding a character class `^(?!\.?$)\d*\.?(?:[27]5|[50]0?)?$`.
Here is another answer: Here's one way:
```/\A (?= \.? [0-9] ) [0-9]* (?: \. (?: [05]0? | [27]5 )? )? \z/x
```
Or with comments:
```/
\A # beginning of string
(?= # look-ahead
\.? # a dot (optional)
[0-9] # a digit
)
# ^ this part ensures that there is at least one digit in the string.
# in the following regex all parts are optional.
[0-9]* # the integer part: 0 or more digits
(?: # a group: the decimal part
\. # a dot
(?: # another group for digits after the decimal point
[05]0? # match 0 or 5, optionally followed by 0 (0, 00, 5, 50)
|
[27]5 # ... or 2 or 7, followed by 5 (25, 75)
)? # this part is optional
)? # ... actually, the whole decimal part is optional
\z # end of string
/x
```
It's a bit tricky because all parts of the number are optional in some way:
```.25``` is valid, so the integer part is optional
```0``` is valid, so the decimal point and following digits are optional
```0.``` is valid, so the decimal digits are optional
The main regex is written in a way that makes all parts optional, but there's a look-ahead assertion before it to make sure that the whole string is not empty or just ```.```.
Here is another answer: You might use an alternation to match either an optional digit followed by a dot the quarter decimal part or match one or more digits followed by an optional dot.
```^(?:\d*\.(?:[27]5|50?|00?)|\d+\.?)$```
Explanation
```(?:``` Non capturing group
```\d*\.``` Match zero or more times a digit followed by a dot
```(?:[27]5|50?|00?)``` Non capturing group which matches 25, 75, 50, 5, 0 or 00
```|``` Or
```\d+\.?``` Match one or more times a digit followed by an optional dot
```)``` Close non capturing group
```$``` Assert the end of the string
|
Title: GotMouseCapture via XAML
Tags: wpf;button;styles
Question: This is my ```button``` style:
```<Style x:Key="NoBorderButton" TargetType="Button">
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="FontSize" Value="15" />
<Style.Triggers>
<Trigger Property="Control.IsMouseOver" Value="true">
<Setter Property="Control.FontSize" Value="18" />
<Setter Property="Foreground" Value="LightSkyBlue" />
</Trigger>
<Trigger Property="Control.IsMouseOver" Value="false" >
<Setter Property="Foreground" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
```
i want to add another ```Trigger``` to my ```button```: ```GotMouseCapture``` and ```LostMouseCapture``` but i didn't find it, only via code behind:
```private void btnClose_LostMouseCapture(object sender, MouseEventArgs e)
{
btnClose.Foreground = Brushes.White;
}
private void btnClose_GotMouseCapture(object sender, MouseEventArgs e)
{
btnClose.Foreground = Brushes.DarkGray;
}
```
Here is another answer: You can use an ```EventTrigger```, here is an example:
```<EventTrigger RoutedEvent="GotMouseCapture">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Foreground"
To="DarkGray"
Duration="0:0:0"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
```
Comment for this answer: In this way the color stay in DarkGray after lost focus and not changed back to white
Comment for this answer: I already try it but in this way it disabled my other trigger that change my Foreground when IsMouseOver
Comment for this answer: XamlParseException: Key cannot be null.\r\nParameter name: key
Comment for this answer: My code was just an example of the `IsFocused` trigger in action. Simply create another `Trigger` for when `IsFocused` is false, and set it's `Foreground` to `White`.
|
Title: How to allow an attribute on an element with string content?
Tags: xml;parsing;xsd;xml-validation
Question: I'm trying to write an XSD for the following XML:
``` <users>
<user id='u1'>A</user>
<user id='u2'>B</user>
<user id='u3'>C</user>
</users>
```
Here is what I have so far:
```<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="users">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="user" maxOccurs="unbounded" type="xsd:string">
<xsd:attribute name="id" type="xsd:string"/>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
```
But it returns errror:
```
Element
'{http://www.w3.org/2001/XMLSchema}element': The content is not valid.
Expected is (annotation?, ((simpleType | complexType)?, (unique | key
| keyref)*))
```
The id attribute is the id of user.
Any idea how I can fix this?
Here is the accepted answer: Here is how to define an element with ```simpleContent``` (```xsd:string```) and an attribute in XSD:
```<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="users">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="user" maxOccurs="unbounded">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="id" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
```
(Your error has nothing to do with ```maxOccurs``` being unbounded. It had to do with the content model of your ```user``` element.)
|
Title: Error message for tel: url scheme
Tags: android;html
Question: I am using:
```<li><a class= "call-us" href= "tel:+1-406-994-4451">+1-406-994-4451</a></li>```
I am receiving the error message "net181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16RR_UNKNOWN_URL_SCHEME" When testing website on Android.
This works with the iphone, but fails every time on Android 5.0.2 (HTC One M8) This is not the actual number, but the results are the same. I have tried this with and without the plus sign, with and without the hyphens. Does anyone have any ideas? Thanks.
Comment: Tried it, still does not work. Beginning to wonder if its just my phone (HTC one). But I have no other devices to test it on.
Comment: What happens if you omit the '+' in your link?
|
Title: Gas Station exercise (process synchronization with semaphores)
Tags: process;operating-system;synchronization;semaphore;pseudocode
Question: I'm trying to write a program in pseudo code for my Operating Systems class: we have a gas station with N pumps and 1 M litre fuel tank. Each car requires to refuel with a given amount of petrol. The fuel tank is supplied by a tank truck that refills it up to maximum capacity, only if no car is refueling.
Cars can get gas only if there's an available pump, if there is enough petrol and if the tank truck is not refilling the fuel tank.
Write a solution in pseudo code which optimises access to resources using semaphores and processes.
And this is what I've done:
```#define M 15;
#define N 3;
sem pumps=N;
sem fuel_tank=3;
int max_capacity=M;
int request;
bool fill=false;
----
CAR:
----
wait(pumps);
request=rand()%3+1;
if(request<max_capacity && fill==false)
{
wait(fuel_tank);
refuel();
max_capacity=max_capacity-request;
signal(fuel_tank);
}
signal(pumps);
-----------
TANK TRUCK:
-----------
wait(pumps);
fill=true;
while(fuel_tank!=3)
sleep(1);
refill();
max_capacity=M-max_capacity;
fill=false;
signal(pumps);
```
Since this is my very first exercise with semaphores and processes, I'm not sure if the above code is correct and could work well.
What do you think about it? Is there something wrong?
Comment: @MartinJames, why does it fail? Can you explain me which kind of problem does it bring to the entire code?
Comment: 'sleep(1);' fail:(
Comment: It would be nice to add comments in the code to explain what you intend to do at line of code and what each variable is used for.
|
Title: g++ compiler error when calling function(vector <vector<int> > &)
Tags: c++;pass-by-reference;stdvector
Question: Can anyone tell me why this simple function call returns the compiler error shown at bottom?
```//This is a type definition that I use below to simplify variable declaration
typedef vector<int> islice;
typedef vector<islice> int2D;
// therefore int2D is of type vector<vector<int> >
// This is the function prototype in the DFMS_process_spectra_Class.hh file
int DumpL2toFile(int2D&);
// This is the type declaration in the caller
int2D L2Data;
// This is the function call where error is indicated
int DumpL2toFile(L2Data); (**line 90 - error indicated here**)
// this is the function body
int DFMS_process_spectra_Class181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16umpL2toFile(int2D& L2) {
string file=sL3Path+L2Info.fileName;
fstream os;
os.open(file.c_str(), fstream181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16out);
os << "Pixel A-counts B-counts" << endl;
char tmp[80];
for (int i=0; i<512; ++i) {
sprintf(tmp,"%5d %8d %8d\n",L2[i][0],L2[i][1],L2[i][2]);
os << string(tmp) << endl;
}
os.close();
return 1;
}
```
//This is the compiler command and error
```g++ -w -g -c src/DFMS_process_spectra_Class.cc -o obj/DFMS_process_spectra_Class.o
src/DFMS_process_spectra_Class.cc:
In member function 'int DFMS_process_spectra_Class181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16processL2()':
src/DFMS_process_spectra_Class.cc:90: error:
cannot convert 'int2D' to 'int' in initialization
```
Why is the compiler confusing ```int2D&``` with ```int```? The call, function prototype, and function are consistently ```int2D``` type!!
//Here is my compiler version
i686-apple-darwin11-llvm-g++-4.2 on Mac OS X 10.8.3
This by the way is the same error I get on my Linux box with g++ 4.3
Thanks for any help, Mike
Here is another answer: ```// This is the function call where error is indicated
int DumpL2toFile(L2Data); (**line 90 - error indicated here**)
```
That's not a function call! Assuming that this line occurs inside a function body (which is not clear from your code), the function call would be:
```DumpL2toFile(L2Data); // No int
```
OP, that's all you need to know. But if you are curious, the compiler is parsing your statement as if it were
```int AnyOldIdentifier(L2Data);
```
which is a declaration of an ```int``` variable called ```AnyOldIdentifier```, initialised to the value ```L2Data```. And it can't initialise an ```int``` to ```L2Data```, because ```L2Data``` is an ```int2D```, not an ```int```.
Comment for this answer: Thanks all!! I actually figured it out on my own. Just a dumb cut and paste problem. I cerated the function prototype, cut and pasted it into the class body and didn't complete the edit!! Sorry for wasting your time. Stupid is as stupid does sometimes.
Here is another answer: You have syntax error around this line:
``` // This is the function call where error is indicated
int DumpL2toFile(L2Data); (**line 90 - error indicated here**)
```
If you call ```DumpL2toFile```. you don't need the return type anymore. this way, compiler treats it as function declaration, however, ```L2Data``` is not a type, it is an object of ```int2D```, this triggers compiling error
Meanwhile, compile error says error insde ```processL2()``` function, while you did not post code of this part.
Comment for this answer: I guess bumping my head while Easter egg hunting with my nieces didn't help :-)
Comment for this answer: Actually I have a different question. Why didn't the compiler complain that this was a shadow declaration? After all I had already declared the function in the .h file. Shouldn't the compiler complain about shadow methods like it does about shadow variables?
|
Title: NavigationView in iPad popover does not work properly in SwiftUI
Tags: ios;ipad;swiftui
Question: I have the following code that displays a popover when a button is tapped:
```struct ContentView: View {
@State private var show = false
var body: some View {
Button("Open") {
self.show.toggle()
}.popover(isPresented: $show, content: {
// NavigationView {
ScrollView {
ForEach(0...10, id: \.self) {_ in
Text("Test popover ...")
}.padding()
}
// }
})
}
}
```
If I add a ```NavigationView``` in popover's content then I get this :
Any idea why this happens?
It works fine if I set a fixed frame for the content, but I do not wanna do that since I want the popover to resize according to it's content.
Comment: Did you find a workaround, or is there a bug report with Apple?
Here is the accepted answer: Probably on iPad they've got into chicken-egg problem with size detection, so just finalised with minimum.
Anyway, the solution would be to set ```.frame``` explicitly, either with predefined values (for iPad it is not so bad), or with dynamically calculated (eg. from outer frame via ```GeometryReader```)
Here is an example. Tested with Xcode 12 / iPadOS 14
```struct TestPopover: View {
@State private var show = false
var body: some View {
GeometryReader { gp in
VStack {
Button("Open") {
self.show.toggle()
}.popover(isPresented: $show, content: {
NavigationView {
ScrollView { // or List
ForEach(0...10, id: \.self) {_ in
Text("Test popover ...")
}.padding()
}
.navigationBarTitle("Test", displayMode: .inline)
}
.frame(width: gp.size.width / 3, height: gp.size.height / 3)
})
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
```
Variant 2: Partially calculated on outer size, partially on inner size.
```struct TestPopover: View {
@State private var show = false
@State private var popoverWidth = CGFloat(100)
var body: some View {
GeometryReader { gp in
VStack {
Button("Open") {
self.show.toggle()
}.popover(isPresented: $show, content: {
NavigationView {
ScrollView { // or List
ForEach(0...10, id: \.self) {_ in
Text("Test popover ...").fixedSize()
}.padding()
.background(GeometryReader {
Color.clear
.preference(key: ViewWidthKey.self, value: $0.frame(in: .local).size.width)
})
.onPreferenceChange(ViewWidthKey.self) {
self.popoverWidth = $0
}
}
.navigationBarTitle("Test", displayMode: .inline)
}
.frame(width: self.popoverWidth, height: gp.size.height / 3)
})
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct ViewWidthKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value += nextValue()
}
}
```
Comment for this answer: This solves the problem for width, but actually I could set a fixed size for that, what's more important is the popover height, let's say I have a `List` in the popover, I need the user to be able to see as much as possible from the list without scrolling, so the popover should adapt to the List's content size, do you have any idea how to get this value ?
Comment for this answer: Height of ScrollView/List can be infinite (if there are hundreds of rows), so out of screen. You can calculate height same as shown for width and decide if to limit it (if it is out of screen height) or assign as-calculated. See [SwiftUI: Make ScrollView scrollable only if it exceeds the height of the screen](https://stackoverflow.com/a/62466397/12299030) for example.
Here is another answer: Asperi's answer is great and thorough, but thought I'd add one for the lazier among us.
The tiny popover window is a bug introduced in iPadOS 13.4 (popovers appeared as you'd expect in 13.0.x - 13.3.x). I filed FB7640734 about it, which currently shows "less than 10" similar reports and is still open.
The easy workaround, which I use in a production app written in SwiftUI running on iOS, iPadOS, and Mac Catalyst is to add this after your NavigationView:
```.frame(minWidth: 320, idealWidth: 400, maxWidth: nil, minHeight: 500, idealHeight: 700, maxHeight: nil, alignment: .top)
```
I.e. in the context of the OP's sample code:
```struct ContentView: View {
@State private var show = false
var body: some View {
Button("Open") {
self.show.toggle()
}.popover(isPresented: $show, content: {
NavigationView {
ScrollView {
ForEach(0...10, id: \.self) {_ in
Text("Test popover ...")
}.padding()
}
}.frame(minWidth: 320, idealWidth: 400, maxWidth: nil,
minHeight: 500, idealHeight: 700, maxHeight: nil,
alignment: .top)
})
}
}
```
This sets a decently-sized popover that will expand between 320-400 points wide and 500x700 points high, which in practice is a good size for a popover (any larger and you probably should be using something other than a popover).
Comment for this answer: iOS15 and still the same issue with small popover
|
Title: Java - Priority in semaphore
Tags: java;multithreading;semaphore
Question: I have multiple threads accessing an external resource – a broswer. But only one thread can access it at a time. So, I am using a semaphore to synchronise them. However, one thread, which takes input from the GUI and then access the browser for the results, should have priority over other threads and I am not sure how to use a semaphore to achieve it.
I was thinking that every thread after acquiring the semaphore checks if there is the priority thread waiting in the queue and if yes, then it releases it and waits again. Only the priority thread doesn't release it once it is acquired.
Is this a good solution or is there anything else in Java API I could use?
Here is the accepted answer: Here's a simple, no frills answer. This is similar to how a read/write lock works, except that every locker has exclusive access (normally all readers proceed in parallel). Note that it does not use ```Semaphore``` because that is almost always the wrong construct to use.
```public class PrioLock {
private boolean _locked;
private boolean _priorityWaiting;
public synchronized void lock() throws InterruptedException {
while(_locked || _priorityWaiting) {
wait();
}
_locked = true;
}
public synchronized void lockPriority() throws InterruptedException {
_priorityWaiting = true;
try {
while(_locked) {
wait();
}
_locked = true;
} finally {
_priorityWaiting = false;
}
}
public synchronized void unlock() {
_locked = false;
notifyAll();
}
}
```
You would use it like one of the Lock types in java.util.concurrent:
Normal threads:
```_prioLock.lock();
try {
// ... use resource here ...
} finally {
_prioLock.unlock();
}
```
"Priority" thread:
```_prioLock.lockPriority();
try {
// ... use resource here ...
} finally {
_prioLock.unlock();
}
```
UPDATE:
Response to comment regarding "preemptive" thread interactions:
In the general sense, you cannot do that. you could build custom functionality which added "pause points" to the locked section which would allow a low priority thread to yield to a high priority thread, but that would be fraught with peril.
The only thing you could realistically do is interrupt the working thread causing it to exit the locked code block (assuming that your working code responded to interruption). This would allow a high priority thread to proceed quicker at the expense of the low priority thread losing in progress work (and you might have to implement rollback logic as well).
in order to implement this you would need to:
record the "current thread" when locking succeeds.
in ```lockPriority()```, interrupt the "current thread" if found
implement the logic between the ```lock()```/```unlock()``` (low priority) calls so that:
it responds to interruption in a reasonable time-frame
it implements any necessary "rollback" code when interrupted
potentially implement "retry" logic outside the ```lock()```/```unlock()``` (low priority) calls in order to re-do any work lost when interrupted
Comment for this answer: @jtahlborn Love the answer... though _priorityWaiting probably should be a counter instead of boolean
Comment for this answer: @kgdinesh - responded in the answer since it was too long for a comment
Comment for this answer: @Duane - the OP stated that there is only one priority thread (and this was stated to be a "simple, no frills answer"). If you want to generalize this to a solution where you could have multiple priority threads, then, yes, _priorityWaiting would need to be a counter. You could also have multiple levels of priorities or other fancier variants...
Comment for this answer: instead of waiting on `_locked` when `lockPriority()` is called, can we interrupt the running thread, let the priority thread finish up and then resume the previously running task?
Here is another answer: You are mixing up concepts here.
Semaphores are just one of the many options to "synchronize" the interactions of threads. They have nothing to do with thread priorities and thread scheduling.
Thread priorities, on the other hand are a topic on its own. You have means in Java to affect them; but the results of such actions heavily depend on the underlying platform/OS; and the JVM implementation itself. In theory, using those priorities is easy, but as said; reality is more complicated.
In other words: you can only use your semaphore to ensure that only one thread is using your queue at one point in time. It doesn't help at all with ensuring that your GUI-reading thread wins over other threads when CPU cycles become a problem. But if your lucky, the answer to your problem will be simple calls to setPriority(); using different priorities.
Comment for this answer: thread priorities and lock priorities are _also_ two different concepts, and i believe you are mixing them up here. a read/write lock is a form of locking with a simple priority mechanism (writer takes priority over readers). OP is looking for a similar concept really (except unlike read/write lock, all lockers would presumably be exclusive).
Comment for this answer: sorry, didn't have time when i posted the comment. have created the answer now.
Comment for this answer: Why would we want to do that? Seriously: priorities and synchronization are two **different** responsibilities. Pushing both into **one** thingy would be **plain** wrong in my eyes. Just because he wants something ... doesn't mean that giving him that would be the correct solution!
Comment for this answer: I am saying that I don't think that one should focus on using a semaphore to fix thread priority problems.
Comment for this answer: It is very simple: if you have a clear example on how using a certain semaphore would fix his problem; just put that in another answer ;-)
Comment for this answer: Without getting into terminologies, how can we actually solve what OP wants? i.e., A "semaphore-like" resource access control structure which natively understands priorities.
Here is another answer: There're no synchronization primitives in Java that would allow you to prioritise one thread over others in the manner you want.
But you could use another approach to solving your problem. Instead of synchronizing threads, make them produce small tasks (for instance, ```Runnable``` objects) and put those tasks into a ```PriorityBlockingQueue``` with tasks from the GUI thread having the highest priority. A single working thread will poll tasks from this queue and execute them. That would guarantee both mutual exclusion and prioritization.
There're special constructors in ```ThreadPoolExecutor``` that accept blocking queues. So, all you need is such an executor with a single thread provided with your ```PriorityBlockingQueue<Runnable>```. Then submit your tasks to this executor and it will take care of the rest.
Should you decide to choose this approach, this post might be of interest to you: How to implement PriorityBlockingQueue with ThreadPoolExecutor and custom tasks
|
Title: regdef.h: No such file or directory how can I includ files requerd by gcc?
Tags: gcc;error-handling
Question: Im trying to cross compile helloWorld to mips but Im getting and error
```hello.S:10:20: error: regdef.h: No such file or directory
```
Here is start of that file
```/*
* hello-1.2/Makefile
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1995, 1997 by Ralf Baechle
*/
#include <regdef.h>
#include <sys/asm.h>
#include <sys/syscall.h>
```
I did tried to includ it by appeding it like so
```export LD_LIBRARY_PATH=/home/slobodan/rtl819x-toolchain/toolchain/rsdk-1.5.5
-5281-EB-2.6.30-51.243.686-82-773714/include/
```
but still Im getting same error, so how can I includ files requerd by gcc ?
Here is the accepted answer: I soled it just by ading -L i.e. gcc -L /path/to/include/
|
Title: Google play game services auto sign out after some time
Tags: android;google-play-services;google-play-games
Question: I have implemented auto sign in for Google play game services in my Android game and having the following issue.
Step1: Open the app first time with Internet connection. User is signed in with the small sign in dialogue.
Step2: Close the app, stop internet connection, again open the app and the user is still signed in.
Step3: Now close the app and open it after 3-4 hours without internet connection. Sign in is failing with error ```Couldn’t connect to server``` and next time its again signing in the user with the small sign in dialogue which should be for the first time. So basically its signed out somehow.
This issue is did not happen before I released the app.
The only change I did is switched ON the ```Save Game``` option in Google Play Game Services before publishing but I don’t think that can cause this problem.
|
Title: JQuery / Javascript - ".click()" method not entirely working?
Tags: javascript;jquery;css;html-table
Question: I have a table with empty divs at first and with Javascript and JQuery, I created an array of works and whatever words are in the Array, I put those words into the td. Here is my html:
```<div id="sideBar">
<table id="sideTable">
<tr><td id='row0'></td></tr>
<tr><td id='row1'></td></tr>
<tr><td id='row2'></td></tr>
<tr><td id='row3'></td></tr>
<tr><td id='row4'></td></tr>
<tr><td id='row5'></td></tr>
<tr><td id='row6'></td></tr>
<tr><td id='row7'></td></tr>
<tr><td id='row8'></td></tr>
</table>
</div>
```
and my Javascript array, if it were this
```var tableHeadings = ['headingOne', 'headingTwo', 'headingThree'];
```
then the Javascript will hide #row3 till #row8 and the three headings will be inputted into #row0, #row1 and #row2 respectively. The td's take the size of the longest td in the row. This part of the code works! I also have two Javascript functions, one for hovering over the td and the other for when you click the td. The one where you hover over the td, the Javascript starts like this
```$('#sideTable td').hover(
```
and the one where you click the td, the Javascript begins like this
```$('#sideTable td').click( function() {
```
The problem is that when you hover over the word, the hover function is perfect, but when I go to click the td, even if the width of the td is really long / there is a lot of information inside the td (say the information in the td is so long that the width of the td becomes 200px), it only allows you to click the first I think 85px of the td. It's so weird. Even if I do
```#sideBar td {
width: 120px;
}
```
and make the width of every td 120px, it still would only allow me to click the first 85px of the td. The hovering is perfect, the moment I hover over a td, regardless of where I hover (regardless of if it is inside the first 85px of the td or not) and regardless of how long the td is, the hover function works and executes perfectly. However, for some reason, the click function only allows me to click inside the first 85px or so of the heading. Why is this?
Note: Even if I try setting the width of the td using Javascript like so
```$('td').css('width','200');
```
it still only allows me to click in the first 85px of the td. If I hover over the rest 115px of the td, the cursor won't even change to a pointer. It doesn't recorgnize for some reason that there is a td there.
The CSS is this
``` #sideBar td {
font-size: 12px;
}
#sideBar {
position: absolute;
top: 90px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
}
```
Also note that I am using I.E8 and not CSS3 and that there is A lot of JS which I wrote and it is quite messy so if I uploaded it, this thread would get downvoted. The JS doesn't really effect the width or anything of the TD though, it is just "if td is hovered then do all of this and if td is click, do this". The problem isn't with the JS code, it's just that the "if td is clicked" only works for the first 85px or so of the td regardless of if the td is longer than that.
Comment: You should provide more information. CSS and JS. When it comes to diagnosis, looking at the code helps more than reading a novel of expected and experienced behaviour IMHO.
Comment: @kraxor I uploaded the CSS, there is A lot of JS and it is quite messy so if I uploaded it, this thread would get downvoted. The JS doesn't really effect the width or anything of the TD, it is just "if td is hovered then do all of this and if td is click, do this". Also, I use I.E8 and not CSS3, if that makes a difference.
Comment: @ᾠῗᵲᄐᶌ hm I can't view the JS filled at work for some reason, I will look at it whe I get home.. Is there a way to patch this issue rather than solve it? For example, is there a way to tell Javascript that everything in a td + 20px to the right of the td is should be clickable?
Comment: @user2719875 I've fiddle with ᾠῗᵲᄐᶌ's code some, and I still don't see anything wrong. Some of your other code is probably messing with it and causing this problem. See [Updated Fiddle](http://jsfiddle.net/tewathia/T2Hxx/2/)
Comment: Like kraxor said, we need more information but my guess is that there is something overlapping the tds so when you click, the event is not reaching the tds. Will need to see more to confirm.
Comment: seems to work fine here http://jsfiddle.net/T2Hxx/
Here is another answer: Try editing your CSS to handle overflow:
```overflow-wrap: break-word
overflow-x: visible
```
Sounds like a CSS thing not a jquery problem. Inspect the elements and see if the mouse even makes it over the whole width of the td.
Comment for this answer: What is that the CSS for? #sideBar or #sideBar td or #sideBar tr? And yes i'm pretty sure it isn't a JS problem. My JS is basically just "if the td is hovered, do all of this, if it is clicked, do all of this". And oh man, also, is that CSS3? I am not using CSS3. It is for a company and the company doesn't use CSS3 and is still only using I.E 8.
Comment for this answer: hm no that still doesn't work, even with the scroll, it still gives the same problem.
Comment for this answer: So 'overflow' and 'overflow-wrap' should be okay no matter the browser. Try this - if in Chrome right click the tr tag and hit inspect element. Then go to the source and hover over the td tag it'll show you when and where its being cut off. So your CSS would reflect this, use the overflow property to help. http://www.w3schools.com/cssref/pr_pos_overflow.asp
|
Title: Choose a random function
Tags: python;python-3.x
Question: Using python 3.5 is it possible to have a list of definitions and have a function choose and call that random definition? I am asking this because all of the docs I have seen for random just says about generating a random pseudo number.
Comment: something that can be called from within that file/class e.g.
e.g. `def intro():
print("hello")
intro()`
Obviously with proper indentations and what not
Comment: Re: "… all of the docs I have seen for random just says about generating a random pseudo number" — The `random` module is included in the standard library and one can read its [fine documentation](https://docs.python.org/3/library/random.html#module-random). There I see the [description of the `choice` function](https://docs.python.org/3/library/random.html#random.choice): "_`random.choice(seq)` — — Return a random element from the non-empty sequence `seq`. If `seq` is empty, raises `IndexError`._".
Comment: [random.choice(seq)](https://docs.python.org/3/library/random.html#random.choice)
Comment: What is a definition?
Comment: So you mean a function? Functions are first-class objects in Python. You can put in them in any container and choose randomly from there.
Comment: add code in question, not in comment.
Comment: @M213081 `seq` can be list with function names
Comment: @M213081: Please edit your question, and include all the essential pieces of information. We have absolutely no idea what you are thinking unless you explain it well..
Here is the accepted answer: ```>>> def foo(): print('foo')
>>> def bar(): print('bar')
>>> from random import choice
>>> choice([foo, bar])
<function foo at 0x10499d668>
>>> choice([foo, bar])()
foo
>>> choice([foo, bar])()
bar
>>> choice([foo, bar])()
foo
```
Comment for this answer: Thank you. This is exactly what I was looking for.
|
Title: Can I use Mailgun and SendGrid on same domain
Tags: php;wordpress;sendgrid;mailgun
Question: I have separate WordPress installs on the root domain, on 3 subdomains of that root domain and on some subdirectories. My partner set up SendGrid to send email notifications to subscribers from the WP installs and it is working well.
We recently installed a custom PHP script that integrates with Twilio on another subdomain of the root domain. The coder integrated this script with Mailgun to send password reset emails and Twilio call notifications to subscribers. We've set the subdomain for Mailgun functionality to be mg.ourdomain.com. We understand that Mailgun functionality also extends to ourdomain.com We have not yet verified the account (added MX records), pending confirmation that we can use both SendGrid and Mailgun on the same domain.
In summary, SendGrid is being used with WP installs on ourdomain.com, subdomain1.ourdomain.com, subdomain2.ourdomain.com, subdomain3.ourdomain.com., ourdomain.com/subdirectory1. Mailgun would be used with PHP script on subdomain4.ourdomain.com Note that for both the WP installs and the PHP script, we will not be receiving any emails, only sending them.
If we can use both SendGrid and Mailgun, is it simply a matter of adding MX records for each email service or is there something else we must do.?
Comment: You can use both for *outgoing* email (but you'll want to make sure you set up your SPF etc. records properly). You cannot use both for *inbound* email. Multiple MX records will mean some email goes to one and other email goes to the second (if same priority).
Here is another answer: You technically can, but you probably don't want to. I would encourage consolidating onto a single sending platform. It sounds like you had a developer hard-code Mailgun into something so you'll need his/her help (or another developer) to swap that out, but on the WordPress side you could easily switch Sendgrid to Mailgun by swapping out the plugin you're using. I personally use the Mailgun WordPress plugin on a dozen or so WordPress sites and it works great.
If you're married to using both, this is what it would look like.
Email DNS setup requires MX records, which point to the servers that will receive mail for your domain, and domain verification records like DKIM and SPF records, which tell email clients what servers to trust when they receive mail from your domain. Since you're probably using your domain for individual email accounts as well (e.g. via Google Apps) you don't want to change your MX records or your individual inboxes will stop receiving mail.
It is possible to set up more than one DKIM record and to create an SPF record that includes multiple sender entries... BUT you don't want your SPF record to get too crowded. The SPF specification includes a hard limit of 10 DNS lookups when email clients validate a message. That sounds like a lot, but consider each domain entry isn't a single lookup, it may be 2 or 3.
Here's an example: this SPF allows Google, Mailgun and Mailchimp to send email from my domain.
```v=spf1 include:_spf.google.com include:mailgun.org include:servers.mcsv.net ~all
```
If I wanted I could add in Sendgrid using something like this:
```v=spf1 include:_spf.google.com include:mailgun.org include:servers.mcsv.net include:sendgrid.net ~all
```
But that's getting dangerously close to the SPF lookup limit, if each of these happen to do 3 lookups I could start to have messages rejected.
Here is another answer: SendGrid Whitelabeling requires a dedicated Subdomain, due to the MX/CNAME records being controlled for Return-Path validation, Bounce returns, etc. But that's just a whitelabeled Domain, it doesn't have to be the same one as where you have the setup installed.
So, you could have any number of WordPress installs, all configured to use the same SendGrid account, and have a distinct whitelabel on that account, such as ```sg.domain.com```.
|
Title: using variable label in sjt.df command inside sjPlot package?
Tags: r;dataframe;statistics;sjplot
Question: considering the use of variable labels in sjmisc or sjplot package, i just want to know how can i use the variable labels that i can set with the set_label() command in the sjt.df() command.
This is an example:
```library(sjPlot)
library(sjmisc)
data("efc")
sjt.df(efc)
```
the result is not showing the variable labels, but as you can see:
```get_label(efc$c12hour)
```
```
[1] "average number of hours of care per week"
```
The variable labels are there.
Please help.
and Thanks.
Comment: Thanks, i was unable to answer before. i really was looking for a html output, i am teaching to some students and they are new in R and the html output help me to get their attention. If there is no way to do that i will use this way. Waiting for a html. Thanks again.
Comment: If you don't need HTML-output, you can use `sjmis181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16descr(efc)`. Use the `max.length`-argument to shorten labels.
|
Title: Google Nexus 7: picture width greater than screen width
Tags: android;nexus-7
Question: Google Nexus 7 is a 800x1280 px tablet (not counting the system 75/64 px bars height).
But when i take a picture with a camera app, the resulting pic dimensions are 960x1280.
There is no magnification set in the camera preferences.
Wondering what gives. If i have to render this picture on the screen and i scale it and maintain the aspect ratio, won't it clip some information from the original height?
Thanks.
Here is the accepted answer: I'm not sure why you expect the resolution of the picture you take to be the same as the screen. When you take a picture with a regular digital camera you don't expect it to match up with it's screen right? The screens on most digital cameras are pretty low resolution.
So yes, if your picture and screen are different aspect ratios, then if you scale it up either you will clip areas or have empty bars on the side.
Comment for this answer: You are right. Since the device height matched the pic height resolution, that threw my thinking off. Thx for putting me back on track @kabuko
|
Title: Understanding Unix process substitution behavior
Tags: unix
Question: ```awk '{print FILENAME, $0}' <(ls) # output: /dev/fd/4 file
awk '{print FILENAME, $0}' < <(ls) # output: - file
```
In the above one-liners, the first one generates file descriptor and then the filename where as the second one generates the hypen (-) character and then the filename. Why this behavior?
Here is another answer: You can see it this way:
```awk '{print FILENAME, $0}' <(ls)
# is the same as
awk '{print FILENAME, $0}' output_of_ls_command
```
```awk``` will read a tmp file (created by ```bash```, let's name it as ```output_of_ls_command```(it's ```/dev/fd/4``` in your case))
```awk '{print FILENAME, $0}' < <(ls)
# is the same as
awk '{print FILENAME, $0}' < output_of_ls_command
```
```awk``` will read stdin (```bash``` read the tmp file, and send the content to ```awk```, ```FILENAME``` is ```-```)
|
Title: Count the number of sheets in a separate workbook and return to a cell in original workbook
Tags: vba;excel
Question: I have written a query that opens a separate file, counts all the unique 13 digit values, and copies all of the data related to that no. into separate sheets in a new workbook. What I now need to do is, from the original workbook where the macro lives, count all of the the sheets in the new workbook and return the count to a cell in the original workbook. For some reason, this baffling me so any assistance would be greatly appreciated.
```Option Explicit
Sub MPANSeparation()
Dim X As Integer 'Holds Count of rows
Dim Y As Integer 'Holds the count of copied cells
Dim MyLimit As Long 'Holds the count of matches
Dim MyTemp As String 'Holds the MPAN #
Dim MyNewBook As String 'Holds the name of the new workbook
Dim FullFileName As String 'Holds the full file name
Dim FileLocation As String 'Holds the file location
Dim FileName As String 'Holds the file name
Dim MPANSeparate As Excel.Workbook
Dim NumberOfSheets As Double
'Turn Off Screen Updates
Application.ScreenUpdating = False
'Turn off calculations
Application.Calculation = xlCalculationManual
'Identifies cell references for upload file
FullFileName = Sheet1.Cells(7, 2)
FileLocation = Sheet1.Cells(8, 2)
FileName = Sheet1.Cells(9, 2)
'Identifies workbook where data is being extracted from.
Application.EnableEvents = False
Application.DisplayAlerts = False
Set MPANSeparate = Workbooks.Open(FullFileName, ReadOnly:=False)
'Ensure we're on the data sheet
Sheets("Sheet1").Select
'Get the count of the rows in the current region
X = Range("A1").CurrentRegion.Rows.Count
'Add a new "Scratch" Sheet after first sheet
Sheets.Add After:=Sheets(1)
'Rename newly added sheet
ActiveSheet.Name = "Scratch"
'Copy all of column A of the first sheet to scratch
Sheets(1).Range("A1:A" & X).Copy Sheets("Scratch").Range("A1")
'Copy all of column B of the first sheet to scratch
Sheets(1).Range("B1:B" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)
'Copy all of column C of the first sheet to scratch
Sheets(1).Range("C1:C" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)
'Remove all duplicates
ActiveSheet.Range("$A:$A").RemoveDuplicates Columns:=1, Header:= _
xlYes
'Select start of range
Range("A1").Select
'Loop to test for len of 13 characters
Do While ActiveCell.Value <> ""
'Logical test (is this cell 13 characters long)
If Len(ActiveCell.Value) <> 13 Then
'Delete the whole row
ActiveCell.EntireRow.Delete
Else
'Move down a cell
ActiveCell.Offset(1, 0).Select
End If
Loop
'Add CountIf formulas to column B (checking A,B & C)
Range("B1:B" & Range("A1048575").End(xlUp).Row) _
.Formula = "=COUNTIF(Sheet1!C[-1]:C[1],Scratch!RC[-1])"
'Add a new workbook
Workbooks.Add
'Get the name of the new workbook
MyNewBook = ActiveWorkbook.Name
'Go back to this workbook
MPANSeparate.Activate
'Select start of range
Range("A1").Select
'Loop to add sheets (one for each MPAN)
Do While ActiveCell.Value <> ""
'Get MPAN #
MyTemp = ActiveCell.Value
'Add new sheet to "MyNewBook"
Workbooks(MyNewBook).Sheets.Add _
After:=Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count)
'Rename newly added sheet to MPAN #
Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count).Name =
MyTemp
'Move down a cell
ActiveCell.Offset(1, 0).Select
Loop
'Select start of range
Range("A1").Select
'The outer copy and paste loop
Do While ActiveCell.Value <> ""
'Select start of range
Range("A1").Select
'Get the first value we're looking for
MyTemp = ActiveCell.Value
'Get the actual count of matches
MyLimit = ActiveCell.Offset(0, 1).Value
'Go to the data sheet
Sheets("Sheet1").Select
'The A loop
'Select start of range
Range("A1").Select
Do While ActiveCell.Value <> ""
If ActiveCell.Value <> MyTemp Then
'Move down a cell
ActiveCell.Offset(1, 0).Select
Else
'Copy the entire row to the appropriate sheet in the new
Workbook
ActiveCell.EntireRow.Copy _
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)
'Move down a cell
ActiveCell.Offset(1, 0).Select
'Increase Y by 1
Y = Y + 1
'If we have all the matches, add headings and go to
NextOuterLoop
If Y = MyLimit Then
Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
GoTo NextOuterLoop
End If
End If
Loop
'The B loop
'Select start of range
Range("B1").Select
Do While ActiveCell.Value <> ""
If ActiveCell.Value <> MyTemp Then
'Move down a cell
ActiveCell.Offset(1, 0).Select
Else
'Copy the entire row to the appropriate sheet in the new
Workbook
ActiveCell.EntireRow.Copy _
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)
'Move down a cell
ActiveCell.Offset(1, 0).Select
'Increase Y by 1
Y = Y + 1
'If we have all the matches, add headings and go to
NextOuterLoop
If Y = MyLimit Then
Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
GoTo NextOuterLoop
End If
End If
Loop
'The C loop
'Select start of range
Range("C1").Select
Do While ActiveCell.Value <> ""
If ActiveCell.Value <> MyTemp Then
'Move down a cell
ActiveCell.Offset(1, 0).Select
Else
'Copy the entire row to the appropriate sheet in the new
Workbook
ActiveCell.EntireRow.Copy _
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)
'Move down a cell
ActiveCell.Offset(1, 0).Select
'Increase Y by 1
Y = Y + 1
'If we have all the matches, add headings and go to
NextOuterLoop
If Y = MyLimit Then
Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
GoTo NextOuterLoop
End If
End If
Loop
NextOuterLoop:
'Reset Y
Y = 0
'Go to the scratch sheet
Sheets("Scratch").Select
'Delete the entire row
Range("A1").EntireRow.Delete
Loop
'Turn off display alerts
Application.DisplayAlerts = False
'Delete the scratch sheet
Sheets("Scratch").Delete
'Turn on display alerts
Application.DisplayAlerts = True
Workbooks(MyNewBook).SaveAs ("C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1" & ".xlsx")
'Ensure we're back on the data sheet
Sheets("Sheet1").Select
'Select start of range
Range("A1").Select
Call forEachWs
'Turn On Calculations
Application.Calculation = xlCalculationAutomatic
'Turn on screen updates
Application.ScreenUpdating = True
End Sub
Sub forEachWs()
Dim ws As Worksheet
'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next
End Sub
Sub resizingColumns(ws As Worksheet)
With ws
.Range("A1:BB1").EntireColumn.AutoFit
End With
NumberOfSheets = Workbooks(FileName).Worksheets.Count
End Sub
```
Comment: Why not just go with `ThisWorkbook.Worksheets("SheetnameWhereCountIsIn").Range("A1").Value = Workbooks(FileName).Worksheets.Count` ? So write it in a cell in a sheet as requested instead of in the "NumberOfSheets" variable in the very end?
Comment: Just after you open the file, Debug.Print MPANSeparate.Worksheets.Count
Here is the accepted answer: The following script opens a workbook and returns the count of sheets in Range A1 in the first sheet of the workbook the macro resides in:
```Sub Test()
Dim fullPath As String
Dim wb As Workbook
fullPath = "Somepath\someworkbook.xlsx"
Set wb = Workbooks.Open(fullPath)
ThisWorkbook.Worksheets(1).Range("A1").Value = wb.Worksheets.Count
wb.Close
Set wb = Nothing
End Sub
```
Comment for this answer: You should replace "Worksheets(1)" with the worksheet you wish to put the value in, e.g. `Worksheets("SomeNameHere")` and the Range with the target cell. - It should thus be `ThisWorkbook.Worksheets("Sheet14").Range("J10").value = wb.Worksheets.Count`
Comment for this answer: Is the sheet name "Sheet14" (the name of the tab in the workbook?) or something else? If it's something else, use the tab name. So `ThisWorkbook.Worksheets("Tab name").Range("J10").value`
Subscript out of range means you do not have a sheet named "Sheet14" at the moment. In the VBA Editor you'll see the "Tab name" between the brackets after "Sheet14" most likely.
Read up on accessing sheets in different ways here http://www.ozgrid.com/VBA/excel-vba-sheet-names.htm
Comment for this answer: No worries, that's why we're here.
Comment for this answer: Thank you for your answer. When I add this in and step through the routine and get to the line ThisWorkbook.Worksheets(1).Range("A1").Value = wb.Worksheets.Count I can see the count in the routine but it doesn't put the count in any cells. The sheet on the original workbook where the button is and where I would like to return the result is Sheet 14 and cell J10 in an ideal world. Am I missing something obvious?
Comment for this answer: I have updated as per your suggestion but now on the same line creates a 'Runtime error 9 : Subscript out of range'. Any ideas?
Comment for this answer: It has worked. Thank you kindly for your assistance.
|
Title: pyspark: count number of occurrences of distinct elements in lists
Tags: python;pandas;apache-spark;pyspark
Question: I have to following data:
```data = {'date': ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-05', '2014-01-06'],
'flat': ['A;A;B', 'D;P;E;P;P', 'H;X', 'P;Q;G', 'S;T;U', 'G;C;G']}
data['date'] = pd.to_datetime(data['date'])
data = pd.DataFrame(data)
data['date'] = pd.to_datetime(data['date'])
spark = SparkSession.builder \
.master('local[*]') \
.config("spark.driver.memory", "500g") \
.appName('my-pandasToSparkDF-app') \
.getOrCreate()
spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.sparkContext.setLogLevel("OFF")
df=spark.createDataFrame(data)
new_frame = df.withColumn("list", F.split("flat", "\;"))
```
I would like to add a new column which holds the number of occurrences of each distinct element (sorted in ascending order) and another column which holds the maximum:
```+-------------------+-----------+---------------------+-----------+----+
| date| flat | list |occurrences|max |
+-------------------+-----------+---------------------+-----------+----+
|2014-01-01 00:00:00|A;A;B |['A','A','B'] |[1,2] |2 |
|2014-01-02 00:00:00|D;P;E;P;P |['D','P','E','P','P']|[1,1,3] |3 |
|2014-01-03 00:00:00|H;X |['H','X'] |[1,1] |1 |
|2014-01-04 00:00:00|P;Q;G |['P','Q','G'] |[1,1,1] |1 |
|2014-01-05 00:00:00|S;T;U |['S','T','U'] |[1,1,1] |1 |
|2014-01-06 00:00:00|G;C;G |['G','C','G'] |[1,2] |2 |
+-------------------+-----------+---------------------+-----------+----+
```
Thank you very much!
Comment: Is the order of column : occurances significant for you?
Here is the accepted answer: You can do this by a couple of groupBy statements,
To start with you have a dataframe like this,
```+-------------------+---------+---------------+
| date| flat| list|
+-------------------+---------+---------------+
|2014-01-01 00:00:00| A;A;B| [A, A, B]|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]|
|2014-01-03 00:00:00| H;X| [H, X]|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]|
|2014-01-05 00:00:00| S;T;U| [S, T, U]|
|2014-01-06 00:00:00| G;C;G| [G, C, G]|
+-------------------+---------+---------------+
```
Explode the ```list``` columns using ```F.explode``` like this,
```new_frame_exp = new_frame.withColumn("exp", F.explode('list'))
```
Then, your dataframe will look like this,
```+-------------------+---------+---------------+---+
| date| flat| list|exp|
+-------------------+---------+---------------+---+
|2014-01-01 00:00:00| A;A;B| [A, A, B]| A|
|2014-01-01 00:00:00| A;A;B| [A, A, B]| A|
|2014-01-01 00:00:00| A;A;B| [A, A, B]| B|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| D|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| P|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| E|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| P|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| P|
|2014-01-03 00:00:00| H;X| [H, X]| H|
|2014-01-03 00:00:00| H;X| [H, X]| X|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| P|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| Q|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| G|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| S|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| T|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| U|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| G|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| C|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| G|
+-------------------+---------+---------------+---+
```
On this dataframe, do a groupBy like this,
```new_frame_exp_agg = new_frame_exp.groupBy('date', 'flat', 'list', 'exp').count()
```
Then you will have a dataframe like this,
```+-------------------+---------+---------------+---+-----+
| date| flat| list|exp|count|
+-------------------+---------+---------------+---+-----+
|2014-01-03 00:00:00| H;X| [H, X]| H| 1|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| G| 1|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| U| 1|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| T| 1|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| P| 1|
|2014-01-03 00:00:00| H;X| [H, X]| X| 1|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| G| 2|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| E| 1|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| C| 1|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| S| 1|
|2014-01-01 00:00:00| A;A;B| [A, A, B]| B| 1|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| D| 1|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| Q| 1|
|2014-01-01 00:00:00| A;A;B| [A, A, B]| A| 2|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| P| 3|
+-------------------+---------+---------------+---+-----+
```
On this dataframe, apply one more level of aggregation to collect the counts to list and find max like this,
```res = new_frame_exp_agg.groupBy('date', 'flat', 'list').agg(
F.collect_list('count').alias('occurances'),
F.max('count').alias('max'))
res.orderBy('date').show()
+-------------------+---------+---------------+----------+---+
| date| flat| list|occurances|max|
+-------------------+---------+---------------+----------+---+
|2014-01-01 00:00:00| A;A;B| [A, A, B]| [2, 1]| 2|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| [1, 1, 3]| 3|
|2014-01-03 00:00:00| H;X| [H, X]| [1, 1]| 1|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| [1, 1, 1]| 1|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| [1, 1, 1]| 1|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| [1, 2]| 2|
+-------------------+---------+---------------+----------+---+
```
If you want the column ```occurance``` sorted, you can use ```F.array_sort``` over the column if you are on spark 2.4+ else you have to write a udf for that.
Here is another answer: For ```Spark2.4+``` this can be achieved without multiple groupBys and aggregations(as they are expensive shuffle operations in big data). You can do this using ```one expression``` of higher order functions ```transform``` and ```aggregate```. This should be the canonical solution for spark2.4.
```from pyspark.sql import functions as F
df=spark.createDataFrame(data)
df.withColumn("list", F.split("flat","\;"))\
.withColumn("occurances", F.expr("""array_sort(transform(array_distinct(list), x-> aggregate(list, 0,(acc,t)->acc+IF(t=x,1,0))))"""))\
.withColumn("max", F.array_max("occurances"))\
.show()
+-------------------+---------+---------------+----------+---+
| date| flat| list|occurances|max|
+-------------------+---------+---------------+----------+---+
|2014-01-01 00:00:00| A;A;B| [A, A, B]| [1, 2]| 2|
|2014-01-02 00:00:00|D;P;E;P;P|[D, P, E, P, P]| [1, 1, 3]| 3|
|2014-01-03 00:00:00| H;X| [H, X]| [1, 1]| 1|
|2014-01-04 00:00:00| P;Q;G| [P, Q, G]| [1, 1, 1]| 1|
|2014-01-05 00:00:00| S;T;U| [S, T, U]| [1, 1, 1]| 1|
|2014-01-06 00:00:00| G;C;G| [G, C, G]| [1, 2]| 2|
+-------------------+---------+---------------+----------+---+
```
|
Title: Python Selenium Detach Option Not Working
Tags: python;selenium;selenium-webdriver
Question: I want to write a Python script using Selenium and Chrome where Selenium won't close the Chrome browser when the script finishes. From doing a bunch of googling, it looks like the standard solution is to use the detach option. But when I run the following script:
```import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com/")
```
It opens up Chrome, goes to Google's homepage, and then closes the browser. It's not throwing any errors.
Any idea why it's not working? I'm using the latest version of Google Chrome on Windows 10, and I've got the latest version of the selenium module installed. I couldn't find anything online that said the experimental detach option no longer existed. And I double checked the API, and it looks like it's the right syntax.
Comment: Where is driver path in your code ?
Comment: @AndersSchneiderman u want the browser to not be closed when your script is done, right?
Comment: If you don't specify the driver path, it uses a default path -- and it was finding the driver just fine. I also tried adding the driver name, and I got the same results
Comment: Sorry, forgot to mention: I tried both chrome_options as well as options. Same result.
Comment: have you tried setting `chrome_options=chrome_options`, rather than `options=chrome_options`?
Here is the accepted answer: This code worked perfectly for me using : ```selenium-wire``` , hope it works for you
```from seleniumwire import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options)
driver.get("https://www.google.com/")
```
Here is another answer: I discovered another way to go: start Chrome in remote debugging mode, then connect to it. That way, not only does the browser stay open, but you can also use your existing Chrome profile so you can take advantage of any sites your cookies allow you to access without having to log in every time you run the script.
Here's what you need to do if you're on Windows 10:
Start Google Chrome up remotely, pointed towards your existing user profile and the port you want to use:
```cd "C:\Program Files (x86)\Google\Chrome\Application"
chrome.exe -remote-debugging-port=9014 --user-data-dir="%LOCALAPPDATA%\Google\Chrome\User Data"
```
In your python script, connect to the local port that this version of Chrome is running on:
```import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "localhost:9014")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://github.com/")
```
Comment for this answer: a great alternative, but i suggest u check this: https://pypi.org/project/selenium-wire/ for future projects with selenium
|
Title: How can I start a session in an app and securely continue it in a browser?
Tags: security;session;access-token
Question: Requirements
I have to split the user experience across two apps:
a downloaded native app
the device's default browser
A user will start by logging in to the downloaded app (username/password). At some point, the user presses a Continue button that launches a browser tab. I need the user's session to persist in the browser so I can display personalized content without requiring another login.
Planned Implementation
First the app logs the user in by calling
https://site.com/login?username=USER&password=PASS
... and the server generates a unique session token and replies...
```{
"sessionToken": "SWORDFISH"
}
```
Then when the user presses the Continue button, the app instructs the OS to open URL...
https://site.com/page.html?sessionToken=SWORDFISH
Questions
With sufficiently long and well-distributed session tokens, can this be considered secure?
Is it bad practice to keep the session token in the URL as the user navigates through different pages on site.com?
Comment: Awesome, thanks for the keyword. [Session Fixation wiki](https://en.wikipedia.org/wiki/Session_fixation) has lots of discussion.
Comment: Using POST for the app / browser transfer would be best but I don't know if it is possible. Then remove the sessionToken from the URL after the first request, changing it into a cookie. This reduces shared token / sessions on G+ / email / etc ;)
Comment: The first thing that comes to mind is Session Fixation attacks.
|
Title: Simple Adder Control Signals on Zynq SoC - Zedboard
Tags: vhdl;fpga;hardware-acceleration;zynq
Question: I am new to the Zedboard and am working up to transferring a complex hardware accelerator I currently have working on a regular FPGA board. Anyway I want to walk before I can run so have done the Zedboard speedway tutorials and am now toying around with small projects. My first of which being an simple adder accelerator:
-Send 2 numbers to the pl(programmable logic), to reg a and b
-the pl adds the numbers
-an interrupt to the PS(CPU) signals the computation has finished.
-In the ISR the PS reads the result from reg c
For this design I am using 3 registers (a,b,c) in the AXI interconnect, I have created the IP templates using CIP.
Basically though what is the best way send a control signal to enable the addition to the PL. So how should I signal to the PL adder that I have loaded the two numbers in reg a and b and now want to add them?
-Should I create a 1bit signal GPIO interconnect, add a 4th 1 bit control register to the IP? or is there a more 'stylish' way to do this by using the BUS2IPdata signals?
-Or is there another way to create custom PS to PL control enable signals?
Many thanks
Sam
Current idea:
-Build a switch in the user_logic HDL based on the BUS2IPWrCE, so when this is asserted to write to reg B I can then signal an enable signal to my adder? Or will I run into some concurrency issues with the data not being fully written straight away?
Comment: Walk before you can run : this says use GPIO as a first step. It'll handle a few switches, registers and lights (display?) just fine. Later, you can develop your own AXI peripheral if you need to avoid the extra layer of hardware, or the GPIO drivers are too slow.
Here is the accepted answer: So to do this I have created the AXI perph using CIP, then modified the used_logic and two new ports, en and interrupt. Following these instructions I employed these external connections.http://www.programmableplanet.com/author.asp?section_id=2142&doc_id=264841
I then connected these two external connections to GPIO interfaces to provide the required functionality.
Here is another answer: In your larger designs, it will be difficult to get performance using a GPIOs to control the scheduling of your accelerators. I suggest setting up FIFOs of command blocks between software and hardware.
For example, your peripheral could implement an AXI Stream slave, to receive commands from software, and an AXI Stream master, to send result indications back to software.
It can assert an interrupt to indicate that there are values in the response FIFO.
For higher performance, set up these FIFOs in DRAM and use AXI read/write masters in your peripheral.
|
Title: 401 error after successful login using browser
Tags: http-status-code-401
Question: Using my browser I point to a URL and I am prompted with a username/password dialog. I enter my username/password and I get my webpage.
I get a 401 error, however, when using curl:
```curl --anyauth --user "$USERNAME:$PASSWORD" $URL
```
wget:
```wget --http-user=$USERNAME --http-password=$PASSWORD $URL
```
Python:
```response = requests.get(url, auth=requests.auth.HTTPBasicAuth(username, password))
response = requests.get(url, auth=requests.auth.HTTPDigestAuth(username, password))
```
The verbose (sanitized) output is below for curl:
```* About to connect() to application.intranet.net port 443 (#0)
* Trying 470.545.8289...
* Connected to application.intranet.net 470.545.8289) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
* Server certificate:
* subject: CN=application.intranet.net,OU=COMPANY - Web Hosting,O=Com Pany Inc.,STREET=address,L=city,ST=state,postalCode=12345,C=US
* start date: Apr 06 00:00:00 2020 GMT
* expire date: Apr 06 23:59:59 2022 GMT
* common name: application.intranet.net
* issuer: CN=COMODO RSA Organization Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
> GET /appname/Reporting/ReportListStart.aspx HTTP/1.1
> User-Agent: curl/7.29.0
> Host: application.intranet.net
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Cache-Control: private
< Content-Type: text/html
< Server: application Server
< WWW-Authenticate: Negotiate
< WWW-Authenticate: NTLM
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Date: Wed, 23 Dec 2020 16:17:22 GMT
< Content-Length: 1293
<
* Ignoring the response-body
* Connection #0 to host application.intranet.net left intact
* Issue another request to this URL: 'https://application.intranet.net/appname/Reporting/ReportListStart.aspx'
* Found bundle for host application.intranet.net: 0x1f4b050
* Re-using existing connection! (#0) with host application.intranet.net
* Connected to application.intranet.net 470.545.8289) port 443 (#0)
> GET /appname/Reporting/ReportListStart.aspx HTTP/1.1
> User-Agent: curl/7.29.0
> Host: application.intranet.net
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Cache-Control: private
< Content-Type: text/html
< Server: application Server
* gss_init_sec_context() failed: : No Kerberos credentials available (default cache: KEYRING:persistent:9013)
< WWW-Authenticate: Negotiate
< WWW-Authenticate: NTLM
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Date: Wed, 23 Dec 2020 16:17:22 GMT
< Content-Length: 1293
<
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>
<h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
</fieldset></div>
</div>
</body>
</html>
* Connection #0 to host application.intranet.net left intact
```
wget:
```--2020-12-23 11:18:14-- https://application.intranet.net/appname/Reporting/ReportListStart.aspx
Resolving application.intranet.net (application.intranet.net)... 470.545.8289, 470.545.8289
Connecting to application.intranet.net (application.intranet.net)|470.545.8289|:443... connected.
HTTP request sent, awaiting response... 401 Unauthorized
Reusing existing connection to application.intranet.net:443.
HTTP request sent, awaiting response... 401 Unauthorized
Reusing existing connection to application.intranet.net:443.
HTTP request sent, awaiting response... 401 Unauthorized
Authorization failed.
```
Python:
```DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): application.intranet.net:443
send: b'GET /appname/Reporting/ReportListStart.aspx HTTP/1.1\r\nHost: application.intranet.net\r\nUser-Agent: python-requests/2.25.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\nAuthorization: Basic U19KaXJhX0ludGVybmFsQXVkaXQ6R2l4X0lLdzFqTEYtMld0cw==\r\n\r\n'
reply: 'HTTP/1.1 401 Unauthorized\r\n'
header: Cache-Control: private
header: Content-Type: text/html
header: Server: application Server
header: WWW-Authenticate: Negotiate
header: WWW-Authenticate: NTLM
header: X-Frame-Options: SAMEORIGIN
header: X-Content-Type-Options: nosniff
header: Date: Wed, 23 Dec 2020 17:01:10 GMT
header: Content-Length: 1293
DEBUG:urllib3.connectionpool:https://application.intranet.net:443 "GET /appname/Reporting/ReportListStart.aspx HTTP/1.1" 401 1293
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): application.intranet.net:443
send: b'GET /appname/Reporting/ReportListStart.aspx HTTP/1.1\r\nHost: application.intranet.net\r\nUser-Agent: python-requests/2.25.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
reply: 'HTTP/1.1 401 Unauthorized\r\n'
header: Cache-Control: private
header: Content-Type: text/html
header: Server: application Server
header: WWW-Authenticate: Negotiate
header: WWW-Authenticate: NTLM
header: X-Frame-Options: SAMEORIGIN
header: X-Content-Type-Options: nosniff
header: Date: Wed, 23 Dec 2020 17:01:10 GMT
header: Content-Length: 1293
DEBUG:urllib3.connectionpool:https://application.intranet.net:443 "GET /appname/Reporting/ReportListStart.aspx HTTP/1.1" 401 1293
```
From my browser there is the initial request that returns a 302:
```Request URL: https://application.wuintranet.net/appname/Reporting/ReportListStart.aspx
Request Method: GET
Status Code: 302 Found
Remote Address: 470.545.8289:443
Referrer Policy: strict-origin-when-cross-origin
Cache-Control: private
Content-Length: 160
Content-Type: text/html; charset=utf-8
Date: Wed, 23 Dec 2020 17:14:54 GMT
Location: /appname/Reporting/ReportListStart.aspx
Persistent-Auth: true
Server: application Server
Set-Cookie: ASP.NET_SessionId=dy2rr35onasw5ctumhuqb4af; path=/; secure; HttpOnly; SameSite=Lax
Set-Cookie: appname_Cookie=ConnectionTitle=DELwLGx+KbrtS0gKvmretg==&IsConnectionTitleSet=True&IsLogOff=False&CurrentOrganization=ELx658BVmiesDFQg7w5RtA==&IsOrganizationRequired=YBfC/taoB3Ll19UPqF9IEA==; path=/; secure; HttpOnly
Set-Cookie: .application_SSO_Cookie=ConnectionTitle=DELwLGx+KbrtS0gKvmretg==&IsConnectionTitleSet=True&IsLogOff=True&CurrentOrganization=ELx658BVmiesDFQg7w5RtA==&IsOrganizationRequired=YBfC/taoB3Ll19UPqF9IEA==; path=/; secure; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: application.wuintranet.net
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
```
and then the browser-generated followup that returns 200:
```Request URL: https://application.wuintranet.net/appname/Reporting/ReportListStart.aspx
Request Method: GET
Status Code: 200 OK
Remote Address: 470.545.8289:443
Referrer Policy: strict-origin-when-cross-origin
Cache-Control: private
Content-Encoding: gzip
Content-Length: 32914
Content-Type: text/html; charset=utf-8
Date: Wed, 23 Dec 2020 17:14:54 GMT
Persistent-Auth: true
Server: application Server
Set-Cookie: appname_Cookie=ConnectionTitle=DELwLGx+KbrtS0gKvmretg==&IsConnectionTitleSet=True&IsLogOff=False&CurrentOrganization=ELx658BVmiesDFQg7w5RtA==&IsOrganizationRequired=YBfC/taoB3Ll19UPqF9IEA==; path=/; secure; HttpOnly
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Cookie: ASP.NET_SessionId=dy2rr35onasw5ctumhuqb4af; appname_Cookie=ConnectionTitle=DELwLGx+KbrtS0gKvmretg==&IsConnectionTitleSet=True&IsLogOff=False&CurrentOrganization=ELx658BVmiesDFQg7w5RtA==&IsOrganizationRequired=YBfC/taoB3Ll19UPqF9IEA==; .application_SSO_Cookie=ConnectionTitle=DELwLGx+KbrtS0gKvmretg==&IsConnectionTitleSet=True&IsLogOff=True&CurrentOrganization=ELx658BVmiesDFQg7w5RtA==&IsOrganizationRequired=YBfC/taoB3Ll19UPqF9IEA==
Host: application.wuintranet.net
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
```
Comment: Please [edit] your question to include the actual HTTP requests you send and the HTTP responses you get when you use all four connection approaches (browser, curl, wget and python).
Comment: It is weird that not all shown requests have the `Authorization: Basic ` header, even though the correct parameters are used. Also, it looks like the HTTP request from the browsers are missing.
Comment: Did not know what you meant, Progman. Had to ask a friend. Now I understand. For others reading this (on Chrome at least) one can inspect network traffic via the developer tools (https://developers.google.com/web/tools/chrome-devtools/network).
wget by default is verbose ... could not figure out a way to make it more verbose.
curl has a "--verbose" option.
For Python I captured network details by following the instructions at https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-by-my-python-application.
Comment: The --ntlm option definitely has an impact. I'm getting a 401, then a 302. I tried using the --location option to get past the 302, but it just keeps redirecting.
I'm inclined at this point, @Samson, to mark this post as solved and open a new one for the 302. Thank you. If you want to add your comment as a solution I will mark it as correct.
Comment: New, related post: https://stackoverflow.com/questions/65468536/how-to-get-curl-to-narrow-to-correct-redirect
Comment: SPNego covers both Kerberos (strong) and NTLM (not so strong) authentication. In this case the server requests explicitly NTLM. But `curl` ignores that request and tries Kerberos auth. _Question:_ did you check whether this version / build of `curl` supports NTLM? It's an old Microsoft thing, some Open Source solutions simply don't want to mess with that...
Comment: In other words, what happens if you replace `curl --anyauth` with an explicit `curl --ntlm`? cf. https://curl.se/docs/manpage.html#--ntlm
Here is another answer: replace
```curl --anyauth
```
with
```curl --ntlm
```
|
Title: Can one compare integral structures on de Rham and crystalline cohomology?
Tags: nt.number-theory;ag.algebraic-geometry;etale-cohomology
Question: Suppose $\mathfrak{X}$ is a smooth projective scheme of finite type over $\mathbb{Z}_p$, with generic fibre $X$. Then there are comparison theorems relating de Rham and crystalline cohomology,
$H^i_{\mathrm{dR}}(X / \mathbb{Q}_p) \cong H^i_{\mathrm{cris}}(\mathfrak{X}, \mathbb{Q}_p)$.
Does this work integrally, i.e. does this isomorphism match up $H^i_{\mathrm{dR}}(\mathfrak{X} / \mathbb{Z}_p)$ with $H^i_{\mathrm{cris}}(\mathfrak{X}, \mathbb{Z}_p)$?
Similarly: what if one introduces also the etale cohomology $H^i_{\mathrm{et}}(X_{\overline{\mathbb{Q}}_p}, \mathbb{Q}_p)$? This contains a natural lattice $H^i_{\mathrm{et}}(X_{\overline{\mathbb{Q}}_p}, \mathbb{Z}_p)$. Does this match up with $H^i_{\mathrm{cris}}(\mathfrak{X}, \mathbb{Z}_p)$, via Fontaine's functor $\mathbb{D}_{\rm cris}$?
Comment: And you don't really need Fontain's theory for curves.:)
Comment: Probably you mean to use ${\rm{H}}^i(\mathfrak{X}_0/\mathbf{Z}_p)$ (i.e., cohomology of special fiber, relative to $\mathbf{Z}_p$ as a PD-thickening of the residue field). The integral comparison isom is valid if $e 2$, since then the divided powers are top. nilpotent. The integral comparison morphism underlies the one with $p$ inverted; it is in the book of Berthelot and Ogus on crystalline cohom. I think that the etale-crystalline case (using $A_{\rm{cris}}$, right?) fails for $i = 2 \dim X \ge p$ since $t^p \in p A_{\rm{cris}}$.
Comment: Dear David: if you're just interested in curves then things become a lot more concrete (and simpler to prove, though $(1/2)\infty = \infty$...). Presumably the degree-1 cohomology is what you care about, and so if $J$ denotes the relative Jacobian then the crystalline cohomology is the (contradvariant) Dieudonne module of the $p$-divisible group $G$ of $J_0$ whereas the etale cohomology is the $p$-adic Tate module of the generic fiber of $J$ (or of $G$). So you're really asking about comparison for $p$-divisible groups in the absolutely unramified case, yes? If so, I can dig up a reference.
Comment: Dear David: Do you care specifically about how the $p$-adic comparison morphism with $B_{\rm{cris}}$ behaves, or just if there is some "reasonable" setup which makes the integral structures match for curves? The point is that the use of $A_{\rm{cris}}$ could be considered as a bit "arbitrary" insofar as there are plenty of other choices of period rings which give the same $\mathbf{Q}_p$-theory (e.g., in Fontaine's original 1982 Annals paper he didn't have $B_{\rm{cris}}$ but axiomatixed what he needed to get a reasonable $\mathbf{Q}_p$-theory and verified stuff for $p$-divisible groups).
Comment: @jnewton: As BCnrd says, one can define `$\mathbb{D}_{\mathrm{cris}}(T)$` for $T$ a finitely-generated `$\mathbb{Z}_p$`-module with an action of Galois, using Fontaine's ring `$\mathbb{A}_{\mathrm{cris}}$`.
Comment: @BCnrd: Thanks, that is really useful. I am mainly interested in curves, so $2 \mathrm{dim}(X) < p$ is a pretty mild condition :-)
Comment: Won't applying Fontaine's $\mathbb{D}_{\rm cris}$ to $H^i_{\mathrm{et}}(X_{\overline{\mathbb{Q}}_p}, \mathbb{Z}_p)$ forget the integral structure? (since $B_{\rm cris}$ is a $\mathbb{Q}_p$-algebra)
Comment: Hey David. To get some sort of feeling as to what is going on (and as people have pointed out it's not as easy as one might hope in small characteristic) you could do worse than look at the introduction to "F-isocrystals and De Rham Cohomology I" by Berthelot and Ogus (Inventiones 72, 1983).
Comment: Faltings (Integral crystalline cohomology over very ramified valuation rings, J. American Math. Soc. (1999) 12:1, p. 117-144,)
has proved integral versions of the comparison theorems. I am more familiar with the case of $H^1$ where the first result in that direction is Fontaine's ``presque décomposition de Hodge-Tate''
(Formes différentielles et modules de Tate des variétés abéliennes sur les corps locaux, Invent. Math., t. 65, 1982, p. 379-409),
see also my Bulletin of SMF paper (1998) for crystalline aspects
using Berthelot-Breen-Messing's crystalline Dieudonné theory.
Comment: Concerning the first part of your question: Kedlaya's algorithm computing the rigid cohomology, as well as its successors, all need to take care of integral structures. However, the cases treated in that litterature are quite specific.
|
Title: How to send from one container to another container using docker-compose?
Tags: docker-compose
Question: I have two containers. When I call the first container using fastapi, then the container sends an image to the second container using requests and the second container receive the image and store it in a volume. I'm getting error.
Files of first container:
main.py
```import base64
import io
import json
import logging
import os
from io import BytesIO
import requests
import uvicorn
from fastapi import FastAPI, File, Form, UploadFile
from fastapi.responses import FileResponse
from PIL import Image
app = FastAPI()
@app.get("/")
def read_root():
img = Image.new('RGB', (200, 50), color = (73,195,150))
img.save('newfile.jpg')
print("image saved")
img.show()
##send the image
api = 'http://localhost:81/test'
filename ='newfile.jpg'
up = {'image':(filename, open(filename, 'rb'))}
#json = {'first': "Hello", 'second': "World"}
request = requests.post(api, files=up)
print(request.text)
return {"image":"sent successfully:", "statuscode":request.status_code}
```
Dockerfile:
```FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app
WORKDIR /app
RUN pip install Pillow requests python-multipart
CMD ["uvicorn", "app.main:app", "--host", "5086201276", "--port", "80"]
COPY . /app
```
Files of the second container:
main.py:
```from fastapi import FastAPI,UploadFile,File,Form
from PIL import Image
import uvicorn
import io
import json
import base64
import logging
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import shutil
app = FastAPI()
def read_imagefile(file) -> Image.Image:
image = Image.open(BytesIO(file))
return image
@app.post("/test")
async def predict_api(file: UploadFile = File(...)):
extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
if not extension:
return "Image must be jpg or png format!"
img = read_imagefile(await file.read())
#img = Image.open(myfile)
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Manipulated",(255,255,255),font=font)
img.save('sample-out.jpg')
return {"image": "saved in vol"}
```
Dockerfile:
```FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app
WORKDIR /app
RUN pip install Pillow python-multipart
CMD ["uvicorn", "app.main:app", "--host", "5086201276", "--port", "81"]
COPY . /app
```
Docker-compose file:
```version: '3.8'
services:
app1:
build: ./app1/
ports:
- 80:80
networks:
- my-proxy-net
app2:
build: ./app2/
volumes:
- myapp:/app
ports:
- 81:81
networks:
my-proxy-net:
external: true
volumes:
myapp:
```
Comment: you should not use localhost but the names of the containers in the same network, or services if you use compose. So in this case use app1 and app2 as hostnames respectivly.
Here is another answer: If your services are in same network, they can reach each other by using their respective container_name as hostname:
In your case for example:
```http://app1
```
Use
```docker container ps -a
```
and check "NAMES" column in order to fight the right name to call
Comment for this answer: updated answer to find the right container name
Comment for this answer: In this case this isn't the container name though. The container name would be something like `compose-project_app1_1`. app1 is the name of the *service* compose creates, although its not a real service, since only a swarm manager can create real docker services.
|
Title: Can static arrays be safely accessed from multiple threads?
Tags: multithreading;delphi;delphi-xe2
Question: If each thread is guaranteed to only read/write to a specific subset of the array can multiple threads work on the same (static) array without resorting to critical sections, etc?
EDIT - This is for the specific case of arrays of non-reference-counted types and record/packed-records thereof.
If yes, any caveats?
My gut feeling is yes but my gut can sometimes be an unreliable source of information.
Comment: OK, I know what that means now. I'd call that fixed size but there you go. It makes no difference whether or not the size is fixed. It makes no difference whether or not the array is of global, local or class scope. It makes no difference whether or not the array is heap allocated or stack allocated. It's just a contiguous array of items.
Comment: No, my mistake. I'd never known that usage. I guess it must have been introduced after I learnt Delphi at the time that dynamic arrays were added, since all arrays before then were static. In any case, static or not makes no [email protected].
Comment: @ArnaudBouchez That's a rather bizarre interpretation of "on the same (static) array". I take **the same** as meaning, well, the same single instance of an array. So, there's no copying here.
Comment: @ArnaudBouchez Yes copying may occur then. But the question makes it clear that copying does not occur.
Comment: @DavidHeffernan There is a difference, IMHO. Static arrays are allocated and copied when read (unless they are passed by reference, of course), whereas dynamic arrays are reference counted and have copy-on-write patterns, which may make a difference. It is (more or less) similar to the `shortstring / string` use patterns. In all cases, static arrays may not be thread-safe, in some situations: see my answer.
Comment: @DavidHeffernan Copying may occur when you pass the data to another sub function, e.g.
Comment: Fair enough. As you say, in any case, there doesn't seem to be an obvious reason why concurrent access should be a problem but sometimes there are dark subtleties which confound such things. Sometimes it is nice to be doubly certain.
Comment: @DavidHeffernan - yes, no copying. All parties get a pointer to the array and an offset range to call their own.
Here is the accepted answer: Suppose that:
You have a single instance of an array (static or dynamic), and
The elements of the array are pure value types (i.e. contain no references), and
Each thread operates on disjoint sub-arrays, and
Nothing else in the system writes to the array whilst the threads are operating on it.
With these conditions, which I believe are met by your data structure and threading pattern, then all algorithms are thread-safe.
Comment for this answer: @J... Yes that is correct. So long as each thread operates on data private to that thread, then algorithms are thread-safe.
Comment for this answer: @arnold er, condition 4 certainly is necessary.
Comment for this answer: @leonardo that's right. And disjoint means that the slices do not overlap each other.
Comment for this answer: @DavidHeffernan - What do you mean for disjoint sub-arrays? Slices of the "main" array, distributed in some way to each thread so they don't access each other's slice?
Comment for this answer: @DavidHeffernan - thank you. I think that the OP needs to be aware that the process of distributing slices to each thread there may be some concurrency issues to be avoided, too.
Comment for this answer: @J... - I wasn't thinking in actually dividing the array. I understand that each thread will be assigned its own slice. I just wanted to point that if that assignment could occur in a thread (for example, worker threads assigning slices by themselves) then you still need to protect that part. But I understand that if this assignment is done on the main thread then it is not an issue. Gawd, just talking about threads is convoluted.
Comment for this answer: I presume this would also be the case with reference type objects IF references to the same object are guaranteed to only exist within a single sub-array (ie: no common references shared between disjoint sub-arrays).
Comment for this answer: @LeonardoHerrera - the array in question will not be divided into new sub-arrays, if that's what you are thinking. Application logic alone will define the ranges of array indices permissible for each thread to access. Consider `arr1 = array[0..99] of double` and threads `0-9` where the n'th thread will work exclusively on array elements 10n->10n+9.
Comment for this answer: @DavidHeffeman, Is condition#4 really necessary? What is the difference of the main thread or another process writing to the array to the threads operating on it?
Here is another answer: No, this could not be thread safe, in some situations.
I see at least two reasons.
1. It will depend on the static array content.
If you use some non-reference counted types (like ```double, integer, bytes, shortstring```), there won't be any issue in most case (at least if data is read/only).
But if you use some reference-counted types (like ```string, interface```, or a nested dynamic array), you'll have to take care of thread safety.
That is:
```TMyType1: array[0..1] of integer; // thread-safe on reading
TMyType2: array[0..1] of string; // may be confusing
```
Additional note: if your ```string``` is in fact shared among some sub-parts of the static array, you could have the reference count be confused. Unless you explicitly call ```UniqueString()``` for each one (inside a critical section, I suspect). For an array of ```double``` or ```integer```, you won't have this issue.
2. It will depend on the access concurrency
Read access should be thread safe, even for reference counted type, but concurrent write may be confusing. For a ```string```, you may have GPF issues in some random cases, especially on a multi-core CPU.
Some safe implementation may be:
Use critical sections (smaller as possible, to reduce overhead) or other protection structures;
Use Copy-On-Write or a private per-thread copy of the content, to be sure;
Latest note (not about safety, but performance): Sharing an array among multiple CPUs may lead into performance penalties due to cache synchronization between CPUs. Performance is sometimes much better when you use separated arrays, ensuring their L1 caching window won't be shared among CPUs.
Be aware that such issues may be a nightmare to debug, on client side: multi-thread concurrency issues may occur randomly, and are very difficult to track. The safer, the better, unless you have explicit and proven performance issues.
Additional note: For your specific case of static array of double, with sub-part of the array accessed by one thread only, it is thread-safe. But there is no absolute rule of thread safeness in all situations, even for a static array. As soon as you use some reference-counted types, or some pointers, you may have random issues.
Comment for this answer: This answer is simply wrong in my view. The thrust of the question is that each thread operates on disjoint sub-arrays. And that only thread that owns each sub-array operates on it. That is thread-safe no matter what the element type is.
Comment for this answer: @J... If each thread operates on its own private sub-array then it makes no difference at all what's in the array. OK, the exception to that is if distinct sub-arrays contain references to a common object.
Comment for this answer: My point is that so long as the underlying data is not shared between threads then all algorithms are thread safe. Your answer would be better if it stated this up front because in fact that's exactly the situation that @J... is asking about.
Comment for this answer: @J... Yes... and no: they contain a pointer to some content, precessed by a reference count! The thread-safe issue is about reference count handling. Even if reference count access use an atomic low-level asm instruction, on multiple threads, you can have some race condition in case of concurrent update. For reading, it will be OK.
Comment for this answer: @DavidHeffernan As I added in my answer, you may have issues with disjoint sub-arrays, if e.g. some `string` are shared in those arrays - which may occur with `string`, unless you explicitly call `UniqueString()`.
Comment for this answer: @DavidHeffernan Reference-counted variables may be shared between threads, even if they are accessed via diverse sub arrays, since they are pointers to some shared content. That is, two threads may access to the same reference count from two diverse sides, at once. This is *indirect* shared data, but it may occur from another layer (e.g. UI). I've edited the answer to reflect this.
Comment for this answer: Good point - I should have been specific about the array type. In this case the elements are packed records of doubles (which I think should be safe).
Comment for this answer: @DavidHeffernan - also a good point. Arrays of reference counted objects hold pointers only, yes?
|
Title: Installed Ubuntu next to Windows but can't find Windows
Tags: boot;grub2;dual-boot;windows-7
Question: I just installed Ubuntu onto my hard drive from a USB drive. When I reached the partitions screen, I noticed it listed the full hard drive as "free space" even though I already had Windows 7 installed.
I knew I had about 50 GB of free space on the hard drive, so I partitioned ```sda1``` for 35 GB and installed Ubuntu onto it, and partitioned ```sda2``` for 4 GB of swap space.
The installation went fine, but when I reach the GRUB boot menu, there is no option for Windows 7 -- only Ubuntu. It seems as though my Windows 7 installation has completely disappeared. This would be very unfortunate, as I had aplenty of files on Windows, so your help is much appreciated.
Comment: It is not clear if you still have Windows in your hard drive. Can you post the output of **sudo fdisk -l** from terminal.
Here is another answer: If you have the Windows 7 rescue CD, boot from it and try fixing the MBR.
Here is another answer:
Boot your computer to the Windows 7 DVD (or to a "Repair CD"). At this screen choose to install now.
Select your language and click next.
Then select the first option I think "Startup Repair" then some processing will done
Then restart your computer. Even after that if it doesn't boot to windows 7 then your partition might be lost.
Here is another answer: if you have a windows boot repair disk, and the automatic repair doesn't work like mine (it was picky I had a windows xp repair disk while I had windows 7 and demanded I buy the windows 7 version...) then get to the command prompt while using the repair disk. It's not clear how you access it, I think you try to repair it, then push cancel or something.
Anyways, once you have the cmd prompt, run this command:
```bootrec.exe /FixMBR
```
If you still have windows, this will reset the master boot record and allow you to access it.
Here is another answer: Since you have your ubuntu installed. I would suggest to try this method as it is faster and easier than getting a repair CD IMHO.
open a new Terminal CtrlAlt+T, then type:
```sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
```
Press Enter.
Then type:
sudo apt-get install -y boot-repair && boot-repair
Press Enter
Now after the Installation has finished:
launch Boot-Repair from either :
the Dash (the Ubuntu logo at the top-left of the screen)
or System->Administration->Boot-Repair menu (Ubuntu 10.04 only)
or by typing 'boot-repair' in a terminal
You will see window :
Click on "Recommended Repair" and it will search for all the exisitng OS in your PC (windows and linux)
Boot-repair wiki page
Here is another answer: I think that the files of Windows 7 is still existing on the hard drive, but the MBR is broken. So you can build a new MBR.
Here is another answer: I think you destroyed the disk partition, but it's possible to rescue some files.
Use a Rescue CD and try ```testdisk``` in console. This program scans the hard disk for lost files and partitions.
Good luck.
Comment for this answer: I agree with this. If you had important documents on Windows, don't write any more on your disk! And use [TestDisk](http://www.cgsecurity.org/wiki/TestDisk) to try recovering some documents. Then you can reinstall Windows , then reinstall Ubuntu.
|
Title: Why I can't add generic class to silverlight unit test project?
Tags: unit-testing;windows-phone-7;generics
Question: I have little problem here.
I have two projects for Windows Phone 7.
One is regular Client appliacation and second is Test project.
Test project can be normal executed. But when i add generic class:
```public class Class1<T>
{
}
```
Then test execution ends with
```Information: Tag expression "All" is in use.
TestInfrastructure: All
TestExecution: Unit Testing
A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll
TestExecution: TestGroupLifestyleClient.Test starting
```
No test is executed. On emulator (or device) appear only "test assemblies" (no test names, no nothing).
When I remove the ```<T>``` part from class it works normaly again.
Comment: Is `Class1` a Testclass?
Comment: Would it be stating the obvious to say that it's not supported? :)
Here is another answer: I've encountered the same problem when mocking/stubbing the functionality of a generic class that my unit tests rely on. If the generic class isn't a test class (i.e. annotated [TestClass]) then a work around is to create this generic class in another project in your Visual Studio solution and then make the project with your unit tests reference this new project. The generic class will then be accessible to your tests and runnable.
My solution structure given below
```= Solution 'MobileApp'
- MobileAppProject
- TestProject
- TestSupportProject
```
Cheers,
Alasdair.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.