INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Checking a user has purchased an app
I created two apps one free and one PRO and published them to the market, now in hindsight I should have taken the time to create an In-App-Billing element to unlock the free to the full. I wish to go ahead anyway and create the in-app billing element in the free version, and then remove the other (PRO) version from the market.
My issue though is how do I determine that a user who installs the free version has previously installed the PRO version and hence auto unlock it?
Assuming they removed the PRO app already from their device, can I access their purchased transactions and then unlock that way?
Otherwise is there a way in the dev console to create a transaction for them without them paying, and when they load the free version, it will restore that transaction?
I didn't use LVL in the PRO version, does that make a difference? | There is no support for this currently. You can check whether a user has bought a paid app using the licensing service (LVL), but it cannot be used in a paid app. You obviously can't create in-app transactions (Google handles this), and IAB has no native support for cupons/activation codes. You can either:
* build your own coupon/activation service (requires a server), or
* manually refund the IAB purchase for users who have already bought the pro one. You will lose the 30% Google fee in this case though. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "android, google checkout, in app billing"
} |
Compare 24 hours format times in moment.js
How to compare two times which are in 24 hours format. I have tried below lines of code?
$("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() {
var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05
var DutyDayEndTime = $("#dd_end_timing").val().trim(); // 13:05
if(DutyDayStartTime.minute() === DutyDayEndTime.minute())
{
alert("cannot be same");
}
});
I am using moment.js library. It throws error message "DutyDayStartTime.minute is not a function". Please help me how will I compare two times in moment.js | You've to use moment js library.
var moment = require("moment")
var DutyDayStartTime = moment([13,05], "HH:mm")
var DutyDayEndTime = moment([13,05], "HH:mm")
DutyDayStartTime.diff(DutyDayEndTime, 'minutes') // 0 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, jquery, momentjs"
} |
best way to send a variable along with HttpResponseRedirect
I am reading a djangobook and get questions about `HttpResponseRedirect` and `render_to_response`.
suppose I have a contact form, which posts data to confirm view. It goes through all the validation and database stuff. Then, as a usual way, I output the html with
return render_to_response('thank_you.html',
dict(user_code = user_code),
context_instance=RequestContext(request))
However, the book suggested "You should always issue a redirect for successful `POST` requests." because if the user "Refresh" on a this page, the request will be repeated. I wonder what's the best way to send the user_code along through `HttpResponseRedirect` to the `thank_you.html`. | Pass the information in a query string:
thank_you/?user_code=1234
Or use a session variable.
The problem with a query string is that the user can see the data. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "django, django views"
} |
Reshape data into image ValueError: could not broadcast input array from shape (1,3072) into shape (32,3)
l'm trying to reshape data into image as follow. Everything work well, except the last line code :
y[i]=image2
l want to store the result in a new variable `y`. I got this error at the line code `y[i]=image2` :
**ValueError: could not broadcast input array from shape (1,3072) into shape (32,3)**
My code:
from numpy import *
import cPickle
import scipy.io as io
from random import randrange
y = [len(v) for v in batch_1.values()]
Y = zeros([len(batch_1['data'][:]),3072])
for i in range(len(batch_1['data'][:])): #len() =10000
image = batch_1['data'][i]
image.shape = (3, 32, 32)
image_result = copy(image.transpose((1, 2, 0)))
image_result = reshape(image_result, (1, 3072))
Y[i] = image_result | The problem is with the extra dimension. Replace `(1, 3072)` with `3072`
**EDIT** :
There are more problems with your code as well. The `Y`is not defined, and by line `image_result= reshape(image2, (1, 3072))` I think you actually meant:
image2 = reshape(image_result, (1, 3072))
The new code should look like this (not tested):
from numpy import *
import cPickle
import scipy.io as io
from random import randrange
Y = zeros([len(batch_1['data'][:]),3072])
for i in range(len(batch_1['data'][:])): #len() =10000
image = batch_1['data'][i]
image.shape = (3, 32, 32)
image_result = copy(image.transpose((1, 2, 0)))
image2 = reshape(image_result, (1, 3072))
y[i]=image2 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python 2.7, image processing, multidimensional array, 2d"
} |
Kubernetes console pods logs to RAM instead Disk
I'm planning for a very high speed applications on kubernetes ,but I encountering performance issues of the kubernetes pod console logs.
When some pod writing console log, he writes it to a file(disk) under the hood and rotates it.
How can I config kubernetes writes the console logs to the RAM instead (rotating aswell ofcourse and shows me the last XX number of logs). | You should check emptyDir and set
emptyDir:
medium: "Memory"
and then do whatever you need with your logs, or go with `hostPath` and use `/dev/shm`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "kubernetes"
} |
MediaWiki default category
I've recently set up the newest MediaWiki install. I'm trying to force users to make an article part of a certain category. I'm using the SelectCategory extension to ask them when editing an article, however it is possible that they don't select any categories and simply save the page without it being attached to a category.
Is there a way (extension/setting/hack) that I can make a default category that all new articles will be a part of if they aren't added in another one? | There is no way that I know of which leaves you with only a few options:
1. Modify the SelectCategory to force selection of a category.
2. Modify MediaWiki code, or create a new extension, to force a category selection.
3. Perform the category selection post-editing (patrols, bots, manual editing, etc...).
Keep in mind that if you edit any MediaWiki code it will be difficult to upgrade in the future. Ideally you probably want to create a custom extension that does what you want. I haven't done any category related MediaWiki coding but the latest versions generally have enough hooks that you can do most things via an extension relatively easily. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 0,
"tags": "mediawiki"
} |
Adding css attribute hover using JQuery
I have a problem when i try to add CSS attributes to this class it gives me an error
My code
$('.openerp .nav-pills > li.active a:hover, .openerp .nav-pills > li.active a:focus, .openerp a.list-group-item.active a:hover, .openerp a.list-group-item.active a:focus').css({'color': res["left_hover_font_color"],'background-color': res["left_hover_bg_color"]});
error:
> Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
Why hover causing a problem here? | JQuery selectors are similar but not exactly the same as css selectors if you want to target an event such as hover or focus you need to use a callback for example:
$('.openerp .nav-pills > li.active a').hover(function() {
$(this).css({'color': res["left_hover_font_color"],'background-color': res["left_hover_bg_color"]});
},function() {
$(this).css({'color': "",'background-color': ""});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, css"
} |
thymeleaf - sum of objects in list inside a list
I use spring boot + thymeleaf and mySQL DB I have 3 entities:
* Category
* SubCategory
* Porducts
The current table
I would like to show the sum of products in the table
This is the code to show the sum of sub category:
<tbody>
<tr th:each="category : ${categories}">
<td th:text="${category.name}" />
<td th:text="${#lists.size(category.subCategories)}" />
</tr>
</tbody> | You can use collection projection and aggregate functions to accomplish this:
<tbody>
<tr th:each="category : ${categories}">
<td th:text="${category.name}" />
<td th:text="${#lists.size(category.subCategories)}" />
<td th:text="${#aggregates.sum(category.subCategories.![#lists.size(products)])}" />
</tr>
</tbody>
The expressions `category.subCategories.![#lists.size(products)]` produces a list of the products in subCategories, which you can just sum using `#aggregates.sum`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "spring mvc, spring data jpa, thymeleaf, spring thymeleaf"
} |
Use a password to protect a text file
Is there any easy/simple way to protect a .txt file with a password? So whenever open the file, password is required, just like opening .pdf with a password protected. Though I still want to be able to edit the text file in general text editors (notepad). | Use NotePad++ and add SecurePad Plugin. Check this link: <
<
< | stackexchange-superuser | {
"answer_score": 10,
"question_score": 8,
"tags": "windows 7, password protection"
} |
Oracle SQL Transpose data
I have a requirement where i have data coming from tables like this
country total_population number_of_cities number_of_airports
US 1,000,000,000 500 25
UK 2,000,000,000 400 20
This is dynamic data. The result i need to show as this
US UK
total_population 1,000,000,000 2,000,000,000
number_of_cities 500 400
number_of_airports 25 20
How can I achieve this ? Any help or pointers are much appreciated. | Here is the solution to the requirement. It basically needed to swap the rows and columns. This can be achived by first unpivoting and then pivoting it back. Here is the query
select *
from (
select
country,
total_population, number_of_cities, number_of_airports
FROM yourtable
) unpivot ( val for stats in (total_population, number_of_cities, number_of_airports))
pivot (sum(val) for country in ('US', 'UK')); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, oracle, pivot, transpose, unpivot"
} |
Connecting +1s on a Google+ Business Page and a webpage
We have a Google+ page, but on our homepage we have ~280 +1s:
Is there any way to connect those likes to the business page? We have used the rel=publisher thing. Or do we have to start fresh like we have? | Yes, according to this Google blog post you can combine all your +1s from Google+, your site and search results.
> You can also link your site to your Google+ page so that all your +1s -- from your Page, your website, and search results -- will get tallied together and appear as a single total.
> ...
> You can link your site to your Page either using the Google+ badge or with a piece of code. To set this up, visit our Google+ badge configuration tool.
I assume that's in your settings somewhere. It may not be there right now as they say they're introducing the badge in the coming days. | stackexchange-webmasters | {
"answer_score": 7,
"question_score": 6,
"tags": "social media, google plus"
} |
HTML: Create a combobox-style control
How can I create a text field inside a select tag of HTML forms.
I have tried
<form>
<select>
<option> <input type="text"/> </option>
<option> myname </option>
<option> yourname </option>
</select>
</form>
But this ain't working.. Any clues please ?
For an example, see this website < the pet breed field | Its not valid have a input inside a option of a select, but what people do is create a custom select where you can have a search box inside it, you can use a little plugin to do that, here it is Choosen | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -3,
"tags": "html, css"
} |
Pear Excel Writer: how to assign leading zeros to column?
There's a section in my website that allows to export an Excel file by clicking a button. The data displayed in the Excel file is taken from my database using SQL.
The following are examples of what is found in the column in my database:
12
34
456
2
7654
43
1234
7
Currently it displays identically as above in the Excel sheet, but what I would like would be for all the rows to have 4 digits. Therefore, data with less than 4 digits would have leading zeros added to it.
Using the same example, here is how I would like it to show in the exported Excel sheet:
0012
0034
0456
0002
7654
0043
1234
0007
This seems like a relatively simple task, but I cant seem to find how to make this happen through my research. I hope someone here will be able to help.
Thank you. | $number = str_pad($value, 4, '0', STR_PAD_LEFT); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, excel, pear, export to excel"
} |
Why can only duration "once" be used on orders in stripe?
I've gotten an error code back from using a stripe coupon which says:
> Only coupons with duration "once" can be applied to orders. The coupon code that you supplied (TESTCOUPON) has duration "forever."
So, fixing this is seems pretty direct, change the duration to "once." But when looking through the docs, I haven't been able to figure out why.
In this section of the docs: <
It states that duration can be `once, forever, or repeating`. But I can't find anywhere that explains clearly what these three are, specifically as applies to why only one of them can be applied to orders. | So, I suppose it makes more sense once you know what "orders" are defined as. Essentially, there's "products" which are really subscriptions, which can have plan types. But an "order" is for a one off payment for something that would normally be a product or service, but is instead just an "order."
Point being, it's a one off payment, a coupon code can only be applied once.
If doing a subscription, you could have:
* once: discount happens on first payment
* forever: repeats every payment
* repeating: you set some extra parameters on how many times it'll repeat
But on an order, it's only bought once. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "stripe payments"
} |
How to deform (randomize) object so it would look different?
I have 3d tooth, and I need to make it look different. Is there any way to deform it? Scaling it, isn't what I need. My model has around 2kk faces and I have troubles editing subdivision and fractal settings.
My goal is writing a script that will randomize my tooth. | Add a Lattice Object and set its resolution for your requirements.  a file from my res/raw folder to the default Android download location?
I am making a soundboard for practice and I want to give the user the ability to download the sound (that I have included in the app in the `res/raw` folder) onClick of a menu item but I can only find information about downloading from an internet url, not something that I already included in the apk.
What is the best way to do this? I would like to give them the option to save to an SD card also if this is possible. A point towards the correct class to use in the documentation would be great! I've been googling to no avail.
Thanks! | Try something like this:
public void saveResourceToFile() {
InputStream in = null;
FileOutputStream fout = null;
try {
in = getResources().openRawResource(R.raw.test);
String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String filename = "myfile.mp3"
fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "android"
} |
RS-232C and Email in 7bit char set
The book "Designing Embedded Hardware" in the chapter "9.3. Old Faithful: RS-232C" mentions that emails are still sent in 7bit char set because of RS-232C:
> It's also not unheard of to see RS-232C systems still using 7-bit data frames (another leftover from the '60s), rather than the more common 8-bit. In fact, this is one of the reasons why you'll still see email being sent on the Internet limited to a 7-bit character set, just in case the packets happen to be routed via a serial connection that supports only 7-bit transmissions.
How can I confirm the observation? | Check out the spec. The original rfc822, for ARPA Internet Text Messages, explicitly states:
> A message consists of header fields and, optionally, a body. The body is simply a sequence of lines containing ASCII characters.
Since ASCII is 7-bit, voila.
Note, however, that there are a whole bunch of additions to that original spec, all the MIME extensions, which allow message header extensions for non-ascii text. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "email, history, protocols"
} |
Diffrence between Simple Router like (CodeIgniter) and Restful Router (Slim Php)
I am a novice PHP coder. Have basic knowledge in php [Self taught]. Presently learning CodeIgniter. But recently checked Slim Php Framework. It has Restful Router.
Can any one please tell, what is difference between CodeIgniter Router and Slim Router. And which one is better?
Thanks in advance. | Codeiginiter maps your class and method to the url. This a easy way to build your mvc project. But in my opinion isn't a good way to build apps if you need more powerful, if anyone wants change urls you have a serious problem.
Slim 3 has a way to map an url to your own class. For example:
$app->get('/myownurl', MyController::class);
You can change it easily.
You could review routes docs: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, codeigniter, rest, router, slim"
} |
How do i search directories and find files that match regex?
I recently started getting into Python and I am having a hard time searching through directories and matching files based on a regex that I have created.
Basically I want it to scan through all the directories in another directory and find all the files that ends with `.zip` or `.rar` or `.r01` and then run various commands based on what file it is.
import os, re
rootdir = "/mnt/externa/Torrents/completed"
for subdir, dirs, files in os.walk(rootdir):
if re.search('(w?.zip)|(w?.rar)|(w?.r01)', files):
print "match: " . files | import os
import re
rootdir = "/mnt/externa/Torrents/completed"
regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')
for root, dirs, files in os.walk(rootdir):
for file in files:
if regex.match(file):
print(file)
**CODE BELLOW ANSWERS QUESTION IN FOLLOWING COMMENT**
> That worked really well, is there a way to do this if match is found on regex group 1 and do this if match is found on regex group 2 etc ? – nillenilsson
import os
import re
regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')
rx = '(.*zip$)|(.*rar$)|(.*r01$)'
for root, dirs, files in os.walk("../Documents"):
for file in files:
res = re.match(rx, file)
if res:
if res.group(1):
print("ZIP",file)
if res.group(2):
print("RAR",file)
if res.group(3):
print("R01",file)
It might be possible to do this in a nicer way, but this works. | stackexchange-stackoverflow | {
"answer_score": 29,
"question_score": 21,
"tags": "python, regex, linux, file, directory"
} |
What ever happened to vim-full package that used to be available in ubuntu?
Why was it removed and is there a way to get it? I know about this post but I am curious as to why it would have been removed?
Also if you do an install like this:
apt-get install vim vim-scripts vim-doc vim-latexsuite vim-gui-common vim-gnome
What is actually happening? Are there different versions of vim installed or does it compile vim with all those options or ...???
Sorry about the multiple questions here but it would seem silly to break them out into individual questions since they are all very related.
BTW I am using 10.04 LTS | It has been replaced by vim-gnome. Packages often get renamed between releaases. This change has been in the works since Hardy.
From Jaunty "This package is simply a transitional package from vim-full to vim-gnome."
Found on Ubuntu pacakges list | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "ubuntu, installation, vim"
} |
Access to my GridViewItem's UI Element in Windows 8 Apps
In XAML I implemented a GridView binded with data. In the GridViewItem I put a StackPanel with TextBlock etc. and I would like to manipulate the look of the TextBlock (by its attributes) when that specific GridViewItem is clicked. I can't reach the TextBlock from the C# code so I can't reach its attributes either. What am I missing here? Thanks in advance. Here is some XAML code:
<GridView x:Name="gw" ...>
<GridView.ItemTemplate>
<DataTemplate>
<GridViewItem x:Name="gwi">
<StackPanel>
<TextBlock x:Name="tb">
<Run Text="{Binding SomeData}"/>
</TextBlock>
</StackPanel>
</GridViewItem>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
In this example, how can I use the "tb" named TextBlock and its attributes? I can use only "gw". | I don't think it's possible to access each individual element in the data template. You can however, modify the TextBlock's attributes using data binding. You can use a binding converter to convert the values as may be required.
Refer to < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, windows 8, microsoft metro, winrt xaml"
} |
CPP Win32 Moving the Mouse, Wont move to where I specify
I took the code from here: How to simulate a mouse movement
I got it and it seemed to be working, I didn't fully test it, but I was able to get the mouse to click a tab on firefox. (Having the program load over the FF window.)
I changed the window struct for the window to be smaller, and gave it a specific position instead of letting windows do it: (0,0).
Then I tried plugging in coords for the mouse to move to (830, 380), and tried (630, 390) both resulted in the mouse going directly to the bottom right corner of the screen. Those are coords for an auto clicker I am working on.
I really haven't modified the code too much.
Does anyone have any idea why this is? I'm sure I must be missing something...
Thanks. | Just use the mouse_event <
or SendInput <
to do the job. I believe the coordinates are normalized to the range of 0-65535 for both X and Y | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c++, mouse, move"
} |
Explode an Array that has a new line in it in PHP
I have an array that is separated by "|". What I wanna do is separate by this identifier.
The array is as follows:-
myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description
What I did was that I just used `explode` on it to get my desired results.
$required_cells = explode('|', $bulk_array);
But the problem is (as shown below) that only my first array is properly exploded and the next first cell of the next array is mixed due to the "new line".
Is it possible that I can get the upper array in consecutive array cells?
Array
(
[0] => myid1
[1] => My Title
[2] => Detailed Description
myid2
[3] => My Title
[4] => Second Row Description
myid3
[5] => My Title
[6] => Second Row Description
) | Explode on newlines, aka `"\n"` first, then loop through that array and explode on pipes, aka `'|'`
$bulk_array = "myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description";
$lines = explode("\n", $bulk_array);
foreach ($lines as $key => $line)
{
$lines[$key] = explode('|', $line);
}
Then `print_r($lines);` will output:
Array
(
[0] => Array
(
[0] => myid1
[1] => My Title
[2] => Detailed Description
)
[1] => Array
(
[0] => myid2
[1] => My Title
[2] => Second Row Description
)
[2] => Array
(
[0] => myid3
[1] => My Title
[2] => Third row description
)
) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, arrays"
} |
Movie with dragon and thing that looks like Godzilla
See this video:
In it, at 1:52, there is a clip of a movie with a dragon and a Godzilla-like (maybe Godzilla itself) creature. I have a crazy idea that it might be CGI. I know it’s a movie because of the aspect ratio. What is it?
The dragon:
) and the other creature is a MUTO.
 return true;
