INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
What is a typical directory path for webserver docroots?
Where would one typically store all the web pages and everything? | Depends on the distro/OS (and Webserver) but with Apache, it's usually /var/www/ (Debian/Ubuntu), /usr/local/www/ (FreeBSD), or depending on how/what you're doing, could also be in /home/user/htdocs|www|public_html. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 0,
"tags": "web server, unix"
} |
Is it possible to set path mappings with wildcards in Azure App Service?
Is it possible to configured wildcard path mapping in Azure portal? I don't want to specify all virtual paths that my frontend is using. `/*` you see on screen below doesn't work.
. Free modules are flat. QED | stackexchange-math | {
"answer_score": 6,
"question_score": 5,
"tags": "commutative algebra"
} |
Combine 2 object of same model Django
Is there any way to combine/merge 2+ objects of the same model to 1 with total values of all field.
I mean like `Author.objects.annotate(Sum('book__pages'))` but for all fields in model.
1 object - `{'user':2, 'events':20, 'time': 233}`
2 object - `{'user':2, 'events':10, 'time': 400}`
need total - `{'user':2, 'events':30, 'time': 633}`
thx | You can use `values()` and then `annotate()`.
MyModel.objects.values('user').annotate(
total_events=Sum('events'),
total_time=Sum('time'),
)
See the Django docs for more info. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "django, django models, django queryset, django annotate"
} |
Вызов скрипта с ключом -h или -help
Обыскал весь интернет, посмотрел в 2 книжках(одни магические слова), никак не могу понять как вызвать скрипт с этими ключами...Подскажите пожалуйста... | import getopt
import sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
print str(err) # print "option -a not recognized"
sys.exit(2)
for o, a in opts:
if o in ('-h', '--help'):
print """Usage: python scrypt.py [OPTION] ...
-h, --help display this help and exit
Report bugs to <[email protected]>
"""
sys.exit()
else:
assert False, 'unhandled option'
if __name__ == '__main__':
main()
Т.е. читать про getopt: | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python"
} |
How to escape from (END) in terminal for binding.pry
I'm stuck inside of a pry session.
There was a long list of text which I had to scroll through and now I can't seem to escape.
I have tried `ctrl + c` and `ctrl + v` and `esc` and `enter`. Nothing seems to work. | Try 'q', the binding for less. But it may depends on which default pager you use. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 7,
"tags": "ruby on rails"
} |
Is it possible to dump an Objects Properties and Methods?
Due to the lack of a class diagramm I need to explore the data structures by dumping objects to see what is in there.
How can I dump the Objects internals to the console?
In this snippet I tried to print the objects but I only get error messages 'TypeError'
def assignPose( plIdx ):
rig = bpy.data.objects.get("rig")
if rig != None:
print("rig=" + str(tuple( rig ))) # TypeError: 'Object' object is not iterable
print( "" + rig.__str__ ) # TypeError: Can't convert 'method-wrapper' object to str implicitly
pl = rig.pose_library
pl.poselib_apply_pose( plIdx )
else:
print("couldn't find rig.") | I found a solution to get started:
def dump(obj):
for attr in dir(obj):
if hasattr( obj, attr ):
print( "obj.%s = %s" % (attr, getattr(obj, attr)))
This is based on one of the methods suggested on this Stackoverflow post and this
Instead of invoking `print` call `dump( anyobject )`
This would print something like:
...
obj.copy = <bpy_func Object.copy()>
obj.cycles_visibility = <bpy_struct, CyclesVisibilitySettings("")>
obj.data = <bpy_struct, Armature("rig")>
obj.delta_location = <Vector (0.0000, 0.0000, 0.0000)>
obj.delta_rotation_euler = <Euler (x=0.0000, y=0.0000, z=0.0000), order='XYZ'>
obj.delta_rotation_quaternion = <Quaternion (w=1.0000, x=0.0000, y=0.0000, z=0.0
000)>
obj.delta_scale = <Vector (1.0000, 1.0000, 1.0000)>
obj.dimensions = <Vector (0.0000, 0.0000, 0.0000)>
obj.draw_bounds_type = BOX
obj.draw_type = WIRE
obj.dupli_faces_scale = 1.0
... | stackexchange-blender | {
"answer_score": 17,
"question_score": 15,
"tags": "python"
} |
Английский vs Russian - как правильно?
Здравствуйте гуманитарии.
Возник вопрос, реализовал систему, а как правильно назвать не сильно знаю.
Сам вопрос - как правильно в русском языке будет написать:
1\. онлайн консультация или online консультация?
2\. оффлайн версия или offline версия? | Согласно Орфографическому словарю правильно:
онлайн-консультация, офлайн-версия. | stackexchange-rus | {
"answer_score": 4,
"question_score": 1,
"tags": "иноязычная лексика"
} |
How to create a fixed vertical navigation?
Here's an example. < As you can see, their shipping methods are rotated and are on both ends of each side. This is what I did:
.vertical{
transform: rotate(90deg);
transform-origin: left top 0;
position: fixed;
}
However I'm using Foundation, so things get a little wacky when I scale the screen down. I just want a simple vertical text in one line, that is fixed in the middle right side of the screen.
` \+ `translate()` for it.
**jsFiddle**
.vertical {
list-style: none;
padding: 0;
margin: 0;
transform: rotate(90deg) translate(50%, 0);
transform-origin: top right;
position: fixed;
top: 50%;
right: 0;
}
.vertical li:first-child {
border: 1px solid;
}
<ul class="vertical">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "html, css"
} |
Typesetting "Na(+)/Cl(-)-dependent"
\documentclass[border=20pt]{standalone}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\begin{document}
Na\textsuperscript{+}/Cl\textsuperscript{-}-dependent
\end{document}
 for the chemical formulas and `\negthinspace` for filling the hole. Such “visual” adjustment cannot generally be taken care of automatically, because they depend on relative shapes of the symbols next to each other.
\documentclass[border=20pt]{standalone}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{chemformula}
\begin{document}
\ch{Na+}\negthinspace/\ch{Cl-}-dependent
\end{document}
. And you can just write everything in one chain $$ \frac{a}{b}<\frac{c}{d}< 2c. $$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "inequality"
} |
Determining which shape is being hovered over - Java
So I have 3 rectangles drawn on my JPanel that are acting as buttons, and what I would like to do is when the mouse is hovered over one of them, the Jpanel will repaint, and change the color of only that rectangle to red.
The only way I can think to do it is to have 3 separate variables that determines if the mouse is over each component. Then there would be code in the repaint method that, if rect1hover is true, then draw using g.setColor to red.
@Override
public void mouseMoved(MouseEvent e) {
if(rect1.contains(e.getX(), e.getY())){
rect1hover = true;
}
}
But this seems really inefficient. Is there a better way to do this? | Sure. Put your drawn rectangles in a `List`. Then you can write this code.
@Override
public void mouseMoved(MouseEvent e) {
for (DrawnRectangle r : rectangles) {
if (r.contains(e.getX(), e.getY())){
r.setHoverBackground();
}
}
}
You'll have to create a `DrawnRectangle` class with a `setHoverBackground` method. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, swing, hover, paint, highlight"
} |
Fast Fourier transform in MATLAB
I have found a bit of code in MATLAB:
y = fft(y, nfft);
Where y is a 512x443 two-dimensional array and nfft = 512.
I thought that _fft_ is for a one-dimensional array and for a two-dimensional array there should be fft2, but fft is working. How is that possible? | From the documentation (emphasis mine):
> Y = fft(x) returns the discrete Fourier transform (DFT) of vector x, computed with a fast Fourier transform (FFT) algorithm.
>
> If the input X is a matrix, Y = fft(X) returns _the Fourier transform of each column_ of the matrix. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "matlab"
} |
Django: I have extended group model, how to make queries to get field value?
I have extended the group model as the following:
class MyGroup(ProfileGroup):
mobile = models.CharField(max_length = 15)
email = models.CharField(max_length = 15)
c_annotates = models.ManyToManyField(Annotation, verbose_name=_('annotation'), blank=True, null=True)
c_locations = models.ManyToManyField(Location, verbose_name=_('locations'), blank=True, null=True)
date_begin = models.DateField(verbose_name=_('date begin'), auto_now=False, auto_now_add=False)
date_end = models.DateField(verbose_name=_('date end'), auto_now=False, auto_now_add=False)
Now the group in database has new attributes like date_begin and date_end. Now I am wondering how can I get the value of date_begin and date_end in the views.py from the corresponding entry of the database? Thanks. | You can query the database to get the model you want:
obj = MyGroup.objects.get(id=...)
After that you can access the values (as they are in the database) by doing:
date_begin = obj.date_begin
date_end = obj.date_end | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, django, django models"
} |
Why does Stata return “unknown function +inrange()”?
I am studying Stata programming with the book _An Introduction to Stata Programming, Second Edition_.
In chapter 4 there is code to `generate` a variable that tests whether some other variables satisfy a logical condition, the code is like:
foreach v of varlist child1-child12{
local n_school "`n_school' + inrange(`v', 1, 5)"
}
gen n_school = `n_school'
When I change this code to suit my own data,
foreach v of varlist qp605_s_1-qp605_s_5 {
local n_med "`n_med' + inrange(`v', 1, 5)"
}
gen n_med = `n_med'
where `qp605_s_1`'s values range from 1 to 17, then Stata returns:
. foreach v of varlist qp605_s_1-qp605_s_5 {
2. local n_med "`n_med' + inrange(`v', 1, 5)"
3. }
. gen n_med = `n_med'
unknown function +inrange()
r(133);
Any ideas what is wrong with this code? | Here is another approach.
* Example generated by -dataex-. For more info, type help dataex
clear
input float(var1 var2)
1 5
2 6
3 7
4 8
end
gen wanted = .
mata :
data = st_data(., "var*")
st_store(., "wanted", rowsum(data :>= 1 :& data :<= 5))
end
list
+----------------------+
| var1 var2 wanted |
|----------------------|
1. | 1 5 2 |
2. | 2 6 1 |
3. | 3 7 1 |
4. | 4 8 1 |
+----------------------+ | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "stata, local, stata macros"
} |
Can I set the scaleFactor of an UIView when I want my drawing code in -drawRect to not waste too much memory?
I am drawing something into -drawRect of an UIView, and in this case I really want a certain amount of pixels. With the retina display, my view has a scaleFactor of 2.0 and when I draw something that is supposed to be 10 pixels heigh, it's actually 20 heigh. Is it okay to set the scale factor back to 1.0 to get a 1:1 mapping between points and pixels? | The official documentation says it's ok.
See 'Accounting for Scale Factors in Core Animation Layers' in 'iOS Application Programming Guide' for details. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "iphone, cocoa touch, uikit, core graphics, retina display"
} |
に usage and meaning in 旅行代金の請求書の控えを2枚目に送った
2 **** This here, what does it mean.
Here's the context (The question doesn't appear in picture below)

I'm trying to archive a build so it will get sent to Fabric. I'm pretty sure Fabric is installed correctly so that's not my concern. I have been searching online but really haven't found anything. Here's the full error
2015-08-25 13:11:09.959 run[26550:11059125] Fabric.framework/run 1.3.16
/Users/Lee/Library/Developer/Xcode/DerivedData/Lista-dhwaxiksyxxmbaceoefmiorzjzal/Build/Intermediates/ArchiveIntermediates/Lista/IntermediateBuildFilesPath/Lista.build/Release-iphoneos/Lista.build/Script-FF08409C1B0A90E700BFB8AD.sh:
line 3: 97f760e8cb7dfcfb21897fa3255a4f21a9b2be11b72ac6b6f94b28a3df41d165: command not found
Command /bin/sh failed with exit code 127
Any ideas?? I'm desperate at this point.
Here's what's in that file:
#!/bin/sh
./Fabric.framework/run 0e8d9569f0d4e9a7da32002c77b2c04a90e56082
97f760e8cb7dfcfb21897fa3255a4f21a9b2be11b72ac6b6f94b28a3df41d165 | There may be some changes in your Fabric framework, try to remove the Run script which you have added in you Build Phases, then integrate the Fabric framework again in your project. Removing the Run script will remove this error.The add the script again so the Fabric will work in your app. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, heroku, twitter fabric"
} |
Why they use Bitwise XOR operator in the XOR-Shift algorithm?
Why the Bitwise XOR operator is used in the XOR-Shift algorithm (Uses to generate random numbers) instead of others Bitwise operations like OR, AND.. etc? | XOR is the only bitwise operator, that can toggle bits from 0 to 1, or 1 to 0. This is essential in any feedback operator, that is supposed to generate a non-monotonic function and specifically to generate a periodic function, so that f(n+N) = f(n), for some N.
E.g. adding bits would generate non-periodic simple sequences:
0, 1, 11, 111, 1111, 11111, ... until all bits are filled or 0, 10, 1010, 101010, 10101010, ...
Anding bits would have the opposite effect, where the starting value should be all bits set:
1111111...1, ..., 1111, 111, 11, 1, 0
In mathematical sense the first sequences are purely growing and the last sequence is diminishing, none of which produce even a seemingly random sequences. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "algorithm, bit manipulation, operators"
} |
Needle Hotend for nonplanar printing
To minimize retractions and travel when printing several objects, some slicers produce gcode for sequential deposition when each object is built in a traditional manner bottom up layer by layer before starting a new object. Of course, there are limitations caused by the hotend geometry  we might even do things like spiralizing contours of a single object. This has also potential for other tricks like producing interlacing layers for better layer bonding etc. I wasn't able to find any ongoing work on minimal geometry hotends. Any links? And what might be the challenges in making one? heatblocks and heating cartridges are out of the question but nichrome wire and a fast PID heat controller might do the job. | The site is not well-suited to crowd-sourced invention, but the drawbacks to your suggestion are (I think) on topic.
The hotend has two main tasks. Accurate control of extrusion, and maintaining the desired volumetric melt rate. One factor which influences extrusion quality is the size of the melt-zone - generally, you want this to be as small as possible because rigid filament is easier to extrude/retract without ooze/stringing. Equally, the melt zone needs to be provided with a thermal mass (physical or virtual) to stabilize its temperature under extrusion.
Whilst it might be feasible to prototype your concept quite easily, it is likely to be expensive in volume - and there is no great direct advantage. So this is a concept which might enable an area of research but it doesn't look like a development objective with its own intrinsic value. | stackexchange-3dprinting | {
"answer_score": 5,
"question_score": 4,
"tags": "hotend, fdm"
} |
Typescript interface - index signature inconsistency
If I declare an interface in Typescript with a single named property and an index signature, my assumption is that the index signature allows me to add properties to the object without syntax errors.
interface Fruit {
colour: string;
[otherProperties: string]: any;
}
This works when I add the properties on declaration so the following compiles OK:
let apple: Fruit = {
colour: 'green',
haveToPeel: false
}
but if I extend after creation
let banana: Fruit;
banana.colour = 'yellow';
banana.haveToPeel = true;
then I get a TS error
> "[ts] Property 'haveToPeel' does not exist on type 'Fruit'."
I've read around on index signatures but can't get to the bottom of how I allow my objects to be extended dynamically after creation without a TS compile error. | This is expected behavior.
To use the index signature you need to use the index syntax -- or use the literal assignment which you demonstrate works.
let banana: Fruit;
banana.colour = 'yellow';
banana['haveToPeel'] = true; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "typescript"
} |
Everytime I try to change the default version of my terminal, VSCode opens up instead
When i am trying to change the default terminal on my windows 11 laptop, the terminal opens up VSCode for some reason. I open the windows terminal, hit settings then VSCode opens up with this settings.json page:
VSCode settings.json
But the thing is I want to have the terminal settings open up, not VSCode. I am trying to change my default terminal from windows terminal to Ubuntu. | What version of Windows Terminal are you using? The settings UI for the Terminal was added in 1.7 (IIRC), and I believe the version that originally shipped with Windows 11 was 1.6. Before 1.7, clicking on "settings" would open the `settings.json` file in whatever your default `.json` editor was.
Future readers: If you're hitting this too, make sure to update your Terminal from the Store. Anything >=1.7 should have the Settings UI. At the time of this post, the latest Stable version in the store was 1.12. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "visual studio code, terminal, windows terminal"
} |
Instability of a system subject to periodic perturbation (cont'd)
This is a follow-up to this question.
Consider the following 2-dimensional system $$ \dot{x}(t) = A(t)x(t) \quad x(0)\in\mathbb{R}^2, $$ where $A(t)$ is a 2-dimensional time-varying matrix. Suppose that the origin of the above system is an **unstable** equilibrium.
Now consider the following "perturbed" system $$ \dot{z}(t) = (A(t)+\delta(t)C)z(t) \quad z(0)\in\mathbb{R}^2, $$ where $C$ is a constant $2\times 2$ matrix and $\delta(t)$ is a **zero-mean periodic** function of $t$.
> **_My question:_** Is the origin of the "perturbed" system **unstable** for every choice of $C$ and $\delta(t)$ as above?
As in my previous question, my feeling is that the answer is in the negative; finding an explicit counterexample does not seem easy though. | The answer would be no, namely a known counter example would be a Kapitza pendulum. This is an inverted pendulum whose base is oscillating vertically. When linearizing at the origin the dynamics can be written as
$$ \begin{bmatrix} \dot{\theta} \\\ \ddot{\theta} \end{bmatrix} = \left( \begin{bmatrix} 0 & 1 \\\ \alpha & -\beta \end{bmatrix} + \sin(\omega\,t) \begin{bmatrix} 0 & 0 \\\ \gamma & 0 \end{bmatrix} \right) \begin{bmatrix} \theta \\\ \dot{\theta} \end{bmatrix}, $$
where $\alpha,\beta>0$ thus $A(t)$, while actually not time varying, is unstable. For certain choices for $\omega$ and $\gamma$ this system can be made stable. For example the system is stable%2B0.2\)*x-x%27) when using $\beta=\omega=\gamma=1$ and $\alpha=0.2$. | stackexchange-math | {
"answer_score": 4,
"question_score": 2,
"tags": "ordinary differential equations, analysis, dynamical systems, control theory, stability theory"
} |
regex to match several string in Python
I have questions with regex in Python.
Possible variations can be
10 hours, 12 weeks or 7 business days.
I want to have my regex something like
string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
so that I expect to find "7 business day" and "12 weeks" but it returns None | string = "I have an 7 business day trip and 12 weeks vacation."
print re.findall(r'\d+\s(?:business\s)?(?:hour|week|day)s?', string)
['7 business day', '12 weeks']
\d+\s(?:business\s)?(?:hour|week|day)s?
Debuggex Demo
The demo should explain how this works. The reason yours wasn't is because it was looking for `7 businessdays` which doesn't match.
Although if you don't want to accept `business week/hour`, you'll need to modify it further:
\d+\s(?:hour|week|(?:business )?day)s?
Debuggex Demo | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, regex"
} |
How to calculate a definite integral with complex numbers involved?
I'm trying to calculate this integral, and I find it difficult when coping with complex numbers.
$$ f(k) = \int_{lnK}^{\infty} e^{ikx} (e^{x}-K) dx =(\frac{e^{(ik+1)x}}{ik+1}-K\frac{e^{ikx}}{ik})|_{x=lnK}^{x=\infty} $$
k is a complex number, Im k>1
and this equation should be equal to $$ -\frac{K^{1+ik}}{k^2-ik} $$ which means the result of the upper limit is 0.
What I cannot understand is that when an infinity multiplied by a complex number, is it still an infinity? It seems like a weird question, and I'm not sure whether I make myself understood. I mean, since exp(-infinity)=0, is exp(a complex number *-infinity) still equals to zero?
Many thanks! | If $k=\alpha+i\beta$ with $\beta>1$ then $$\left|e^{(ik+1)x}\right|=\left|e^{i\alpha x}\>e^{(1-\beta) x}\right|= \bigl|e^{(1-\beta) x}\bigr|\to0\qquad(x\to\infty)\ .$$ It follows that the improper integral $$\int_a^\infty e^{(ik+1)x}\>dx:=\lim_{b\to\infty}\int_a^b e^{(ik+1)x}\>dx\tag{1}$$ is convergent, and there is no "multiplication with $\infty$" happening. Just compute the $\int_a^b$ on the RHS of $(1)$ the ordinary way, and you will see that the $\lim_{b\to\infty}$ of this integral exists. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "integration, definite integrals, complex numbers, exponential function, exponentiation"
} |
Return a Task instead of awaiting the inner method call
I see some colleague code where he chooses to not await the database call and just return the Task. E.g.
public Task<UpdateResult> AddActivityAsync(ClaimsPrincipal principal, Activity activity)
{
return _userManager.SaveToDatabaseAsync(principal, activity);
}
as `_userManager.SaveToDatabaseAsync` is async, I would have implemented this way
public async Task<UpdateResult> AddActivityAsync(ClaimsPrincipal principal,
Activity activity)
{
return await _userManager.SaveToDatabaseAsync(principal, activity);
}
The calling method of this method always await it:
await _profile.AddActivityAsync(..., ...)
Is there any benefit to not make the inner method async and just return the Task, letting the caller await it ? I thought we had to write Async all the way down... | You do not need to await a method which returns a `Task<T>`, the code will just run asynchronously if you have the `async` keyword on the method. You colleague has removed that and so is running synchronously deliberately and lets the calling code implement it if they so choose.
It depends at which layer this code is being run. If it is deep it may be better to let the higher code layers choose ansynchronous execution and maintain control there.
You definitely don't need to 'write async all the way down'. The purpose of the `async` keyword is simply to mark a method as being able to return a `Task<T>` and be able to use the `await` keyword. The `await` keyword is what invokes the framework to execute the Task and provide asynchronous processing.
TL;DR: It's a choice.
_I welcome anyone improving or correcting me on this as I am no guru._ | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 6,
"tags": "c#, asynchronous, async await, task"
} |
How to use bootstrap for text in html.erb
It can be a pretty stupid question. I stylized menu by using bootstrap, but in my navbar I want to add a text, but when I add text it complitly move up. And what i want to ask is "How can i add bootstrap-sass styling to text?"
This is part of code what I need to style:
<% if user_signed_in? %>
<li>Hello, <%= current_user.email %></li>
This is bootstrap styling what I've used:
<li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>
And screenshot, how it looks:
?
Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar
I believe your issues stem from inconsistent line-heights combined with vertical-align issues. You may just have to add your own CSS to override the Bootstrap defaults. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, css, ruby on rails, twitter bootstrap"
} |
Analytics in Jobs seems broken
I have a feeling there's some analytics data that is going unrecorded in the new 'Jobs' section. Screenshot from a Windows 10 machine running Chrome 47. I'm able to reproduce the errors in Firefox as well.
 | stackexchange-meta_stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "bug, status completed, stack overflow jobs"
} |
When is a Sylow $p$-subgroup normal?
Let $A_5$ be the alternating group of degree 5. I would like to prove that the number $s_5$ of Sylow 5-subgroups of $A_5$ ist 6. With $|A_5| = \frac{5!}{2} = 60 = 5 \cdot 12$ and the Sylow theorems I get that 12 is a multiple of $s_5$ and $s_5 = 1 + 5k$ with $k \in \mathbb{N}_0$. Therefore $s_5 \in \\{1,6\\}$. I could exclude the case $s_5 = 1$ by finding at least two Sylow 5-subgroups of $A_5$, but it is enough to show that a Sylow 5-subgroup of $A_5$ is not normal. Unfortunately, I don't see how this is apparent.
1. How can be shown that a Sylow 5-subgroup of $A_5$ is not normal?
2. How does the answer for (1) generalize for groups other than $A_5$? | 1. elements of $A_5$ are totally explicit. 5-Sylow are cyclic of order $5$ , generated by a $5$-cycle. So, pick for example $s=(1 \ 2 \ 3 \ 4 \ 5)$ . I am pretty sure that if you pick a random element $t$ of $A_5$, $tst^{-1}$ won't be a power of $s$.
2. You cannot expect a general reasonable answer( except the trivial one: given a subgroup $H$ of $G$, compute $gHg^{-1}$ ofr all $g\in G$ and see if it is contained in $H$. Of course you can use generators of $H$ and/or $G$ to reduce to a small number of verifications, but still...)
To prove my point: any group $G$ with odd order has a non trivial normal subgroup. I really doubt that if I give you a group $G$ of huge odd order and a subgroup $H$, you will be able to decide if $H$ is normal or not.
Proving that a given group does or does not have a nontrivial normal subgroup is difficult. For example, the classification of finite simple groups took decades of efforts, and involves extremely difficult mathematics. | stackexchange-math | {
"answer_score": 4,
"question_score": 1,
"tags": "abstract algebra, group theory, normal subgroups, sylow theory"
} |
In what ways is the NFT marketplace different from the stock market?
Non-fungible tokens (NFTs) are all the rage. Creators can create works for digital art (and other types of digital assets) and sell them online. The sales occur on a cryptocurrency exchange like Bitcoin or Ethereum.
It has been compared to a stock market, where people speculate on assets with the express goal of reselling the asset and pocketing the difference.
But stocks are backed by companies, and the stocks themselves pay dividends to their owners. From what I understand this is not the case with NFTs. This means the only goal with NFTs is resell what you purchase to pocket the difference.
Am I missing something? Can buyers also attempt to monetize their NFT by licensing it out, like an icon or logo? | NFTs provide artificial scarcity in a market where the assets can be perfectly duplicated.
Consider an original oil painting. It is virtually impossible to _perfectly_ duplicate one, down to the brush strokes and amount and type of paint used at each point. As such, it's easy* to tell who owns the original and who owns a mere "reproduction".
A digital asset, though, can be duplicated perfectly, since the asset _is_ the description of the asset. Buying an NFT essentially amounts to a cryptographically signed record that _you_ bought it, not someone else.
And just like the oil painting, owing the original provides little more benefit than the right to say you own the original. Only time will tell if we, as a society, decide that distinction is worth paying for.
* * *
* Good forgeries exist, but given enough effort they can usually be identified. | stackexchange-money | {
"answer_score": 7,
"question_score": 2,
"tags": "stock markets, markets, non fungible tokens"
} |
JavaDoc: @link to MyClass.class
Is there correct JavaDoc syntax for `{@link Foo.class}`? Neither this, nor `{@link Foo#class}` works. Or is this not possible?
Let me expand a bit:
I have a function `registerException(Class<? extends Exception> exceptionClass)` that get's called with things like `registerException(IOException.class)` and started writing the following JavaDoc for it:
/**
* Registers a new {@link Class Class<? extends Exception>}
* (e.g. <code>IOException.class</code>} that can be flattened by this handler.
*
* @param exceptionClass - the exception class
*/
and I was thinking whether I could place a `{@link ...}` around `IOException.class`. | The .class is not needed (and apparently doesn't work).
As noted in a comment, {@link IOException IOException.class} should create a link with an appropriate text label. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "java, javadoc"
} |
Cryptsharp C# Visual Studio 2022 no definition
I've tried to run
string cryptedPassword = Crypter.MD5.Crypt(Passwort, new CrypterOptions()
{
{CrypterOption.Variant, MD5CrypterVariant.Apache}
});
from the cryptsharp documentation
But I don't seem to be able to run it.
`Passwort` is a random 5 char string
I have this code:
using System; using CryptSharp;
using System.IO;
using System.Security.Cryptography;
but keep running into errors:
> Crypter has no definition for MD5
> MD5CrypterVariant not available
What am I missing ?
Thanks in advance | If you want to use MD5 crypt algorithms, we need to install the following NuGet packages. <
 {
cout << i << " ";
} | Вы не этого хотите?...
int num = 0;
for (char i : test1)
{
cout << i;
if (++num == 4)
{
cout << " ";
num = 0;
}
} | stackexchange-ru_stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "c++, строки, вывод"
} |
Intersection of two cell arrays of strings in MATLAB
I have two cell arrays, X and Y. Each cell array is made up of strings : i.e, X{i} is a string for all i, and so is Y{i}. I would like to find the intersection of the two cell arrays, (presumably a third cell array} that has the strings common to both X and Y. | There might a single function that does this - I don't remember. But you can do it pretty easily with `ismember`:
a = {'a', 'b', 'c'};
b = {'b', 'd', 'a'};
intersection = a(ismember(a, b)); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "matlab, cell, intersection"
} |
Email address search by last name in Thunderbird 7
When I compose an email and enter the email address, if I enter the recipient's first name, Thunderbird automatically finds the recipient's email address from my address book. However, if I enter the recipient's last name, middle name, or any other name included in the address book, it does not deliver anything. For example, the email address of `Elizabeth Liz Smith` can be only found by `Elizabeth`, not others. If the name is saved as `Smith, Elizabeth`, then it is only searchable by `Smith`. That means, whatever comes first in the address book.
On the other hand, in Gmail, I can search by any name. Interestingly, in the address book of Thunderbird, I can search by any name.
Is there any workaround to enable the 'search-by-any-name' in the Thunderbird's composition window? | I answer my question. Thanks Andrei Drynov for the important help.
I have used Zindus do sync the Thunderbird address book with Google Contacts. Zindus, unfortunately, sync only DisplayName, and does not sync First Name and Last Name.
Using other add-ons, like Google Contacts or gContactSync, I was able to search by any name. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "thunderbird"
} |
Spring 20 - Validation rules that use "$UserRole.DeveloperName" are triggering when they should not
After the Spring 20 release my validation rules that make use of the field "$UserRole.DeveloperName" are triggering when they should not.
I'm currently trying to create a case from a community (with a Customer Community User), through a flow, and I keep receiving the same error of FIELD_CUSTOM_VALIDATION_EXCEPTION, because the field "$UserRole.DeveloperName" could not be accessed.
When I deactivate all the rules that make use of this field reference, the flow works right. I know that the problem is not the validation rules, because I've tested all the situations on last Friday (03/01) and it was working perfectly, and today (06/01) the org was updated, and nothing is working anymore.
Is anyone else facing the same issue? How to get through it? I need those validation rules, so keeping them deactivated is not really an option. | This could be an issue due to the Spring 20 Security update.
This is documented here
As per the update
> Access to user roles is available for users with the View Roles and Role Hierarchy permission. Editing user roles is available for users with the Manage Roles permission.
So your rule might be breaking due to it.
One solution i can think of is you might need to switch to custom permissions due to this update if these permissions are not available for community users | stackexchange-salesforce | {
"answer_score": 3,
"question_score": 5,
"tags": "case, validation rule, bug, spring 20"
} |
Error: Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-6-sun-1.6.0.26/lib/tools.jar
I am trying to build jasperserver on linux. It uses ant and maven. While executing the ant command it gives this exception. I checked on the same path however the lib folder is not there at the same path. How can I resolve this issue?
Thanks!! | tools.jar is present only in jdk, not jre. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 5,
"tags": "maven, ant, java, jasperserver"
} |
defaultdict(None)
I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example:
states = defaultdict(None)
if new_state_1 != states["State 1"]:
dispatch_transition()
I would have thought that states["State 1"] would return the value None and that if new_state is a bool that I would have gotten False for **new_state != states["State 1"]** , but instead I get a KeyError.
What am i doing wrong?
Thanks,
Barry | `defaultdict` requires a callable as argument that provides the default-value when invoked without arguments. `None` is not callable. What you want is this:
defaultdict(lambda: None) | stackexchange-stackoverflow | {
"answer_score": 121,
"question_score": 58,
"tags": "python"
} |
Animating :after in css
Im trying to figure out why this simple code isn't working.
<
@keyframes testing {
from: {font-size: 42px;}
to: {font-size: 64px;}
}
a:after {
content: "Hello!";
animation: testing 1s infinite;
}
-
<a></a>
Can anyone explain? | Remove `:` from the keyframe like this
@keyframes testing {
from {
font-size: 42px;
}
to {
font-size: 64px;
}
}
a {
}
@keyframes testing {
from {
font-size: 42px;
}
to {
font-size: 64px;
}
}
a:after {
content:"Hello!";
animation: testing 3s infinite;
}
<a></a> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "css"
} |
How to install tomcat on aws ec2 instance with ubuntu
I've install Tomcat 6 on an AWS EC2 instance with Ubuntu. I've followed these steps:
1. `sudo apt-get install tomcat6 tomcat6-admin`
2. `sudo /etc/init.d/tomcat6 restart`
3. `sudo gedit /etc/tomcat6/tomcat-users.xml`
4. `sudo /etc/init.d/tomcat6 restart`
but when I put the public DNS of my instance in the navigator ( it doesn't find anything. | I'd forgotten to install jdk 1.6 before | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "tomcat, ubuntu, amazon ec2, installation"
} |
Simple OLS $\beta_1$ Formula?
Reviewing my econometrics books and was just confused by the following derivation:
We use the fact that $\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)\left(y_{i}-\bar{y}\right)=\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right) y_{i}$ to write the OLS slope estimator equation as $$ \hat{\beta}_{1}=\frac{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right) y_{i}}{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2}} $$
I don't believe I've ever seen the above formula written that way. I don't understand how that fact above is the case, or how the formula is the same as the general $\hat\beta$ below? $$ \hat{\beta}_{1}=\frac{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)\left(y_{i}-\bar{y}\right)}{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2}} $$ | $$ \sum_{i=1}^n (x_i - \bar{x})( y_i - \bar{y} ) = \sum_{i=1}^n (x_i - \bar{x} ) y_i - \sum_{i=1}^n (x_i - \bar{x} ) \bar{y} = \sum_{i=1}^n (x_i - \bar{x} ) y_i - \bar{y} ( n\bar{x} - n \bar{x}) = \sum_{i=1}^n (x_i - \bar{x} ) y_i $$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "statistics, regression"
} |
Configure sender address for all users in mutt
I have CentOS running mutt. When mails are sent from mutt (via a shell script), it takes the current user name as sender address causing it to go into the spam.
I receive mail as
From: tech
What I need is:
From: [email protected]
All I need is a single place change that reflects everwhere. i.e. if I send from the root user, the from address should be `[email protected]`. | Do you have a system-wide mutt RC file? Perhaps it is here: `/etc/mutt/Muttrc`? Within the file, set the hostname with `set hostname=myserver.com`. | stackexchange-unix | {
"answer_score": 1,
"question_score": 1,
"tags": "email, mutt"
} |
How to transform a PostGIS bounding box?
I need to query the bounding box of a table (in WGS 84, srid 4326), and transform it to Web Mercator to be consumed by an OpenLayers map.
Currently, I am using this to retrieve the bounding box:
SELECT ST_Extent(geom) FROM mytable
Which returns the string `"BOX(2067507.49369776 650368.674310103,2095742.80207396 691604.021270793)"`. I have tried a variety of ways to transform this, but none have worked.
Transforming the geometry before getting the extent doesn't work:
SELECT ST_Extent(ST_Transform(geom, 3857)) FROM mytable
It returns:
ERROR: transform: couldn't project point (2.0841e+06 678457 0): latitude or longitude exceeded limits (-14)
Does anyone know what would be causing this error? | That coordinate set isn't in SRID 4326. If it was in 4326, it would look like a longitude / latitude pair. The error is telling you whats wrong - its expecting something in the range [-180...180, -90...90].
You need to figure out what the real source SRID is. | stackexchange-gis | {
"answer_score": 7,
"question_score": 0,
"tags": "postgis, coordinate system, extents"
} |
Perl checking if network interface is up (linux)
everyone, I am currently working on a script in perl to check if certain interface is up.
I have tried different methods in linux I tried reading /proc/net/dev which did work but in my if statement I had it compare against eth1 and it always said eth1 was up even though it was not in /proc/net/dev the interface will only be in there is it was up (I have a usb ethernet adapter and wasn't even plugged in)
At the moment I went the cheap route.
#!/usr/bin/perl
$cheapway = `ifconfig eth1`;
if($cheapway){
print "$cheapway";
}
else {
print "eth1 is down";
}
I mean this works, but it feels like bad programming practice. Thanks in advance | You can check the file `/sys/class/net/<interface>/operstate` in Linux to determine an interface's state. The following should work for eth1:
my $interface = 'eth1';
open(my $fh, '<', "/sys/class/net/$interface/operstate") or die $!;
my $state = <$fh>;
close($fh);
chomp($state);
if ( $state eq 'up' ) {
print "Interface $interface is up\n";
else {
print "Interface $interface is down\n";
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "linux, perl, interface"
} |
changing label value in background?
i am changing the label's value through timer(having interval of 1 second) by incrementing the count of an integer variable... I close the app....label starts incremented its value from where it was stopped...so app resumes it self from where it was stopped...but is there any way to take the labels value to the time for which it is closed i.e. if I close the app at the labels value 23...and close the app for 10 seconds...so when i open the app the labels starts incrementing itself from 33?? Thanks... | You could use a `NSDate` to store the initial time (i.e., when the timer was started) and then subtracting the `NSDate` from current time every second and setting the label to the difference. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "iphone"
} |
OData with EF Core / ASP.NET Core - Good or Bad?
I've read a lot about OData with EF Core / ASP.NET Core. It seems to me that everybody has an opinion on this and It's gotten a bit confusing, so at the risk of sounding dumb, I have a few questions:
Please note:
! I'm NOT talking about the classic ASP.NET 4.6 or 4.7 with EF6 !
! I'm talking about ASP.NET Core with EF Core !
1. Considering building API - Is there stuff that EF Core alone couldn't handle as well as EF Core with OData?
2. Considering building API - Is it not better to build clean RESTful APIs instead of OData style APIs?
3. Isn't implementing OData stuff sacrificing best practices for convenience?
4. What about long term? Aren't ASP.NET Core + EF Core being built with speed and efficiency in mind and thus won't they be faster and more efficient on their own? | I will go with Shawn Wildermuth's advice that I found on Pluralsight:
> OData means that queries are on the client so that **versioning OData services becomes risky** and it feels like **MS is moving away from it** so I don't have confidence in the long-term viability of it either. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 9,
"tags": "entity framework, asp.net core, odata, entity framework core, asp.net core webapi"
} |
Make a number of dataframes by using loop
I have data frame "df" following:
df=data.frame(time=as.factor(rep(c(0.01*(1:100)),each=49)),
roi=rep(1:49,100),
area=runif(4900, 5.0, 7.5),hours=(rep(1:10,each=490)))
The df is split into 10 smaller data frames based on column "hours"
x=split(df,df$hours)
In each sub-data frame one new data frame "br[i] is made following:
br1=data.frame(x$`1`[c(1,round(nrow(x$`1`)*(1:4)/4)),])
br1$Min=c(0,15,30,45,60)
br2=data.frame(x$`2`[c(1,round(nrow(x$`2`)*(1:4)/4)),])
br2$Min=c(0,15,30,45,60)
...
br10=data.frame(x$`10`[c(1,round(nrow(x$`10`)*(1:4)/4)),])
br10$Min=c(0,15,30,45,60)
The question is how to made 10 data frames "br" automatically without repeat such above commands in many time?
Thanks so much for any response! | Try:
lapply(split(df,df$hours), function(x) {
br=data.frame(x[c(1,round(nrow(x)*(1:4)/4)),])
br$Min=c(0,15,30,45,60)
return(br)
}) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "r, loops, dataframe"
} |
Unable to run a Subclipsed Groovy script in Eclipse
After installing the Groovy plug-in in Eclipse, clicking Run brought up a list: Groovy Console - Groovy Script - Java Application. I'd select **Groovy Script** and it would take off.
Now, after checking out a colleague's Groovy project with Subclipse, opening a script in it, clicking **Run** brings up "The selection cannot be launched, and there are no recent launches".
Selecting **Run As...** shows '(none applicable)'. So I select **Run Configurations...** and click **Groovy Script** , but the **Run** button stays dimmed. Eclipse evidently needs more info, but what? | I suspect your colleague didn't check in the .project file. It contains the "nature" that defines the project as being a Groovy project. I don't know for certain but it is not uncommon for eclipse actions to be predicated on the presence of an appropriate nature.
I would also check the .classpath is present and valid as it should contain the Groovy libraries required to compile and run your script.
Assuming they are missing, get your colleague to add them, and after syncing you should be good to go. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "eclipse, groovy, run configuration"
} |
How to load packed (but not signed) Edge extension?
I know how to load unpacked Microsoft Edge extension.
Now I have my extension packed (but not signed yet) to a `.appx` file. Can I load the extension via the `.appx` file?
I tried to open the `.appx` file by double-click on it, it shows:
Installation failed
Reason: This one isn't signed with a trusted certificate. | Yes, you can install an Edge extension from a package, but it **must be** signed by the certificate which should be added to the **trusted people** store as described in the documentation. Well, I see, that you have a problem with signing, so you can try to use this extension sample, which contains **.bat** file to build a package and sign it (Visual Studio 2015 is required - see the second line of build.bat). I have published this sample to report about the bug. Hope this will help you. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "microsoft edge extension"
} |
Mercurial repository corruption
This is somewhat related to this question but is a different question.
We have a central Hg repository, served to users via SSH and mercurial-server. We have a number of Mac, Linux and Windows clients connecting to it.
It has happened twice now that one of the Windows users has corrupted their repository, then pushed back to the central one corrupting it. I want to write an incoming hook script on the central repository to prevent a transaction from being accepted if it will corrupt the central repo.
Although unfortunately I don't know enough about Mercurial to write such a script. Any possibility that someone else has come across this? Personally I'm not quite sure why hg doesn't do this by default. | Recent versions of Mercurial (since 1.5) support validation of incoming data. Add
[server]
validate = True
to your server's hg config (either `.hg/hgrc` or the hgwebdir config should work fine) to have the server verify incoming data and refuse invalid pushes. The client will then see an error akin to:
remote: abort: missing file data for beta:dddc47b3ba30e54484720ce0f4f768a0f4b6efb9 - run hg verify
Hope that helps! | stackexchange-serverfault | {
"answer_score": 4,
"question_score": 14,
"tags": "mercurial, corruption"
} |
Is it possible for a user to interact with my web site before all document ready handlers have run?
It is not possible for the user to interact with the page before the document ready event fires - we're pretty sure that this is guaranteed, but would love a W3 link for that as well.
We've registered some JQuery-based document ready handlers - are those guaranteed to be run before the user can interact with the page as well? | It's entirely possible.
The Ready event doesn't fire until the entire DOM has been loaded (i.e. the HTML document has been fully parsed).
Since browsers use progressive rendering, the document can be interacted with before then. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "javascript, jquery"
} |
Check if string starts with other string in Haskell
I'd like to know whether my string starts with another string. For example:
startsWith "(" "(test string)" == True
Is there such a function that comes with Haskell? | Since strings are lists of characters, we can import `Data.List` and use the general function `isPrefixOf`:
isPrefixOf :: Eq a => [a] -> [a] -> Bool
Example:
Prelude Data.List> isPrefixOf "abc" "abcxyz"
True | stackexchange-stackoverflow | {
"answer_score": 17,
"question_score": 9,
"tags": "haskell"
} |
there is an integer $N_0$ such that for all $N\geq N_0$ the equation $ax+by=N$ can be solved with both $x$ and $y$ nonnegative integers.
Let $a$ and $b$ be two relatively prime positive integers. Prove that every sufficiently large positive integer $N$ can be written as a linear combination $ax+by$ of $a$ and $b$ where $x$ and $y$ are both _nonnegative_ , i.e. there is an integer $N_0$ such that for all $N\geq N_0$ the equation $ax+by=N$ can be solved with both $x$ and $y$ nonnegative integers.
**Proof:** Let $a,b$ be positive integers. Assume that $a$ and $b$ are relatively prime. i.e. $\gcd(a,b)=1$. i.e. $ax+by=1$ for some $x,y\in \mathbb{Z}$. **How can I restrict this result to $x,y$ are positive integers?**
Let $N$ be an integer such that $N\geq N_0$. Then $$ N = N(ax+by) = a(Nx)+b(Ny) $$ So $n$ can be written as a linear combination of $a$ and $b$. | Hint: Consider $N_0 = ab-a-b+1.$ To prove this consider the numbers $0,b,2b,...,(a-1)b$ and use the fact that they are all distinct modulo $a$ and thus represent all possible remainders modulo $a.$
On the other hand, the Euclidean algorithm approach you want to salvage seems not likely to work. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "number theory"
} |
Enabling core dumps inside open source GDB code
I was looking at the open source GDB code. I wish to write a target dependent code for a processor ( just like ARM and MIPS, etc). I have defined the appropriate files on similar lines. For most cases, my target is able to have GDB working. However, when I try to evaluate core dumps, I get: This version of GDB does not support core dumping.
This was a check put in the file: target.c
As you know, in GDB we have a strata of types of files that can be debugged. I wanted to know the exact place where ARM/ MIPS or any other processor architecture can enable core dumping.
Thanks
PS: I took a look at opne source arm-linux-tdep.c and arm-tdep.c but could not conclude anything. | Figured it out. As per the GDB documentation, we need to include supply_gregset, etc. routines inside our tdep files. Also, in the Makefile.in, we need to include corelow.o to the TARGET_OBS This ensures that we build GDB to support core dumping | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "gdb, arm"
} |
Prove $(1-\epsilon )\cdots(1-\epsilon ^{n-1})=n $ where $\epsilon = \exp(\frac{2\pi i}{n}), n\in \mathbb{N}, n \neq {0,1}$
I have a problem with proving the following: $$(1-\epsilon )\cdots(1-\epsilon ^{n-1})=n,$$ where $$\epsilon = \exp\left(\frac{2\pi i}{n}\right), n\in \mathbb{N}, n \neq {0,1}.$$ I tried to use fact that $$x^n-1=(x-1)\left(x-\exp\left(\frac{2\pi i}{n}\right)\right)\dotsm\left(x-\exp\left(\frac{(n-1)\cdot 2\pi i}{n}\right)\right).$$ When we divide RHS by $(x-1)$ on LHS we get $\dfrac{x^n-1}{x-1}$, which is the sum of the geometric series with first term $1$ and on the RHS almost desired expresion—the only problem is that if $x=1$ then LHS explodes.
Any hints? Thanks in advance. | Note that $1,\epsilon, \epsilon^2, \ldots, \epsilon^{n-1}$ are roots of $x^n=1$. Hence, $$(x^n-1) = (x-1)(x-\epsilon)(x-\epsilon^2)\cdots(x-\epsilon^{n-1})$$ This gives us $$\dfrac{x^n-1}{x-1} = (x-\epsilon)(x-\epsilon^2)\cdots(x-\epsilon^{n-1}).$$ Since the right-hand side is continuous, we can calculate it by taking the limit: $$\lim_{x \to 1}\dfrac{x^n-1}{x-1} = \lim_{x \to 1}(x-\epsilon)(x-\epsilon^2)\cdots(x-\epsilon^{n-1}).$$ By l'Hôpital's rule, $$\lim_{x \to 1}\dfrac{x^n-1}{x-1} = \left.\dfrac{d(x^n)}{dx} \right \vert_{x=1} = n.$$ | stackexchange-math | {
"answer_score": 5,
"question_score": 3,
"tags": "complex numbers"
} |
Accessing html5 canvas objects
I have a KineticJs project where I am creating several rectangles with a loop. I am not giving them any type of PII. But using the drag component , I am able to drag them separately. What's going on behind the scenes of canvas that we cant see anything in developer tools. I'd like to be able to see what is going on, like the `x` and `y` coordinates of everything I have on the screen.
<canvas width="1578" style="width: 1578px; height: 1200px; position: absolute;" height="1200"></canvas>
That is all that is displayed in developer tools for a canvas with 10 rectangles. | The canvas is just a bitmap drawing surface. Like MS Paint (or a paint canvas in real life), the drawing surface has no memory of the stuff you've drawn on it. All it can do is tell you about current pixels.
Either KineticJS or you need to keep track of every relevant object that you want to remember.
In KineticJS, you have a Stage object that has Layers, and those layers have Groups and Shapes.
You're interested in getting all of the Shapes in a given layer.
You need to look for that in the KineticJS tutorials and documentation.
You should read these before continuing:
<
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "html, canvas, drawing, html5 canvas"
} |
MySQL ORDER BY whatever_is_the_first_field DESC or inverse MySQL default sorting
How to do this in MySQL :
SELECT * FROM table_name ORDER BY 1 DESC;
Without having to SELECT the first or any column or knowing how its Primary key looks like.
Note: I know this is a bad practice but it is an access protected file & meant to be used by devs only and for for test proposes. kind of a quick retrieve of 10 last rows from different databases `db_tests.php?fct=lastTen&db=mssql_2&table=t_user`
* * *
UPDATE: The full query is :
select * from t_user LIMIT 10 order by 1 desc | You have your clauses in the wrong order. You have to put the `LIMIT` clause **after** the `ORDER BY` clause.
SELECT *
FROM t_user
ORDER BY 1 DESC
LIMIT 10 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql"
} |
kernel stack vs user-mode application stack
Is the kernel stack a different structure to the user-mode stack that is used by applications we (programmers) write?
Can you explain the differences? | Conceptually, both are the same data structure: a stack.
The reason why there are two different stack per thread is because in user mode, code must not be allowed to mess up kernel memory. When switching to kernel mode, a different stack in memory only accessible in kernel mode is used for return addresses an so on.
If the user mode had access to the kernel stack, it could modify a jump address (for instance), then do a system call; when the kernel jumps to the previously modified address, your code is executed in kernel mode!
Also, security-related information/information about other processes (for synchronisation) might be on the kernel stack, so the user mode should not have read access to it either. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "language agnostic, stack, kernel"
} |
How is Icomparer.Compare() method called when Sort is implemented?
* **Who calls Icomparer.Compare() Method?**
Consider the following sample.
Array.Sort(Myfiles, new customSort())
.
.
.
private class customSort : IComparer<object>
{
public override int Compare(obj A, obj B)
{
return (A.Value==B.Value?(0):((A.Value < B.Value)?(-1):(1)));
}
}
If Myfiles contain collection of objects,
* **How are A and B decided**.
* **Are A and B consecutive objects in th Myfiles collection?**
* **If not, How is A and B selected from Myfiles?**
* **Does the Array.Sort() method has to do anything with it?** | This method uses the introspective sort (introsort) algorithm as follows:
* If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.
* If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.
* Otherwise, it uses a Quicksort algorithm.
From <
For first option here is a nice gif: | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, .net, sorting, compare, icomparer"
} |
Will this relay driving circuit work or can it be improved?
I am building an IoT connected ECU for electric 2 wheelers.
 Let $p>0$, $X_i's$ be i.i.d. with $EX_1 = 0$. If $S_n/n^{1/p}\rightarrow 0$ a.s., then prove that $E|X_1|^p<\infty$.
