INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Mapping same entity to itself as a collection Ok, say i have a "Person" entity which needs to have "Person"s as property (say, friends) Since this is a many to many connection, If i'd create this schema using SQL (Which i'm not, i'm using the hbm.ddl.auto to do it for me) i'd probably make another table containing 2 columns with 2 ids (1 for each friend) However, i'm not sure how to annotate this in hibernate, i did this: class PersonEntity { . . @ElementCollection private List<PersonEntity> friends ; . . } Problem is, i'm not sure it's the best way.. for instance, i'm "thinking" that whenever i add a friend to the list and persist it will be inserted as the next row in the table, and since i can't seem to index this field i'm imagining the data retrieval will be inefficient. Can you suggest better ways to solve this problem?
You're looking for `@ManyToMany` and `@JoinTable`. The api doc of ElementCollection says: > Defines a collection of instances of a basic type or embeddable class You have a collection of entity instances. See < for how to use those annotations.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "hibernate, collections" }
How can we use where condition in array_merge result in codeigniter Here when I use my code like this am getting error `Function name must be a string in`,please have a look. public function get_date_wise_agent_report($start_date,$end_date,$agent = NULL,$abc = NULL) { $results1=$this->db->get('datas')->result(); $results2=$this->db->get('abc_datas')->result(); $data=array_merge($results1,$results2); $this->db->where_in('Date(date) >=',$start_date); $this->db->where_in('Date(date) <=', $end_date); return $data(); } I had used `array_merge` to combine two results and from that I need to get get results between the two dates hope you can help me. Thanks.
Your code should be corrected as below. public function get_date_wise_agent_report($start_date, $end_date, $agent = NULL, $abc = NULL) { $this->db->where("DATE(date) BETWEEN '{$start_date}' AND '{$end_date}'") $query = $this->db->get('datas'); $results1 = $query->result_array(); $this->db->where("DATE(date) BETWEEN '{$start_date}' AND '{$end_date}'") $query = $this->db->get('abc_datas'); $results2 = $query->result_array(); //Here you need to use $query->result_array() instead of $query->result() because result() returns a object. //Go to following link to learn more about result //Here I assumed both `datas` and `abc_datas` tables are having `date` column. $data = array_merge($results1,$results2); return $data; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, codeigniter, array merge" }
Mixing inner and outer joins in SQL Server 2008 I have a database with 3 tables. These tables represent membership information. I only want to retrieve results for groups that a specific user does NOT belong to. I'm not sure how to do this. Currently, I'm looking at the following: SELECT g.*, a.* FROM GroupInfo g INNER JOIN [Address] a ON a.[ID]=g.[AddressID] OUTER JOIN [GroupMembership] m ON m.[GroupID]=g.[ID] WHERE m.[MemberID]<>@memberID I'm concerned about accuracy and performance. Am I going the correct way?
Another approach is Select * From GroupInfo g Join Address a On a.Id = g.AddressId Where Not Exists (Select * From GroupMembership Where GroupID = g.GroupID And MemberID = @memberID)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql server 2008" }
Add a file to subversion with special characters like '%' in the filename I want to commit a version of jruby into my svn repository and there are a number of files under the jruby-1.2.0/share/ri/1.8/system/Matrix directory with the special character '%' in the file names. When I try to check these files into svn I get the following error: > svn: Commit failed (details follow): > svn: '/!svn/wrk/jruby-1.2.0/share/ri/1.8/system/Matrix/%252f-i.yaml' path not found The actual file name is '%2f-i.yaml'. So, it appears that svn is encoding the file name replacing the '%' character with '%25' causing the error message. Is there something special I need to do with svn so that the '%' character is not encoded?
The files under share/ri should be ignored and not committed back to the repository; they are the expanded RI document sources for core libraries and classes. In other news, JRuby has moved to Git for source control. Check out < for details on how to check it out.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "svn, jruby" }
authenticating linux client with active directory I am attempting to setup a linux client to authenticate with active directory. I tried following this article, but have had no luck authenticating: < I am hoping to authenticate with active directory so that I don't need to re-authenticate when printing and can automatically mount all shares. Will setting this up provide those capabilities for me?
If you set up Kerberos authentication using either `pam_krb5` or `pam_winbind`, then yes, you will get password-less authentication to services. * * * But note that the article is out of date in some places, and plain incorrect in others. 1. Arch has switched to MIT Kerberos (`krb5`) long ago. Heimdal is not used. (`krb5.conf` syntax remains the same.) 2. Do _not_ put `kdc` settings in `krb5.conf`'s `[realms]`. It is better to use DNS SRV records to find this information, which is what Windows does. If the KDCs change, you shouldn't need to edit hundreds of `krb5.conf`'s. 3. Do not put the KDC addresses in `/etc/hosts` either. Let DNS handle that. 4. `pam_krb5` does not need to be built manually; it's in the official repositories. 5. You do not _need_ `pam_krb5` if you are using Winbind (which is the recommended way). 6. `allow_weak_crypto` should not be necessary; both Heimdal and MIT Kerberos support the RC4-HMAC enctype used by pre-2008 Windows versions.
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "linux, active directory, pam" }
No Wifi with Lubuntu 14.04 on HP Netbook I just installed Lubuntu 14.04 on a HP Mini 110 netbook but I can't get the Wifi to work. It works with other distro's like Linux Mint and Elementary OS but not with Lubuntu : no Wifi icon and impossible to configure Wifi through **Preferences > Network Connections** (the save button stays grayed out). I tried some solutions I found on the forum like `Fn`+`f2` and configuring `nm-applet` but no change. Updating Lubuntu also didn't fix it. What could I try next? Complete diagnostics through the wireless-script here: < Thanx in advance for any tips or suggestions! Zendrik
The dmesg portion of the script results shows that firmware is missing. If you have a wired connection, in terminal `sudo apt-get update && sudo apt-get install firmware-b43-installer` Reboot and wifi should function
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 2, "tags": "wireless, lubuntu" }
Use static Apex method in Salesforce page public class Settings { public static String getMyValue() { return custom_object__c.getAll().values()[0].value__c; } } When I try and access this in a page like this... {!Settings.getMyValue()} ...it says... > Error: Unknown function Settings.getMyValue. Check spelling
You could define an attribute and a getter in the page's controller: public string settingsValue; public string getSettingsValue() { return Settings.getMyValue(); } you should then be able to call {!settingsValue} from the page. I don't think you can call methods from a page that are not in the controller.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "salesforce, apex code" }
npm installation error when installing package libxml I am trying to install the package libxml with the command > npm i libxml Unfortunately, I get the following error which I dont really understand. % npm i libxml npm ERR! code 1 npm ERR! path /Users/smo/Documents/adep2/adep-export-tool-js/node_modules/libxml npm ERR! command failed npm ERR! command sh -c ./build.sh npm ERR! ./build.sh: line 8: node-waf: command not found npm ERR! ./build.sh: line 9: node-waf: command not found npm ERR! cp: build/Release/o3.node: No such file or directory npm ERR! A complete log of this run can be found in: npm ERR! /Users/smo/.npm/_logs/2021-06-14T12_12_32_467Z-debug.log If someone could explain at least explain the error to me it would be pretty helpful.
I solved it. This happened because I was using the wrong node version. The package libxml reuires to the node version 14.x.x. and mine was 16.3.0
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, npm, installation, libxml2" }
Add image to textview from an external/internal url I want to know how to add an image to an `TextView` from an internal and external URL. Say I have an URL ` using `picasso` I can easily do `Picasso.with(this).load(url).into(imageView);` But how do I use it in case of `TextView` ?
You don't. Either use an `ImageView` and a `TextView` inside of a `RelativeLayout` or use an `ImageView` and a `TextView`, where in first place the `ImageView.visiblity` is gone and changes to visible due download and the `textView.visiblity` is is visible in first place and changes to gone due download. Maybe for clarification: textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Picasso.withContext(context).download(...).into(imageView).etc(); textView.setVisiblity(View.GONE); imageView.setVvisibility(View.VISIBLE); } });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, textview, imageview, picasso" }
How does the RC component of a organic photodiode impact the response speed? As I hate abstractions, I'm trying to understand at the physical level how capacitance forms within photodiode and how it decreases the performance with resistance.
A photodiode in the dark is just a diode. If you reverse bias it, the PN junction acts as an insulator - it doesn't allow current to flow. The PN junction has two wires going into it. Pretty much by definition, two conductors with an insulator between is a capacitor. If you shine a light on the photodiode, it starts to conduct. The capacitor turns into a leaky capacitor. * * * As for the RC bit. If you put a resistor in series with a capacitor when charging or discharging it, less current flows, the time to charge increases, and the dV/dt (rate of change of voltage) goes down. Practical photodiode circuits are likely to have resistors in them to keep the diode reverse biased. If the resistor is too high, and you're trying to transmit high bandwidth data, then the voltage won't change quick enough.
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "resistance, solar cell, capacitance, photodiode, photonics" }
How to hatch PolyCollection instance? Is it possible to hatch PolyCollection instance? I want to hath a PolyCollection returned from fill_betweenx. import matplotlib.mlab as mlab from matplotlib.pyplot import figure, show import numpy as np x = np.arange(0.0, 2, 0.01) y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) fig = figure() ax1 = fig.add_subplot(111) PC = ax1.fill_betweenx(x, 0, y1) # I want to do something like this # PC.set_hatch('\') # but there is no such method show()
It's a bit of a hack, but you should be able to do something like this: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import PathPatch x = np.arange(0.0, 2, 0.01) y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) fig, ax = plt.subplots() pc = ax.fill_betweenx(x, 0, y1, color='blue') # Now we'll add the hatches... for path in pc.get_paths(): patch = PathPatch(path, hatch='/', facecolor='none') ax.add_patch(patch) plt.show() !enter image description here
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python, matplotlib" }
.def files C/C++ DLLs I am not understanding the point of using .def files with DLLs. It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit __declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL. So how do you use .defs when linking with the client application, do they replace the need to use a header or .lib file?
My understanding is that .def files provide an alternative to the __declspec(dllexport) syntax, with the additional benefit of being able to explicitly specify the ordinals of the exported functions. This can be useful if you export some functions only by ordinal, which doesn't reveal as much information about the function itself (eg: many of the OS internal DLL's export functions only by ordinal). See the reference page. Note that the names in the .def file must match the names in the binary. So if you using C or C++ with 'extern "C" { ... }', the names will not be mangled; otherwise you must use the correct mangled names for the specific version of the compiler used to generate the DLL. The __declspec() function does this all automatically.
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 28, "tags": "c++, c, dll" }
Split column in pandas and retain the first split The following will work: s = pd.Series(["one_here_there", "two_here_there", "there_there_here"]) s.str.split("_", n=1).transform(lambda x: x[0]) I'm wondering if there's something more "built in", that avoids the use of `lambda`, as I've heard they are often abused.
Yes, you do not need to use lambda here. You can use s.str.split("_", n=1).str[0] Or you can use s.str.split("_", n=1).str.get(0)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, pandas" }
Timing in requestAnimationFrame In the ongoing construction of my urban transportation model, I am trying to get the timing right. I would like to be able to a) Set the animation speed -- I presume it is trying for 60fps right now, but I would like to be able to set it faster or slower. I tried this code: var fps = 5; function draw() { setTimeout(function() { requestAnimationFrame(animate); }, 1000 / fps); } draw(); but given that rAF is called three different times, I am not sure how to implement it. I tried it on all three, without success. b) I would like to set a slight delay in the launching of each "vehicle," so that they don't all set out at once. Fiddle here: <
To throttle the animation, just do this: // define some FRAME_PERIOD in units of ms - may be floating point // if you want uSecond resolution function animate(time) { // return if the desired time hasn't elapsed if ( (time - lastTime) < FRAME_PERIOD) { requestAnimationFrame(animate); return; } lastTime = time; // animation code } To change the start time of your vehicles, you'd need to build that in the logic of the vehicle itself. I wouldn't animate each vehicle individually.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 8, "tags": "javascript, canvas" }
wrong MC colors when launched via xterm -e mc I use ini-customized color theme in Midnight Commander 4.8. [Colors] base_color=linux:normal=cyan,rgb002:input=white,cyan:inputunchanged=black,cyan:dhotnormal=red When I launch xterm and then manually launch mc it works OK but when I use `xterm -e mc` I get green panels instead of dark blue. All the environment variables are the same in both cases. Same behavior in gnome-terminal or terminator. So what's the proper way to launch it?
How did you check that env vars are the same? Running `printenv` or something similar from `mc` is unreliable: there bashrc has been sourced after `mc` was started. Instead you should look at `/proc/XX/environ` where XX corresponds to mc's pid. You need to convert 0 bytes into newlines, e.g. (if only a single mc process is running): tr '\0' '\n' < /proc/`pidof mc`/environ I have a feeling that the difference will be somewhere around `$TERM` (e.g. `xterm` vs. `xterm-256color`) or `$COLORTERM`.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "linux, terminal, colors, midnight commander" }
Change tag on hover - replace image with text I have an image with a value and I want to be able to hover over the image and change it to text (to show what the image means, because the image is rather small) I've tried using `replaceWith` but that doesn't work when you stop hovering. $(document).ready(function(){ $("#apples").hover(function(){ $(this).replaceWith("<span id=\"apples\">apples: 10</span>"); }, function(){ $(this).replaceWith("<span id=\"apples\"><img src=\"images/apples.png\" alt=\"apples\"/> 10</span>"); }); }); Hopefully I explained that correctly. I just want to switch out the image of an apple with the text that says apples when the user hovers over it.
You need to replace the inner html of the element, otherwise the original element (which has a hover event listener) ceases to exist: $("#apples").hover(function(){ $(this).html("apples: 10"); }, function(){ $(this).html("<img src=\"images/apples.png\" alt=\"apples\"/> 10"); });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery, html" }
Creating dictionary from a numpy array "ValueError: too many values to unpack" I am trying to create a dictionary from a relatively large numpy array. I tried using the dictionary constructor like so: elements =dict((k,v) for (a[:,0] , a[:,-1]) in myarray) I am assuming I am doing this incorrectly since I get the error: `"ValueError: too many values to unpack"` The numPy array looks like this: [ 2.01206281e+13 -8.42110000e+04 -8.42110000e+04 ..., 0.00000000e+00 3.30000000e+02 -3.90343147e-03] I want the first column `2.01206281e+13` to be the key and the last column `-3.90343147e-03` to be the value for each row in the array Am I on the right track/is there a better way to go about doing this? Thanks Edit: let me be more clear I want the first column to be the key and the last column to be the value. I want to do this for every row in the numpy array
This is kind of a hard question on answer without knowing what exactly myarray is, but this might help you get started. >>> import numpy as np >>> a = np.random.randint(0, 10, size=(3, 2)) >>> a array([[1, 6], [9, 3], [2, 8]]) >>> dict(a) {1: 6, 2: 8, 9: 3} or >>> a = np.random.randint(0, 10, size=(3, 5)) >>> a array([[9, 7, 4, 4, 6], [8, 9, 1, 6, 5], [7, 5, 3, 4, 7]]) >>> dict(a[:, [0, -1]]) {7: 7, 8: 5, 9: 6}
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "numpy" }
Delta of numbers in file On our server a cronjob has logged a count of files in a shared directory. The log is of the form: 2003-07-03T16:05 279 2003-07-03T16:10 283 2003-07-03T16:15 282 By now this file has far over a million entries. I am interested in finding the biggest changes we ever had (negative and positive). I can write a program to find this, but is there some tool that can give me a list of deltas? The original is on Solaris, but I have a copy of the file on my Linux Mint system.
If you have the package `num-utils` installed, you can do: cut -d ' ' -f 2 inputfile | numinterval | sort -u The first and the last number there give the min, resp. max changes. If that list is too long and you also have `moreutils` installed you can do: cut -d ' ' -f 2 inputfile | numinterval | sort -u | pee "tail -1" "head -1" On Mint you should be able to install those packages, on Solaris you probably have to compile from source.
stackexchange-unix
{ "answer_score": 7, "question_score": 5, "tags": "text processing, numbering" }
Undefined reference to `registerrpc' I have this simple server that has to register a procedure to make it available over RPC. here is my server.c: #include <rpc/rpc.h> int * p_double(int n){ static int d; d = 2 * n; return &d; } int main(){ registerrpc(0x22222222, 1, 1, p_double, xdr_int, xdr_int ); svc_run(); return 0; } When I try to compile it i get these errors : > gcc -o s server.c /tmp/ccd0Roxs.o: In function `main': server.c:(.text+0x47): undefined reference to `registerrpc' collect2: ld returned 1 exit status What I got from that is that it cannot find `registerrpc` anywhere or at least in `rpc/rpc.h` I am using Ubuntu 12.04, and another student in my class got it to work by installing `portmap` So I tried doing the same thing. Unfortunately this did not help with anything. (I am not sure if this belongs here though, sorry)
The rpc header you are using does not define a `registerrpc` function. I believe you are probably following a guide based on another operating system (or possibly an older version). I think the best solution would be to find a guide for doing the same thing with the functions in your `rpc/rpc.h`. However, on Ubuntu it seems you can install an alternative RPC library with `apt-get install libtirpc-dev`, and then compile with the options: gcc -o server -I /usr/include/tirpc server.c -l tirpc
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c, linux, rpc" }
Possible to use javascript FileSystem in incognito? Trying to get something like this < to work in incognito, but the FileSystem API throws security error.
The FileSystem API is not well supported. I recommend using IndexedDB API instead, or use the localForage polyfill library if certain features of that library are not available in certain browsers. These should be supported in Incognito mode. I quickly tested with Local Storage and that works.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, google chrome, filesystems" }
student A has a 0.85 chance to solve problem, student B has a 0.9 chance to solve the problem A - has a 0.85 chance to solve a problem B - has a 0.9 chance to solve a problem 1) find the probability that the problem will be solved if A and B try to solve it independently of each other. 2) find the probability that both students will solve the problem if they are solving it independently. 3) if the problem was solved by one student, find the probability that it was student A that solved the problem. * * * S - the event that the problem got solved For 1) we have: $P\left(S\right)=P\left(AB^c\right)+P\left(A^cB\right)+P\left(AB\right)=98.5\%$ For 2) we have $P(AB)=76,5\%$ For 3) wouldn't it just be $P(AB^C)$?
Your $3^{rd}$ Case will amount to: $$P(AB^C|AB^C+BA^C)$$ This means to show that favourable outcome is that only A solves the problem: $0.85*0.1$ And total such probablity when only one person solved the problem:$0.85*0.1+0.9*0.15$ Thus your probablity comes out to be$$\frac{0.085}{0.085+0.135}=\frac{17}{44}$$ Hope it solves your problem now?
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability, discrete mathematics" }
Theme in magento PHP I have a rather simple question. I want to install a new magento theme. In the documentation it says to overwrite the default 'app' and 'skin' folders with the theme's 'app' and 'skin' folders. "8. Upload the "app" and "skin" folders from the template themeXX folder to your Magento root folder (accept the replacement)" However, when I am doing that, it prompts me to download magento again thru the magento installation wizard. To me, it sounds more reasonable to just copy the contents of the 'app' and 'skin' folders of the new theme into the default 'app' and 'skin' folders of the magento framework as they contain some other folders that probably should remain intact. Any suggestions please?
below url help for create new theme < < hope this help you
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, magento" }
Overlapping with Fusion Chart While I drag an element (DIV or SPAN or any ), over the FusionChart control, the draggable element disappears. Sometimes the elements comes under the FusionChart. I need to drag the element over the Fusion Chart control. Here I am using Drag and Drop using jQuery. And i am dragging a text. What is the solution ?
Set the SWF's wmode parameter to "transparent". var Chart1 = new FusionCharts(this.chart, "ChartId1", this.width, this.height); Chart1.addParam("WMode", "Transparent"); // this line is the one you're looking for Chart1.setDataXML(this.dataxml); Chart1.render(this.chart1div); Example code here.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, jquery ui, fusioncharts" }
Geometrical meaning of the formula for the area of a triangle using a $3\times3$ matrix. I know the geometrical meaning of the determinant of a matrix, and I know that, for example, the area of a parallelogram defined by two vectors $$ v=\begin{bmatrix}a \\\b \end{bmatrix},\quad w=\begin{bmatrix}c \\\d \end{bmatrix}, $$ is equal to $$ \det \begin{pmatrix} a & c \\\ b & d \end{pmatrix}. $$ I know that the area of the triangle $ABC$ is equal to $$\frac{1}{2} \det\begin{pmatrix} 1 & 1 & 1\\\ x_A & x_B & x_C \\\ y_A & y_B & y_C \end{pmatrix}. $$ I would like to find a geometrical proof of the last formula. Why is the area of a triangle (numerically) equal to the volume of the solid generated by the three vectors $[1, x_A, y_A]$, $[1, x_B, y_B]$, $[1, x_C, y_C]$? I can verify it, but I can't _see_ it.
Subtract the second and the third columns by the first (this is geometrically a shear). Now you get a block lower triangular matrix and the determinant becomes the area of a parallelogram (or strictly speaking, a slanted cylinder with a parallelogram base and unit height) with two adjacent sides $\pmatrix{x_B-x_A\\\ y_B-y_A}$ and $\pmatrix{x_C-x_A\\\ y_C-y_A}$. Multiply it by one half, you get the area of the triangle.
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "determinant, analytic geometry, triangles, area" }
Balancing biscoff spread for stuffed brownies There is a recipe online for nutella stuffed brownies that I really like, and I want to swap out the nutella for biscoff to make a biscoff stuffed brownie. The recipe is this one in question: < The biscoff spread is this one: (< The problem is not with the recipe, but with the substitution. I think that just freezing a slab of biscoff (like it says to do with nutella) would make for a cloying brownie. Is there anything I can do to "mellow" the biscoff spread so it isn't too cloying? I am thinking of blending in a neutral oil/butter to add more bulk without any flavour. Any suggestions would be greatly appreciated, thanks!
Two options come to mind for me: The first option I would suggest is simply using a thinner layer of biscoff spread. You can use one that is just a couple of millimetres thick instead of the half a centimetre of nutella in the recipe. The second option would be to look up a recipe for biscoff cookie dough (American-style edible cookie dough flavoured with biscoff) and use that as filling for a more mellow flavour.
stackexchange-cooking
{ "answer_score": 3, "question_score": 0, "tags": "baking, substitutions, dessert, brownies" }
gremlin - how to compute standard deviation in a single query? On Kelvin Lawrence's excellent gremlin guide, there's a section on how to compute the standard deviation for a list of property values. mean=g.V().hasLabel('airport').values('runways').mean().next() count = g.V().hasLabel('airport').count().next() g.withSideEffect("m",mean). withSideEffect("c",count). V().hasLabel('airport').values('runways'). math('(_ - m)^2').sum().math('_ / c').math('sqrt(_)') How would you condense this down into a single query?
I keep meaning to go add that to the book. It's actually Issue #174 on the repo. Here's the query: gremlin> g.V().hasLabel('airport'). ......1> values('runways').fold().as('runways'). ......2> mean(local).as('mean'). ......3> select('runways').unfold(). ......4> math('(_-mean)^2').mean().math('sqrt(_)') ==>0.7510927827902234
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "gremlin" }
Create dictionary with key from one dataframe column and values from another dataframe column I have the following df and wish to create a dictionary with `clust` as the key and `Feature` as a list of the values. How would I go about creating the `desired dict`? `df` Feature clust 0 I_0 2 1 I_1 3 2 I_2 1 3 I_3 1 4 I_4 2 5 N_0 3 6 N_1 3 `desired dict` {1: ['I_2','I_3'], 2: ['I_0','I_4'], 3: ['I_1','N_0','N_1']} Cheers :)
First aggregate list for `Series` and then convert it to `dictionary`: desired dict = df.groupby('clust')['Feature'].agg(list).to_dict()
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "pandas, dataframe, dictionary" }
How to predict only those values that our model is 95% sure of? I have 5 classes. I made a XGBoost Classification model and used `model.predict(test)` to predict the classes of test dataset. Out of all those values predicted by my model, I would like to know only those values that my model is more than 95% sure that the predicted value is correct. I mean, I would only like those predictions that my model is very confident of predicting. How do I find those predictions?
Have a look at the `predict_proba` method of the `XGBClassifier` class which will give you the probabilities for each class instead of just the predicted class. You can then use these probabilities to only select the class with the highest probability if the probability is above the treshold you want to set (in this case 0.95).
stackexchange-datascience
{ "answer_score": 1, "question_score": 0, "tags": "machine learning, confidence" }
Excluding remote branches from "git log -all" Are there ways to list the git log graph from all local branches only? Consider the command: `git log --oneline --graph --decorate --all` Where the " **\--all** " flag would be something like " **\--localbranchesonly** ".
`--all` means "everything in `refs/`" (plus HEAD as well). `--branches` means "everything in `refs/heads/`". `--remotes` means "everything in "`refs/remotes/`". `--tags` means "everything in "`refs/tags/`". Except for `--all`, they all take optional patterns that restrict the match even further. As Josh Lee mentions, `--exclude` can be used to limit the matches. There is also `--glob`, which is like `--all` in that it applies to all references, but like the others in that it accepts a pattern. Hence `--branches=<pattern>` essentially means `--glob=refs/heads/<pattern>`. Note that these are shell style globs, not regular expressions; and metacharacters in them may need to be protected from the shell.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 9, "tags": "git" }
When is it preferable to store data members as references instead of pointers? Let's say I have an object `Employee_Storage` that contains a database connection data member. Should this data member be stored as a pointer or as a reference? * If I store it as a reference, I don't have to do any `NULL` checking. (Just how important is NULL checking anyway?) * If I store it as a pointer, it's easier to setup `Employee_Storage` (or `MockEmployee_Storage`) for the purposes of testing. Generally, I've been in the habit of always storing my data members as references. However, this makes my mock objects difficult to set up, because instead of being able to pass in `NULL`s (presumably inside a default constructor) I now must pass in true/mock objects. Is there a good rule of thumb to follow, **specifically with an eye towards testability?**
It's only preferable to store references as data members if they're being assigned at construction, and there is truly no reason to ever change them. Since references cannot be reassigned, they are very limited. In general, I typically store as pointers (or some form of templated smart pointer). This is much more flexible - both for testing (as you mentioned) but also just in terms of normal usage.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 11, "tags": "c++, tdd, reference, mocking, pointers" }
minimum date of the year I have one text box and i have to show minimum date of the current year in that texbox that means: suppose consider if i select current_time (09/11/2009) then(01/01/2009) should be shown in text box awaiting ur response
**Edit:** As Noldorin points out, the simplest and most terse solution is something like this: var firstDayOfYear = new DateTime(DateTime.Today.Year, 1, 1); **My old answer:** This should do it. var now = DateTime.Now var firstDayOfYear = now.Subtract(TimeSpan.FromDays(now.DayOfYear - 1)).Date Edit: Actually this would be a bit cleaner: var today = DateTime.Today var firstDayOfYear = today.Subtract(TimeSpan.FromDays(today.DayOfYear - 1))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net" }
In jQuery, how do I apply .not to $(this) as well as other elements? So, I have a html document with divs that have classes `class1` and `class2`. What is the proper jQuery syntax to use if I want to apply a certain function to all divs except the one that I just clicked (i.e., `$(this)`) and all those with `.class1` and `class2`? (Incidentally, `$(this)` need not possess either of these classes.) I've tried various combinations, such as $('div').not($('.class1,.class2',this)).addClass('class3'); but none seem to work. Many thanks!
You can string together `.not` functions. Refer to the following example. $(".clickme").click(function () { $('div').not('.class1, .class2').not(this).addClass('class3'); }); .class3 { background:red; } <script src=" <div class="class1">class1</div> <div class="class2">class2</div> <div>will light up</div> <div class="clickme">Click me</div>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery" }
Conditional Graph in grid.arrange Is there a way to use a structure like grid.arrange( ifelse(somecondition,graph1,graph2), ifelse(somecondition2,graph3,graph4), ncol=2 ) where `graphX` is either a plot (created with `ggplot2`) or a grob defined previously. It looks like `ifelse` evaluates the `grob` object to something else (a dataframe ?) before printing so `grid.arrange` doesn't get the right input to work properly. I also tried to store all the graph objects in a collection and use that within `grid.arrange` but coudn't get a proper data structure to work nicely.
use `if() ... else ...`, not `ifelse`, p1 = qplot(1,1) p2 = qplot(1,2) p3 = qplot(1,3) p4 = qplot(1,4) grid.arrange( if(1 == 2) p1 else p2, if(3 == 3) p3 else p4, ncol=2 ) If you want to store them in a list first, pl = list(if(1 == 2) p1 else p2, if(3 == 3) p3 else p4) grid.arrange(grobs=pl, ncol=2)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "r, ggplot2, gridextra, grob" }
Use an MVC Master Page in a WebForm page I have an MVC application that I am creating that I have to integrate regular WebForms into the site. The WebForm pages will be using a ReportViewer control so I believe that won't work in a regular MVC view because ReportViewer uses ViewState, etc. Is it possible for me to create a regular Web Form that uses an MVC View Master page? If so...is it possible to use the Html helper methods such as RenderPartial?
> Is it possible for me to create a regular Web Form that uses an MVC View Master page? I don't know for sure, but it might work, as long as it's just markup and doesn't use any MVC-specific features. > If so...is it possible to use the Html helper methods such as RenderPartial? Nope. If you use it this way, the `Html` property will not be set automatically, and I don't know of any way to hack it in. We began a project in WebForms and realized partway through that MVC suits our purposes far better, so until we can finish migrating away from WebForms we have to maintain two separate versions of each of our "portal" elements (tabs, logout buttons, etc.). It's a pain, but it's doable.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "asp.net mvc, master pages, webforms" }
Responsive menu with resizing I need to responsive button like this: we have 15 buttons on a menu. When the browser is resizing, some buttons add to `<select>` like this: !enter image description here I have this jsFiddle to demonstrate the problem:
This is too much manipulation when the window is resized. I don't know if this can be done with CSS. You should prefer that.. But here is a working but dirty **fiddle with Javascript/jQuery**. You should listen to the `resize` event. $(document).ready(function (event) { buildMenu(); $(window).resize(function (event) { buildMenu(); }); });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, html, css" }
Cocos2D/3D: How to generate and load compressed texture? I'm messing around with PVRTexTool GUI, but only the uncompressed 32 bit texture is shown correctly by the app. I've tried so far all OpenGL ES 2.0 formats !enter image description here and some OpenGL ES 1.0 !enter image description here ...but some won't load and others are shown in black. I'm loading the texture with this code // load texture CC3Texture* texture = [CC3Texture textureFromFile:@“my_texture.pvr”];
Have a look at the `CC3DemoMashUpScene addSkyBox` method. In there, you can uncomment the line that loads the `Skybox.pvr` file. You'll also need to uncomment the line in the `initializeScene` method that invokes the `addSkyBox` method. `Skybox.pvr` is a cube-map texture, containing six compressed PVRTC 2bpp textures. You can use the PVRTexTool to open this texture and compare it to the textures you are trying to load.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "cocos2d iphone, textures, cocos3d" }
What does curly brackets do in Xpath? I am reading a legacy framework written in C#, there is a constant string defined as following: private const string NAVBAR_PANEL_TEMPLATE = ".//*[@id='navbar']//*[contains(@class, 'platform-nav-{0}')]"; This string is to be used for element-searching by xpath. To my understanding, it can be translated as: "looking for elements whose ids are equal to 'navbar', under those matching elements, looking for elements whose class contains 'platform-nav-{0}'". I am really confused by the last {0}, what does it represent?
It is likely not part of the XPath expression. The code is likely passing `NAVBAR_PANEL_TEMPLATE` to `String.Format()` and substituting a value in place of `{0}`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, xpath" }
Short Circuit - can it cause/detecting damage It's a fairly simple question, can a short circuit in a modern PC cause damage, or are they pretty well protected? The situation being my PC shutdown unexpectedly on my wife. I had to open it up, tip it on its side to and turn it on/off a few times to figure out the problem. Hearing a little crack I figured out that it was something sparking, then taking off the other panel noticed one of the power connectors dangling right above a rivet in the case. The last short caused my CMOS to become corrupt, I got a bad checksum message when it loaded, so I restored the default settings. It seems to be working at the moment, I'm actually typing this on the machine but I'm wondering if there might be any hidden damage caused by such an event, or whether everything should be fine? And if so, is there a way to detect such damage?
The actual case is probably grounded and not cause any issues. A short circuit through some of the more delicate components would be a problem. If it shorted through and IC chips they are probably fried. Considering you are actually typing on this computer would indicate that it most likely shorted to ground and didn't cause any damage.
stackexchange-superuser
{ "answer_score": 3, "question_score": 1, "tags": "power supply, hardware failure" }
How many zero divisors at $\mathbb{Z}_{80}\times\mathbb{Z}_{100}$? How many zero divisors at $\mathbb{Z}_{80}\times\mathbb{Z}_{100}$? I assume it: $(80-\varphi(80))\cdot(100-\varphi(100))$, I'm right or I miss somthing?? Thank you!
$(a,b)\in A\times B$ is a zero divisor iff $a$ is a zero divisor in $A$ or $b$ is a zero divisor in $B$. Note that e.g. $(1,0)$ is a zero divisor because $(1,0)\cdot(0,1)=(0,0)$. So you should have $80\cdot 100-\phi(80)\cdot \phi(100)$ instead.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "ring theory, finite rings" }
How can I correctly fetch the Riot API with JS? i've been trying to fetch some data from the riot's api, and I have a problem: This is the important part of the code: const getUsuario = async (name) => { const resp = await fetch(`${APIRUL}${name}${apikey}`, { method: 'GET', mode: 'no-cors', headers: { "Content-Type": "application/json", }, }); const { data } = await resp.json(); return data; }; getUsuario("user-name"); If i put **mode: cors**. I have a problem with CORS, but if I have as the example above, it shows up this: champions.js:15 Uncaught (in promise) SyntaxError: Unexpected end of input at getUsuario (champions.js:15) This is the line 15: const { data } = await resp.json();
I found a similar error to what you are seeing here: fetch() unexpected end of input Try printing the response before turning it to json and see if you see type `opaque`. This is specific to fetch requests made with mode `no-cors`. There seems to be a lot of restrictions to what you can do with this kind of response. Updated: The RiotGames api server does not return the CORS headers for a reason. Most likely they don't want you to access their API directly from the browser. You need to have a backend make those api requests for you which can then forward the responses to your frontend.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, riot games api" }
jQuery load only once I try to do some jQuery scripts on my rails project. I'm very beginner in both so i have many problems... Right now i dont know how to load jQuery not only once. If i understand, jQuery in rails is loading only once in header - so it works only on first visit? Because when i click for example on logo - that has link_to root_path - jQuery stop working. My jQuery code: $(document).ready(function() { $('.tooltip').tooltipster({ animation: 'grow' }); }); It works when only on reload. What should i do to make this works after clicking on link_to root_path - its stay on that same page but jQuery stop working.
I suspect you are using turbolink. Some info of Turbolink on railcasts. $(document).on("ready page:change", function() { $('.tooltip').tooltipster({ animation: 'grow' }); });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "jquery, ruby on rails" }
Adobe InDesign: Simple "animation" in interactive PDF I would like to use InDesign to create a very simple interactive PDF in which a sound file is playing while a couple of elements appear over time. Is something like that possible within an interactive PDF? So far I have only been able to place fully animated sequences in the form of a `.mp4` or `.flv` file inside InDesign and export it as an interactive PDF. But the animation I need is incredibly simple (objects merely have to appear after time) and I would like to try solving this inside InDesign rather than creating an animation with After Effects and placing it into the PDF as a video. Plus this usually leads to the quality of the video of the animation being very, very poor when I export the PDF and open it.
Animation tools were added into InDesign a while back, so hopefully they are available in whichever version you are using. Go to the Window\Interactive\Animation. From this animation menu, you are able to add many simple animation options, including the type of animation you are hoping to create. Make sure when you export your InDesign document to PDF, that you use the Interactive PDF export option, otherwise your PDF will not have the animations included within it.
stackexchange-graphicdesign
{ "answer_score": 4, "question_score": 5, "tags": "adobe indesign, pdf, animation" }
how to decrease the size of ScrollBars on FireMonkey I have a ScrollBox in my application, I want to decrease the width of it's ScrollBars how can I change the size of ScrollBars ? I'm using Delphi XE6
Try this one: Right-Click on your ScrollBox > Edit Custom Style. At Structure seach for `ScrollBox1Style1` (you can rename later). Has a child with style name: `hscrollbar` and other `vscrollbar` that represents the scrollbars. Change the height property of the `hscrollbar` and the width of `vscrollbar`. Then click 'Apply and Close' at the menu bar.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "delphi, firemonkey" }
Is there a group/organization/network of people who create TeX/LaTeX-based versions of old or public domain texts? Simply put, is there a Project Gutenberg for TeX and Friends?
I don’t know whether this is a group or a solo effort, but there are resources for typesetting Project Gutenberg books at www.pmonta.com/etext/, which links to the resources at www.sandroid.org/GutenMark/. And, as michal-h21 commented, Project Gutenberg itself often presents mathematical and scientific works as LaTeX files with the PDF output (e.g., Euclid).
stackexchange-tex
{ "answer_score": 12, "question_score": 12, "tags": "typography, books, publishing" }
Create multiple text files what would be a neat way to create multiple *.txt files on application startup i.e check if they exist if not create them. I need to create about 10 text files. Will I have to do like this for every single file: var MyFile: textfile; ApplicationPath: string; begin ApplicationPath := ExtractFileDir(Application.ExeName); if not FileExists(ApplicationPath + '\a1.txt') then begin AssignFile(MyFile, (ApplicationPath + '\a1.txt')); Rewrite(MyFile); Close(MyFile); end else Abort; end;
Something like this, perhaps: var ApplicationDir: string; I: Integer; F: TextFile; begin ApplicationDir := ExtractFileDir(Application.ExeName); for I := 1 to 10 do begin Path := ApplicationDir + '\a' + IntToStr(I) + '.txt'; if not FileExists(Path) then begin AssignFile(F, Path); Rewrite(F); Close(F); end end;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "file, delphi, application start" }
__contains filter doesn't work on mysql, works on local SQLite db I have following code snippet: profiles_list = Profile.objects.filter( company=request.user.company, ) search_query = None search_key = None if request.method == 'POST': search_key = request.POST.get('skey') search_query = request.POST.get('squery', None) profiles_list = profiles_list.filter( **{'%s__contains' % search_key:search_query} ) On my local dev machine with SQLite database, if I type in search_query, for example "Owal" it returns me a record where search_key contains "Owal", so I get for example "Kowalski". I tried it on production server with MySQL and it doesn't work. Do you know why?
From Django documentation: > SQLite doesn’t support case-sensitive LIKE statements; contains acts like icontains for SQLite. See the database note for more information. Suggestion: Use `%s__icontains` instead.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "django, django models, django orm" }
How can I use the ternary operator with multiple values? Hi I'm trying to understand why my code seems to work in the if/else form but doesn't seem to work with the ternary operator. For the true value I want that it reduces the balance and puts my message. Below is what I have tried: # With ternary operator. This doesn't work: def withdraw(pin_number, amount) puts pin_number == pin ? @balance -= amount "Withdrew #{amount}. New balance $#{@balance}." : puts pin_error end # With if/else statement. This does work: def withdraw(pin_number,amount) if pin_number == @pin @balance -= amount puts "Withdrew #{amount}." else puts pin_error end end ~~
Since a ternary operator is exactly that (an **operator** ), you can't split it over multiple instructions. However, blocks make it possible to "squash" multiple instructions into a single expression. def my_withdraw(pin_number,amount) puts ( pin_number == @pin ? begin @balance -= amount "Withdrew #{amount}." end : pin_error ) end Of course, this is completely illegible and I would never recommend you use that sort of syntax in the real world. But for the sake of science, why not.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby" }
Connect to vmware virtual machine via network I want to connect to my vmware vm from home. To work network i'm connecting through VPN. VM sits on one of the workstations (can connect to it through RDC). Any tips how to do that? What software do i need (got VMWare workstation atm)? p.s. i'm quite a newbie at this.
IF you can RDP to this VM from a separate machine within your work LAN then you should be able to do the same from your home system if you are allowed to open a VPN connection to your work network. It's possible that your work network might block RDP over the VPN link, again test this by connecting to a machine that you know RDP works for when connecting from within your work LAN. The basic set up on your VMware Workstation system will require that you use bridged networking to connect your VM to your work network (not NAT or local only).
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "vmware workstation, virtualization" }
Время в PostgreSQL Здравствуйте. Вот интересует след. вопрос: Как в PostgreSQL сделать так, чтобы время указывало на текущий часовой пояс (а то я как бы нахожусь в зоне +3 часа) но когда создаю пост.. У меня created_at (столбец) указывает на время +0 часов. Создаю пост в 11 вечера, а указывает на 9 вечера. Как это можно исправить?
Справился с заданным вопросом через before_filter :set_timezone def set_timezone min = request.cookies['time_zone'].to_i Time.zone = ActiveSupport::TimeZone[min] end application.js application_controller function SetTimeZone() { var today = new Date(); var offset = -(today.getTimezoneOffset()/60); $.cookie('time_zone', offset); } SetTimeZone();
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "время, ruby, postgresql, ruby on rails" }
Android moving from one app to another I have two separate apps. the packages are as follows: > com.example.incrediblemachine.rnt > > com.example.incrediblemachine.palpal i would like to do the following: when clicked on a button on the rnt app, i want the palpal app to open. is there any way to do this?
Use **getLaunchIntentForPackage** method in your Button onClick() . Before that install com.example.incrediblemachine.palpal app in device /emulator. Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.incrediblemachine.palpal"); startActivity(launchIntent); } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, android, android intent" }
Receiving an EventArc trigger for a specific GCS bucket only I'm trying to setup an EventArc trigger on a google cloud run project, to be run whenever a new file is uploaded to a particular bucket. The problem is, I can only get it to work if I choose `any resource`, i.e files uploaded to any of my buckets would run the trigger. However, I only want it to run for files uploaded to a specific bucket. It asks me to enter the 'full resource name' if I choose 'a specific resource'. But there seems to be no documentation on how to format the bucket name so that it will work. I've tried the bucket name, `projects/_/buckets/my_bucket_name`, but the trigger never runs unless I choose 'any resource'. Any ideas how to give it the bucket name so this will work?
I think the answer may be buried in here .... cloud.google.com/blog/topics/developers-practitioners/… If we read it deeply, we seem to see that event origination is based on audit records being created. We see that a record is created when a new object is created in your bucket. We then read that we can filter on resource name (the name of the object). However it says that wildcards are not yet supported ... so you could trigger on a specific object name ... but not a name which is prefixed by your bucket name.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "google cloud platform, google cloud storage, google cloud run, event arc" }
how can i convert my grails application from http to https under Linux operating system? how can i convert my grails application from http to https under Linux operating system
the configuration depends on what container you are running the application in your production environment. You should be deploying a war to your Production Server not doing a `grails run-app -https` here is a stackoverflow question with a configuration for Tomcat. I am certain you can google around and find proper configuration based on your application server
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "grails" }
Dealing with a T in a date time string in pandas I have this dataset: my_df = pd.DataFrame({'id':[1,2,3], 'date':['2019-05-16T12:39:40+0000','2019-05-16T12:39:50+0000','2019-03-28T19:36:42+0000']}) id date 0 1 2019-05-16T12:39:40+0000 1 2 2019-05-16T12:39:50+0000 2 3 2019-03-28T19:36:42+0000 And I want to convert it to date time, but there is a T in the middle I can't parse. This is what I have tried: my_df['date'] = pd.to_datetime(df['date'], format='yyyy-mm-ddThh:mm:ss') But it returns: ValueError: time data '2019-05-16T12:39:40+0000' does not match format 'yyyy-mm-ddThh:mm:ss' (match) Please, can you help me with this question? Am I parsing wrongly the string?
You don't need to specify the format, pandas can recognize it already In [2]: my_df = pd.DataFrame({'id':[1,2,3], ...: 'date':['2019-05-16T12:39:40+0000','2019-05-16T12:39:50+0000','2019-03-28T19:36:42+0000'] ...: }) In [3]: my_df Out[3]: id date 0 1 2019-05-16T12:39:40+0000 1 2 2019-05-16T12:39:50+0000 2 3 2019-03-28T19:36:42+0000 In [4]: pd.to_datetime(my_df['date']) Out[4]: 0 2019-05-16 12:39:40+00:00 1 2019-05-16 12:39:50+00:00 2 2019-03-28 19:36:42+00:00 Name: date, dtype: datetime64[ns, UTC]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas" }
New command for a height-flexible rect I'm trying to create a command that will take in one argument and create a rectangle around that number of empty lines. I have the following: \newcommand{\putansbox}[1]{ \framebox[\textwidth]{ \vspace{\the\baselineskip} } } It only creates one line though. How can I use the `#1` in here?
`\framebox` is a horizontal box, so you cannot add vertical space to it, without using a vertical box like `\parbox` inside. Here is another solution with an invisible rule: \documentclass{article} \newcommand{\putansbox}[1]{% \framebox[\textwidth]{\rule{0pt}{#1\baselineskip}} } \begin{document} \noindent\putansbox{5} \end{document} And if you don't want the box to break the line width, you may use, e.g. \newcommand{\putansbox}[1]{% \framebox[\dimexpr \linewidth-2\fboxrule-2\fboxsep\relax]{% \rule{0pt}{#1\baselineskip}% }% } To not forget the answer to your question: You may use the #1 as a prefix of `\baselineskip` because `\baselineskip` is a length and lengths may be used like units.
stackexchange-tex
{ "answer_score": 10, "question_score": 6, "tags": "macros, boxes" }
Построчное считывание данных из текстового файла и вывод на экран Господа, подскажите, пожалуйста. Я вот написал для себя тренировочный код, который бы построчно считывал данные из текстового файла и выводил на экран. Создал текстовый файл, состоящий из 5 строк на англ. языке. Однако когда запускаю программу, то отображается пустой экран. Подскажите, пожалуйста, в чем проблема. static void Main() { StreamReader fs = new StreamReader(@"D:\1.txt"); string s = ""; while (s != null) { s = fs.ReadLine(); } Console.WriteLine(s); }
static void Main() { string text = ""; using (StreamReader fs = new StreamReader(@"D:\1.txt")) { while (true) { // Читаем строку из файла во временную переменную. string temp = fs.ReadLine(); // Если достигнут конец файла, прерываем считывание. if(temp == null) break; // Пишем считанную строку в итоговую переменную. text += temp; } } // Выводим на экран. Console.WriteLine(text); }
stackexchange-ru_stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c#, файлы" }
Parse Lego Digital Designer *.lxf files I was toying with Lego digital designer the other day (< and I was wondering if the saved file could be relatively easily parsed. As anybody ever done that before? I'm looking for code examples, no matter the language :) Thanks ! Romain
Maybe this would help: < A .lxf file is just a zip file, on the page I mentioned there is a short description of the format. For more details you should read the source.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "parsing, lego mindstorms" }
Contenteditable set carret on a child node I'm having some difficulties while trying to set the carret after an `<i>` tag inside a `contenteditable`. Here is what I have : <p contenteditable="true"><i>H</i><i>e</i><i>l</i><i>l</i><i>o</i></p> How do I put the carret after the .. let's say 3rd `<i>` tag here? I already tried this solution : var el = document.getElementsByTagName('p')[0]; var range = document.createRange(); var sel = window.getSelection(); range.setStart(el.childNodes[0], 3); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.focus(); But I don't know how to make it work with the position of the `<i>` tags instead of the chars.
var el = document.getElementsByTagName('p')[0]; var range = document.createRange(); var sel = window.getSelection(); range.setStart(el.childNodes[3], 0); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.focus(); <p contenteditable="true"><i>H</i><i>e</i><i>l</i><i>l</i><i>o</i></p> In `p` 5 child nodes are there, if you want to set caret at child node use `range.setStart(el.childNodes[3], 0);`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, html" }
Setting default folder permissions for newly created accounts After creating new accounts via WHM I find that all folders created in the public_html folder have a permission of 775 which often leads to a 500 error in a browser. I am currently executing the following command via SSH `find . -type d -exec chmod 755 {} \;` from the `public_html` folder for every new account that I create on my VPS. How can I set the default permissions for new files/folders VPS-wide so that I don't have to SSH in and run that command every tyime I create a new account on my VPS?
The folks over at the cPanel Forum helped me get to the bottom of this. Turns out that this behavior happens when using connection protocol SFTP. I've **changed the connection protocol to FTP** and **all new folders are now created with 755 permissions**. I hope this helps someone!
stackexchange-stackoverflow
{ "answer_score": -2, "question_score": 3, "tags": "centos, cpanel, vps, whm" }
Field theory in four dimensions I was reading Schwartz's book on QFT. In chapter 14.5 at p.267, while speaking about path integral he says: > [...] the path integral (and field theories more generally) is only known to exist (i.e. have a precise mathematical definition) for free theories, and for $\phi^4$ theory in two or three dimensions. $\phi^4$ theory in five dimensions is known not to exist. In four dimensions, we do not know much, exactly. We do not know if QED exists, or if scalar $\phi^4$ exists, or even if asymptotically free or conformal field theories exist. **In fact we do not know if any field theory exists, in a mathematically precise way, in four dimensions**. Is this because we have to deal with renormalisation? How can we say that we are not sure if a field theory exists in four dimensions, although we can get results from our calculation?
There are a couple of points to be precise: * in four spacetime dimensions there is no scalar relativistic interacting field theory that can be rigorously defined (i.e. in which the unitary dynamics can be constructed), at least for the moment. This does not mean it is not possible, but we have not the mathematical tools to do it. The physical calculations are perturbative, and even if they strongly suggest that a mathematical theory is definable, there is no rigorous result as your book says. * The triviality of the scalar field theories in higher dimensions is due to a result of Aizenmann and Frohlich, however it is only a result that holds when you take the limit of lattice theories (and so in principle it does not exclude to obtain field theories by other methods)
stackexchange-physics
{ "answer_score": 2, "question_score": 0, "tags": "quantum field theory, mathematical physics, renormalization" }
How can i refer an exist textbox via string variable which contains the textbox object name? public void findspecific(int winnerx, int winnery) { string ineed = "tb" + winnerx + winnery; ineed.text = "Something"; // --> this line isn't work because "ineed" is a string. } all the textboxes name starts with "tb" and the winnerx and winnery numbers together locate that textbox where the winner is I cant use ineed.Text because its a string not a button reference. How can i refer to tb(x)(y) button with "ineed" string variable?
For WinForms: public void findspecific(int winnerx, int winnery) { string ineed = "tb" + winnerx.ToString() + winnery.ToString(); Control[] matches = this.Controls.Find(ineed, true); if (matches.Length > 0 && matches[0] is TextBox) { TextBox tb = (TextBox)matches[0]; tb.Text = "Something"; } else { MessageBox.Show(ineed, "No Match Found!"); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, object, casting, reference, textbox" }
Label inside form(splash screen) not displaying I have made a simple splash screen in a C# winforms application. The problem is that the form shows up, but I have a label inside my form which doesn't show up. A black box is shown where the label should be displayed. I have made a Form, keeping the properties `ShowInTaskbar=False`, and `FormBorderStyle=None` . The form's `opacity` is set to 50%. Then I have a label inside this form, with `text='Loading...'` . I have used this code to show the form: splashScreen splash=new splashScreen(); splash.Show(); I've used `splash.Close()` to close it when I want to
This is most likely because your app is too busy loading to render the label. For a splash screen to be responsive while the app is loading it needs to be multi threaded. You can find information on how to do that here.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, winforms, splash screen" }
SSJS to delete files on enhanced FTP I have a Tracking Extract which pushes the Zip file to Enhanced FTP. I want to delete these files after they have imported into a Data Extension How can I do that? am thinking of writing an SSJS activity that can delete the files. Is that possible?
You can open a support request to enable the 'Delete file from ET FTP or Safehouse' Extract Type in the Data Extract Activity, which will delete the file that matches the filename that you defined in the 'File Naming Pattern' field. Here's a screenshot of this Extract Type (and other available options). ![Data Extract Activity Options](
stackexchange-salesforce
{ "answer_score": 6, "question_score": 0, "tags": "marketing cloud, ssjs, ftp" }
Alternative to django form processing boilerplate? The suggested pattern for processing a form in a view seems overly complex and non-DRY to me: def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render_to_response('contact.html', { 'form': form, }) That's a lot of conditionals, it repeats the ContactForm() construction, and the whole block is repeated everywhere a view needs to process a form. Isn't there a better way of doing it?
You can avoid the repetition, of course. Mostly, you need to pass in as arguments the class of form and template name to use, a callable to process the cleaned data when a valid form is submitted, and a destination for the redirect after such processing; plus, you need a little extra code to call the form class just once, to produce either a bound or unbound form, and deal with it properly. I.e.: def process_any_form(request, form_class, template_file_name, process_data_callable, redirect_destination): form = form_class(request.POST if request.method == 'POST' else None) if form.is_bound and form.is_valid(): process_data_callable(form.cleaned_data) return HttpResponseRedirect(redirect_destination) return render_to_response(template_file_name, {'form': form})
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 7, "tags": "django, dry, boilerplate" }
How to retrieve a specific value from an array with keys and values in cakephp3 I am trying to access a specific value in the array that is formed after my query. $query = $views->find('all'); $results = $query->all(); $data = $results->toArray(); $results = $query->toArray(); echo $results[0]; the echo shows `{'id':1, 'date':2016-07-27,'amount':30}` I just want to get the 30 from amount. How would I go about doing that?
Just access the property of the array echo $results[0]['amount'] php docs on arrays
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, cakephp, cakephp 3.0, cakephp 3.x" }
Finding indefinite integral $\int \frac{x^2}{(x \sin x + \cos x)^2} dx $ I need hint in finding the integral of $$\int \frac{x^2}{(x \sin x + \cos x)^2} dx $$ I tried dividing the term by $x^2\cos^2x$ and then substituting $\tan x$.
with the hint from above we get $$\frac{\sin (x)-x \cos (x)}{x \sin (x)+\cos (x)}+C$$
stackexchange-math
{ "answer_score": 0, "question_score": 3, "tags": "integration, indefinite integrals" }
What is the formula for calculating reverse CAGR in Excel? How should we calculate CAGR growth for every year in **Ms-Excel** when we have the **_Starting figure_** and the **CAGR rate for the entire period**? !CAGR Calculation So in the image (link above) I have the Starting Value and the CAGR percentage (highlighted in yellow) for each of the country. I need to calculate the Future Value for every year (area highlighted in green). For example, the global value of smartphones in 2018 is $55 billion. During the period 2018-2027 the CAGR is 6%. So how can I calculate the value for 2019, 2020, 2021, all the way up to 2027?
Assuming that the Global value for 2019 is in cell C3 and the CAGR column is column L, enter the following formula in cell C3 and then copy the formula to the rest of the range. =B3*(1+$L3/100) The formula works by converting the value in column L (the CAGR) to a percentage and adding that percentage to the cell immediately to the left of the cell with the formula.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "microsoft excel" }
Is it right for chain rule in trace function? The objective function is $$ f(X)=\min_X trace(B^TX^TCXBD) $$ we know the following derivatives from Matrix Cookbook, $$ \frac{\delta{trace(B^TX^TCXB)}}{\delta X}=C^TXBB^T+CXBB^T \\\ \frac{\delta trace(XD)}{\delta X}=D^T $$ then, is it reasonable for the following rule? $$ \frac{\delta f(X)}{\delta X}=\frac{\delta f(X)}{\delta \\{B^TX^TCXB\\}}\cdot \frac{\delta{trace(B^TX^TCXB)}}{\delta X}=D^T(C^TXBB^T+CXBB^T) $$
Sorry,I've found the following relations $$ tr(ABC)=tr(BCA)=tr(CAB) $$ then, we have $$ tr(B^TX^TCXBD)=tr(CXBDB^TX^T) $$ then, from the Matrix Cookbook, we have $$ \frac{\delta{tr(EXFX^TG)}}{\delta X}=E^TG^TXF^T+GEXF $$ then, let $$ E=C,F=BD,G=I $$ we could get the answer.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "convex analysis, convex optimization, trace, matrix rank" }
1999 Chevy Cavalier transmission-to-engine support brace I'm removing the engine from a 1999 Chevy Cavalier (2.2L bi-fuel). Step 28 in the service manual in `Remove the transmission-to-engine support brace.` I've looked all around the transmission-engine connection and could not find anything that appears to hold the transmission the the engine aside from the 6 bolts directly connecting them. Where will I find this brace? ![engine-transmission flywheel]( ![engine-transmission rear]( Addendum: I tried adding the following to the answer, but lack edit rights. @Ben located the bracket for me. The easiest access to the bolts is through the right wheel well using a 13mm socket and long extension. ![transmission bolts]( ![engine bolts]( Removing the oil filter would likely make access even easier, but mine seems seized.
I was wrong about the placement of the bracket. In some cars they have a bracket that goes from the bell housing to around the oil pan. I believe in your second picture it's the bracket on the left hand side. ![enter image description here](
stackexchange-mechanics
{ "answer_score": 3, "question_score": 2, "tags": "engine, chevrolet, automatic transmission, cavalier" }
How to highlight div background color as red? I am using following div in my laravel app and currently I have boarder style now I need color background as red adtype ==1 and other green. <div style="border-style: solid; color: {{ $vehicule->adtype === 1 ? 'black' : 'blue' }} "> <img src="/images/{{ $upload->resized_name }}" height="150" width="250"> </div> how can I do this?
`color` is for the text, use `background-color` property. background-color: {{ $vehicule->adtype === 1 ? 'red' : 'green' }}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, css, laravel" }
Create IEnumerable<T>.Find() I'd like to write: IEnumerable<Car> cars; cars.Find(car => car.Color == "Blue") Can I accomplish this with extension methods? The following fails because it recursively calls itself rather than calling IList.Find(). public static T Find<T>(this IEnumerable<T> list, Predicate<PermitSummary> match) { return list.ToList().Find(match); } Thanks!
This method already exists. It's called FirstOrDefault cars.FirstOrDefault(car => car.Color == "Blue"); If you were to implement it yourself it would look a bit like this public static T Find<T>(this IEnumerable<T> enumerable, Func<T,bool> predicate) { foreach ( var current in enumerable ) { if ( predicate(current) ) { return current; } } return default(T); }
stackexchange-stackoverflow
{ "answer_score": 62, "question_score": 25, "tags": "c#, extension methods, ienumerable" }
How to search word with and without special characters in Solr We have used **StandardTokenizerFactory** in the solr. but we have faced issue when we have search without special character. Like we have search "What’s the Score?" and its content special character. now we have only search with "Whats the Score" but we didn't get proper result. its means search title with and without special character should we work. Please suggest which Filter we need to use and satisfy both condition.
If you have a recent version of Solr, try adding to your analyzer chain `solr.WordDelimiterGraphFilterFactory` having `catenateWords=1`. This starting from `What's` should create three tokens `What`, `s` and `Whats`. Not sure if `'` is in the list of characters used by filter to concatenate words, in any case you can add it using the parameter `types="characters.txt"`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "solr" }
Use new SQL table for each "conversation" in db I have this web application I'm developing for my major project, one of it features is messaging between registered users. The whole messaging system is created that every time when message is sent, new record in table conversations is created and new table in second database is created, table name is made from id of both users and conversation id. In this table whole conversation between two ppl is stored. My question is, is this good approach or creating tables at my database on daily basis would be to much for server to handle?
Creating new tables based on request is never a good idea. You could create a table which connects user_ids to a conversation: conversations: id : 2348 started_at: 2013-03-28 17:13:00 user_conversations: id : 538 conversation_id: 2348 message : "Hey Jakub, how are you?" user_id : 5831 posted_at : 2013-03-28 17:14:50 id : 539 conversation_id: 2348 message : "Hey Anyone, I'm fine, how are you?" user_id : 95234 posted_at : 2013-03-28 17:15:30 etc. id: PK, key on user_id You might want to play around with keys tho, but this is a nice setup for this. You will connect messages to a user and a coversation. This way a conversation is not limited to 2 users either.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, sql, database, web applications" }
Javascript Regex to replace a sub directory in url I am trying to match a sub directory in a URL that comes after a specific directory: then append a directory to the matched string. `/applications/app1` should be `/applications/app1/beta` `/applications/app2/` should be `/applications/app2/beta/` `/applications/app2/settings` should be `/applications/app2/beta/settings` `/applications/app3?q=word` should be `/applications/app3/beta?q=word` I wrote this: `path = path.replace(/(\/applications\/(.*)(\/|\s|\?))/, '$1/beta');` But doesn't work if the app-name is in the end of the string. **Note:** I don't have the app name I only know that it follows `/applications/`
path.replace(/(\/applications\/[^/?]+)/g,'$1/beta'); After some consideration, I prefer the following: path.replace(/(\/applications\/[^/?]+)($|\/|\?)(?!beta)/g,'$1/beta$2'); "/applications/app1/beta" -> "/applications/app1/beta" "/applications/app1" -> "/applications/app1/beta" "/applications/app1/settings" -> "/applications/app1/beta/settings" "/applications/app1?q=123" -> "/applications/app1/beta?q=123" It will ignore `/applications/beta` when matching.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "javascript, regex" }
How to query logicblox I have an entity predicate eg. "Person" with related functional predicates storing attributes about the entity. Eg. Person(x), Person:id(x:s) -> string(s). Person:dateOfBirth[a] = b -> Person(a), datetime(b). Person:height[a] = b -> Person(a), decimal(b). Person:eyeColor[a] = b -> Person(a), string(b). Person:occupation[a] = b -> Person(a), string(b). What I would like to do is in the terminal, do the equivalent of the SQL query: SELECT id, dateOfBirth, eyeColor FROM Person I am aware of the print command to get the details of a single functional predicate, but I would like to get a combination of them. lb print /workspace 'Person:dateOfBirth'
You can use the "lb query" command to execute arbitrary logiql queries against your database. Effectively you create a temporary, anonymous, predicate with the results you want to see, and then a rule for populating that predicate using the logiql language. So in your case it would be something like: lb query <workspace> '_(id, dob, eye) <- Person(p), Person:id(p:id), Person:dateOfBirth[p] = dob, Person:eyeColor[p] = eye.'
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "sql, logicblox, logiql" }
Is there any way to check if the emails sent by my app are open? Hello I have developed an application that works with React.js and Node.js. I use AWS and SES (Simple Email Service) to send some emails. My question is whether there is any way I can keep track of emails sent and opened by my users to prevent them from qualifying me as spam or that my SES account health will decrease too much. I have seen that there are some browser extensions with which it marks the emails sent with a double tick if the user have read it, but I do not have a record such as in gmail. Has anyone encountered any similar problems? Is it possible via AWS or via Node to achieve this? Greetings and thanks in advance.
I agree with @Ravi's answer above - SES does provide notifications \- however in my experience the open notification is a lot less reliable than the delivered and bounce notifications. Tracking opens is difficult as browsers, popup blockers/security software and email clients themselves can disable/break features like read-receipts and tracking pixels in the name or privacy. The most reliable way of tracking opens is to have a clickable link in the email body (and a compelling reason for your user to click on it) and include a unique id in the URL that you can capture server-side.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "node.js, amazon web services, amazon ses" }
getting total without flat-rate from cart in magento How can i get total value in cart without flat rate? That means by using this code: $totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals(); $subtotal = $totals["subtotal"]->getValue(); i got each products sub total. So i used this code: $subtotal = $this->helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); now i got the total value that included the flat-rate also. for example: here i got 35 as total but this include 20 product price + 15 flat-rate. So i want to get only the total of all products price in carts. How can i get this?
you want to get the subtotal then Mage::getSingleton('checkout/cart')->getQuote()->getSubtotal(); don't be afraid to use xdebug and debugging sessions within your IDE to observe what values the variables have inside objects. Simplest way to see what you need is to dump variables to display like print_r(Mage::getSingleton('checkout/cart')->getQuote()->getData()); and just see which variable has the value you need.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "magento, cart, subtotal" }
What am i missing Set-DynamicDistributionGroup I am trying to apply dynamic distribution group recipient filter to take the country into account Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCore -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")} And i get the 'cannot be null' error, but the documentation says that only 'identity' is required, so i'm puzzled by this. > Cannot retrieve the dynamic parameters for the cmdlet. You cannot call a method on a null-valued expression. \+ CategoryInfo : InvalidArgument: (:) [Set-DynamicDistributionGroup], ParameterBindingException \+ FullyQualifiedErrorId : GetDynamicParametersException,Set-DynamicDistributionGroup
Its countryCode not CountryCore as written in your statement (looks like a typo). Try: Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCode -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")}
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "powershell, exchange server" }
eglot - javascript I am trying to set up eglot on ubuntu and emacs 26.1. I have installed version 1.4 When I run `M-x eglot` I get: [eglot] I guess you want to run `javascript-typescript-stdio', but I can't find `javascript-typescript-stdio' in PATH! However I can't find anything about it in the instructions. Does anybody know what I have to install to make it work. When I follow the link it takes me to a low level package that doesn't seem to correspond to an npm package.
In order to use `lsp` for javascript you have to install its corresponding `lsp-server` e.g. `javascript-typescript-langserver`. If you have `node` and `npm` already installed you can just install the package globally: npm install -g javascript-typescript-langserver If you don't have `node` already installed I suggest using `nvm`. NVM is a command line tool that lets you manage your node version. If you use it you can install different versions of node or control the exact version you want to use. If you don't want to use `nvm` you can download and install node from the official site.
stackexchange-emacs
{ "answer_score": 4, "question_score": 1, "tags": "javascript" }
Get Data between two different Date with MYSQL Table : (Employee) ![Data]( I need to get Data Between two Days I'm using the following query to get data between two dates SELECT * FROM employee WHERE Price ((DATE('2020-01-01') BETWEEN DATE(start_date) AND DATE(end_date)) OR (DATE('2020-01-03') BETWEEN DATE(start_date) AND DATE(end_date)) OR (DATE(start_date) >= DATE('2020-07-03')) AND DATE(end_date) <= DATE('2020-07-03')); I Got the following Result : ![REsult]( But I Expect the Following result ![excpect]( So, How can i get my expected result data in mysql
Your query seems to have nothing to do with your sample data. Based on your data, you seem to need to generate the dates. You can do this using a recursive CTE and then `join`: with recursive dates as ( select date('2020-01-01') as dte union all select dte + interval 1 day from dates where dte < date('2020-01-04') ) select d.dte, e.end_date, e.employeename from employee e join dates d on d.dte between e.start_date and e.end_date Here is a db<>fiddle.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql, database" }
Bitwise operator & giving unexpected result The & operator deals with the binary format of a decimal number. So `10 & 9 = 8` because 1010 (10) 1001 (9) ===== 1000 (8) This previous example runs fine. But when I try to do `010 & 010` I expect the result to be 10. However I get 8. Can anyone explain to me why this is happening ?
Because a number that starts with a `0` is considered as being octal, not binary. `10` is considered **decimal** , because it's default. So the `10 & 9 = 8` test is resolved in decimal. When it starts with a `0`, it's considered **octal**. So `010 & 010` is resolved in octal, as (in decimal): `8 & 8`. `0x` is considered as **hexadecimal**. And as `Oli Charlesworth` and `delnan` pointed out to me, there's no C standard for binary, although some compilers (such as GCC) consider `0b` as **binary** representation. Interesting info here: Writing binary number system in C code
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c, binary, bitwise operators" }
get driver for dell wireless card iam using laptop dell inspiron 15R 5537 ... using dell wireless card 1705 ... and wireless is not defined on any linux distro i tried (ubuntu , debian , elemetary OS luna , gentoo ) :( i searched google for it .. but i couldn't find any useful solution .. btw when it type ifconfig .. it displays lo and eth0 only .. and iwconfig no wireless driver ... and lspci it contain the network ethernet but no wireless defined
Then there is no driver for that card available. Perhaps a bleeding-edge distribution (rolling experimental release like Fedora's rawhide) has this enabled, or there is an experimental driver you can compile yourself. You might rummage in Linux wireless, perhaps there is something cooking there. I seem to remember Dell offered (offers?) some of it's machines with Linux preinstalled, perhaps you can find a driver there. As a workaround, there are some USB WiFi cards that do work with Linux (but check them out first, I've got one at home that worked fine but _only_ with open networks, any sort of encryption made it loose connection after a few minutes; should check how it goes now...).
stackexchange-unix
{ "answer_score": 0, "question_score": 0, "tags": "linux, wifi" }
format of sound data What is the low level actual format of sound data when read from a stream in Java? For example, use the following dataline with 44.1khz sample rate, 16 bit sample depth, 2 channels, signed data, bigEndian format. TargetDataLine tdLine = new TargetDataLine(new AudioFormat(44100,16,2,true,true)); I understand that it is sampling 44100 times a second and each sample is 16bits. What I don't understand is what the 16 bits, or each of the 16 bits, represent. Also, does each channel have its own 16bit sample?
I'll start with your last question first, yes, each channel has its own 16-bit sample for each of the 44100 samples each second. As for your first question, you have to know about the hardware inside of a speaker. There is a diaphragm and an electormagnet. The diaphragm is the big round part you can see if you take the cover off. When the electromagnet is charged it pulls or pushes a ferrous plate that is attached to the diaphragm, causing it to move. That movement becomes a sound. The value of each sample is how much electricity is sent to the speaker. So when a sample is zero, the diaphragm is at rest. When it is positive it is pushed one way and when it is negative, the other way. The larger the sample, the more the diaphragm is moved. If you graph all of the samples in your data, you would have a graph of the movement of the speaker over time.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, audio, recording, audioformat" }
'Try Code Review' flag There are several flagging options akin to the following: > Questions about general computing hardware and software are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. You may be able to get help on Super User. I frequently see new users ask questions that would fare well on Code Review, but really have no place on SO. Such questions get flagged and closed quickly with ill-fitting justification, and I worry that this might deter the new users from joining Stack Exchange in a more permanent capacity... the questions are often well constructed despite being off topic here. Have we considered plans to implement a similar flag option for Code Review if/when it finishes its beta?
Yes, Code Review is likely to be a migration target ( _belongs on another site_ ->) _when it comes out of Beta_ ; Tim Post (community manager) has already stated this: > However, I'll go out on a limb and say that we'll _very likely_ set this up once Code Review is set to graduate, possibly even before the design and such are ready. Of all the migration paths on the network, this is definitely one of the more obviously good ones. Manual (moderator-handled) migrations have been very successful so far, with 87 migrations and only 9% rejected in the past 90 days. This is on par with Cross Validated and Super User migrations, and only DBA saw more migrations. However, Beta sites cannot ever be part of that list, so we'll have to wait until that point.
stackexchange-meta_stackoverflow
{ "answer_score": 56, "question_score": 59, "tags": "discussion, flags, migration, codereview se" }
Is the hypothesis of $G$ being a finite group necessary in this exercise? I've been trying to solve an exercise for my Algebra class and even found this question asked already: Suppose $H$ is the only subgroup of order $o(H)$ in the finite group $G$. Prove that $H$ is a normal subgroup of $G$. Although, is the finiteness hypothesis a must for this exercise?
Suppose $H$ is the only subgroup of $G$ of order $|H|$. Fix an element $g \in G$ and let $K = gHg^{-1}$. Take $a,b \in K$. There exist $a' , b' \in H$ such that $a = ga'g^{-1}$ and $b = gb'g^{-1}$. Thus $$ ab = ga'g^{-1} gb' g^{-1} = ga'b'g^{-1} $$ which is an element of $K$ since $a'b' \in H$. Moreover, $e \in H$ since $H$ is a subgroup, so $$ e = geg^{-1} \in K $$ Thus, we have shown $K \leq G$. Now, consider the maps \begin{align} f &: H \to K \\\ &h \mapsto ghg^{-1} \\\ g &: K \to H\\\ &k \mapsto g^{-1}k g \end{align} I leave it to you to check that $g = f^{-1}$, which shows that $|H| = |K|$. By assumption, this means $H = K = gHg^{-1}$. Since $g \in G$ was arbitrary, this proves that $H$ is a normal subgroup of $G$. Notice that nowhere did we need to assume that $G$ was finite.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "abstract algebra, group theory, finite groups" }
Tensorflow, TRT models installation problem I installed `tf_trt_models` on Jetson-nano following the instructions here. I am getting the following error Installed /home/tarik-dev/.local/lib/python3.6/site-packages/slim-0.1-py3.6.egg Processing dependencies for slim==0.1 Finished processing dependencies for slim==0.1 ~/tf_trt_models Installing tf_trt_models /home/tarik-dev/tf_trt_models running install Checking .pth file support in /home/tarik-dev/.local/lib/python3.6/site-packages/ /home/tarik-dev/.virtualenvs/nanocv/bin/python -E -c pass TEST FAILED: /home/tarik-dev/.local/lib/python3.6/site-packages/ does NOT support .pth files bad install directory or PYTHONPATH
Found the solution. In the install script, because I am in virtualenv, I will need to remove `--user` Here is the install.sh script #!/bin/bash INSTALL_PROTOC=$PWD/scripts/install_protoc.sh MODELS_DIR=$PWD/third_party/models PYTHON=python if [ $# -eq 1 ]; then PYTHON=$1 fi echo $PYTHON # install protoc echo "Downloading protoc" source $INSTALL_PROTOC PROTOC=$PWD/data/protoc/bin/protoc # install tensorflow models git submodule update --init pushd $MODELS_DIR/research echo $PWD echo "Installing object detection library" echo $PROTOC $PROTOC object_detection/protos/*.proto --python_out=. $PYTHON setup.py install --user popd pushd $MODELS_DIR/research/slim echo $PWD echo "Installing slim library" $PYTHON setup.py install --user popd echo "Installing tf_trt_models" echo $PWD $PYTHON setup.py install --user
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "tensorflow, tensorrt, nvidia jetson nano" }
CK Editor, placeholder plugin & dynamic items For my needs, I need different set of placeholder items for different CKEditor instances. I have changed the dialogs\placeholder.js to select box. I am trying to add placeholder items via few different ways, but I am having no luck. My dream would be to add the the placeholders via the on page CKEditor call - CKEDITOR.replace ... **dialogs\placeholder.js** elements: [ // Dialog window UI elements. { id: 'name', type: 'select', style: 'width: 100%;', label: lang.name, items:[ ['CompanyName'], ['Address'], ['City'], ['State'], ['Zip'] ], Thanks in advance. <
I have figured it out. Edit the dialog page _and write bad (improper) code_ This is what worked for me. (ColdFusion) Change where the dialog points to (in my case from .JS to .CFM): CKEDITOR.dialog.add( 'placeholder', this.path + 'dialogs/placeholder.CFM' ); Open the /placeholder/dialogs/placeholder.js and save as placeholder.cfm On the top of cfm page: <cfquery datasource="data" name="query"> SELECT DISTINCT State FROM Addresses ORDER BY State</cfquery> In the middle: items:[ <cfoutput query="query"> ['#State#'], </cfoutput> ], **Do not add script tags or such, don't add anything else.** That's it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, ckeditor" }
How do I do a lot of ellipses with the while-loop and change the color grey from the middle to the outside a little brighter? How do I do a lot of ellipses with the while-loop and change the color grey from the middle to the outside a little brighter? I've tried a bit: size(200,200); background(255); float width-ellipse = 20; float height-ellipse = 20; while(w < 200)){ stroke(0); fill(125); ellipse(100,100,w,h); w = w + 20; w++; h = h + 20; h++; }
There probably is a better way to do this. However, this may work for you. Draw a darker smaller ellipse centered in the middle of the previous ellipse then repeat. Take a look here: < Also, your while loop has 2 closing "))" parenthesis. Try the following: void draw() { background(50); noStroke(); for (int p = 0; p < 500; p+=100) { for (int i = 1; i < 100; i++) { fill(float(150 - i)); ellipse(200, 100+p, 400-i*2, 120-(i*1.2)); } } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "processing" }
When is curl_global_init() necessary at all? Though its document says this function is MUST, but I saw two examples, one has it, the other doesn't. < < Is this function necessary at all?
If it is designed it will be necessary. The documentation says: > This function must be called at least once within a program (a program is all the code that shares a memory space) before the program calls any other function in libcurl. The environment it sets up is constant for the life of the program and is the same for every program, so multiple calls have the same effect as one call. But please note that in documentation of curl_easy_init: > If you did not already call curl_global_init(3), curl_easy_init(3) does it automatically. This may be lethal in multi-threaded cases, since curl_global_init(3) is not thread-safe, and it may result in resource problems because there is no corresponding cleanup.
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 18, "tags": "c, curl" }
Why does using css break tabset in Rmarkdown I have found that if I specify the css for a section then it breaks the `{.tabset}` for that section of the document. Please see the bellow example. Is there any way to stop this? --- title: "test" output: html_document --- <style type="text/css"> .mycontent{ } </style> # R Markdown Some text # Sets of working tabs {.tabset} ## Tab 1 ## Tab 2 # <div class="mycontent"> # Sets of broken tabs {.tabset} ## Tab 1 ## Tab 2 </div> The document: ![enter image description here](
You can custom specific sections with CSS chunk by adding ids or classes to section header, see 3.1.4.1 Custom CSS. Obviously, you can ignore the CSS style applied below. --- title: "test" output: html_document --- ```{css my-content, echo = FALSE} .mycontent{ float: right; color: blue; } ``` # R Markdown Some text # Sets of working tabs {.tabset} ## Tab 1 ## Tab 2 # Sets of broken tabs {.tabset .mycontent} ## Tab 1 ## Tab 2 ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, r markdown" }
Can I find all of a certain base model in App Engine? Given a class-like relationship: class A(db.Model): pass class B(A): pass Can I get all of the base class? The query: models.A.all().fetch(1) returns an empty list.
The datastore doesn't natively support this sort of polymorphism - but you can use the polymodel class to do this. Just inherit from PolyModel instead of Model and things will behave more or less as you expect them to.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, google app engine" }
Can't set Shotwell Photo Viewer as default XFCE4 I installed Ubuntu Minimal and installed XFCE4 as my choice of DE. After that, I installed Shotwell Photo Manager, but I can't set the Photo Viewer as my default for images. I can right click and "open with" Shotwell Photo Viewer, but when I go into properties and attempt to set Shotwell as the default, I get the Manager instead of the viewer. Any ideas?
I have Ubuntu 13.04, with XFCE4. Here is what I did. I don't know why its not working, but see what I did, just to be sure. I right click of the image, and choose Properties, and then changed the Open With to Shotwell. !enter image description here !enter image description here !enter image description here If that doesn't help, then do this. Right click on the image, choose Open With, and then Open with other Application. Once the new screen comes up, choose Shotwell, and make sure the you click on Use as default for this kind of file. !enter image description here !enter image description here
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 2, "tags": "default, shotwell, xfce4" }
What is the value of this expression > If $ \log_p q + \log_q r + \log_r p = 0 $ > > Then what is the value of, > > $$(\log_p q)^3 + (\log_q r)^3 + (\log_r p)^3$$ > > given that $p,q,r \neq 1$ > > A. It is odd prime > > B. It is even prime > > C. Odd composite > > D. Irrational I have tried using the identity that, if $ a + b + c = 0$, $a^3+b^3+c^3= 3abc$ , but it gives me the answer $0$.
**HINT** $x^3+y^3+z^3=3xyz$ when $x+y+z=0$. AND $\log_p q=\frac{\log q}{\log p}$, $\log_q r=\frac{\log r}{\log q}$, $\log_r p=\frac{\log p}{\log r}$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "logarithms" }
Filter and sum different columns in a numpy array I have a large numpy array `data` that I wish to filter by one column `[:,8] <= radius` and get the sum of a different column `[:,7]` So far I have the following which returns an "invalid slice" error. >>> data.slice (4700, 9) >>> np.sum(data[np.where(data[:,8] <= 50):,7]) IndexError: invalid slice I'm pretty new to python so really can't seem to figure out what I'm doing wrong here. Any thoughts or explanations would be appreciated.
There's no need for the `np.where` call. data = np.random.normal(size=(20, 2)) np.sum(data[data[:,0] < 0, 1]) In this example, I want the rows where `data[:,0] < 0` is `True`, and I want column `1`. So just slice with those and take the sum.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "python, arrays, numpy" }
What does this do in de.yml? date: <<: *datetime I've had a strange error where single characters appear instead of full weekday representations when utilizing the I18n.localize method. This answer clarified a lot, and helped me to inserted the correct translations. But other error messages about missing translations appeared until I removed the following: date: <<: *datetime time: <<: *datetime Do I need those though? What is their purpose?
Yes, you need this. It places `datetime` fragment to `date` and `time`. Here is an example: defaults: &defaults a: b c: <<: *defaults d: <<: *defaults is same as c: a: b d: c: b
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, internationalization, yaml" }
removing jRadioButton automatically in java I have a set of `JRadioButton`s placed inside a `JPanel`. Also I have a "delete" button, such that if a `JRadioButton` is selected and then this "delete" button is pressed, the `JRadioButton` should be deleted from the `JPanel`. I tried this following (action listener for the delete button) but it didn't work. // bg: buttonGroup private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int count = -1; for (Enumeration e=bg.getElements(); e.hasMoreElements(); ) { JRadioButton b = (JRadioButton)e.nextElement();count++; if (b.getModel() == bg.getSelection()) { bg.remove(b); jPanel1.remove(jPanel1.getComponent(count)); } } }
Did you call jPanel1.revalidate(); jPanel1.repaint(); after deleting?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, swing, removechild, jradiobutton, buttongroup" }
How to position topLevel() widget relative to root window? I have created a topLevel widget and was wondering if there was a way to position the new window relative to the root window.
Get `root` window position: x = root.winfo_x() y = root.winfo_y() Use `geometry` to set the position: w = toplevel.winfo_width() h = toplevel.winfo_height() toplevel.geometry("%dx%d+%d+%d" % (w, h, x + dx, y + dy)) where `dx` and `dy` are the offsets from the current position.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "python, python 3.x, tkinter" }
How to use a sub-query as value for inserting? I have a query like this: INSERT INTO table1(col1,col2,col4) VALUES (1, (select col1 from table2 where col2 = :param), 1); The above query works as well. Now I want to use two columns from `table2`, like this: INSERT INTO table1(col1,col2,col3,col4) VALUES (1, (select col1,col2 from table2 where col2 = :param), 1); But second query doesn't work, How can I fix it?
INSERT INTO table1(col1, col2, col3, col4) select 1, col1, col2, 1 from table2 where col2 = :param;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, insert, subquery" }
How often do MXLogic lists get updated? Some domain refused to accept email from my domain due to MXLogic filtering. I've sent an email to `[email protected]` and they responded promptly that they changed their records. Question: how long does it take for MXLogic subscriber to receive the updated filtering lists? Are they doing updates once an hour, a day or something like that?
MX Logic is now a McAfee SaaS service. As a cloud-based service, it should be updated for all of their subscribers as soon as McAfee makes the changes, give or take a few minutes. If you want an exact number, you can always contact McAfee and ask them.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "smtp, spam, spam filter, rbl" }
How to compare two lists and write the differences to a file? Python3 masterlist = ["subdomain.com", "subdomain2.com", "subdomain3.com", "subdomain4.com","subdomain5.com", "subdomain6.com"] originaldomains = ["subdomain.com", "subdomain2.com", "subdomain32.com", "subdomain43.com","subdomain55.com", "subdomain6.com"] Write differences from both lists into a file. # Combine these into a masterlist masterlist = list1 + list2 if os.path.exists('masterlist'): print('Overwriting masterlist') with open('masterlist', 'r') as f: originalsubs = f.readlines() I have masterlist as var1, and original subs as var2. I want write the differences (hopefully) in my same code block of my if statement? If possible?
The difference in lists can be quickly achieved using Python Sets. It's worth knowing how these work. masterlist = [ 'subdomain.com', 'subdomain2.com', 'subdomain3.com', 'subdomain4.com', 'subdomain5.com', 'subdomain6.com' ] originaldomains = [ 'subdomain.com', 'subdomain2.com', 'subdomain33.com', 'subdomain44.com', 'subdomain5.com', 'subdomain6.com' ] # get the differences master_set = set( masterlist ) original_set = set( originaldomains ) difference_set = master_set.symmetric_difference( original_set ) # write to a file fout = open( "diff.txt", "wt" ) for item in difference_set: fout.write( item + "\n" ) fout.close() I've purposefully not written this to a "finished homework assignment" standard. Please read the linked documentation, and use it to understand the code. Then write your own solution.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python 3.x, list, compare" }
Probability problem with sets Tv company receives 90 job application. Information about applicants: -------------------------------------------- | have bachelor | dont have bachelor | | (B) | (B) negation | --------------------------------------------- exp | 18 | 9 | (D) | | | --------------------------------------------- no exp | 36 | 27 | (D) | | | negation|------------|--------------------| Calculate probability for: `P(D/B) and P(B neg/ D neg )` answers: `P(D/B) => 1/3`, `P(B neg/ D neg ) => 3/7` I tried to do this-> D/B = D - DnB = 18+9 - 18 = 9 P(D/B) = 9/90 = 1/10 (wrong) and D/B = B - BnD = 54 - 18 = 36 P(D/B) = 36/90 = 4/10 (wrong) I have no idea where I am wrong. How to figure out the answer?
**Calculating P(D|B)** P(D|B): Probability, that a applicant has already experiences- given he/she has a Bachelor. You have $54(=18+36)$ applicants having a Bachelor. Now you read off the number of the applicants with a bachelor and experiences. The number is 18. Thus $P(D|B)=\frac{P(D \cap B)}{P(b)}=\frac{18}{54}=\frac{1}{3}$ The base is here all the applicants, who have a Bachelor. Now you calculate/read off, how many of them has experiences. If you have already a contingency table, then it is quiet easy.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability" }