else if (num === 1) return false;
//console.log(num);
isEven(num-2);
}
isEven(16); // Epected Log: 0 but instead it returns undefined | Because for arguments different than 0 or 1 there is no return value. The last line:
isEven(num-2);
should be
return isEven(num-2); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "javascript, recursion"
} |
How to restart mono web application without restarting apache?
Is there any way to restart **ONE** web application in mono without having to restart Apache?
Currently I'm doing a `sudo service apache2 restart` everytime I deploy my .NET web application to mono, but it restarts all my other applications, requiring them **ALL** to get reloaded into memory at next web request. | Enable the `mod_mono` control panel.
In `httpd.conf`, add
<Location /mono>
SetHandler mono-ctrl
Order deny,allow
Deny from all
Allow from 127.0.0.1
</Location>
You will need to modify the addresses that can access it in the `Allow from` line.
Reload `httpd` and now you can go to ` You can, among other things, reload all or individual mono applications. | stackexchange-unix | {
"answer_score": 3,
"question_score": 2,
"tags": "apache httpd, mono"
} |
Replotting a closed figure from command line in Python without re-executing code
I wrote a simple Python code to plot a signal. File is called signal.py
samples=np.arange(t*fs)/fs
signal=np.sin(2*np.pi*f*samples)
signal*=32767
signal=np.int16(signal)
wavfile.write(input("Name your file: "),fs,signal)
plt.plot(signal)
plt.show()
When called in cmd line,
_python signal.py_
The code runs. I can see the plot. All is well. But after i close the plot, without re-running the code, is it possible to plot ONLY the signal again, as if all the variables were stored in a workspace of sort , similar to MATLAB.
i tried >> _plt.plot(signal)_
_'plt.plot' is not recognized as an internal or external command, operable program or batch file_.
Or maybe the question should be , if its possible to store the variables in a workspace from where you can call and plot the variables ? | While this is not the perfect answer, the closest workaround I have come to find is
run the python shell in cmd,
>
> python
> import signal
> import matplotlib.pyplot as plt
> plt.plot(signal.signal)
> plt.show()
>
After this i can close the figure and run just the last 2 lines to re-open the figure. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
programmable timer / clock generator
I need to generate a square wave / clock with configurable frequency between say 60 to 500Hz. There are not stringent requirements on the frequency stability. I need to be able to modulate this frequency at run time periodically (say once every few seconds) using an external uC using either GPIO or I2C. I have looked at programmable oscillators and programmable alarm ICs and have yet to find any that can do what I want. I am OK with having a roll your own type of circuit for this as long as it's not super complicated.
The purpose of this is to provide timing control to some external power FETs which will switch a regulated DC voltage on and off. I don't want this switching to be halted if the software running on the uC dies for some reason. So I want an external IC to control the switching.
Can you recommend a circuit that can meet my needs? | Most microcontrollers have a PMW/Counter logic block available that runs independently of the CPU. Check the datasheet to see if that's available on your micro, it's free and easy. | stackexchange-electronics | {
"answer_score": 3,
"question_score": 0,
"tags": "oscillator, clock, timer, 555"
} |
Can't display a `BooleanRegion` in the Wolfram Cloud Notebook
I can't manage to display a `BooleanRegion` in the Wolfram Cloud Notebook:
floor = Block[{
outer =Rectangle[{0, 0}, {2900, 6350}],
x1 = Rectangle[{2900-445,0}, {2900, 740}],
x2 = Rectangle[{2900-450, 6350-520}, {2900, 6350}]
}, BooleanRegion[Xor, {outer, x1, x2}] ];
Graphics[{FaceForm[Pink], floor//Region}, AspectRatio -> Automatic]
It seems to produce a _blank_ graphic object: . It's strange why Blizzard did not add an option to disable the Win key in D3. They have it in SC2. | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 1,
"tags": "keyboard, wine, games"
} |
Substring template matching xslt
I've struggled some time now. I just started with xslt, and I got things working just fine. Templates are used wherever possible and I've tried to keep myself from using for-loops.
My problem is this: I have a number of nodes with similar names, only difference is a postfix number from 1 to (currently) 5. These should all be transformed into a node without the numbers. So basically, here is what I have:
<title1>some title</title1>
<some_other_nodes>....</some_other_nodes>
<title2>some title2</title2>
.
.
.
<title5>....</title5>
And this is what I want:
<title>some title</title>
.
.
.
<title>some title2</title>
.
.
.
<title>....</title>
Is it possible to do substring matching with templates (matching just the title-part)?
Thanks for your help! | For elements of the form titleN, where N is some number, use a match condition like ...
_(corrected:)_
<xsl:template match="*[starts-with(name(),'title')]
[number(substring(name(),6))=number(substring(name(),6))]">
etc...
Less generically, but quick and dirty, if you want SPECIFICALLY title1 through to title5, you might also think about ...
<xsl:template match="title1|title2|title3|title4|title5"> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "xml, templates, xslt, xslt 2.0"
} |
Where do components get added in Unity?
In unity's GameObject class, there are a few default data members. When we add a component to the game object, light for example, where exactly does it get added? Does it become a part of the GameObject class? | In the past, components used to be added to the GameObject itself, in such a way, that you could call `myGameObject.renderer` to get an object's `Renderer`.
This however changed to the call of `myGameObject.GetComponent<Renderer>()`, which hides the details of where the components are saved, which shouldn't be relevant anyway. Since for most (if not all) cases it doesn't matter for the user where components are, but that they belong to an object.
As @DMGregory noted, when you (used to) refer to a component with the first way (`myGameObject.renderer`) it acts like a getter behind the scenes, so the `GetComponent` function just replaced that, it still seems to work the same way, as in, you can get a component from a `GameObject` but the implementation details are unclear and not needed. | stackexchange-gamedev | {
"answer_score": 0,
"question_score": 0,
"tags": "unity"
} |
Exibindo determinados valores em Python
Preciso de ajuda com o seguinte:
* Possuo uma variável que gera números inteiros aleatórios de (0 a 400).
* Em um determinado número de execuções, desejo que seja(m) exibido(s) o(s) valor(es) e a posição(ões) do(s) valor(es) menor(es) que 100.
* Possuo um código (veja abaixo) que estou trabalhando, porém ele não está agindo de maneira adequada.
Onde estou errando?
## Meu código
from random import randint
aleatorio = randint(0,400)
maximo = 100
for i in range(1,maximo + 1):
if aleatorio < 100:
print (aleatorio[i]) | A melhor maneira é usar um dicionário, em que cada chave pode ser a posição do valor correspondente menor que 100:
from random import randint
pos = {}
for idx, val in enumerate(range(400)):
rand_num = randint(0, 400)
if rand_num < 100:
pos[idx] = rand_num
DEMONSTRAÇÃO | stackexchange-pt_stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, python 2.7"
} |
MCLK in I2S audio protocol
I am working with the I2S audio protocol in one of my projects and I'd like to use it in one of my final projects for a class of mine. Quite honestly though, I don't entirely understand the MCLK line. You'd think, "Oh that just stands for Master Clock" and you might be right but since everything has to do with audio and sampling rates, I get confused.
I'm using the CS42436 in software mode: in short it takes in 3 signals (that I'm questioning).
MCLK - Master Clock (Input) - Clock source for the delta-sigma modulators and digital filters.
SCLK - Serial Clock (Input) - Serial clock for the serial audio interface. Input frequency must be 256 x Fs
FS - Frame Sync (Input) - Signals the start of a new TDM frame in the TDM digital interface format.
Can somebody explain how to use these clock signals in reference to this picture?
!I2S Protocol
I know the middle signal is the serial clock, but the other two I don't understand at all. | The top signal is Frame Sync (FS). FS is used to indicate whether the audio is for the left or right channels. Don't think of them as "left" and "right" though, those are just arbitrary names. Think of them as channel 0 (FS clear) and channel 1 (FS set), time-division multiplexed onto a single communications link.
The bottom signal is the serial data that is being clocked into(?) your MCU.
MCLK is not visible in that diagram. It is the clock that is used by the audio codec (in your case, a CS42436) to time and/or drive its own internal operation. It is a relatively high frequency; a common value is 256*Fs (where Fs is the sample rate, e.g. 44.1kHz). Values in the range of 10-60MHz are pretty typical. | stackexchange-electronics | {
"answer_score": 7,
"question_score": 10,
"tags": "audio, i2s"
} |
Representation Theorem For Compact set in R
I am trying to prove following
A non empty bounded closed set S in R is either closed interval or can be obtained form closed interval by removing union of countable collection of open set whose end point belong to that set .
My Attempt: If closed interval then done .If Closed And bounded set but not interval Then Form bounded it must have some supremum and infimum and by closeness it must belongs to that set .
Now say M is sup S and m is inf S.$S\subset [m,M]=I$ {Proper set as we have done that case already}. $\exists x\in I $ such that $x\notin S$ So consider set T={x|x$\in I$, $x\notin S$} Which is non empty and bounded below by m.So it must has inf .That inf belong to S due to closeness .How to proceed further ? | I'm not happy with the sentence "I can visualize this that any compact set in ${\mathbb R}$ is either closed interval or finite point in ${\mathbb R}$". Whatever the exact intended meaning of this sentence: One of the most famous compact sets in ${\mathbb R}$, the Cantor set, has uncountably many components.
Nevertheless, the claim you want to prove is true and easy to prove. Take a compact set $K\subset{\mathbb R}$. The points $a:=\inf K$ and $b:=\sup K$ belong to $K$. The complement $\Omega:={\mathbb R}\setminus K$ is open. It consists of countably many disjoint open intervals, among them ${\mathbb R}_{<a}$ and ${\mathbb R}_{>b}$. Remove these from $\Omega$ and obtain $\Omega'$. Then $K=[a,b]\setminus\Omega'$, as desired. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, general topology, metric spaces"
} |
Calling scope.$parent.function outside the directive in a controller
i have this function inside my directive link function:
scope.$parent.resetData(){
scope.data = '';
}
in my html:
<ul ng-model="selectedObject">
<li>{{ object.label }}</li>
</ul>
<button ng-click="resetData()">reset!</button>
<directive data={{ selectedObject.dataset }}></directive>
and in my app.controller
$scope.$watch('selectedObject', function(){
$scope.resetData(); //this cant be used
});
i cant use $scope.reset() in the controller scope, is there a way to be able to re-use that function in the simpliest way instead of doing a factory/service for this dataset? | Feed the directive `selectedObject` instead of `selectedObject.dataset` and let it manage the reset internally.
It would be more encapsulated, which would be good. If changing `selectedObject` always resets the data, thinking of the directive as a component and having the logic inside makes it more self-contained. That way outside code doesn't have to worry about helping the directive do its job. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, angularjs"
} |
Are throw-away lines referencing bigoted activity against the CoC?
In some cases, references to bigoted activity are essential to the question itself:
* Example from Academia
* Example from the Workplace
However, I saw a question today from IPS that made me wonder about how we can best follow community guidelines across the site. This question includes a flippant reference to pornography use.
The line is irrelevant and will likely be edited out soon to avoid distracting from the question. That isn't relevant to this question, which is largely theoretical. **What I am asking is specifically about non-essential lines or comments referencing discriminatory or harmful activity against certain groups.** Is that against the CoC? | Every community should discuss how they want to handle situations where potentially offensive or sensitive topics are important to the question or answer. Here is a good discussion from ELU about an example used in an answer that was unintentionally offensive.
A different site might have a different answer to how such examples should be handled based on their subject matter and their community norms. Gratuitously or extremely offensive material is always a violation though. | stackexchange-meta | {
"answer_score": 10,
"question_score": -16,
"tags": "discussion, code of conduct, rules"
} |
Repaint all cells with "white" color fill to "no fill"
I've inherited a spreadsheet in Excel which inconsistently uses "no fill" or "white fill" for most cells ( _most_ \-- there also exist other cells with other colors, i.e. for specific input assumptions or output values).
I'd love to be able to replace all the cells with "no fill" with "white fill" (or perhaps depending on how it looks, those with "white fill" to "no fill").
Is there any easy way to do this? (I'm on Windows if that helps).
Thanks, /YGA | You can select `Ctrl + H` set the **Find What** format **Fill** to `White` and **Replace with** format **Fill** to `No Color`:
` will return a list of the 3 `span.a`s. I wonder if there's an easy way to return a list of 4 elements including the divA itself?
I know I could start from a higher level node, but let's assume there might be other `.a` elements that I don't want to mess with them.
In reality I still need to test whether `divA` matches my selector or not. So is there a way for css selector to test an element itself?
I could create a parent node and run querySelectorAll from there. But if there's an easier way, I don't need to go that far. | > I still need to test whether divA matches my selector or not. Is there a way for css selector to test an element itself?
`querySelector()` cannot return the context element it's running on.
What you can do is use @Andreas' solution followed by a `filter()`/`matches()` combo.
[divA, ...divA.querySelectorAll('.a')].filter(el => el.matches('.a')); | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 11,
"tags": "javascript"
} |
True or false about the existence of a Linear Transformation
Let $V,W$ two vector spaces over the field $F$.
If $x_1, x_2\in V$ and $y_1, y_2\in W$, then there exists a linear transformation $T: V\to W$ so that $T(x_1)=y_1$ and $T(x_2)=y_2$.
I think that statement is false, but, I do not know how to prove it.
Thanks for your help! | Without further restrictions on $x_1$, $x_2$, $y_1$, $y_2$ the statement in general is not true. For example, if $x_2=\lambda x_1$ but $y_2\ne\lambda y_1$ then obviously you can not find $T$. However, if $x_1$ is linearly independent from $x_2$ and similarly $y_1$ is linearly independent from $y_2$, then you can always find a $T$, and if the space has dimension larger than 2 there are infinitely many solutions. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, linear transformations"
} |
.htaccess issue with redirecting not working
My `.htaccess` file works fine but I want to make a change on the redirect.
Currently, it redirect the url to `
Now... I want to remove the `url` path from it. So, I want `
My code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(url)/(.*)$ /tool/script.php?url=$2 [L,QSA]
I have tried:
RewriteRule ^/(.*)$ /tool/script.php?url=$2 [L,QSA]
And
RewriteRule ^(.*)$ /tool/script.php?url=$2 [L,QSA]
But all is giving me 404 error. Any help will be appreciated! | $2 doesn't exist, it should be $1 to reference the first (and only, in your code) match. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, apache, .htaccess, redirect"
} |
How do I get the SQL command text when I insert a new record with Linq?
var newUser = new tblUser() {
Email = strEmail,
Password = strPassword,
DateBirth = DateTime.Parse(strDateBirth),
};
db.tblUsers.InsertOnSubmit(newUser);
db.SubmitChanges();
I want to get the actual SQL query that linq generated. | You need to set the DataContext.Log property to a writer, you can wrap a writer around a stringbuilder then after your insert response.write your stringbuilder.tostring...
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
Context.Log = writer;
...
DOINSERT & SUBMITCHANGES
...
Response.Write(sb.ToString()); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 5,
"tags": "linq, insert"
} |
Generating strings from context free grammars
The problem is implementing an algorithm, that generates all strings with length between **l** and **r** from given context free grammar **G**.
I have come up with simple approach: run BFS on grammar graph, remembering states. But it fails on some recursive rules:
(1) S -> 0 | SSS | λ
I can't simply limit maximum string length, because rules can contain λ (empty strings), so non-terminals can reduce final string length. (eg. running (1) with `l = 1`, `r = 2` will output only 0 in my implementation)
I also tried to limit maximum number of applied rules, but it is obviously wrong too.
How i can limit or change my algorithm, so it will never go in endless loop and will work correctly? | You can transform the grammer to Greibach normal form, and then each step1 in the creationis increasing the size of the produced word, and you will be able to limit the length of the word as initially explained in the question.
* * *
(1) except possibly the first, if the empty word is in the grammer | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "algorithm, context free grammar"
} |
boldsymbol badly modifies spacing
In the example below, it is my feeling that `\boldsymbol` badly increases the horizontal spacing with the index:
\documentclass[fleqn,11pt]{book}
\usepackage{amsmath}
\begin{document}
$\boldsymbol{\sigma}_0$ $\sigma_0$
\end{document}
Shouldn't this be corrected?
!enter image description here | Load the `bm` package and the problem goes away, both using `\bm` and `\boldsymbol` (which gets redefined by `bm` to be the same as `\bm`).
This spacing issue is one of the reasons why `\bm` should be used for bolding math instead of `amsmath`'s `\boldsymbol`.
\documentclass[fleqn,11pt]{book}
\usepackage{amsmath,bm}
\begin{document}
\begin{align*}
\boldsymbol{\sigma}_0&\\
\bm{\sigma}_0&\\
\sigma_0&
\end{align*}
\end{document}
!enter image description here
The difference can be seen with the following example
\documentclass[fleqn,11pt]{book}
\usepackage{amsmath}
\let\amsboldsymbol\boldsymbol
\usepackage{bm}
\begin{document}
\begin{tabular}{rr}
\verb|amsmath's \boldsymbol| & $\amsboldsymbol{\sigma}_0$ \\
\verb|\bm| & $\bm{\sigma}_0$ \\
& $\sigma_0$
\end{tabular}
\end{document}
!enter image description here | stackexchange-tex | {
"answer_score": 13,
"question_score": 8,
"tags": "math mode, spacing, symbols, amsmath, bold"
} |
How to download a file from URL in Linux
Usually one would download a file with a URL ending in the file extension.
To download Ubuntu ISO, one would simple
wget
However, I came accross a site that I suspect uses ASP.Net / IIS.
A link to a ISO is in this form _(I removed link contents incase of ... policies)_ :
I am not sure how to download this since it has the MD5 and expiry time as parameters, and so wget only downloads a web page, not this ISO.
Any suggestions? | Use
wget "
Explanation: There is "&" character in the url. On linux and alike systems, this makes it a background process. Solution it to enclose url in double quoutes (") so that its treated as one argument. | stackexchange-superuser | {
"answer_score": 21,
"question_score": 20,
"tags": "linux, download, wget"
} |
socket descriptor vs file descriptor
read(2) and write(2) works both on socket descriptor as well as on file descriptor. In case of file descriptor, User file descriptor table->file table and finally to inode table where it checks for the file type(regular file/char/block), and reads accordingly. In case of char spl file, it gets the function pointers based on the major number of the file from the char device switch and calls the appropriate read/write routines registered for the device. Similarly appropriate read/write routine is called for block special file by getting the function pointers from the block device switch.
Could you please let me know what exatly happens when read/write called on socket descriptor. If read/write works on socket descriptor, we cant we use open instead of socket to get the descriptor? | Socket descriptors are associated with file structures too, but a set of file_operations functions for that structures differs from the usual. Initialization and use of those descriptors are therefore different. Read and write part of kernel-level interface just happened to be exactly equivalent. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 16,
"tags": "linux"
} |
How to walk a tar.gz file that contains zip files without extraction
I have a large tar.gz file to analyze using a python script. The tar.gz file contains a number of zip files which might embed other .gz files in it. Before extracting the file, I would like to walk through the directory structure within the compressed files to see if certain files or directories are present. By looking at tarfile and zipfile module I don't see any existing function that allow me to get a table of content of a zip file within a tar.gz file.
Appreciate your help, | You can't get at it without extracting the file. However, you don't need to extract it _to disk_ if you don't want to. You can use the `tarfile.TarFile.extractfile` method to get a file-like object that you can then pass to `tarfile.open` as the `fileobj` argument. For example, given these nested tarfiles:
$ cat bar/baz.txt
This is bar/baz.txt.
$ tar cvfz bar.tgz bar
bar/
bar/baz.txt
$ tar cvfz baz.tgz bar.tgz
bar.tgz
You can access files from the inner one like so:
>>> import tarfile
>>> baz = tarfile.open('baz.tgz')
>>> bar = tarfile.open(fileobj=baz.extractfile('bar.tgz'))
>>> bar.extractfile('bar/baz.txt').read()
'This is bar/baz.txt.\n'
and they're only ever extracted to memory. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "python"
} |
Does using an MVC approach to (PHP-based) web applications necessarily mean that it will be more scalable than other approaches?
From what I understand MVC frameworks are pretty hefty (Zend,Cake,CodeIngniter), so it almost seems contrary to talk about scalability and suggest using MVC. | Zend, Cake, CodeIgniter... they all come with a bunch of stuff you don't need. A basic MVC framework is simple, and does not need many files to work.
Also, applications built upon a MVC structure are no more or less scalable than other approaches may be, but **may** be more organized. It's subjective. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "php, model view controller, frameworks"
} |
Make Emission Bloom From Behind an Object?
I'm perplexed why I can't get an emissive object to bloom out from behind another object. Any tricks to this? 
* Add a _Point_ lamp with Strength 10.000 W
Important here is set **Custom Distance** (here 1.3)
.
mother(person3,person2).
say_hi(X) :- father(X,person1) , write('Hello1').
say_hi(X) :- father(X,person2) , write('Hello2').
I want to have a list of different sentences: the program should return different sentences each time that you call say_hi
So , the expected output of the program should be:
?- say_hi(person1)
Hello1
?- say_hi(person1)
Hello3
?- say_hi(person4)
Hello4
The different elements of the list should be written in a random way | If you want just once each list' element, here is a possible definition (in SWI-Prolog), that returns elements on backtracking:
get_random([E], E) :- !.
get_random(L, E) :-
length(L, C),
R is random(C),
length(Skip, R),
append(Skip, [X|Tail], L),
( E = X
; append(Skip, Tail, Rest),
get_random(Rest, E) ).
test:
?- get_random([a,b,c,d,e,f],X).
X = e ;
X = f ;
X = d ;
X = b ;
X = c ;
X = a. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "list, prolog"
} |
using sum and group by and ifnull
I have a table of money owed, along with a team identifier (could be 1,2,3 for example)
I have another table which gives a name to these team identifiers (so 1 could refer to Team1, 2 could refer to John's jokers etc)
The first table can have multiple entries for money owed and I need to get the total owed per team identifier, and use the team name if it exists.
So I left join the tables and use a sum clause and get a total amount owed per teamname, or null if the teamname is not present. If it is null then I want to use the team identifier, so the results would look like
name total
.....................
team1 100
John's jokers 1000
99 50
where 99 is a team identifier because there was no teamname and there was a null present.
I tried using ifnull(columnName, teamID) but this failed when using a sum clause.
Could anyone help with this problem please | I think ifnull() is used like this:
select ifnull(teams.team_name, teams.team_id) from teams;
So in this case it tries to retrieve the name of the team, and if that comes back null it instead uses the team's identifier. In this case your query would look like this:
select ifnull(teams.team_name, owing.team_id), sum(amount_owed)
from owing left join teams on owing.team_id = teams.id
group by owing.team_id
Make sure the group by asks for the ID field from owing, not teams, otherwise you'll be grouping on a null field.
Does this resolve the issue? | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "mysql, sql"
} |
Is 'alias' a reserved word?
I'm using Angular 2 and Typescript. I've a component with a property declared like this.
alias: string;
When I try to bind this to a input tag in my template likte this.
<input class="form-control" type="text" required
[(ngModel)]="alias" ngControl="alias" #alias="ngForm" />
When running this code I get an error saying,
> angular2.dev.js:23925 EXCEPTION: Error: Uncaught (in promise): Cannot reassign a variable binding alias
If I change the property name from 'alias' to 'nameOrAlias' everything works as expected without errors. Why? | > Cannot reassign a variable binding alias ...
You get this error because you are trying to assign template variable with the same name `alias`:
<input class="form-control" type="text" required
[(ngModel)]="alias" ngControl="alias" #alias="ngForm" />
<!-- ^--- "alias" reasignment -->
So you should rename either template variable or component property. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "angularjs, typescript, angular"
} |
Eclipse::Indirectly referenced from required .class files
I am facing a weird issue. When I add some external JARs to the classpath I get the error "It is indirectly referenced from required .class files". But when I remove all of them I get rid of this error. Here re the entries for .classpath
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="bundle/src/main/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="C:/external_jars/cq-wcm-api-5.7.8.jar"/>
<classpathentry kind="lib" path="C:/external_jars/cq-wcm-commons-5.7.8.jar"/>
<classpathentry kind="lib" path="C:/external_jars/cq-wcm-core-5.7.116.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
Do let me know if I need to provide any other info.
Thanks in advance | That error means you have some unresolved dependency, i.e. one of those jar files depends on some other jar file that you have not added to your classpath.
I believe this is a duplicate of: Eclipse error: indirectly referenced from required .class files? | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 8,
"tags": "java, eclipse"
} |
How to add a dynamic area to a twitter bootstrap table row
I have a requirement where I am using twitter bootstrap table to display user properties such as email , first name , last name , password etc.
Now i wanted to create something like in facebook account settings page. When I click on the edit button the row gets enlarge and than you can put your edit elements there in a form which has a submit button and a close button. On submitting the row again shrinks backs to the original and also on clicking the close button.
Is this possible using twitter bootstrap? | Facebook are using a UL (unordered list) element rather than a table which is kind of better as tables are only meant to be used for displaying tabular data.
All they are doing is that when you click "edit" a hidden DIV is being populated (probably by AJAX) with the form and it's labels etc.
Then the user can either edit and save thir information which will post it back to the database or they can cancel the form which obviously unpopulates the hiddeb DIV and returns the row to it's previous state.
Bootstrap has no default programming built in for this functionality but given the basic concept above it shouldn't be too tricky for a good developer to knock up. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "twitter bootstrap"
} |
Looking for Diode L V 108 datasheet
What is this diode and what is it used for?
. | stackexchange-electronics | {
"answer_score": 0,
"question_score": -4,
"tags": "diodes"
} |
Ssh github + gitlab, how to make?
I want to not type my username and password every time when work with something git, so my ssh config is:
Host gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile /root/.ssh/id_rsa_gitlab
IdentitiesOnly yes
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile /root/.ssh/id_rsa
IdentitiesOnly yes
I makes 2 different rsa keys, add pub keys to github and gitlab, but it keep asking me login and pass, pls can someone help me with it? | Navigate to the project directory and type `git config --list`.
If `remote.origin.url` looks like ` you will need to change it to the one that looks like `[email protected]:gitlab-org/gitlab-ce.git`. This can be found on the main page of any project on GitLab.
Use git-remote to set the new URL.
`git remote set-url origin [email protected]:gitlab-org/gitlab-ce.git`
This answer shows an example of the process. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "git, ssh"
} |
TFS 2010 custom build step
I am playing with TFS 2010, and am trying to setup a build process that will have some custom steps.
These include things like, stopping/starting IIS, search and replace files etc... across environments.
I have tried to look for examples online and have not found anything clear and meaningful on how to just run a script or something over the source files. Looking at the default build process template (DefaultTemplate.xml) I cant make much sense of it.
How do I go about doing this ? | For info on customising the TFS2010 workflow build templates have a look at Ewald Hoffman's series. Start with Part 1 (archived here).
I should also mention that since it looks like you're doing deployment then you may want to break deployment automation away from build automation. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "tfs, tfsbuild, tfs 2010"
} |
How to find the last valid value's index in list or array
I would like to find the last valid value. I found some code for dataframe but can't find for the code for list or array
List = [nan, 1, 4, 6, 8, 122, 12, 34, 54, nan, nan, nan,nan, nan]
The result should look like this:
print(some_function_for_last_valid_index(List))
output : 8
(output is an index) | This is one approach
**Ex:**
import numpy as np
lst = [np.nan, 1, 4, 6, 8, 122, 12, 34, 54, np.nan, np.nan, np.nan,np.nan, np.nan]
lst = [i for i in lst if not np.isnan(i)]
#or lst = filter(lambda x: np.isfinite(x), lst)
print(len(lst)) #8 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python, list, nan"
} |
iphone: How to remove white strip from bottom?
I changed the background color to black.
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithRed: (10.0/255) green: (10.0/255) blue: (10.0/255) alpha: 1.0];
}
but both in device or Emulator it shows a white strip in the end. How to get rid of this ... please help
!enter image description here | To this happen you probably are adding a subview that are white, or your view is with the wrong frame size, or your frame is with the wrong initial point.
Try this code to change the view frame to be equal to your device frame:
[self.view setFrame:[[UIScreen mainScreen] bounds]]; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c, ios, ipad"
} |
Getting the user who created a 365 group
Is it possible to extract from Microsoft Graph to fetch what user has created a specific 365 group? I need to get which user created specific team site.
Best R, Thomas | For non admins users you can use this:
` object id}/createdOnBehalfOf `
For every user you can use the List directoryAudits operation with the following query and extract initiatedBy/user/id from each returned record.
` eq 'GroupManagement' and activityDisplayName eq 'Add group' ` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "microsoft graph api, microsoft teams, microsoft graph sdks"
} |
How would I make a Twitter-like feed using SQL/PHP?
On the site I am building, users can follow others and post things. I am trying to compile a feed page that allows users to see all the posts in chronological order from people they follow (pretty much what Twitter does).
The SQL table for holding "posts" (entitled "posts") is set up with the columns:
* "id" (autoincremented)
* "material" (text content of post)
* "whencreated" (when posted)
* "authorid" (user that posted it)
The SQL table for holding following/followers (entitled "follow") contains the columns:
* "id"(autoincremented)
* "followerid" (id of follower)
* "followingid" (id of who they are following)
I essentially need to know how to loop through a person's "following" ids and list out the posts by each following id in chronological order. Once again, the result is pretty much a clone of Twitter.
Thanks! Sorry if this is too specific. | Something like this maybe?
SELECT posts.* FROM posts
INNER JOIN follow ON posts.authorid = follow.followingid
WHERE follow.followerid = ?
ORDER BY posts.whencreated DESC
Where `?` is the ID of the current user.
I suggest you to have a look at these info pages about INNER JOIN and ORDER BY.
This is only the SQL part, I'm going to leave the PHP part as an exercise. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, sql, feed"
} |
Smack API - How to display loop jxTaskpane for expand and collapse roster list
i have problem to display Taskpane for loop. i have a code to get the groups of roster (Groups : Friends - Business - Company, so on) my code is :
Roster rost = xmppcon.getRoster();
Collection<RosterGroup> groups = rost.getGroups();
for(RosterGroup group : groups){
DefaultListModel model = new DefaultListModel();
model.addElement(group.getEntries());
String GroupNameCount = group.getName() + "("+group.getEntryCount()+")";
jXTaskPane1.setTitle(GroupNameCount);
jXList1.setModel(model);
}
but jxTaskpane not loop, but when i print group name it print 2 line (because in database user A have two group is Friends and NIIT)
sample print
System.out.println(group.getName());
result:
Friends
NIIT | You're using the same instances of JXTaskPane and JXList at each iteration of the loop. You should really create one instance (`JXTaskPane jXTaskPane1 = new JXTaskPane()`), and same for the JXList in the loop.
When you've setup the JXTaskPane, add it to the containing component. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, smack, jxtaskpane"
} |
Cannot read property 'msie' of undefined jquery.colorbox.js:66
I am getting below exception while using jquery colorbox with
<script src="
Below is the exception-
Uncaught TypeError: Cannot read property 'msie' of undefined jquery.colorbox.js:66
(anonymous function) jquery.colorbox.js:66
(anonymous function) jquery.colorbox.js:814
Uncaught TypeError: Object [object Object] has no method 'colorbox' HRS_HRAM.JN_HRS_APP_SCHJOB.GBL&country=FRA?PortalActualURL=https%3a%2f%2fhr…fpsc%2fhrmssox%2f&PortalHostNode=HRMS&NoCrumbs=yes&PortalKeyStruct=yes:497
(anonymous function) HRS_HRAM.JN_HRS_APP_SCHJOB.GBL&country=FRA?PortalActualURL=https%3a%2f%2fhr…fpsc%2fhrmssox%2f&PortalHostNode=HRMS&NoCrumbs=yes&PortalKeyStruct=yes:497
c jquery.js:7341
p.fireWith jquery.js:7403
b.extend.ready jquery.js:6875
H
Does anyone know what is the problem? And how to fix it? | The page for jQuery Colorbox says (emphasis mine):
> Released under the MIT License. Source on Github (changelog).
>
> **Compatible with: jQuery 1.3.2+** in Firefox, Safari, Chrome, Opera, Internet Explorer 7+ The plugin is not compatible with your version of jQuery.
It seems like the plugin is too old for jQuery 1.9.1, probably because it's using the `.browser` property.
You'll have to fix the plugin, or reintroduce the property as described here. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "javascript, jquery, html"
} |
Reduction from Hamiltonian cycle to Hamiltonian path
I'm looking for an explanation on how reducing the Hamiltonian cycle problem to the Hamiltonian path's one (to proof that also the latter is NP-complete). I couldn't find any on the web, can someone help me here? (linking a source is also good).
Thank you. | Note: The below is a Cook reduction and not a Karp reduction. The modern definitions of NP-Completeness use the Karp reduction.
For a reduction from Hamiltonian Cycle to Path.
Given a graph $G$ of which we need to find Hamiltonian Cycle, for a single edge $e = \\{u,v\\}$ add new vertices $u'$ and $v'$ such that $u'$ is connected only to $u$ and $v'$ is connected only to $v$ to give a new graph $G_e$.
$G_e$ has a Hamiltonian path if and only if $G$ has a Hamiltonian cycle with the edge $e=\\{u,v\\}$.
Run the Hamiltonian path algorithm on each $G_e$ for each edge $e \in G$. If all graphs have no Hamiltonian path, then $G$ has no Hamiltonian cycle. If at least one $G_e$ has a Hamiltonian path, then $G$ has a Hamiltonian cycle which contains the edge $e$. | stackexchange-math | {
"answer_score": 30,
"question_score": 22,
"tags": "graph theory, computer science"
} |
Hide legend in plotly express (not Plotly)
I have a scatteplot I’m trying to present, with lots of symbols and colors. This makes the default legend unreadable. Is there a way to hide the legend (equivalent, or similar to showlegend=False when using traces and graph objects)?
Here’s my graphing line:
`fig = px.scatter(df_revised, x='df_x', y = 'df_y', color = 'type', symbol = 'country', hover_data = ['id'], marginal_y="histogram", marginal_x="histogram")`
I've seen the question mentioned here, but that is not useful, as it's changing the plotting library to plotly rather that the express version.
I have also tried `fig.update_layout(showlegend=False)` but that return an error `AttributeError: 'ExpressFigure' object has no attribute 'update_layout'` | With the version you have right now, `fig.layout.showlegend = False` should work (and continues to work with the latest version!). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, matplotlib, plotly, data visualization, plotly express"
} |
Git Newbie - How often should I push to Heroku
I'm used to the traditional way of using FTP - where I simply upload a chaged file and refresh the page to view the changes.
However, is this OK to do so with Git? Or should I be running a local server on my PC then pushing a final, complete version to Heroku Master? | Git isn't a drop-in replacement for FTP. IMO you should always develop on a local system. Commit significant changes with useful comments as regularly as you can bear to. Push when you NEED to see the app in Heroku, or if you get paranoid that you need a remote backup of your Git repos. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "git, heroku, push, development environment"
} |
Rx.js, Subscribe is called with undefined
I'm using Rx.js to stream my results from an AJAX call to multiple units.
But I have encountered issue when there is more than on observer subscribing to MapObserver. When the first subscriber will always get the correct data but the rest will get undefined.
this.observable = new Rx.Subject();
observeMap = this.observable
.map(createMarker.bind(this));
var s1 = observeMap.subscribe(console.log.bind(console, 1));
var s2 = observeMap.subscribe(console.log.bind(console, 2));
!Console Logs Please advice, Thanks! | I just found a solution for my question, in order to share an observable across few subscribers, you can use share method.
this.observable = new Rx.Subject();
observeMap = this.observable
.map(createMarker.bind(this))
.share();
var s1 = observeMap.subscribe(console.log.bind(console, 1));
var s2 = observeMap.subscribe(console.log.bind(console, 2)); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, node.js, reactive programming, rxjs"
} |
How to list all rows from table and display specific column data from wordpress database
I have table called wp_email_subscription and inside table I have rows of emails from subscribed users. Each row contains id, email, and name column.
I have also created admin page for plugin where I would like to list all emails from subscribed table.
Basically I don't know how to use wpdb functions, I have read wpdb instructions from wp website but I don't understand.
what I need is to select all from wp_email_subscription and foreach row to display email and name column in list. | you have to use `global wpdp` variable and `get_result` function in your code page like this...
global $wpdb;
$row = $wpdb->get_results( "SELECT * FROM wp_email_subscription");
foreach ( $row as $row )
{ echo "email:".$row->email.";} //$row->your_column_name in table
like this, you can access all columns by `$variable->col_name` | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 5,
"tags": "database, plugins, wordpress"
} |
How can the word 'priori' be used?
I am only familiar with 'a priori', such as 'a priori conditions'. Now a friend uses the word as follows:
> "the supremacy of nature and the priori and inevitability of death and of history."
I do not know if maybe they mean 'priority', or maybe they mean something esoteric and beyond me. | I believe using 'priori' by itself is incorrect. It should be 'a priori' (meaning prior to). Similarly, using 'posteriori' by itself is incorrect. It should be 'a posteriori' (meaning posterior to).
Here's an excerpt from the wiki link that describes them:
> The terms "a priori" and "a posteriori" are used in philosophy to distinguish two different types of knowledge, justification, or argument: 'a priori knowledge' is known independently of experience (conceptual knowledge), and 'a posteriori knowledge' is proven through experience. Thus, they are primarily used as adjectives to modify the noun "knowledge", or taken to be compound nouns that refer to types of knowledge (for example, "a priori knowledge"). However, "a priori" is sometimes used as an adjective to modify other nouns, such as "truth". Additionally, philosophers often modify this use. For example, "apriority" and "aprioricity" are sometimes used as nouns to refer (approximately) to the quality of being a priori." | stackexchange-english | {
"answer_score": 2,
"question_score": 2,
"tags": "single word requests"
} |
Plus sign in the middle of a ring
I would like to draw in `chemfig` the following picture:
!enter image description here
But I am struggling with the "+" sign in the middle of the circle. Is there a way to draw it? Thank you!
What I have so far is this:
\documentclass{article}
\usepackage{chemfig}
\begin{document}
\chemfig{
N**[0,-150,dash pattern=on 2pt off 2pt]5(
(-R)-(-R^1)-[,,1,2]{+\hspace{0.3cm}}|{O}-[,,2,1]--
)
}
\end{document}
which does the work, but I really don't like the way it is done (e.g. it does not scale). | The following examples uses that the `tikz` code for the arc uses a center node named `arccenter`. The `tikz` option argument for the `\draw` command of the arc can be used with option `late options` to put a label in the center:
\documentclass{article}
\usepackage{chemfig}
\begin{document}
\chemfig{
N**[0,-144,dash pattern=on 2pt off 2pt,
late options={name=arccenter,label=center:+}]
5( (-R)-(-R^1)-O--- )
}
\end{document}
> !Result | stackexchange-tex | {
"answer_score": 21,
"question_score": 19,
"tags": "chemfig"
} |
Linux command to "link" files
When I do "ls -lrt", there is a file that is listed and I want to create link for example,
myfile.config -> /users/yue/home/logs/myfile.config
When making changes in `myfile.config` it also affects the file in `/users/yue/home/logs/myfile.config.`
What command in linux allows for that? Also, what is this called? | Figured it out,
Its actually "ln -s " command | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "linux"
} |
NumPy np.zeros() cannot interpret multi-dimensional shape as a data type
Here's the code I want to run :
print(np.zeros(3, 2))
If I'm not wrong it should return :
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]
But instead, get this error :
print(np.zeros(3,2))
TypeError: Cannot interpret '2' as a data type
And when I try running this :
print(np.zeros(3,))
It worked perfectly find and return the output as I expected
How can I fix this? Thank you | First `numpy.zeros`' argument _shape_ should be
> int or tuple of ints
so in your case
print(np.zeros((3,2)))
If you do `np.zeros(3,2)` this mean you want `dtype` ( _The desired data-type for the array_ ) to be `2` which does not make sense. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, numpy"
} |
OrbitControls.js and re-focusing orbit target on a new selected object
I am very bad at three.js - but I believe I have cobbled together a basic raycast on a set of objects, to select the object of interest.
<
I am now trying to have OrbitControls.js focus the target vector on that object, i.e., once selected, be able to orbit around that object. I have tried a few variations, where some lead to what appears to be an empty (or out of camera range) scene.
`controls.target.set(obj.position)`
where `obj` is the raycast object and `controls` is the OrbitControl instance.
The quick(?) question: how do you set the orbit center of three.js OrbitControl given an object from a raycast? | It turns out that the fbx model on raycast seemed to return one of its child objects in the child object's coordinate system (though the material coloring seemed to color the whole object). Setting it to the parent seems to have solved it.
1. Check to see if it's a child object or child segment that is returning the same local coordinate
2. for controls.target setting, the vector3 is an object that needs to be copied `.copy` (thanks @WestLangley) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "three.js"
} |
JAVA logical operations
I really don't understand this kind of "operations" or what are they called :
System.out.println((1<2) ?5: (3<4) + " ");
Is the same with this code ?
if(1<2)
return 5;
else if (3<4)
But after ':' it says _Dead code_ . Why is that ? | Compiler evaluates constant expressions at compile time. Because of that, the expression `1<2` is fully equivalent to the expression `true`, making the initial part of your conditional expression look like this:
System.out.println((true) ? 5 : (3<4) + " ");
// ^^^^^^^^^^ ^^^^^
// Important code |
// |
// Useless code -----------+
The compiler does not stop at evaluating `1<2`, it goes on to evaluating the rest of the expression, which produces `5`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java"
} |
Good way to store phone numbers in django models
I was creating a model, and one of the fields is for a phone number. What exactly would be the best way to hold a phone number in a django model?
What would allow for the best functionality? | Use this package < just install it with pip | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "django, django models"
} |
Prove that there are infinitely many perfect squares starting with 2018
> Prove that there are infinitely many perfect squares starting with 2018(as for example 20187049,201810436 are perfect square.
First of all I had assumed that there are finitely many perfect square numbers starting with 2018 and thought proving this by contradiction. Now let M is the maximum number starting with 2018. I can realize that we can find another number N\gt M which is a perfect square starting with 2018 . But I failed to find any direct method of solving this. Somebody please give any hint or the full solution.
N.B. If you have any types of confusion please command I will surely answer. So command before down voting or closing this question. | Since $$\sqrt{2019\cdot10^n}-\sqrt{2018\cdot10^n}=\frac{10^n}{\sqrt{2019\cdot10^n}+\sqrt{2018\cdot10^n}}>\frac{10^n}{2\sqrt{2019\cdot10^n}}=\sqrt{\frac{10^n}{4\cdot2019}}>1$$ for $n\ge4$, there must be an integer in that interval. And that means there is an integer square with $n+4$ decimals starting with $2018$ for every $n\ge4$. | stackexchange-math | {
"answer_score": 6,
"question_score": 3,
"tags": "elementary number theory"
} |
What is the best way to use three different losses on two classifiers?
Two classifiers need to be trained simultaneously, and I have three losses, as shown in the figure. Classifiers 1 and 2 will be updated by losses 1 and 2. Furthermore, loss 3 should update the two classifiers concurrently. Here's what I did
loss1.backward()
loss2.backward()
loss2.backward()
Is this correct? . To give values to $\lambda_i$ you may simply assign $\lambda_i = 1$ or you can grid search to obtain better values.
Normally, you want $\lambda_i$ to compensate for the differences in the gradient norms of $loss_i$, to avoid one of them overshadowing the rest. For that, I suggest you monitor the norm of the gradients of $loss_i$ in a training rehearsal to understand the value ranges that are appropriate for each $\lambda_i$. | stackexchange-datascience | {
"answer_score": 1,
"question_score": 0,
"tags": "machine learning, pytorch, optimization"
} |
"Je dois vous rencontrer" vs. "J'ai besoin de vous rencontrer": Lequel est le plus poli et le plus formel?
> Je dois vous rencontrer.
vs.
> J'ai besoin de vous rencontrer
Lequel est le plus poli et le plus formel?
**P.S.** I have a few very important questions about an emergency topic and I need to meet the person in charge of a department at a university. | > Je dois vous rencontrer.
implique une obligation morale, voire un ordre. Or d'après le contexte tu t'adresses à un supérieur auquel tu demandes un service qu'il peut, ou non, t'accorder. Il vaut donc mieux dire :
> J'ai besoin de vous rencontrer.
Et si tu veux être encore plus poli tu mettras le verbe au conditionnel :
> J'aurais besoin de vous rencontrer pour vous demander.... | stackexchange-french | {
"answer_score": 5,
"question_score": 3,
"tags": "politesse, formulation"
} |
Using performSelector in a For loop ? iPhone
I have an array (called array in the code below) which contains a number of MyView objects. I am trying to iterate through these objects in a For loop and add them as a subview one by one, each after a delay of one second. The problem with the code below is that all the objects are added at once after a delay of one second. Can anyone suggest how I can correct ?
Thank you in advance.
- (void)startMethod {
for (MyView * myview in array) {
[self performSelector:@selector(addSubView:) withObject:myview afterDelay:1];
}
}
- (void)addSubView : (UIView *)view {
[soundController playSound];
[self.view addSubview:view];
} | The time to execute the loop isn't enough to delay selectors perform. You probably need to delay yourself using for example a counter.
-(void)startMethod {
NSUInteger i = 0;
for (MyView * myview in array) {
i += 1;
[self performSelector:@selector(addSubView:)
withObject:myview
afterDelay:i];
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c, xcode, multithreading, for loop"
} |
What capabilities does Apache Storm offer that are not now covered by Kafka Streaming?
I'm very naive about data engineering but it seems to me that a popular pipeline for data used to be Kafka to Storm to something.... but as I understand it Kafka now seems to have data processing capabilities that may often render Storm unnecessary. So my question is simply, in what scenarios might this be true that Kafka can do it all, and in what scenarios might Storm still be useful?
EDIT: Question was flagged for "opinion based".
This question tries to understand what capabilities Apache Storm offers that Apache Kafka Streaming does not (now that Kafka Streaming exists). The accepted answer touches on that. No opinions are requested by this question nor are they necessary to address the question. Question title edited to seem more objective. | You still need to _deploy_ the Kafka code somewhere, e.g. YARN if using Storm.
Plus, Kafka Streams can only process between the same Kafka cluster; Storm has other spouts and bolts. But Kafka Connect is one alternative to that.
Kafka has no external dependency of a cluster scheduler, and while you may deploy Kafka clients in almost any popular programming language, it still requires external instrumentation, whether that's a Docker container or deployed on bare-metal.
If anything, I'd say Heron or Flink are true comparative replacements for Storm | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "apache kafka, apache storm"
} |
Every path $f:[a,b] \rightarrow \mathbb {R}^n$ of class $C^1$ is rectifiable, and the lenght $\mathcal {l}$$(f)= \int_{a}^{b} |f'(t)|dt$
Good evening everyone! I am in trouble to demonstrate the folowing theorem:
"Every path $f:[a,b] \rightarrow \mathbb {R}^n$ of class $C^1$ is rectifiable, and the length $\mathcal {l}$$(f)= \int_{a}^{b} |f'(t)|dt$".
I want to show that $\lim_{|P|\rightarrow 0}\mathcal l$$(f,P)= \int_{a}^{b} |f'(t)|dt$. So, given $\varepsilon >0$, I take a partition $P=\\{t_0,t_1,...,t_k\\}$ and a point $\phi_i=t_{i-1} \in [t_{i-1},t_i]$. Then there exists $\delta_1 >0$ such that $|P|< \delta_1 \Rightarrow \left|\int_{a}^{b} |f'(t)|dt-\sum_{i=1}^k |f'(t_{i-1})|(t_i-t_{i-1}) \right|< \varepsilon$. I must get a result like $|P|< \delta_1 \Rightarrow \left|\mathcal{l}(f,P)-\int_{a}^{b} |f'(t)| dt \right| < \varepsilon$, but how? | If $P=(t_0=a,....,t_n=b)$ is a partition, let $l_P(f) = \sum_{k=0}^{n-1} |f(t_{k+1})-f(t_k)|$. We have $l_P(f) = \sum_{k=0}^{n-1} | \int_{t_k}^{t_{k+1}} f'(t) dt | \le \sum_{k=0}^{n-1} \int_{t_k}^{t_{k+1}} |f'(t)| dt = \int |f'|$, from which it follows that $f$ is rectifiable.
Now let $g_P = \sum_{k=0}^{n-1} \inf_{ [t_k,t_{k+1})} |f'(t)| 1_{ [t_k,t_{k+1}) } $. We have $g_P(t) \le |f'(t)|$ and since $f$ is $C^1$, for any $\epsilon>0$, we can find a partition such that $|f'(t)| -g_P(t) < \epsilon {1 \over b-a}$. Hence we have $\int g_P \le \int |f'| \le \int g_P + \epsilon$.
Using the mean value theorem, we have $l_P(f) = \sum_{k=0}^{n-1} |f'(\xi_k)| (t_{k+1}-t_k)$, for some $\xi_k \in [t_k,t_{k+1})$, and hence $\int g_P \le l_P(f)$.
Combining the above, we have $\int g_P \le l_P(f) \le \int |f'| \le \int g_P + \epsilon$. It follows that $\sup_P l_P(f) = \int |f'|$, where the $\sup$ is taken over all partitions of $[a,b]$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "real analysis"
} |
How can I get application by process
it's impossible to get app info(name, maybe other) by `Process` class? I know i can get **.exe** file name, but i want get app name. It is desirable that the solution be cross-platform?
Example: . I can parse title, but this is not a universal way. | To get the descrition of the executable file for a running process, you can use
string GetProcessDescription(Process process)
{
try
{
return process.MainModule?.FileVersionInfo?.FileDescription;
}
catch
{
return null;
}
}
The exception handler is necessary because you might not have the permission to access the information, or the process might not have a file module at all. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, process, cross platform"
} |
Write dynamic content inside dynamic div
I am creating dynamic `<div>` blocks with `id`s that contain `i` from for loop.
I am getting error if I want to get a specific `<div>` in dynamic `<div>`s
Error: `Cannot read property 'getElementById' of undefined.`
document.getElementById("roomModal_"+i).document.getElementById("modalDialog_"+i).document.getElementById("modalContent_"+i).document.getElementById("modalBody_"+i).document.getElementById("images");
If I just write `document.getElementById("images")` then I can get it, but the point is that each dynamic `<div>` block has its own content.
<
Am I missing something? | The `getElementById()` will return an object and you can't call `.document.getElementById` on object.
So you can't nest the js selectors as you do now, instead use `querySelector` like :
var img = document.querySelector("#roomModal_"+i+" #odalDialog_"+i+" #odalContent_"+i+" #odalBody_"+i+" #images");
Since you're using `id`'s and the `id` should be unique in same document you could just do :
var img = document.querySelector("#images");
//Or
var img = document.getElementById("#images");
To get the element with specific `images`.
Hope this helps. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, html"
} |
Hilbert space problem
> Let $(H, (\cdot,\cdot))$ be a Hilbert space over complex numbers and $x,y\in H$. Suppose $$|(z,x)|\leqslant |(z,y)|$$ for all $z\in H$. Is it true that $x=\lambda y$ for some $\lambda\in\mathbb C$?
Any help is appreciated. | This is not true. Put $x=\alpha y$, where $|\alpha|\leq1$.
Given the edit to the question, observe that if $(z,y)=0$, then $(z,x)=0$. So $\\{y\\}^\perp\subset\\{x\\}^\perp$, and use this to show that $x\in\text{span}\\{y\\}$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "functional analysis, hilbert spaces, inner products"
} |
Custom TextView in android with different color words
Is it possible to have a `textview` to have different color for every word? Or even every letter? I tried extending `textview` and creating it but however I thought of the problem is, how would I draw all the the text out at the same time with different colors? | Use `android.text.Spannable`
final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
new ForegroundColorSpan(Color.BLUE),
wordStart,
wordEnd,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);
**EDIT** : To make all "Java" green
final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);
final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
spannable.setSpan(
span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
myTextView.setText(spannable); | stackexchange-stackoverflow | {
"answer_score": 32,
"question_score": 15,
"tags": "android, textview"
} |
mysql unique (multiple keys )
hi guys I have attached a pic for the table structure.. !mysql unique
**The problem**
I am adding a new record to db and it says its duplicated when `title` is different is there something wrong on the way I have structured all three to be unique?
I need the title,parent, eid to be unique as only if all three have the same data in it, if one of the fields is different treat it as a non duplicate
**UPDATED** The title `bla bla` does not exist on db yet
INSERT INTO `test_table` (`id`,`title`,`parent`,`lang`)VALUES(1,'Bla bla',0,25); | The error is because of the duplicate value for `id` and not for `title`.
`id` is your primary key so duplicates are not allowed. Also your schema says that `id` is an auto increment field, so you need not enter its value explicitly. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "mysql, mysql error 1062"
} |
java's DO_NOTHING_ON_CLOSE
I have this snippet of the code:
public class Main_class {
public static void main(String[] args) {
JFrame first = new JFrame();
first.setTitle("Hello");
first.setSize(300, 100);
first.setLocation(300, 100);
first.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
first.setVisible(true);
}
}
I receive primitive frame, my question is how do I supposed to close the window without windows manager task, thanks in advance | If you _want_ to close it anyways I would implement a close listener that disposes the frame:
public static void main(String[] args) {
final JFrame first = new JFrame();
first.setTitle("Hello");
first.setSize(300, 100);
first.setLocation(300, 100);
first.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// do other stuff....
first.setVisible(false);
first.dispose();
}
});
first.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
first.setVisible(true);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java"
} |
Uniform continuity of $x^{\frac1{2}}\sin({\frac1{x^3}}$ and $f:|f(x)-f(y)\le\sqrt{|x-y|}$
> Whether these two functions are uniformly continuous:
>
> 1)$f$ such that $|f(x)-f(y)|\le\sqrt{|x-y|}\ \forall x\in(0,1)$
>
> 2)$f$ such that $f(x)=x^{\frac1{2}}\sin(\frac1{x^3})\forall\ x\in(0,1)$
For 1), I think there exists a counterexample because $|x-y|\le\sqrt{|x-y|}\forall x\in(0,1)$. As for 2), I think this is similar to $x\sin \frac1{x}$. Any ideas. Thanks beforehand. | 1) If $f:[0,1]\to \mathbb{R}$ is such that :
$$\forall (x,y)\in[0,1]^2,\vert f(x)-f(y)\vert\le\sqrt{\vert x-y\vert}$$
Then $f$ is uniformly continuous because given any $\epsilon>0$, if we choose $\delta=\epsilon^2$, we readily see that :
$$\forall (x,y)\in[0,1]^2, \vert x-y\vert\le\delta\implies\vert f(x)-f(y)\vert\le\epsilon^2$$
2) If $f$ is defined by :
$$f:[0,1]\to\mathbb{R},x\mapsto\cases{\sqrt{x}\sin(\frac{1}{x^3})\quad\mathrm{if}\,0<x\le1\cr0\quad\mathrm{otherwise}}$$
then $f$ is continuous (because $\sin$ is bounded and therefore $\lim_{x\to0}f(x)=0=f(0)$) and hence uniformly continuous by Heine theorem | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, continuity, uniform continuity"
} |
Regex parsing of digits and alphabets of variable lengths and frequency
I am still a newbie to regex and find it rather steep in grasping it all in one go. Hence, I reaching out to you all to understand how I can grab the first group of digits or alphabets in the following example
01_crop_and_animal
02_03_forestry_fishing
05_09_13_15_19_23_31_39_other_location
68201_68202_operation_of_dwellings
a_agriculture_forestry_and_hunting_01_03
b_f_secondary_production_05_43
Digits seems to appear multiple times, and can have length of 2 to 5. Alphabets occur once or twice. I would essentially like to see the output as:
01
0203
0509131519233139
6820168202
a
bf
Thanks for your help! Rob | It can be done in 2 step.
* 1rst step, match the digits/letters:
^(a-z?|\d{2,5}(?:_\d{2,5})*)(?![a-z\d])
Demo & explanation
* 2nd step, remove the underscores. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "regex"
} |
Is Junk Email auto scheduled for deletion in Outlook 2007?
Does Outlook 2007 automatically delete Junk email at scheduled intervals? | The short answer is "No" to "scheduled".
If you are in a Microsoft Exchange environment, you could set up a rule to delete it automatically, or in stand-alone Outlook, you can have it deleted it before it goes to the folder, by checking "Permanently delete suspected junk e-mail instead of moving it to the Junk E-mail folder."
!enter image description here | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "microsoft outlook 2007, spam prevention"
} |
ODE involving two functions
If I have the following two ODEs: $$f'(x)g(x)=f''(x)g(x)+f'(x)g'(x)$$ $$f(x)g'(x)=f(x)g''(x)+f'(x)g'(x)$$ With the initial conditions of: $\begin{cases}f(0)=g(0)=1 \\\ f'(0)=a>0 \\\ g'(0)=b>0 \end{cases}$
Is it possible to solve for $f$ and $g$ or do we need more information? | For the first equation, you can make the substitution $h(x)=f'(x)g(x),$ at which point it simplifies down to $h'(x)=h(x),$ with solution $h(x)=A e^{x}.$ Next, you can make the substitution $z(x)=f(x)g'(x),$ at which point the second equation becomes $z'(x)=z(x),$ with solution $z(x)=B e^x.$ So, we have \begin{align*} f'(x)g(x)&=Ae^x\\\ f(x)g'(x)&=Be^x. \end{align*} It follows that $f'(x)g(x)+f(x)g'(x)=(A+B)e^x,$ or $(f(x)g(x))'=(A+B)e^x.$ Then $$f(x)g(x)=(A+B)e^x+C $$ follows. The initial conditions imply $1=A+B+C,$ and \begin{align*} a\cdot 1&=A\\\ b\cdot 1&=B. \end{align*} So, we must have $1=a+b+C,$ and $$f(x)g(x)=(a+b)e^x+1-a-b. $$ This appears to be as far as you can go without more information. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "ordinary differential equations, analysis"
} |
Was Barty Crouch Jr. an Occlumens?
An _Occlumens_ is a practitioner of _Occlumency_ , while _Occlumency_ means closing the mind. Despite being in the same school with two great Legilimens (Dumbledore and Snape), he was only discovered to be an impostor after the last round of the Triwizard Tournament in _Goblet of Fire_ :
> “Moody,” Harry said. He was still in a state of complete disbelief. “How can it have been Moody?”
>
> “This is not Alastor Moody,” said Dumbledore quietly. “You have never known Alastor Moody. **The real Moody would not have removed you from my sight after what happened tonight. The moment he took you, I knew — and I followed.”**
Does this mean that Barty Crouch Jr. is an Occlumens? Because if not, then Snape or Dumbledore would have found it out earlier, right? | # It is unclear
It is not stated anywhere in the books that Legilimency was applied to fake Moody/Crouch jr. The conclusion Dumbledore made (quoted in the question) is based on pure logic, not Legilimency or any other magical means.
So unless any other canon information is available, we cannot tell. | stackexchange-scifi | {
"answer_score": 7,
"question_score": 4,
"tags": "harry potter, barty crouch jr"
} |
strdup() causing memory leaks?
I've implemented a function that returns a string. It takes an integer as a parameter (`age`), and returns a formatted string.
All is working well, except from the fact that I have some crazy memory leaks. I know strdup() is the cause of this, but I've tried to research some fixes to no avail.
My code is:
const char * returnName(int age) {
char string[30];
sprintf( string, "You are %d years old", age);
return strdup(string);
}
Valgrind's output is:
==15414== LEAK SUMMARY:
==15414== definitely lost: 6,192 bytes in 516 blocks
==15414== indirectly lost: 0 bytes in 0 blocks
==15414== possibly lost: 0 bytes in 0 blocks
==15414== still reachable: 0 bytes in 0 blocks
==15414== suppressed: 0 bytes in 0 blocks
Any help in resolving this memory leak issue is greatly appreciated. | From `man strdup`:
> Memory for the new string is obtained with `malloc(3)`, and can be freed with `free(3)`.
So you need to `free` the space allocated and returned by `strdup`.
Say you invoke `returnName` like that:
const char* str = returnName(3);
After you're done with `str` you can `free` it like this:
free((char*) str);
The cast is needed because `free` expects a **non-const** `void*`. This explicit conversion is alright here because `returnName` actually should return constant data1. Calling `free` is only a nasty implementation detail here.
* * *
1 As discussed with @M.M in the comments to this answer. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c, memory leaks, strdup"
} |
Using select by location is a stand alone script
I have script that I run quite regularly in the python window of Arcmap 10.2.2 and am in the process of converting it to a toolbox script so that others can use it more easily.
It uses select layer by location a number of times, for example:
arcpy.SelectLayerByLocation_management(Contours_G_1m, "CONTAINS", peakpoints)
It worked fine in the python window but now that its in a tool it fails with
> Parameters are not valid. ERROR 000368: Invalid input data
This is not at all surprising because this tool works on a layer and the script does not add a layer to the map when it creates a new feature class.
Is there any way of selecting the feature in a shapefile rather than a layer by location, or a workaround for using this tool in a script? | the input data of selectlayerbylocation is a **layer**. When you take it from ArcGIS python Windows, the feature class is already accessed through a layer, but with a stand alone script it is necessary to create the layer first.
This can be done with MakeFeatureLayer_management (in_features, out_layer, {where_clause}, {workspace}, {field_info}) | stackexchange-gis | {
"answer_score": 1,
"question_score": 1,
"tags": "arcpy, arcgis 10.2, python script tool, select by location, error 000368"
} |
Geoserver WMS layer does not show up in OpenLayers
I want to add a wms-overlay to an existing openlayers-map on a website. The layer is stored on geoserver. When i open the layer on geoserver, it works just fine. The data itself is in EPSG:31297.
But when i load the website openlayers is empty. Although the layer is shown in the layerswitcher.
I know there are a few questions concerning that topic, usually it had something to do with the project. However, in this case the projection should be fine. I can't figure out why it doesn't work.
Here is the code:
// My layer
var wms_layer = new OpenLayers.Layer.WMS (
"Layer",
"
{
layers: "master:dauersied_2mio",
transparent: "true",
projection: "EPSG:3857"
},
{isBaseLayer: false}
);
map.addLayer(wms_layer); | I totally forgot to declare a projection when initializing the map object. Now it works like a charm.
map = new OpenLayers.Map('map', {
projection: new OpenLayers.Projection("EPSG:3857")
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "openlayers, geoserver"
} |
Terms not appearing in wp_dropdown_categories
I am trying to use wp_dropdown_categories at front end. I got the dropdown box with default "uncategorized", the rest of the category is not there.
function cats_dropdown(){
require_once(ABSPATH . '/wp-admin/includes/template.php');
$args = array('taxonomy' => 'category');
?>
<div>
<?php wp_dropdown_categories($args); ?>
</div>
<?php
}
In the same function, if I try to output wp_terms_checklist, it works. This is confusing. Anything I missed in the dropdown? | It could be that it won't show empty categories, categories that has no posts attached to them.
Try to change `$args = array('taxonomy' => 'category');` to `$args = array('taxonomy' => 'category', 'hide_empty' => 0);` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "taxonomy"
} |
What does どころか mean here?
This is the prologue to a video game. Below are the official subtitles in the NTSC-U release.
>
> _" However, there are only a few scholars in the world who believe this."_
>
>
> _Clair: "You must be one of those scholars then, professor."_
>
>
> _Koji: "Actually, this idea is not even accepted as theory."_
Running the last sentence through google translate **without** gives:
> - It is not treated as theory. | "AB" has two different usages:
1. Quite contrary to A, (the fact is) B; Far from A, (it's) B
(B is the opposite of A)
> * 3
> *
> *
2. Not (just) A but even B; Even A is an understatement, (the fact is) B
(B is an extreme version of A)
> * 1
> *
> *
> *
Either way, B has to be something surprising.
As you can see in this question, the "traditional" usage is 1. Some learning resources mention only the first usage. However, the second usage is not uncommon, and at least this page and this page explain both usages.
In your example, the second usage is intended. Being is already bad, but the fact () is even worse.
>
> Calling it a minority opinion is not enough; it's not even recognized as a theory. | stackexchange-japanese | {
"answer_score": 2,
"question_score": 2,
"tags": "grammar, particles, syntax, conjunctions"
} |
An example of a non-convergent Cauchy sequence in $C^\infty$ with the Sobolev norm
I apologize in advance if this question is a duplicate, but I couldn't find an answer.
Studying Sobolev Spaces, I came across with the following proposition:
> The Sobolev Space $H^m(\Omega)$ is the completion, with respect to the Sobolev norm $\|\cdot\|_{H^m}$, of the space $C^{\infty}(\overline{\Omega}).$
Now I'm trying to find a non convergent Cauchy sequence in $C^{\infty}(\overline{\Omega})$ with the norm $\|\cdot\|_{H^m}$ but without success.
Can anyone give me some suggestion/hint? Thanks. | Since the dimension of $\Omega$ was not specified, let's use a one-dimensional domain, $(-1, 1)$. Given $m$, let $k$ be an odd integer greater than $2m$. Consider the sequence of $C^\infty$ smooth functions $f_n(x) = (x^2+ 1/n)^{k/2}$. It converges to $|x|^k$ which is not $C^\infty$ smooth, but is $C^m$ smooth. Moreover, the derivatives of $f_n$ of orders $0, \dots, m$ converge uniformly to the corresponding derivatives of $f$, which implies $\|f_n-f\|_{H^m}\to 0$, hence $\\{f_n\\}$ is a Cauchy sequence with respect to the $H^m$ norm.
Let's justify the claim about the convergence of derivatives. By induction, $$ f_n^{(j)}(x) = P_{j}(x, 1/n) (x^2+ 1/n)^{k/2-j},\quad j=0, \dots, m $$ where $P_{j}$ is some polynomial of two variables. When $n\to \infty$, we have $P_{j}(x, 1/n)\to P_j(x, 0)$ and $(x^2+ 1/n)^{k/2-j} \to |x|^{k-2j}$ uniformly on $\Omega$.
* * *
Essentially the same example, $(|x|^2 + 1/n)^{k/2}$, can be used in higher dimensions. | stackexchange-math | {
"answer_score": 2,
"question_score": 5,
"tags": "real analysis, sobolev spaces, distribution theory, cauchy sequences"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.