Let $E|X_1|^p = \infty\implies E|X_1|^p = \sum_{n=1}^{\infty}P(|X_n|>n^{1/p})=\infty$ and thus by BC lemma $|X_n|/n^{1/p} \geq 1 $ i.o. with probability $1$. How can I relate $S_n$ to $|X_n|$ so as to arrive at a contradiction? Thanks. | $\frac {X_n} {n^{1/p}}=\frac {S_n} {n^{1/p}}-\frac {S_{n-1}} {(n-1)^{1/p}} \frac {(n-1)^{1/p}} {n^{1/p}} \to 0$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, probability theory, convergence divergence"
} |
Create IISRewrite rule for non www to www for toplevel domain only
I'm trying to redirect my non-www users to the www version. But only for our topdomain.
This is my current rule:
<rule name="Redirect Non WWW" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(?!www)(.*)domainname\.com$" />
</conditions>
<action type="Redirect" redirectType="Permanent" url=" />
</rule>
This works, but a bit too well unfortunately. We also have a few subdomains: < . The rule also redirects these, as they don't contain www.
How can I make my rewrite rule only redirect visitors to < and not our subdomains? | <rule name="Redirect Non WWW" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^domainname\.com$" />
</conditions>
<action type="Redirect" redirectType="Permanent" url=" />
</rule> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iis, umbraco, umbraco7, url rewrite module"
} |
Css3 quicklink container background
I have the following CSS3 code for a quick link container. I don't know why but the gradient background is not under the text. If i remove the `float: left` from `div.quicklinks`, I will display the gradient background but i want some text to the left. Thanks
div.quickLinksContainer {
clear:both;
border-top: 1px solid #999999;
text-align:center;
margin: auto;
width: 100%;
padding: 10px;
background-image: linear-gradient(bottom, rgb(179,175,176) 49%, rgb(237,237,237) 75%);
}
div.quickLinks {
font-size: 12px;
float:left;
}
.quickLinks h2 {
color:#666666;
font-size:14px;
font-weight:bold;
margin-bottom:10px;
}
.quickLinks li a {
color:#555555;
text-decoration:initial;
} | The reason the background isn't behind the content is because of
div.quickLinks {
float:left;
}
If you rather put the background gradient directly inside `div.quickLinks` it will work.
See this fiddle for demo.
**EDIT** On background on the comments:
When you float the content, the parent container, in this case `quickLinksContainer`, doesn't know how big the content is. Thus, for the container to have the correct size you'll have to specify it. For instance like this:
div.quickLinksContainer {
height: 150px;
}
See the updated fiddle | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
Unix cat starting from line
What is the best way to output from a file starting from a specific line (big number like 70000). Something like:
cat --line=70000 <file> | Take a look at tail, more precisecly, it's --lines=+N switch:
tail --lines=+100 <file> | stackexchange-superuser | {
"answer_score": 75,
"question_score": 54,
"tags": "command line, cat"
} |
Getting the three previous months in PHP is showing the same result
I need the three previous months from the current month.
I got this code from Stack Overflow here:
echo date('M Y', strtotime('-0 month'));
echo date('M Y', strtotime('-1 month'));
echo date('M Y', strtotime('-2 month'));
echo date('M Y', strtotime('-3 month'));
The result is supposed to be:
Mar 2020
Feb 2020
Jan 2020
Dec 2019
But, I'm getting:
Mar 2020
Mar 2020
Jan 2020
Dec 2019
What's the problem? Is it because of the leap year in February? | I am also new to this concept, but this is what I found and it seems to work.
When you use `strtotime('-1 month')`, you would get February 31. This day doesn't exist, so that's probably what causes the issue.
I found this format that would get the first day of the month, that should fix the problem. It might not be the cleanest way to do it, but this seems to work.
echo date('M Y', strtotime('first day of -0 month'));
echo date('M Y', strtotime('first day of -1 month'));
echo date('M Y', strtotime('first day of -2 month'));
echo date('M Y', strtotime('first day of -3 month'));
By writing "first day of" before the -* month, you will grab the first day instead.
Check out _Relative Formats_ where you can find all the formats you can use. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, date"
} |
How do I align the columns in CSS flexbox?
I'm having two issues with the layout of my weather app
1. the white space around the bottom and right edges
2. I can't figure out how to align the weekdays with the column of 5 red boxes underneath it so they're both side my side
I'm taking a mobile first approach so you need to view it in the dev console using the phone screen sizes as I haven't added the media queries yet.
< | * On `.footer` set `bottom: -1px;` (it will stick it to the bottom)
* Add the class `.col-xs-6` to `#weekDay` (it will use half 12 column grid)
* Add the other `.col-xs-6` to `#weekly_forecast` (it will use the other half of the 12 column grid)
* Add `line-height: 140px;` to `h2` to align it vertically with the red `div`s.
* For bigger `width` viewports replicate same formula with `col-md-*`s
;
To something like this:
start syntax E
= E "+" T
| T
;
syntax T
= T "*" F
| F
;
syntax F
= "(" E ")"
| "a"
; | Yes, the utility can be found in 'lang:: rascal::format::Grammar'
'grammar2rascal' formats an entire grammar as a rascal program which defines the same grammar.
'topProd2rascal' maps a single rule back to its concrete definition in rascal notation. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "context free grammar, data conversion, rascal"
} |
Is there a way to use thread local variables when using ACE?
I am using ACE threads and need each thread to have its own int member. Is that possible? | ACE calls this "Thread Specific Storage". Check this out: ACE_TSS. That's about all I know about it, sorry can't be more help.
The Wikipedia page for thread-local storage says there is a pthreads way to do this too. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "c++, multithreading, thread local, ace"
} |
Boot Ubuntu 16.04 into command line / do not start GUI
I want my Ubuntu 16.04 to not start GUI on boot and show command line console only. I have tried the following recipies but none of them are for version 16.04 and so they do not seem to work — GUI starts anyway:
1. GRUB_CMDLINE_LINUX=”text”
2. Changing the default runlevel
Ideally I also want to be able to start GUI by typig a command. | You could disable the display manager service with `systemctl`. For example if your display manager is `lightdm` then run:
sudo systemctl disable lightdm.service
This will prevent the service from starting at boot.
**Edit** :
I forgot to mention how to start the GUI. It is as simple as starting the systemd service:
sudo systemctl start lightdm.service | stackexchange-superuser | {
"answer_score": 28,
"question_score": 34,
"tags": "linux, command line, boot, gui, ubuntu 16.04"
} |
How do I add caps to paths clipped by a mask in Adobe Illustrator?
Below is a blown up, cropped sample of a project I’m working on in Adobe Illustrator. The shaded portion is a cross-hatched shadow effect created by applying a clipping mask to a pair of blended paths.
Unfortunately, this creates some unnaturally sharp points that don’t look nearly as pretty is a natural engraving or etching. Is there some effect or transformation I can apply to the layer (or to the mask itself) that will achieve the same results as if the ends of the paths were capped?
UPDATE: Here it is:
!so I’ve uploaded it here | Use pathfinder to crop the shade, unite the whole pattern and then apply round corners effect | stackexchange-graphicdesign | {
"answer_score": 2,
"question_score": 0,
"tags": "adobe illustrator"
} |
How to open text links in magnific-popup?
On my web page, on "PROJECT" section (first photo), I don't know how to make the magnific popup to open links rather than not zoom pictures.
Any suggestions? | In your website you have a `scripts.js` file. Remove or comment lines going from 22 to 45. Those lines contains the code that runs the `magnificPopup` jQuery plugin. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, magnific popup"
} |
How to create this JSON in my ASP.Net MVC controller?
I am using jqGrid with a multiselect field. I have a demo that works fine using this code:
{
name: "Subject",
index: "Subject",
width: 120,
formatter:'select',
editable: true,
edittype:'select',
editoptions: {
value: '1:sport;2:science',
multiple: true,
size: 2
},
editrules: { required: false}
},
But this JSON is hard coded with the multiselect options. I'm trying to find a way where I can return the data that is now hardcoded as:
'1:sport;2:science'
to come from a controller action in my MVC code. Is this possible? | You could use have your controller action return a JsonResult:
public ActionResult Foo()
{
var data = "1:sport;2:science";
var model = new
{
name = "Subject",
index = "Subject",
width = 120,
formatter = "Select",
editable = true,
edittype = "select",
editoptions = new
{
value = data,
multiple = true,
size = 2
},
editrules = new
{
required = false
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In this example I have used an anonymous type but you could define a view model that matches this structure and then return an instance of this view model. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery, asp.net mvc, json"
} |
Linear Algebra - Which of the following sets is a subspace of $M_{3\times3}$
Which of the following sets is a subspace of $M_{33}$,
1) $S=\\{A∈M_{33} : \mathcal N(A)\ni e_1\\}$
2) $S=\\{A∈M_{33} : \det(A)=0\\}$
3) $S=\\{A∈M_{33} :A^{\tau}A=I_3\\}$
4) $S=\\{A∈M_{33} :A \text{ is diagonalizable} \\}$
The answer is $A$, could anyone give me the explanation? | **Hints:**
**For (1):** If $A, B \in S$, this means $Ae_1=0$ and $Be_1=0$. Then $Ae_1+Be_1=0+0=0 \implies (A+B)e_1=0$. This shows that the sum of the matrices $A$ and $B$ is also in $S$ (hence $S$ is closed under addition). Now you can check if $S$ is closed under multiplication by a scalar.
**For (2):** Try with $A=\begin{bmatrix}1&0&0\\\0&1&0\\\0&0&0\end{bmatrix}$ and $B=\begin{bmatrix}0&0&0\\\0&1&0\\\0&0&1\end{bmatrix}$. What can you say about the sum $A+B$?
Hopefully you can take it from here. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, matrices, vector spaces"
} |
Ways to take a site offline for maintenance without killing running php started from http side?
I wrote a script `upload_songs.php`
When executed from the command line
$ php upload_songs.php
I can take the site offline
$ a2dissite my_website
$ service apache2 reload
and `upload_songs.php` will continue to run
However when I execute `upload_songs.php` from the http side by going to `my_website.com/upload_songs.php` if I do the following
$ a2dissite my_website
$ service apache2 reload
The php process `upload_songs.php` gets killed. How can I take the site offline for maintenance without killing running php processes that have been started from the http side? | apachectl graceful
This will wait until all connections are closed before restarting apache.
Docs for apachectl < | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "php, linux, apache, apache2"
} |
Compute $\lim_{n\to\infty }\int_E \sin^n(x)dx$
Let $E$ Lebesgue measurable of finite measure. Compute $$\lim_{n\to\infty }\int_E\sin^n(x)dx.$$
I already have the solution, but I did differently, and I would like to know if it's correct or not.
We can see that $\sin^n(x)\longrightarrow 0$ pointwise.
Let $\varepsilon>0$. By Egoroff theorem there is a closed set $F\subset E$ s.t. $m(E\backslash F)<\varepsilon$ and $\sin^n(x)\to 0$ uniformly. Therefore, $$\int_E|\sin^n(x)|dx\leq \int_{F}|\sin^n(x)|dx+\int_{E\backslash F}dx=m(E\backslash F)+\int_{F}|\sin^n(x)|dx\underset{n\to\infty }{\longrightarrow} m(E\backslash F)<\varepsilon$$ Therefore $$\lim_{n\to\infty }\int_E\sin^n(x)dx=0.$$
Do you think it work ? | Yes, this is a fine proof (modulo the fact that when you write pointwise, it really should be "pointwise almost everywhere"). It can be simplified significantly, though: Use the dominated convergence theorem with dominating function $\chi_E$.
It's also worth remarking that a slight reworking of your proof gives a proof of the dominated convergence theorem (on spaces of finite measure) from Egoroff's theorem; some knowledge about continuity of measures is needed to control integral over $F$, but it's not too much extra effort. | stackexchange-math | {
"answer_score": 4,
"question_score": 4,
"tags": "measure theory, lebesgue integral"
} |
Он - борется, они - бор(?)тся
Как правильно написать: "борЯтся" или "борЮтся"? | борются, так как образован от глагола бороться - 1 спр. | stackexchange-rus | {
"answer_score": 1,
"question_score": 0,
"tags": "орфография"
} |
MEAN stack - What is the difference between storing my views in the public folder or the server views folder?
When doing the front end, I have all my HTML files in public/app/views. I noticed that many people also have a views folder for the server side, for example containing .ejs files. Is that just so they can use a templating engine like Jade? If I am not using a templating engine, can I keep all my views in the public folder? | If you don't need to compile the views, you can place them in the public folder.
In fact, it will probably be faster since you don't have to request the rendered view to the server like
router.get('/partials/:name', function (req, res){
var name = req.params.name;
res.render('partials/' + name);
});
Hope it helps! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angularjs, node.js, express, mean stack"
} |
Is that possible for Linux and windows machines to be infected with KeRanger ransomware?
According to theguardian The Transmission site offers the open source software that was infected with the ransomware called KeRanger malware, it's programmed to encrypt files on an infected personal computer then the hackers will asks users to pay ransoms. Is that possible for windows and linux users to be affected by KeRanger after using Transmission client? | No, but it's hard to say this because it's a new kind of ransomware.
Ransomware isn't currently spreading to other computers, it only stays on the infected computer. | stackexchange-security | {
"answer_score": 1,
"question_score": 0,
"tags": "windows, malware, linux, macos, ransomware"
} |
Can't move a window in Unity (it's stuck)!
Silly question, but I can't move my steam friends list window, the top bar is somehow underneath the main bar of unity at the top.
In Windows you can right-click (or shift-click in Windows 7) and select to 'Move' when a window can be seen directly.
Something similar possible here?
Thanks, | Try to press **alt** (keep it pressed) and then click with the mouse on the window and move it.
Also, try **alt + spacebar** , **move** (or **m** ), and move it with the arrows.
Any result? | stackexchange-askubuntu | {
"answer_score": 19,
"question_score": 9,
"tags": "unity, gui, window"
} |
passing an array from model to controller
In my model, I am getting all emails in an array. I want to show this array of emails in controller, not in view.
Here my model is:
public function cron_job(){
$this->db->select('email');
$this->db->from('wc_buyer');
$query = $this->db->get();
return $query;
}
and the controller is:
public function cron_job(){
$this->load->model('home/Home_model');
$data['a'] = $this->Home_model->cron_job();
}
How can I show this print this array of emails in variable in controller? | Try like this
public function cron_job(){
$this->db->select('email');
$this->db->from('wc_buyer');
$query = $this->db->get();
$result = array();
foreach ($query->result() as $row){
$result[] = $row;
}
return $result;
}
public function cron_job(){
$this->load->model('home/Home_model');
$data['a'] = $this->Home_model->cron_job();
print_r($data['a']);
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "php, codeigniter"
} |
Maximum number of unsuccessful reviews allowed in test cricket
In ODIs where DRS is used, each side is allowed at most one unsuccessful player review in an inning. What is the corresponding rule for test cricket? | > In ODIs where DRS is used, each side is allowed at most two unsuccessful player reviews in an inning.
This is incorrect. Quoting from the current ODI playing conditions, Appendix 6, Section 3.5(a):
> Each team is allowed to make **one** unsuccessful Player Review requests per innings.
(my emphasis). Exactly the same section in the current Test Match playing conditions answers your question:
> each team is allowed to make a maximum of two unsuccessful player review requests in the first 80 overs of the innings, and a maximum of two unsuccessful player review requests after 80 overs for the remainder of the innings. | stackexchange-sports | {
"answer_score": 2,
"question_score": 1,
"tags": "rules, cricket, officiating"
} |
Type casting for Core Data attribute setting
I am trying to set a Core Data attribute but am getting incompatible type errors. I have a float attribute in a Core Data entity on iPhone 3.0. Core Data auto-generates an interface for a managed data object that provides property access to it:
@property (nonatomic, retain) NSNumber * volume;
and an implementation for it:
@dynamic volume;
I create an instance of the managed data object, which I call attrVolume, and use that to access that Core data entity attribute through a Core Data managed object context:
[attrVolume setVolume:[txtVolume.text floatValue]];
The compilation error is:
> incompatible type for argument 1 of 'setVolume:'
Any ideas how to cast that value and not get that compilation error? Is there a way to cast to NSNUmber?
Any help appreciated // :) | `-floatValue` returns a value of type `float`. You are then trying to set the value of `volume`, which takes an `NSNumber` to this `float` value, which fails.
You need to create an `NSNumber` from the float value of your string and assign that to `volume`:
NSNumber* volNum = [NSNumber numberWithFloat:[textVolume.text floatValue]];
[attrVolume setVolume:volNum]; | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "core data, casting, nsstring, attributes, nsnumber"
} |
Отображения графика кластеризации методом k-средних
Есть датасет, по двум выборочным столбцам которого я хочу провести кластеризацию с помощью метода k-средних, но получаю ошибку:
> x and y must have same first dimension, but have shapes (10,) and (1,)
Код:
from sklearn.cluster import KMeans
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df=pd.read_csv('train.csv')
wcss=[]
x=df.iloc[:,[4,80]].values
for i in range(1,11):
kmeans=KMeans(n_clusters=i, init='k-means++', random_state=42)
kmeans.fit(x)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show() | У вас лишний отступ в коде. Отрисовку нужно делать после того, как вы собрали данные по всем вариантам кластеризации. На каждой итерации цикла у вас получается одно значение, нужно собрать их все для отрисовки:
for i in range(1,11):
kmeans=KMeans(n_clusters=i, init='k-means++', random_state=42)
kmeans.fit(x)
wcss.append(kmeans.inertia_)
# отрисовка после того, как собраны все данные
plt.plot(range(1, 11), wcss)
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
Кстати, не уверен, что с одним кластером не будет ругаться, мне кажется нужно от 2-х кластеров начинать пробовать. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, numpy, matplotlib, кластеризация"
} |
How is memory allocated in this line of code "int **v = new int*[n]; "?
int **v = new int*[n];
I'm confused as to what this does? could someone please explain? | This allocates an array of `n` pointers to `int`. A pointer to the first element in this array of pointers is stored in `v`. It is a double pointer, such that accessing an element via `v[i]` returns a stored pointer from the array. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c++, arrays, pointers, memory management, syntax"
} |
Why is the PHP get_headers() Last-Modified different from the apache file info
I have an Apache directory listing of files on a remote server (in Australia/Adelaide +930) I have no control over. This server shows the correct last modified date of a file as: 14-Aug-2009 09:41
I have a PHP script on my US server to check the date of the remote file. `get_headers()['Last-Modified']` returns: Fri, 14 Aug 2009 00:11:11 GMT
How do I get my PHP script to output the same as Apache? | You're in Adelaide, Australia, which is GMT +9:30. `get_headers()` is giving you GMT time. apache is giving you local time. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, apache, last modified, get headers"
} |
PHP Sessions vs. Cookies
> **Possible Duplicate:**
> Cookie VS Session
> PHP: How do Cookies and Sessions work?
I'm trying to learn PHP. I have a project website where numbers are constantly being generated, and changed and stored in javascript variables. There is very little php involved except in storing these variables to a database when the user hits the "store to database" button. Today I was using the site, navigated to another website and went back and all my data was gone as i had not stored it to the database first. I would like to save that data so it repopulates if I leave the page. what would be the best method of doing this? php sessions, cookies, or javascript cookies? please advise, thanks in advance! | > php sessions, cookies, or javascript cookies?
There is either a session or cookie so there are **two** things not three.
Now a **session is also a cookie** but is saved on **server** unlike simple JS cookie which is saved in **user's machine**.
> I would like to save that data so it repopulates if I leave the page
If it is **sensitive** information, always use **database** to store it and if it is **not** sensitive data:
* Use cookies or `localStorage` but it can be **deleted** by user
* Use session which can't be deleted by a user but will **expire** based on php.ini settings
On the other hand, to save it **permanently** , use the database instead. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "php, javascript, session, cookies, store"
} |
context.SaveChanges not working
My update method is not working in an ASP.NET MVC 3 application. I have used the following EF 4.1 code:
[HttpPost]
public ActionResult UpdateAccountDetails(Account account)
{
if (ModelState.IsValid)
{
service.SaveAccount(account);
}
}
and `SaveAccount` looks like this:
internal void SaveAccount(Account account) {
context.SaveChanges();
} | internal void SaveAccount(Account account) {
// Load current account from DB
var accountInDb = context.Accounts.Single(a => a.Id == account.Id);
// Update the properties
context.Entry(accountInDb).CurrentValues.SetValues(account);
// Save the changes
context.SaveChanges();
}
Alternative:
internal void SaveAccount(Account account) {
context.Entry(account).State = EntityState.Modified;
context.SaveChanges();
} | stackexchange-stackoverflow | {
"answer_score": 20,
"question_score": 13,
"tags": "asp.net mvc, asp.net mvc 3, entity framework, entity framework 4.1"
} |
Perl string match fails when it shouldn't
I have the following code in my script.
if($description =~ /\'/) {
print "I am here\n";
$description =~ s/\'/'/g;
}
print "description = $description\n";
When I run this script, I don't get the `"I am here\n"` output as the comparison fails.
But, when the `$description` string does contain an apostrophe.
`$description = "The baseball player’s spiritual redemption and recovery from drug addiction.";`
Context: I am parsing a string got from a call to nytimes bestsellers api(returned in json format) and this string is stored in `$description` string. | Your sample string doesn't contain an apostrophe. It contains a `U+2019 RIGHT SINGLE QUOTATION MARK`.
It should match `/\x{2019}/` | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "perl, string comparison"
} |
Is there an RSS feed that alerts subscribers of new/updated packages in the official repositories?
I'm a serial apt-getter (running it often throughout the day), and I find it a great way to see where Ubuntu developers are most active. That being said, an RSS feed would probably be a smarter/safer way to keep up on what packages are being updated and when. | There was **one**, but it has since been discontinued until further notice. If you want to follow security notices though (I know not exactly the same, but still useful), you can add the feed from here: <
_**Update:_**
_Try these feeds (may not provide anything):_
* **
* **
* **
* **
* ** | stackexchange-askubuntu | {
"answer_score": 6,
"question_score": 7,
"tags": "apt, updates, rss"
} |
What does this colon do in struct? it is not a bitfield
In C programming, What does this colon do in struct?
struct ABC:XYZ {int num;}
where XYZ is also a struct. This does not seem to be a bitfield. What does ':' mean here? | The code:
struct ABC:XYZ {int num;}
means "define a struct `ABC` which inherits from `XYZ` and has a `num` member of type `int`. Specifically the `:` means "inherits from".
That code is equivalent to:
struct ABC : public XYZ {int num;}
For `struct`s the default inheritance visibility is `public`, for `class`es it's `private`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "c++, struct"
} |
laravel undifined variable in foreach loop
i am trying to send an object to a view and it says its undefined this is my controller and i have included `use App\Drug`
public function index()
{
$drugs = Drug::all();
return view('signup7')->withDrugs($drugs);
}
and this is my view
@foreach ($drugs as $drug)
<h5>Name : {{ $drug->generic_name}}</h5>
<h5>Ctegory : {{ $drug->dieases_category_id}}</h5>
<h5>Price: {{ $drug->sell_price}}</h5>
@endforeach
this is my route
Route::get('/medication/search', 'DrugsController@index')->name('drug.index'); | public function index()
{
$drugs = Drug::all();
return view('signup7',['drugs'=>$drugs]);
}
This is a method according to the official documentation of Laravel 7. When passing information in this manner, the data should be an array with key / value pairs. Inside your view, you can then access each value using its corresponding key. You can also pass data using the with() method :
return view('signup7')->with('drugs',$drugs); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "laravel, eloquent"
} |
Is my solution to this puzzle wrong or a transposition of the official one?
I saw the following puzzle recently in a newspaper:
> ## Black to play and win
>
>
> 6rk/6qp/2Bp4/P1pP1p2/3bnP2/6BQ/7P/5R1K w - - 0 1
>
My proposed solution was
1. ... Nf2+
and the lines I foresaw were
2. Bxf2 Bxf2
3. Rxf2 Qg1 mate
2. Bxf2 Bxf2
3. (something else) Qg1+
4. Rxg1 Rxg1 mate
2. Rxf2 Bxf2
3. Bxf2 Qa1+ and interposing B or Q only delays the end
However, the given solution was
>
> 1. ... Bf2!
> 2. Rxf2 ...
>
> (If `2. Bxf2? Nxf2+ 3. Rxf2 Qg1 mate`)
>
>
> 2. ... Nxf2+
> 3. Bxf2 Qa1+ and white resigns
I can see three possibilities:
1. I missed something
2. My solution is as good as the official one
3. They're actually equivalent under transposition
Which is the case? | They're not _equivalent_ , but your solution is just as good. In fact, it's more easy to find because Nf2+ is a 'forcing' move. | stackexchange-chess | {
"answer_score": 4,
"question_score": 6,
"tags": "analysis, puzzles"
} |
How can I pass parameter to a link generated by ActionLink() in ASP.NET MVC?
I have a route that I can access using the following pattern
ResponsesTotals/Show/1
ResponsesTotals/Show/2
.....
.....
ResponsesTotals/Show/n
From a different view, I need to list names and when the user clicks on them I want to direct them to the routes showing above.
Here is what I have tried
@model List<Proj.Model.Survey>
<ul>
@foreach (var survey in Model)
{
<li>@Html.ActionLink(survey.Name, "Show", "ResponsesTotals", new { SurveyId = survey.Id })</li>
}
</ul>
But that for some reason is generating wrong URLs. Here is what is being generated
ResponsesTotals/Show?Length=15
How can I pass a parameter to the link? | Add `null` for the last parameter so you hit the correct method:
@Html.ActionLink(survey.Name, "Show", "ResponsesTotals", new { SurveyId = survey.Id },null) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "asp.net, asp.net mvc, razor, asp.net mvc 5"
} |
Engineering mechanics(statics)
 stating that 'a' is being replaced by 'b' in one figure and is being replaced by 'c' in the other figure. If A and B were not the same, there would be reference to that in (e). | stackexchange-engineering | {
"answer_score": 0,
"question_score": -1,
"tags": "mechanical engineering, structural engineering, civil engineering, statics, beam"
} |
Poison Darts - can they be stopped? Are items stolen if they kill?
Couple of question regarding certain interactions with poison darts.
Firstly, can the kill chance be protected from (either by roles or items)?
Secondly, if the kill part does happen, and the target had any items, who gets the items from that kill? Would it be the player who threw the dart, or the current holder of the poison darts (since they could have been passed along on a later night) | As per this question - what offensive items does a protector protect against _currently_ poison darts cannot be protected against by any item or role.
Secondly, if a player is killed by the poison, any items they are carrying will go to the grave with them, no 'tick' of a poison is not considered a visit from the attacker. | stackexchange-gaming | {
"answer_score": 2,
"question_score": 2,
"tags": "werewolv.es"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.