INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Find the lone number
I’m trying to search through an array and print out the only number within it which doesn’t have a pair, so in this case '4'.
The result keeps coming up as 2 so even though I feel I have the logic correct, I am definitely overlooking something.
I've been trying to solve this for a while and keep getting stuck
Many thanks in advance.
Here's the code:
int main(){
int arr[] = {1, 1, 2, 2, 3, 3, 4};
int n = sizeof(arr)/sizeof(*arr);
int foundNum = 0;
int counter = 0;
while(counter !=n) {
int i = 0;
if (arr[i] != arr[i + 1]) {
foundNum = arr[i];
} else {
arr[i] = arr[i+2];
}
counter += 1;
}
std::cout << foundNum;
return 0;
} | You have `counter`, so you should use that to determine the index to inspect instead of the new variable `i`.
Also to move the search position to `+2` position, you should add `2` to the loop variable instead of modifying the array.
#include <iostream>
int main(void){
int arr[] = {1, 1, 2, 2, 3, 3, 4};
int n = sizeof(arr)/sizeof(*arr);
int foundNum = 0;
int counter = 0;
while(counter !=n) {
if (counter + 1 >= n || arr[counter] != arr[counter + 1]) {
foundNum = arr[counter];
counter += 1;
} else {
counter += 2;
}
}
std::cout << foundNum;
return 0;
} | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "c++, arrays, algorithm, logic"
} |
How can I set UIDatePicker to display dates for today and onward?
Is there a way to set the date of the UIDatePicker to be dynamic? How can I set the `Minumum Date` to be the current date?
 {
super.viewDidLoad()
view.backgroundColor = .white
// Create a DatePicker
let datePicker: UIDatePicker = UIDatePicker()
// Posiiton date picket within a view
datePicker.frame = CGRect(x: 10, y: 50, width: self.view.frame.width, height: 200)
// Set some of UIDatePicker properties
datePicker.timeZone = NSTimeZone.local
datePicker.backgroundColor = UIColor.white
datePicker.datePickerMode = .date
datePicker.minimumDate = Date()
self.view.addSubview(datePicker)
}
}
 AS (json:map[]);
DUMP A;
and the output that i wanted is:
([amount#3,food#Tacos,person#Alice])
Thanks! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, hadoop, apache pig"
} |
How can I parse a dataframe which has only date and month columns to new column with pd.datetime format?
A small snippet from my dataframe
I have separate columns for month and date. I need to parse only month and date into a pandas datetime type(other datetime types would also help), so that I could plot a TimeSeries Line plot.
I tried this piece of code,
df['newdate'] = pd.to_datetime(df[['Days','Month']], format='%d%m')
but I threw me an error
KeyError: "['Days' 'Month'] not in index"
How should I approach this error? | an illustration of my comment; if you take the columns as type string, you can join and strptime them easily as follows:
import pandas as pd
df = pd.DataFrame({'Month': [1,2,11,12], 'Days': [1,22,3,23]})
pd.to_datetime(df['Month'].astype(str)+' '+df['Days'].astype(str), format='%m %d')
# 0 1900-01-01
# 1 1900-02-22
# 2 1900-11-03
# 3 1900-12-23
# dtype: datetime64[ns]
You could also add a 'Year' column to your df with an arbitrary year number and use the method you originally intended:
df = pd.DataFrame({'Month': [1,2,11,12], 'Days': [1,22,3,23]})
df['Year'] = 2020
pd.to_datetime(df[['Year', 'Month', 'Days']]) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, pandas, dataframe, datetime, data science"
} |
Stop all docker containers at once on Windows
How can I stop all docker containers running on Windows?
`docker stop` is for 1 container only.
Any command/script to make it stop all containers? | You could create a **batch-file** ( _.bat_ or _.cmd_ ) with these commands in it:
@ECHO OFF
FOR /f "tokens=*" %%i IN ('docker ps -q') DO docker stop %%i
If you want to run this command directly in the console, replace `%%i` with `%i`, like:
FOR /f "tokens=*" %i IN ('docker ps -q') DO docker stop %i
In **Git Bash** or **Bash for Windows** you can use this Linux command:
docker stop $(docker ps -q)
_Note: this will fail if there are no containers running_
For **PowerShell** , the command is very similar to the Linux one:
docker ps -q | % { docker stop $_ } | stackexchange-stackoverflow | {
"answer_score": 159,
"question_score": 77,
"tags": "docker, command line"
} |
Containment Tree?
OK thought I understood IDipose but just reading the best practices section of Accelerated VB.NET and it states that "The object doesn't contain any objects that implement iDispose, so you don't need to iterate through the containment tree calling iDispose"
Is this "containment tree" just what the program know's he has used and then distroys, or is there a contaiment class / collection that I should be looking at when I distroy an object ? | I haven't read the book but I've never heard of this “containment tree”. In context, it sounds as if this merely means all fields (of a given class) that also implement `IDisposable` and consequently have to be disposed in the class’ `Dispose` method (if the `disposing` argument is `True`) – or rather, in your case, since there are _no_ such fields you don’t have to take any further action. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "vb.net, garbage collection, dispose"
} |
Rails: NameError: uninitialized constant Rack::LiveReload
I'm working on a **Rails 4.2** application on **Ubuntu 20.04**.
I'm trying to run a rake task using the command below:
rake my-task
But when I run it I get the following error:
> NameError: uninitialized constant Rack::LiveReload
Trying to figure out how to resolve it | **Here's how I solved it** :
The issue had to do with me not specifying the rails environment within which I wanted to run the rake command.
To specify the rails environment, I could use the `RAILS_ENV` variable this way:
rake my-task RAILS_ENV=production
OR if my environment is a **staging** environment:
rake my-task RAILS_ENV=staging
OR you could use the `export` command to pass the rails environment:
export RAILS_ENV=production
rake my-task
OR if my environment is a **staging** environment:
export RAILS_ENV=staging
rake my-task
**Reference** : websocket-server.rb and scheduler.rb Rack::LiveReload problem
That's all. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, rake"
} |
Google Sheets query ("SELECT A WHERE B <> '0'")
I have a table for event planning where A is the items and B is the quantities.
I then want it to turn into a list where it just has the items if B is more than 0. I have tried using `=QUERY(Job!A3:B16, SELECT A WHERE B <> '0')` but I get `#VALUE!` back and the error pop up says
> In Array Literal, an Array Literal was missing values for one or more rows.
Is there a better formula to use or a better way to use this? | Try
=QUERY(Job!A3:B16, "SELECT A WHERE B <> 0 ")
you can also use FILTER
=FILTER(Job!A3:A16,Job!B3:B16<>0) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "google sheets, google sheets formula, array formulas"
} |
PPTP without GRE: possible?
_[I hope this is not off-topic here]_
I'm trying to set up a PPTP tunnel between a Linux (Debian 6) Server and a Windows 7 Client.
The problem is, that **the PPTP connection itself** (ports 1723 and 47) **must be tunneled** via a custom program because the Linux server is behind a **NAT**. This tunnel is made by a custom Windows program that listens to ports 1723 and 47 (localhost) and forwards these TCP connections to to the remote server. This tunnel already works fine for generic connections like SSH and has been used for years now. It allows me to connect to any TCP port on the Linux server.
The problem with PPTP is, apparently, that it needs to transmit GRE packets which aren't TCP connections and thus don't reach the other network (and the VPN connection setup times out).
Can I configure the PPTP connection somehow so that it doesn't use these GRE packets or perhaps encapsulates them in a TCP connection?
Any other suggestions greatly appreciated. | No, this is not possible.
PPTP is using TCP port 1723 to build up the tunnel, but the data carried over the VPN always GRE.
This is then the IP protocol 47 (Not TCP!)
Anyway PPTP is security wise not a good solution and should be replaced by a better protocol.
OpenVPN is one of the flexible VPN solutions | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, debian, vpn, tunnel, pptp"
} |
Artihmetic overflow error when string into a smalldatetime
Hi I have a program that uses DateTime.Now.ToString() to get the time and then plugs it into a coloum that is smalldatetime. This worked before but now I get this error.
"Arithmetic overflow error converting expression to data type datetime. The statement has been terminated."
What am I doing wrong?
This is my SQL statement
command.CommandText = @" INSERT INTO Mail1 (UserID, Subject, Feedback, Date_Sent_On)
VALUES (@UserID, @Subject, @Feedback, @Date_Sent_On)"; | The `@Date_Sent_On` parameter should be of type `DateTime` instead of `string` and you should pass `DateTime.Now` as its value.
Using `DateTime.Now.ToString()` is very unreliable, because formatting the date with `ToString()` is culture dependent - it can produce different results depending on the regional settings of your computer and the culture settings in the application. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, sql"
} |
Caché Object Script Code guidelines
I work with InterSystems Cache and look for Caché Object Script coding guidelines. Does someone have any example? | There's this project. It provides Caché Object Script Code guidelines | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "coding style, intersystems cache, intersystems"
} |
How are you supposed to use the with() method with Eloquent?
/**
* Set the relationships that should be eager loaded.
*
* @param dynamic $relations
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function with($relations)
{
if (is_string($relations)) $relations = func_get_args();
$eagers = $this->parseRelations($relations);
$this->eagerLoad = array_merge($this->eagerLoad, $eagers);
return $this;
}
I can't find any documents on how to use this method. What is `$relations` suppose to be? | The relation name or the method name that defines the relation:
if you have a model as
class Post extends Eloquent {
public function author()
{
return $this->belongsTo('User');
}
}
You do
$posts = Post::with('author')->all();
And it will eager load the users in your posts rows. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, laravel, eloquent"
} |
JSON pretty format only of part of a file in vim
In VIm, is there a way to print a JSON snipped inside a file in the "pretty" format?
For example, having the following file
# a comment
def my_func():
pass
{"bla": [1, 2, 3], "yes": false} # <--- pretty print this
# another comment
<foo>why do I mix everything in one file?</foo>
<bar>it's an example, dude</bar>
I would like to change the marked line to
{
"bla":[
1,
2,
3
],
"yes":false
}
I'm looking for something like `:%!python -m json.tool` but only for the selected lines. | Specifying the line number should work. For example:
:5!python -m json.tool
Or if it takes multiple lines:
:4,6!python -m json.tool | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 5,
"tags": "json, vim"
} |
How to add specific row from datagridview to listbox in VB.net
When clicking a button, I want the values from a specific row from my `DataGridView` to be placed in the `ListBox`. For example, when pressing the Budgie button, I want all the details about the Budgie, which is in row 1, placed in the `ListBox` (it's so I can calculate costs) However, when I press the button all that shows up in the `ListBox` is `DataGridViewRow { Index=1 }` What do I need to change to show the values rather than that?
Private Sub btnBudgie_Click(sender As Object, e As EventArgs) Handles btnBudgie.Click
Me.lstSales.Items.Add(DataGridView1.Rows(1))
End Sub | This works if you select the whole row:
Dim Item As String = ""
Try
Dim c As Integer = DataGridView1.SelectedRows(0).Cells.Count - 1
If c <= 0 Then
c = 0
End If
For x = 0 To c
Dim cell As DataGridViewCell = DataGridView1.CurrentRow.Cells(x)
If x = DataGridView1.SelectedRows(0).Cells.Count - 1 Then
Item = Item & cell.Value
Else
Item = Item & cell.Value & " - "
End If
Next
ListBox1.Items.Add(Item)
Catch ex As Exception
MessageBox.Show("An error occured. Have you selected a whole row?" & Environment.NewLine & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "vb.net, datagridview, listbox"
} |
What typeface does Pentagram use for the Sundance Institute brand?
Total beginner here. What typeface does Pentagram use for the Sundance Institute? Any help would be appreciated!
Thanks.
!Sundance Institute brand identity | Trade Gothic with a modified "d". It's stated in the linked article about the new logo.
< <
!enter image description here | stackexchange-graphicdesign | {
"answer_score": 1,
"question_score": 0,
"tags": "font identification"
} |
Get http post request body in perl
Request header (from Firebug):
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Content-Type application/json;charset=utf-8
Request json:
{"key":"value"}
So how to get request body in perl? | What webserver?
Usually POST data is available by simply reading from STDIN.
If you are using the venerable CGI module (under mod_perl or not), you can get the body via:
$cgi->param('POSTDATA')
(if, as in this case, the content type isn't application/x-www-form-urlencoded or multipart/form-data) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "json, perl"
} |
Grid-like container with adaptive width
I would like to have container, that satisfies following conditions:
* it has 2 rows and unlimited amount of columns
* all items inside it are one-word text elements, that have their width
* all items inside it are equal width, defined by the widest element (longest word)
I was thinking about using a flexbox. Since all of the items have known height (because they are one line of text), I can define wrappable container like this:
display: flex;
flex-flow: column wrap;
height: 100px;
All items inside the same column are equal in width. But I want all of the items have the same width. Should I use grid? If yes, how? | You can try CSS grid like below:
.grid {
display: inline-grid;
grid-template-rows: 1fr 1fr; /*two equal rows*/
grid-auto-columns: 1fr; /*all columns will be equal*/
grid-auto-flow: column;
}
span {
outline: 1px solid;
padding: 5px
}
<div class="grid">
<span>some_text</span>
<span>text_long</span>
<span>text</span>
<span>a</span>
<span>text</span>
<span>some_text</span>
<span>some_looong_text</span>
<span>some_text</span>
</div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css, flexbox, css grid"
} |
Android how to apply Listener on AppCompatAutoCompleteTextView Filtered Items
I have a `AppCompatAutoCompleteTextView` , i have also set an `adapter` on my `AppCompatAutoCompleteTextView` . But I need to `handle` an `event` in which no items(filtered items ) is shown in my `AppCompatAutoCompleteTextView` . I just don't know how to `handle` this specific `event` i have also read the docs but its not that simple . So kindly help me out
For Eg: Case 1: Suppose my string array contains 2 items Apple , Android. Now whenever the user will type "A" , a drop-down list will appear showing filtered items In this particular case the drop-down list would have 2 items : Apple and Android
Case 2: When the user types "Ax" , now the drop-down list will not appear. At this specific event , when there is no SUGGESTION or drop-down list shown . I need to display a toast. | There is a method called **onFilterComplete()** in _AutoCompleteTextView_.
//count is the number of values computed by the filter
public void onFilterComplete (int count){
if(count==0){
//your code here
}
}
You should implement your code in the If block, As you want to handle things when the result is empty. ThankYou I hope this is helpful. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, android"
} |
connect to mysql database using php on different port
my connection string is:
$connection = mysql_connect("localhost", "root", "") or die("Could Not Connect to DB: ".mysql_error());
but on my computer i have installed IIS server first so localhost:80 is reserved by it so I changed my port to 8080 changing httpd.conf file in apache folder.
Now what should I change in connection string to connect to my database. I am using XAMPP .
should I tried writing these: 1:
$connection = mysql_connect("localhost:8080", "root", "") or die("Could Not Connect to DB: ".mysql_error());
2:
$connection = mysql_connect("localhost,8080", "root", "") or die("Could Not Connect to DB: ".mysql_error());
But Not working Help please. Thank You | Default port number which Mysql server uses is 3306 Web servers default port is 80
Web server and Mysql server are independent.
Do not change your api to connect to your mysql | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, mysql, apache, database connection"
} |
Do I need the bedrooms to let my spouse move in with me?
I recently bought a plot of land and built the manor which, once semi-built, comes with two small beds. I have a bard, a driver, a steward, a housecarl, and two kids. Does this mean I don’t need the bedroom or will I be unable to let my spouse move in with me without it? | If you want your spouse to live with you in a Hearthfire manor, then yes, you do:
> " _In the base game, a spouse will move into any house you own.
> **For Hearthfire houses, you must have built a bed for your spouse**._"
Do note that you don't need to own a house at all: marriage is possible without you owning property, in which situation you can live with your spouse (or ' _betrothee_ '). | stackexchange-gaming | {
"answer_score": 4,
"question_score": 1,
"tags": "the elder scrolls v skyrim, skyrim hearthfire"
} |
Hungarian characters in Firebird database
I cannot seem to get Hungarian accented characters to store properly in my Firebird database despite using ISO8859_2 character set and ISO_HUN collation.
This string for example:
> Magyar Képzőművészeti Egyetem, Festő szak, mester: Klimó Károly
gets displayed as
> Magyar Képzomuvészeti Egyetem, Festo szak, mester: Klimo Karoly
What am I doing wrong? | Your string is UTF8 encoded. It's working fine with IBExpert and an UTF8 database. Make sure that you're using the correct character set (DB connection, DB column, string). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "firebird, firebird2.1"
} |
Simple, streaming, lossless image compression
Does anyone know of any image compression techniques with the following characteristics:
* lossless
* streaming - I want to compress on the fly, pixel-by-pixel.
* low-memory overhead - I can afford to buffer a single line, but ideally not even that.
* no dynamic dictionaries
* "real-world" images only, so performance on "nasty cases" like chequerboards is not important
* 2-3x compression (5x-10x would be even better, but that's asking a lot I know)
* can operate on 10-16 bit pixels (depending on my camera)
My images will be ~1k pixels wide, with pixel rates of ~20Mpix/sec. The pixel depth will be something between 10 and 16 bits per pixel (depending on the choice of camera). Assume sub-16-bit pixel widths would be represented within a 16-bit word for now, rather than needing to be extracted from a continuous bit-stream.
Some form of delta+arithmetic coding perhaps? | You can consider using Huffyuv : <
This is no great better than simple zip, but still slightly optimized for images.
Any Image related compression comes from the techniques like Vector quantization or Transform coding. In order to make use of transform such as DCT/Wavelet yet make it lossless you can think of JPEG-LS or JPEG2000 for compression. Only thing is, it is not _streaming_ in your sense of definition. | stackexchange-dsp | {
"answer_score": 4,
"question_score": 8,
"tags": "image processing, image compression"
} |
$\overline{(a+\overline{b})\cdot (\overline{a}+b)}$ simplification boolean algebra
For context: I am learning Boolean Algebra by myself for fun and one of the questions in the book I am reading was a long boolean expression and the task was to simplify it to be the XOR boolean expression. I have managed to come quite a bit but cannot progress any further.
I am unable to simplify $\overline{(a+\overline{b})\cdot (\overline{a}+b)}$ to be $a\overline{b} + \overline{a}b$.
There seem to be no laws associated with this type of boolean multiplication. Can anybody point me in the right direction? My original equation is of an XOR logical operation, but not in its "final form" so to say. | If you develop your product you get: $$(a+b')(a'+b)=\overbrace{aa'}^0+ab+a'b'+\overbrace{bb'}^0=ab+a'b'$$
Yet you want $a\oplus b=(ab'+a'b)$ to appear not $(ab+a'b')$.
But notice that for any $x$ then $x+x'=1$ therefore:
$$1=a'(b+b')+a(b+b')=(ab'+a'b)+(ab+a'b')$$
So in the end $(ab+a'b')=(ab'+a'b)\ '$ | stackexchange-math | {
"answer_score": 0,
"question_score": -1,
"tags": "boolean algebra"
} |
Re-Write url? Syntax?
I was working on a website for a client. I wanted to re-write a url but don't know how to go about it. I have very less time. I am looking for a tutorial, but would be quite helpful if someone could help me.
Following is the url that I receive:
www.example.com/shop/url_encoded_category_name/product?productid=
I want to re-write it to:
www.example.com/shop-public-home.php?productid=
The problem here is that "url_encoded_category_name" will be some text and will be something different every time.
I am looking for a quick tutorial, and will close the question if I found a solution.
I am highly thankful for any help you can provide.
Jehanzeb k. Malik | You will probably use apache mod_rewrite, if you use an apache http server. All apache modules have excellent documentation including good examples. You will find all details you are looking for in that documentation: <
You can either setup the rewriting rules in the central server configuration (preferred way) or decentralized using so called ".htaccess" files. You can use more or less the same rules for both approaches. Check the `RewriteEngine`, `RewriteRule`, `RewriteMap` and `RewriteCond` commands. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "url, url rewriting"
} |
How to route every invalid request to a default path using node/express
I'm trying to build a server that user will be able to enter these valid paths:
/art/thisProject
/art/thatProject
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path `/art/myProject`:
/some/url
/something
/another/u/rl
I guess the error comes because of a false use of `"*"`or with false understanding of how to override router rules.
How do I do it?
this is my code:
app.get('/', function(req, res) {
res.redirect('/art/myProject')
});
app.get('/art/:project', function(req, res){
var project = req.param('project');
var filePath = 'art/' + project + '/' + project;
res.render(filePath)
});
app.get('*', function(req, res) {
res.redirect('/')
}); | This should work:
app.get('/*', function(req, res) {
res.redirect('/')
});
Or this:
app.use(function(req, res) {
res.redirect('/')
});
Both must of course be put last. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "javascript, regex, node.js, express"
} |
How to make a TeamCity build fail (timeout) if it takes too long?
How do we put a timeout on a TeamCity build?
We have a TeamCity build which runs some integration tests. These tests read/write data to a database and sometimes this is very slow (why it is slow is another open quesiton).
We currently have timeouts in our integration tests to check that e.g. the data has been written within 30 seconds, but these tests are randomly failing during periods of heavy use.
If we removed the timeouts from the tests, we would want to fail the build only if the entire run took more than some much larger timeout.
But I can't see how to do that. | On the first page of the build setup you will find the field highlights in my screenie - use that!enter image description here | stackexchange-stackoverflow | {
"answer_score": 41,
"question_score": 29,
"tags": "teamcity"
} |
How does redis separates the multiple user instance running on same server?
My **Confusion** regarding Redis
If I install Redis on my server and my **4 different clients** connect to that **same** redis server, so how will the data between them will be kept separate so as one client does not override the key-value pair that other client has saved.
Eg:-
**client-1 set name= "adam"**
**client-2 set name= "henry"**
So as Redis server is **common** between these clients the name key set by client-1 will be **overwritten** by client-2, So when **client-1 execute get name == > henry (As it has been updated which is wrong, he was expecting it to be adam)**
So how does Redis separates the multiple user instance running on same server ? Does it create separate databases internally or stores as per user or what ? | Redis itself doesn't separate your data. You'd have to separate those by yourself. There are many options to do that.
1. Using Redis database: Redis supports multiple databases. Each application (in your case, client) can be set/allocated to use to use one specific database. This allocation has to be done in application end, not in Redis.
The limitations of this approach are: i) Redis supports at most 16 databases (denoted from 0 to 15). ii) Redis cluster mode supports only one database.
Note: SELECT command is used to select a specific database.
2. Namespacing: Each application can be (for example) assigned an unique prefix. They'd prefix all their keys with that assigned prefix.
3. Use separate Redis instance per application. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "redis"
} |
How can I keep the input data structure in a for loop?
I have a list of tuples which looks like this:
l = [('xx-1711640.html', 'Hello'),
('xx-8411747.html', 'Bye')
]
The actual list got thousand of entries. Now I want to use an regex for the tuples. To do this I have a for loop. Additionally I want the output to be also a list of tuples.
My code:
ret = []
for line in l:
for i in line:
try:
reg = re.sub(r'.+-', '', i)
ret.append(reg)
except:
print(line)
However with this code my output looks like this:
ret = ['1711640.html', 'Hello', '8411747.html', 'Bye']
When I want it to look like this:
ret = [('1711640.html', 'Hello'), ('8411747.html', 'Bye')]
How can I do this correctly? | Use:
ret = []
for m,n in l: #unpack tuple
try:
m = re.sub(r'.+-', '', m)
ret.append((m, n))
except:
print(m,n)
**Output:**
[('1711640.html', 'Hello'), ('8411747.html', 'Bye')] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "python, regex, python 3.x, list, tuples"
} |
Remove dash from string but not from middle when its surrounded by (a-z)
I read similar questions but those are not answer exactly to my question.
i want to remove any dash from my string but not that dash in middle of string that surrounded by (a-z) or (A-Z) like my example test case.
i already use this regex code but it clean all dash:
string.replaceAll("\\-", "");
* * *
## Test Case
* \--good
* -good
* **g-ood***
* g--ood
* good-
* good--
* * *
## Result
* good
* good
* **g-ood***
* good
* good
* good | Using a regex to do that is the right thing to do. However, your regex is capturing **every** hyphens. What you need is to check for letter before and after.
((?<!\w)-|-(?!\w))
This regex will look for hyphens that have nothing before **OR** hypen that has nothing behind and replace them.
!Regular expression visualization
Using this regex, you can replace those occurrence by nothing, like you did before.
string.replaceAll("((?<!\\w)-|-(?!\\w))", "");
here is a regex101 for you to test more cases | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, regex, string"
} |
How to use Cocoa's Responder Chain when Application is Minimized
I'm using the responder chain (sendAction:to:from:) to communicate from sub-views up to the document. The problem is when the window is minimized, if there are any actions still occurring, they fail because the responder chain is broken. I can't make the window a key window since it's minimized. Any ideas? | I just found out how to do this using NSResponder:
- (BOOL)tryToPerform:(SEL)anAction with:(id)anObject
If the receiver responds to anAction, it invokes the method with anObject as the argument and returns YES. If the receiver doesn’t respond, it sends this message to its next responder with the same selector and object. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "cocoa, action, target, chain"
} |
Ground wire with 1/2 EMT Conduit
Do I need to run a ground wire with conduit? I have installed a line of lights using 1/2 EMT and tied into another circuit that is grounded coming off the panel. There are about 7 lights in a back room at my business. In addition, should the last light in the circuit feed back to the panel? The lights are just for supplemental lighting in the work areas. | Not if you don't want to. The EMT piping is itself a valid ground path, provided there is a ground path that is continuous back to the panel. All my work is in EMT and I don't own any green wire.
If you need to bond from the EMT to a ground wire, most likely there is a hole tapped for a 10-32 screw on the metal junction box, it may be sitting up on a pucker to give the ground screw some clearance.
UK-style "ring circuits" are illegal in the United States and the wiring of the circuit should not be looped back to the panel.
Sometimes conduit winds up being laid in a ring simply out of coincidence but the wires inside do not go in a loop. | stackexchange-diy | {
"answer_score": 2,
"question_score": 1,
"tags": "electrical, grounding, conduit"
} |
How to attach a local CSS file to a website?
I want to keep a CSS file in my PC but want to link that file in website and whatever changes I will do in local file that changes should reflect in site.
I'm not logged in as Admin in my PC. Is it possible?
I need any online/offline method Compatible with Windows XP 32 bit | You could check out the Stylish extension for mozilla firefox. Not exactly what you're looking for, but it allows you to overwrite CSS for arbitrary websites (or firefox's chrome, if you like) | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "windows xp, website, webserver"
} |
Showing 0 first posts and 0 late answers since 2 months?
My reputation is 300+. I wanted to review the new questions and answers. Earlier it showed me to review. But presently every time whenever i check, It is showing `0 First Answers` and `0 Late Answers`. It means all reviewed or what is the issue ? | Review section has following review task with the required reputation
* First Posts (You need at least 125 reputation to review First Posts.)
* Late Answers (You need at least 125 reputation to review Late Answers. )
* Suggested Edit (You need at least 2k reputation to review Suggested Edit Posts.)
* Low Quality Posts (You need at least 2k reputation to review Low Quality Posts.)
* Close Votes (You need at least 3k reputation to review Close Votes.)
* Reopen Votes (You need at least 3k reputation to review Reopen Votes.)
As you can see that only `First Post` & `Late Answers` can be done by users who has >= 125 & <= 2K reputation. The number of users are getting increase day by day. So there are lots of users with the same privilege doing the review task for the same two sections. This is the only reason that both of those queue are empty.
You need to be very quick & regularly visit the review section for the same review tasks. | stackexchange-meta | {
"answer_score": 5,
"question_score": 5,
"tags": "support, review"
} |
automate do something without open page
i want make script evry 15min connect to 4 address and get new link . how i can make page for do this without open page every time and script do this automate???
php can make this script? if i need some program please advise me .
like this :
$ad1='
$ad2='
$ad3='
link1=str('
do This evry 15 min on server automate | As @k102 mentioned, use cron. It allows you to schedule a job to occur at any time interval. If you are on Windows, check out this Stack Overflow answer: What is the Windows version of cron? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, automation"
} |
Factorization in non-Noetherian integral domain
Let $A$ be an integral domain, suppose that $a\in A$ factors in a product of irreducible elements, $a=a_1a_2\cdots a_n$.
> If $a$ factors also as $a=b_1b_2\cdots b_m$ can we conclude that every $b_i$ factors as a product of irreducibles?
I suspect that this is false, but I can't construct a simple counterexample and the standard examples of non-Noetherian integral domains don't seem to work | To produce a counterexample, you can just _force_ it.
Let $A$ be the ring defined by
$$A = \mathbb{Z}[x,y,t_1,t_2,t_3,...]/I$$
where
$$I = (xy - t_1^2,\,t_1 - t_2^2,\,t_2 - t_3^2,\,t_3-t_4^2,\,...)$$
and let $a = xy.$
Then $a$ is a product of the irreducible elements $x,y$.
But also $a = t_1^2,\,$ and $\,t_1$ is not a product of irreducibles. | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "abstract algebra, ring theory"
} |
did javascript or jquery has method as Server.UrlEncode() in asp.net
did javascript or jquery has method as Server.UrlEncode() in asp.net
eg:when using
$.get("a.aspx?pk=1&k="+kvale, function(data) {
dosth(data);
});
url must encode | You can convert any string to a URL-encoded string (suitable for transmission as a query string or, generally speaking, as part of a URL) using the JavaScript functions `escape`, `encodeURI` and `encodeURIComponent`.
escape('
"https%3A//www.stackoverflow.com/%3Fwow.php"
Source: < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, asp.net"
} |
Mots masculins se terminant en -AIN dont le féminin est en -INE
Le mot « sacristain » admet les féminins « sacristaine » et « sacristine ». Le mot « génovéfain » n'admet que le féminin « génovéfine ». Mes deux questions sont :
1. Existe-t-il d'autres mots masculins se terminant en -AIN et admettant un féminin en -INE ?
2. D'où vient cette féminisation particulière ? L'origine est-elle cléricale ? | Il y a _copain_.
Dans ces deux cas (les sources que je peux consulter donnent _génofévaine_ comme féminin de _génofévain_ ), la formation du féminin est plus tardive que celle du masculin s'il faut en croire Grevisse (Bon usage, 14e éd, §495). Les locuteurs ont vraisemblablement présumé que le masculin était en -in. _Sacristaine_ est d'ailleurs attesté (notamment comme féminin de l'adjectif). | stackexchange-french | {
"answer_score": 3,
"question_score": 4,
"tags": "genre, étymologie"
} |
How to find out how long an array has to be when being initialized?
Imagine i have an byte-array ids.
Later i want to store data in it this way:
ids[cz << 24 | cx << 16 | y << 8 | z << 4 | x]
cz, cx, y, y, z, x are int values in this case.
So how long does the array need to be when i create it? I thought i would have to initialize the array this way:
byte[] ids = new byte[maxCz * maxCx * maxY * maxZ * maxX];
But it always gives me an ArrayIndexOutOfBoundsException. | The largest component in the OR-ed expression is `cz << 24`. Assuming that `maxCz` is 2k-1, and that the remaining `max` values are selected in a way for the bits of different components to not overlap, you need to allocate
byte[] ids = new byte[(maxCz+1) << 24];
When `maxCz` is 7, this is a 128 MB allocation, so the array is going to be very large. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "java, arrays, byte, byte shifting"
} |
Most suitable graph for displaying coordinate data
I have extracted some sets of matrices from a CSV file that comes from recording data (X,Y) every N seconds in a C++ application.
In my C++ application I was tracking two objects and saving the coordinates of both in my CSV file like so:
x1, y1, x2, y2
x1, y1, x2, y2
...
I would like to display both objects `(x,y)1` and `(x,y)2` in the same graph at the same time, but `scatter` does not seem to allow this.
Something like the following would be ideal:
scatter(Log1(:,1),Log1(:,2), Log1(:,3),Log1(:,4)) | Use `hold``on`.
Something like
scatter(Log1(:,1),Log1(:,2));
hold on
scatter(Log1(:,3),Log1(:,4)); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "matlab, matlab figure"
} |
Ancestry of Struckers in "The Gifted"
Are the Struckers in " **The Gifted** " television series related to Baron Wolfgang von Strucker? Like his descendants or it's just a coincidence.
**_PS:_** I just started watching the series. | In the episode "threat of eXtinction", we learn that the father, Reed Strucker, is the grandson of Andreas von Strucker). There was no mention of how Andreas and his twin relate to other characters in the Marvel Universe.
However, Hydra and Baron Strucker are intellectual properties of the MCU/Disney while X-men & mutants are Fox properties. That means that any further tie probably won't be made apparent. Most likely it will be treated like Deadpool where the links are not expressly stated, but rather implied.
**UPDATE:** With Disney's recent acquisition of much of Fox, an X-Men/MCU crossover is back on the table. It may now be possible that Baron von Strucker is tied to the other 4 generations of the Strucker family shown in the TV show. I would guess not until season 2 or later, though. | stackexchange-scifi | {
"answer_score": 5,
"question_score": 1,
"tags": "marvel, the gifted"
} |
Does ADFS (as SP) support integration with an OpenID IDP
Does ADFS (as SP) support integration with an "OpenID connect" IDP ?
Thanks. | For OIDC, you need ADFS 4 or 5 (server 2019).
ADFS only supports OIDC IDP i.e. only OIDC in.
It does not support OIDC out so cannot function as an OIDC SP. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "openid, openid connect, adfs, adfs3.0"
} |
Navigation controller toolbarItems array is nil?
In one app I work on, I have to put many (more than 5) toolbarItems on the toolbar of a UINavigationController, and need to replace one of the toolbar items when user taps it.
For making the code less clogging in `-application:didFinishLaunchingWithOptions`, I set up navigation controller in storyboard (OK, maybe it's evil..) instead of programmatically. The toolbars displays all right. The only problem is I cannot grab toolbarItems in code:
`NSMutableArray *toolbarItems = [[[self navigationController] toolbarItems] mutableCopy];`
`toolbarItems` is always nil. Thus I cannot get my hands on one of the toolbarItems and change it as I intend to.
Is it normal or I am missing something obvious? | OK, I just fix it.. I should call `[self toolbarItems]` instead of `[[self navigationController] toolbarItems]`. Hope this post could help others. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "ios, uinavigationcontroller"
} |
Do Noetherian rings have the IBN property?
I know that commutative rings and division rings have the invariant basis number property. I'm curious what else are there.
> Do Noetherian rings have the invariant basis number property?
If not, what about Artinian rings or semisimple rings? And how do I prove this? | Let $R\neq\\{0\\}$ be Noetherian and let $m > n$ be natural numbers. Consider the homomorphism $f ~:~ R^m \to R^n$ given by the projection onto the first $n$ coordinates.
The assumption $R^m\cong R^n$ leads to a contradiction, as $f$ has non-zero kernel but it is also a surjective endomorphism of a Noetherian module, hence bijective (this is easily proved using the ascending chain condition). | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "abstract algebra, ring theory, noetherian"
} |
Why does this file apparently not exist when attempting to delete it?
A month or so back, I untarred the Linux source in a folder in Cygwin (I was curious as to whether or not it would compile with MinGW 'cause my other computer running Linux is a slow single core Sempron). I tried deleting it, but there's 1 file left, and it will not delete...
Cygwin resides in `C:\cygwin`, and I untarred the source in `C:\cygwin\src\linux-3.7.1`. It didn't compile... So I tried deleting the folder. It was going well, until at the end, when I realized not all files are deleted. I tried deleting `linux-3.7.1` folder again, and an error popped up:
!Item not found
I opened the folder, and found that there's 1 source file left: `aux.c`, which is in `C:\cygwin\src\linux-3.7.1\drivers\gpu\drm\nouveau\core\subdev\i2c\aux.c`.
It will not:
* Delete
* Open
* Move
General properties:
!General
Security properties:
!Security
**How do I remove this file?** | Try this from an (elevated) command prompt:
del \\?\C:\cygwin\src\linux-3.7.1\drivers\gpu\drm\nouveau\core\subdev\i2c\aux.c | stackexchange-superuser | {
"answer_score": 15,
"question_score": 10,
"tags": "windows 7, file permissions"
} |
How to filter with wms background maps in Tableau
I created a map with locations plotted in Tableau and have utilized a background map from NOAA to show which locations are being impacted by excessive rainfall. How do I filter the data so only those that fall within the excessive rainfall areas appear on the map? Alternatively how do I get aggregate measures of the locations that fall within the excessive rainfall zone? | It's not a perfect solution, but one method that I found success with is creating a filter action and then using the lasso selection tool on the dashboard to select all of the points within the desired area in order to filter the desired values. More info on the filter action can be found here. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "tableau api, wms, noaa"
} |
What's the difference in rows and sections in NSIndexPath in Swift?
I can't seem to see what exactly a section is. I know what a row is in UITableViewController, but what is a section. Is it a separate piece of information? I'm a beginner and couldn't find a clear answer anywhere else on the web. | A section is a group of rows. For example, in the settings app, different rows are grouped into sections.
Sections can have titles and allow for information to be broken apart. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "ios, xcode, swift, nsindexpath"
} |
Passing a String from one method to another method
I need to pass a String from one method to another method and now I'm a bit clueless.
The String values (callbackURL & donationId) I want to pass are inside this method:
public void postData() {
.
.
.
.
String callbackURL = tokens.nextToken();
String donationId = tokens.nextToken();
}
and I want to pass the values to another method, let's say it's called `private examplePayment()`. How am I able to perform that? | public void postData(){
.
.
.
.
String callbackURL = tokens.nextToken();
String donationId = tokens.nextToken();
examplePayment(callbackURL, donationId);
}
private void examplePayment(String callback, String donationid){
//deal with your callback and donationid variables
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "java, android"
} |
Django Forms: pass parameter to form
How do I pass a parameter to my form?
someView()..
form = StylesForm(data_dict) # I also want to pass in site_id here.
class StylesForm(forms.Form):
# I want access to site_id here | You should define the __init__ method of your form, like that:
class StylesForm(forms.Form):
def __init__(self,*args,**kwargs):
self.site_id = kwargs.pop('site_id')
super(StylesForm,self).__init__(*args,**kwargs)
of course you cannot access self.site_id until the object has been created, so the line:
height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))
makes no sense. You have to add the attribute to the widget after the form has been created. Try something like this:
class StylesForm(forms.Form):
def __init__(self,*args,**kwargs):
self.site_id = kwargs.pop('site_id')
super(StylesForm,self).__init__(*args,**kwargs)
self.fields['height'].widget = forms.TextInput(attrs={'size':site_id})
height = forms.CharField()
(not tested) | stackexchange-stackoverflow | {
"answer_score": 64,
"question_score": 51,
"tags": "django, django forms"
} |
How to center react-select element
I'm trying to put the React-select element to the center of the page. (Please Note, I'm not trying to center the text/menu but I'm trying to center the select box)
Inline Styles didn't work for me, hence I have added a div tag and was able to control the width as shown below :
<div style={{width: '300px'}} >
<Select options={selectOptions} value={selectedOption} onChange={this.handleChange}/>
</div>
But I'm not able to center the select element.
Any help on this ? | Well, that could be solved easily by using a few CSS attributes. You know, I am sure that `display: flex, justify-content: 'center', align-items: center` will work as you desire.
<div style={{width: '300px', display: 'flex', justify-content: 'center', align-items: 'center'}} >
<Select options={selectOptions} value={selectedOption} onChange={this.handleChange}/>
</div> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, reactjs, react select"
} |
Let $X_{1}, ... , X_{n}$ independent Bernoulli variables with same parameter $p$. Prove that $X_{1} + ... + X_{n} \sim B(n,p)$.
Let $X_{1}, ... , X_{n}$ independent Bernoulli variables with same parameter $p$. Prove that $X_{1} + ... + X_{n} \sim B(n,p)$.
I tried to prove it by induction, but I got stuck on the very first step. How should I show that I can observe each $X_{i}$ as $B(1,p)$? I mean, I know that sum $X_{1} + ... + X_{n}$ is interpreted as random variable $X$ and all those $X_{i}$ are i-th time of repeating the experiment but is the reversed claim valid? | By definition:
* A Bernoulli random variable $A$ with parameter $p$ has $\mathbb P(A=0)=1-p$ and $\mathbb P(A=1)=p$
* A binomial random variable $B$ with parameters $n$ and $p$ has $\mathbb P(B=k)={n \choose k}p^k(1-p)^{n-k}$ when $k \in \\{0,1,\ldots, n\\}$
When $n=1$, these definitions say the same thing | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "probability"
} |
Netbeans UI empty in DWM
I'm trying to use dwm Windows Manager, everything is fine (1mb ram ;) but when I run netbeans it load but with a grey and empty interface. (it works fine in Unity or E17 )
Any Idea ?
I have found out this < but the solutions proposed doesn't work for me | Perhaps your issue is the same as this xmonad issue?
<
> The Java gui toolkit has a hardcoded list of so-called "non-reparenting" window managers. xmonad is not on this list (nor are many of the newer window managers). Attempts to run Java applications may result in `grey blobs' where windows should be, as the Java gui code gets confused.
A solution is to export _JAVA_AWT_WM_NONREPARENTING=1.
Edit: According to < you can also use "wmname LG3D" to hack the window manager's name. | stackexchange-superuser | {
"answer_score": 5,
"question_score": 5,
"tags": "linux, ubuntu, netbeans, dwm"
} |
How to reduce width of div using JQuery, CSS so that the left section is reduced and not the right?
This sounds like a stupid question but I cannot figure an easy way of doing it. Let us say that I have a fixed-width Div with the string ABCDEFGHIJ as its content. If I reduce the width it will stop showing HIJ or whatever from the right side. I want the visibility of the content from the left side getting impacted. So, let's say that the div has a width of 100px, then
$(div).css('width':'50px');
should not impact the display of EFGHIJ, for example.
Yes, I could have an inner div and shift its position to the left, for example, by the amount of width reduced. Is there a shorter way of doing this?
Thanks | To Hide the beginning letters but not the last letters, you need to change the direction of the letters using css `direction: rtl`.
and also to hide the letters, you should mention `overflow: hidden` and some width to the container.
**Working Fiddle** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, css"
} |
Running time of quicksort
Suppose `B(n)` and `W(n)` are respectively the best case and worst case asymptotic running times for sorting an array of size n using `Quick Sort`. Consider the two statements:
> (1): `B(n)` is `O(W(n))`
> (2): `B(n)` is `Theta(W(n))`
**Select ONE answer:**
> A. Both `(1)` and `(2)` are true
> B. `(1)` is true but `(2)` is false
> C. `(1)` is false but `(2)` is true
> D. Both `(1)` and `(2)` are false
I think the answer is A but I am not sure | B(n) = O(n * lg(n))
W(n) = O(n^2)
1) B(n) < W(n) implying B(n) = O(W(n)).
2) B(n) = Theta(W(n)) equals to W(n) = O(B(n)). As before B(n) < W(n), therefore W(n) is not bounded by B(n), making 2nd statement incorrect.
Solution is B, first statement is true and the second is false. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "algorithm, time complexity, quicksort"
} |
Programatically adding rows in table using loop but just last record gets display
This code add last row in the Table . I mean just last record get displayed I thought its a problem of viewstate so tried to EnableViewState but it says that its not like that
Employee emp = new Employee();
Table tb = new Table();
TableRow tr1 = new TableRow();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
TableCell tc3 = new TableCell();
for(int i=0;i<7;i++){
emp = con.GetNextEmployee();
if (emp != null)
{
tc1.Text = emp.name;
tc2.Text = emp.position;
tc3.Text = emp.ext;
tr1.Cells.Add(tc1);
tr1.Cells.Add(tc2);
tr1.Cells.Add(tc3);
tb.Rows.Add(tr1);
}
}
Panel1.Controls.Add(tb);
Kindly help me | move these lines into the loop:
TableRow tr1 = new TableRow();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
TableCell tc3 = new TableCell();
why part: actually you don't need to re-define them.
but the objects must be RE-created after you add them to your table.
because: when you add a row/cell to the table. row/cells' "reference" is being added to table.
so, second time you change the row or cell, actually, you are changing the row/cell "that is already in your table" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, asp.net, visual studio 2010"
} |
Exclude GND trace from GND groundplane in Eagle
I have a board layout in Eagle with a groundplane. Now I have a trace inside of this groundplane which is also GND but this one shouldn't merged into the groundplane.
The reason is, that i want to connect a decoupling capacitor to an ic and the groundlead from the capacitor to the ic should be separate from the groundplane.
How can I achieve this? | It would really help to have a picture of your layout to evaluate if what you want to do makes sense.
Some ways to achieve what you want
* Use the Restrict layer to prevent the GND polygon from filling the area where you trace is routed.
* Separate your GND signal with a 0-Ohm resistor or some other placeholder. Eagle will obviously treat this as an independent signal (GND2 for example), not connecting it to GND.
* Just route your GND signal on another layer. | stackexchange-electronics | {
"answer_score": 0,
"question_score": -1,
"tags": "pcb, eaglecad, grounding"
} |
Как отобрать срез строк после фильтрования строк фрейма?
Имеется фрейм данных:
data = {'фрукт': ['арбуз','арбуз','арбуз','арбуз','груша', 'груша', 'груша', 'груша', 'вишня', 'абрикос', 'абрикос', 'абрикос', 'банан'],
'страна': ['россия','сша', np.nan, 'россия', np.nan, np.nan,'канада', 'франция', 'португалия', 'испания', np.nan, np.nan, 'перу'],
'вид_фр': ['1','2','3','10', '5', '7', '5', '6', '10', '5', '5', '7', '7']
}
dates = pd.DataFrame(data, columns = ['фрукт','страна', 'вид_фр'])
 со второй строки, содержащей грушу до значения следующего за послдней строкой, которая содержит грушу.
Как можно это сделать?
Ожидаемый результат:
.shift(fill_value=False)]
Вывод:
фрукт страна вид_фр
5 груша NaN 7
6 груша канада 5
7 груша франция 6
8 вишня португалия 10 | stackexchange-ru_stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "python, pandas"
} |
Android - Is there a system broadcast intent when an app is killed to reclaim resources?
I'm attempting to write a BroadcastReceiver to be notified when the Android OS kills an app in order to reclaim resources. I've tried filtering on "android.intent.action.PACKAGE_RESTARTED" but I never seem to receive that broadcast, even when I force close an application.
So, am I using the correct intent action filter? If not, what is the proper one? Or is this simply not possible?
Thanks! | Steve,
Unfortunately, if there is such an Action, it is not documented. The closest that you could get to is to run a service in the "foreground" and check if a particular application is running. There is no reason, after all, that you couldn't create such an Intent.
FuzzicalLogic | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "android, android intent, broadcast"
} |
Can I create a SQL script to backup my MS Access database?
I am working on a MS Access database. Can I script the data, and the database objects, into a SQL script? | I guess you want to backup your data programmatically from within your database Application?
For this scenario, split frontend and backend (data) into two separate MDB files. Then your frontend part can copy the data file to your backup folder programmatically, for example, by using the FileSystemObject. If you don't know how to split frontend and backend, look here. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ms access"
} |
A confusion on DC operating point in SPICE
LTspice calculates the DC operating points for the below circuit as as:
 If I would perform DC operating point for this circuit with pen and paper, I would first: **short all the inductors and open all the capacitors**. But then circuit becomes as:
 In LTspice if we _do not_ skip the initial operating point solution and obtain results, is that equivalent to: we first do a DC operating point analysis and we set uic for each component and do a transient analysis? | > I would first: short all the inductors and open all the capacitors. But this seems wrong. What am I doing wrong here?
SPICE is a numerical simulator. There is a rounding error in every SPICE result.
In particular, SPICE only tries to solve the node equations until the currents balance to within an error defined by the parameter `ABSTOL`. In LTSpice the default value of `ABSTOL` is 1 pA, so if the currents at any node balance to within 1 pA, LTSpice considers that "good enough". You can change the value of `ABSTOL` using a `.OPTIONS` directive.
The errors you see are on the order of 1 pA, so this is expected behavior.
> In LTspice if we do not skip the initial operating point solution [when doing a transient analysis] and obtain results, is that equivalent to: we first do a DC operating point analysis and we set uic for each component and do a transient analysis?
Yes, this is equivalent. | stackexchange-electronics | {
"answer_score": 5,
"question_score": 0,
"tags": "ltspice"
} |
How to write methods accessible by all views
I am working with rails 3.1.10. I want to write a couple of methods which I can call from any of the views. I found this question very helpful.
What I did: 1\. created a module lib/unbxd_api.rb:
module UnbxdApi
require 'net/http'
def method1
end
def method2
end
end
2. In app/helpers/application_helper.rb
module ApplicationHelper
include UnbxdApi
But I am getting the following error:
`<module:ApplicationHelper>': uninitialized constant ApplicationHelper::UnbxdApi (NameError)
Why am I getting this error and how can i resolve it? | That because Rails does not load lib directory anymore. You have to do that explicitly by saying:
config.autoload_paths += Dir["#{config.root}/lib/**/"]
inside your _config/application.rb_ file.
Note: If you want a helper method that's available to all views file then I would suggest you to create helper `UnbxdApiHelper` instead inside _app/helpers/unbxd_api_helper.rb_. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, ruby"
} |
What might cause this FOUC for my pseudo-element SVG-icons?
I have a problem with FOUC for pseudo-elements on this site:
;
} | Seems like the problem was that I inserted the SVG in my content-attribute like this: `content: url(./images/menu-icons_about-the-city.svg);`. Apparently it's better to use it as a background, which makes it render _way_ faster.
My new code now looks like this:
a.headermenu__link:before {
display: block;
margin: auto;
margin-bottom: .5em;
height: 4em;
background-position: center;
}
.headermenu__about-city:before {
content: '';
background: url(./images/menu-icons_about-the-city.svg) no-repeat;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "css, svg, background image"
} |
Lambda expressions are not supported in -source 6
when i package my code, i get this error `Error:(13,48) java: lambda expressions are not supported in -source 6`.
I tried installing different JDK, but doesnt change. I tried jdk 11, 1.8, 13. | You need to specify in the pom the java version your project uses. Add this section to your `pom.xml` to specify java 8 for instance
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build> | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "java, maven"
} |
"Deconstruct assignment requires an expression with a type on the right hand side"
The following code:
(object ret, Expression subexpr) = expr switch {
// instance member
MemberExpression mexpr when mexpr.Expression is not null =>
(mexpr, mexpr.Expression),
// instance method call
MethodCallExpression callExpr when callExpr.Object is not null =>
(callExpr, callExpr.Object),
// include instance method calls, or static extension method calls
MethodCallExpression callExpr when
callExpr.Method.GetCustomAttributes(typeof(ExtensionAttribute)).Any() &&
callExpr.Arguments.FirstOrDefault() is not null =>
(callExpr, callExpr.Arguments.First()),
_ => (null, null)
};
does not compile, with:
> CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
**Why is this happening? How can I fix it?** | This seems like a simple case of "the compiler can't figure out the type of the switch". If you replace the deconstruction with a simple `var x =` to let the compiler figure out what type the switch expressions should evaluate to, the error message changes to a much more useful:
> No best type was found for the switch expression
The tuples that you return each case are of type:
(MemberExpression, Expression)
(MethodCallExpression, Expression)
(MethodCallExpression, Expression)
The compiler probably can't decide what common ancestor of `MemberExpression` and `MethodCallExpression` it should use.
Even a simple "hint" like this,
((object)mexpr, mexpr.Expression),
or:
((Expression)mexpr, mexpr.Expression),
so that the compiler doesn't need to find common ancestors, fixes the problem. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "c#"
} |
running brew commands is full of 'Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.'
This affects many other things too but in brew you may see lots of things suggesting: 'Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.'
Brew explicitly recommends you do not run it under sudo. | running brew doctor gave me useful answers to this
Provided software update is closed you may be able to agree to the license by opening Xcode.app, but I couldn't... so instead I ran:
sudo xcodebuild -license
Which if you scroll to the bottom lets you type 'agree' and then you're good to go. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 6,
"tags": "macos, homebrew"
} |
Long equals in tikz
How could I proceed to make an "equal" arrow in a diagram in tikz? To be clearer, what I would like to obtain is the equivalent of the following command in xy:
> \ar@{=}[direction]
Two examples of what I want (done in tikz):
 to [out=45, in=180] (3,0) node [anchor=mid west] {$= A$};
\end{tikzpicture}
\end{document} | stackexchange-tex | {
"answer_score": 18,
"question_score": 11,
"tags": "tikz pgf"
} |
How to measure and treat BSA bottom bracket housing misalignment?
I own an old Raleigh steel frame ('89) and wanted to install a cartridge bottom bracket (Shimano UN55).
I noticed it was difficult to fit it in the housing. When installed, the square taper shaft showed considerably more friction when turned.
Also, when I took the BB out again I saw rubbing marks on one side of the inner face of the lock ring, but only on one side. The threading itself is not damaged. When installing only one side of the BB, everything goes in smoothly.
To me it looks as if the BB housing is somehow misaligned. How do I measure it? And how do I treat it? | The two sides of a threaded shell showing axial or angular misalignment like this can usually be repaired by chasing and facing the shell with the normal procedure. Essentially what's happening here is the cutter on its pilot makes a new path for the threads to clear up the effects of heat distortion.
One could contrive a scenario where the two sides' threads were machined out of alignment from the start, but in practice it's not very likely, and distortion from brazing/welding is almost always the culprit.
There aren't any real alternatives to a proper piloted BB tap/facer set here. For most people it's going to be a shop fix.
Sometimes it's parroted that cartridge BBs made shell prep less important, but this is the counterpoint, as problems like this with mating the large amount of contact area between the cartridge and the adapter cup can keep the whole thing from working right. | stackexchange-bicycles | {
"answer_score": 3,
"question_score": 3,
"tags": "shimano, repair, bottom bracket, steel"
} |
Use of undeclared type 'ResponseJSONObjectSerializable'
Here's the code:
import Alamofire
import SwiftyJSON
public protocol ResponseJSONObjectSerialiazable {
init?(json: SwiftyJSON.JSON)
}
extension Alamofire.Request {
public func responseObject<T: ResponseJSONObjectSerializable> (completionHandler:(NSURLRequest?, NSHTTPURLResponse?, Result<T>) -> Void) -> Self {
//Error: Use of undeclared type 'ResponseJSONObjectSerializable'
...
}
}
I'm using Swift 2.0 and Alamofire 2.0 | It's just a simple typo `…liazable` vs. `…lizable`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift, alamofire"
} |
Finding the average of an array after dropping lowest value? (VB)
I'm developing a program that asks the user to input 5 numbers. The lowest of the 5 numbers will be dropped, and then the other 4 numbers are to be averaged.
I'm quite new to VB, but I believe I'm currently on the right path here...
I've sorted the array to help identify the lowest number, but I do not know how to exclude the lowest number and to then average the other remaining 4.
Here is my code so far:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim i As Integer
For i = 1 To 5
IntArr(4) = InputBox("Enter Number" & i)
Next
Array.Sort(IntArr)
'textbox1.text = ???
End Sub
End Class
Can anyone please assist or at least point me in the right direction? | In keeping with the spirit of your code, something like the following would work.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim OutArr(3) As Integer
For i = 0 To 4
IntArr(i) = InputBox("Enter Number " & i)
Next
Array.Sort(IntArr)
Array.Copy(IntArr, 1, OutArr, 0, 4) 'exclude the lowest number
TextBox1.Text = OutArr.Average()
End Sub
End Class | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "vb.net"
} |
Execute 2 bash commands on same line
I made a bash script to output the content for the `*txt` files and to print also the name of the file executed on the same line. But for no reason the first line has only the output and the next line has the name of the first output + the output of the next file. How can I have the `file name` \+ `output`?
for i in *.txt; do cat "$i" && echo -n "$i"; done
Outputs:
ignore
alex.txt11111
alex1.txtda
alex2.txtnu
alex3.txt
Correct would be
alex.txt ignore; alex1.txt 11111; alex2.txt da; alex3.txt nu | You are printing the contents of the file first, then printing its name without a newline (`echo -n`). You should do the opposite: print the name without a newline, but with an extra space at the end, then print the contents of the file.
for f in *.txt; do
echo -n "$f "
cat "$f"
done | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "linux, bash, scripting"
} |
Finite field as a splitting field of some irreducible polynomial
In many texts that I've read regarding finite fields, it always appears to be simply stated that a finite field is a splitting field of some irreducible polynomial, without proof. What are some good sources that actually provide an explicit proof? Now on p. $3$ of the lecture notes < of Keith Conrad, Lemma $2.1$ states that a field of power $p^n$ (cardinality of a finite field) is a splitting field of the polynomial $x^{p^n} - x$, but I'm not sure if this is irreducible. Might this be of any help? | No, $x^{p^n} - x$ is not in general irreducible. What it is, though, is the product of all irreducible polynomials over $\mathbb{Z}/p$ whose degrees divide $n$. The field with $p^n$ elements will be the splitting field of any factor of $x^{p^n}-x$ that is a multiple of any of those irreducible polynomials of degree $n$.
There will be many such irreducible polynomials of degree $n$, always at least one and usually nearly $p^n/n$ of them.
In particular, even when $x^{p^n}-x$ is not itself irreducible, it is a factor of itself and does have an irreducible factor of degree n. It's the splitting field both of itself and of that factor. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "reference request, finite fields, splitting field"
} |
Building apk to debug and release mode without changing Android Google API key each time?
I use **gmaps in my app** and the **api key from a file** looks like:
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
<!-- DEBUG -->
<!-- AIzaSyB#####MY_DEBUG_API_KEY_HERE -->
<!-- RELEASE -->
AIzaSyBS####MY_RELEASE_KEY_HERE
</string>
I wouldn't like to **change beetwen keys each time i build a release because** i could easily forget about it and in that way gmaps wont work in released app.
I taught about using only one key but from almost every source i looked up it is marked as bad practice.
So is there an easy way/option maybe with build type/flavour to somehow made the build process "smart" to :
**When i build in debug mode my build could use the debug api key and vica vera with the release build?** | You can define resource files in build type specific folders.
For example, in `/app/src/debug/res/values/strings.xml`:
<string name="google_maps_key">debug_maps_key_here</string>
And in `/app/src/release/res/values/strings.xml`:
<string name="google_maps_key">release_maps_key_here</string>
The build system will automatically use only the resources for the build type it is currently building, thus using the correct key for each build. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "android, android build, android debug"
} |
Question About Relation Between Time and Color of a femtosecond Laser Pulse
This is a problem in Tipler's _Modern Physics_ :
Laser pulses of femtosecond duration can be produced, but for such brief pulses it makes no sense to speak of the pulse’s color. To demonstrate this, compute the time duration of a laser pulse whose range of frequencies covers the entire visible spectrum ($4.0\times 10^{14}$ Hz to $7.5\times 10^{14}$Hz).
* * *
Since the frequences range is the whole visible spectrum I calculated the change in angular frequency first $$\Delta \omega=2\pi\Delta f = 2\pi (3.5\times10^{14})=2.199\times 10^{15}\text{rad/s}$$
and using the uncertainty relation $\Delta\omega\Delta t\geq \frac{1}{2}$ I calculated the minimum time interval to be $$\Delta t = \frac{1}{2\Delta\omega} = 2.27376\times 10^{-16}\text{ s}=0.227376\text{ fs}$$ What exactly does this tell me about the color of the pulse and why it doesn't make sense to speak about it? | In your calculation you started with the assumption that the pulse contains all frequencies in the visible spectrum. In other words, you assumed that the pulse contains all colors and is therefore a white (colorless) pulse. So your calculation does not tell you anything about the color of the pulse; you "told the calculation" that the pulse was colorless. | stackexchange-physics | {
"answer_score": 1,
"question_score": 0,
"tags": "visible light, waves, heisenberg uncertainty principle"
} |
Solutions and Office.com
Does anyone know when/how office.com will integrate with sandbox solutions
Google
Only returns the placeholder page
<
Is there any other information around? | Sandbox solutions are not going to be on the store. Its all about the Apps now. | stackexchange-sharepoint | {
"answer_score": 0,
"question_score": 1,
"tags": "sandbox solution, solution package"
} |
Filter Column with separate condition in SQL
I am trying to find login and logout time from a table. I am able to figure out login and logout time.
You can see below link for that. Login Logout Time in SQL Server
The solution for this is
SELECT DISTINCT AGENTID, CAST(EVENTDATETIME AS date) AS [Date],
MIN([EVENTDATETIME]) OVER (PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date) ORDER BY [EVENTTYPE]) AS first_login,
MAX([EVENTDATETIME]) OVER (PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date) ORDER BY [EVENTTYPE] DESC) AS last_logout,
FROM #temp
Now here what i suppose to do this filter column **first_login** by **EVENTTYPE = 1** and **last_logout** by **EVENTTYPE = 1**.
Can you suggest a way to do that. | Use a `case` expression in `MIN` and `MAX` window functions.
SELECT DISTINCT
AGENTID,
CAST(EVENTDATETIME AS date) AS [Date],
MIN(CASE WHEN EVENTTYPE = 1 THEN [EVENTDATETIME] END) OVER(PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date)) AS first_login,
MAX(CASE WHEN EVENTTYPE = 1 THEN [EVENTDATETIME] END) OVER(PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date)) AS last_logout
FROM #temp | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server"
} |
Running executable file with additional options or arguments
I'm writing a bash script `Test.sh` that aims to execute `anotherscript` (a linux executable file):
#!/bin/bash -l
mp1='/my/path1/'
mp2='/my/path2/anotherscript'
for myfile in $mp1*.txt; do
echo "$myfile"
"$mp2 $myfile -m mymode"
echo "finished file"
done
Notice that `anotherscript` takes as arguments `$myfile` and options `-m mymode`.
But I get the file not found error (says `Test.sh: line 8: /my.path2/anotherscript: No such file or directory`).
My questions are:
1. I have followed this question to get my bash script to run the executable file. But I'm afraid I still get the error above.
2. Am I specifying arguments as they should to execute the file? | I suggest you use
sh -c "$mp2 $myfile -m mymode"
instead of just
"$mp2 $myfile -m mymode" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "bash"
} |
Not able to access empty dataframe which is defined outside the function in python
I have defined `indicator` dataframe outside the function. I am trying to append value to the dataframe inside the function. But i am getting unresolved reference error.
Source code:
indicator = pd.DataFrame()
def chart(x):
df # sample dataframe
indicator = indicator.append(df)
for i in range(array_length):
chart(x)
print(indicator)
> I am getting syntax error : Unresolved reference 'indicator'
Can anyone help solve this issue. Thanks | You are performing an assignment inside your function, so `indicator` is treated as a local variable and an `UnboundLocalError` is raised. Try either
1. Declaring `indicator` global
2. Pass `indicator` to your function _(recommended)_ :
def chart(df2):
return df2.append(df)
indicator = chart(indicator)
Note that the exception occurs on `indicator` rather than `df` because no assignment takes place on `df`, so the interpreter resolves it to be global without issue. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, pandas, dataframe"
} |
Why does NullBooleanField in form give a dropdown when rendered in template?
When I change the form field to CharField, there is no dropdown in the template, BooleanField does not have one either. Why does NullBooleanField get a dropdown(in forms)? What if I dont want a drop down? Is this in built in generic view? | Due to the HTML specification of the checkboxes they only send value when checked. Quote from the HTML 4 spec:
> When a form is submitted, only "on" checkbox controls can become successful.
You have no way to figure whether a missing values means it is just missing or is false.
`NullBooleanField` allows you to make that difference but it can not use a checkbox because of the HTML specifications so it has to fall back to a dropdown in order to offer a choice between false value and no value. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "django, django rest framework, django forms, django templates, django views"
} |
Error wss://mqtt.eclipse.org when create mqtt client
I am in my first mqtt project and my project is ok in local. But when I deployed it to heroku, It failed. This is the error:
> Mixed Content: The page at '< was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://mqtt.eclipse.org/mqtt'. This request has been blocked; this endpoint must be available over WSS. k._doConnect @ mqttws31.min.js:36 k.connect @ mqttws31.min.js:31 I.connect @ mqttws31.min.js:65 (anonymous) @ app.js:10
I declared client in app.js file.
var MQTT_CLIENT = new Paho.MQTT.Client("mqtt.eclipse.org", Number(80), "/mqtt", MQTT_CLIENT_ID);
Thanks for help! | This is the browser keeping you secure under the Same Origin Policy
The web page that you have deployed had been securely loaded over HTTPS, to prevent unsecured content being mixed in with this it will block any connection to a none TLS protected location. In this case you are trying to make a unsecured connection the `mqtt.eclipse.org` on port 80.
The solution is to tell the Paho client to connect to the Secure Websocket endpoint on port 443. You can do this by passing a full URL to the Paho Client constructor
var MQTT_CLIENT = new Paho.MQTT.Client("wss://mqtt.eclipse.org", MQTT_CLIENT_ID); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, eclipse, websocket, mqtt"
} |
bit64 integers with fst
I have data in a csv containing long integers. I am exchanging this data between csvs and `fst` files.
For example,
library(bit64)
library(data.table)
library(fst)
library(magrittr)
# Prepare example csvs
DT64_orig <- data.table(x = (c(2345612345679, 1234567890, 8714567890)))
fwrite(DT64_orig, "DT64_orig.csv")
# Read and move to fst
DT64 <- fread("DT64_orig.csv")
write.fst(DT64, "DT64_fst.fst")
DT_fst2 <-
read.fst("DT64_fst.fst") %>%
setDT
# bit64 integers not preserved:
identical(DT_fst2, DT64)
Is there a way to use `fst` files for `data.table`s containing `bit64` integers | It looks like `fst` might be dropping column attributes either when saving or loading (please ask as an issue on `fst` package). You can put the column types back yourself in the meantime. `bit64::integer64` is a plain `double` under the hood so no bits have been lost. Just the type information telling R how to print the column.
> DT_fst2
x
1: 1.158886e-311
2: 6.099576e-315
3: 4.305569e-314
> setattr(DT_fst2$x, "class", "integer64")
> DT_fst2
x
1: 2345612345679
2: 1234567890
3: 8714567890
> identical(DT_fst2, DT64)
[1] TRUE | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "r, data.table, bit64"
} |
How to set button image by variable?
i am trying to set the button image by variable like this:
[collideButton setImage:[UIImage imageNamed:@"key%@.png",[getKeyboarLabel]] forState:UIControlStateNormal];
this is not working an error comes expected identifiers! i dont know where do i missed anything.
if i set image by this code:
[collideButton setImage:[UIImage imageNamed:@"keya.png"] forState:UIControlStateNormal];
it works good.. now please tell me where is the problem in uper code? | use `[NSString stringWithFormat@"key%@.png", key]`;
NSString *imageFilename = [NSString stringWithFormat:@"key%@.png", getKeyboarLabel];
[collideButton setImage:[UIImage imageNamed:imageFilename] forState:UIControlStateNormal]; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "ios, image, uibutton, set"
} |
Does GWT have its own notion of classpath?
Does the GWT compiler have a notion of its own "classpath" that is separate from the normal compile-time classpath? Does a GWT app (and its internal workings) have the notion of its own classpath that is separate from the normal JRE runtime classpath? | GWT has the notion of modules. Each module does declare what packages are in its source path. Modules can extend other modules. Every Class the GWT compiles has to be in the source path of one module your main module extends from.
The notion of sourcepath combined with modules builds some kind of separate classpath just for the GWT Compiler. But it has nothing to do with the java classpath. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "gwt, classpath, java"
} |
can some one help me how to use IList in c#
I'm am trying to test wcf method in C#. method return type is ilist. I need to catch that returned data in to an ilist and then i have to retrive each item from ilist. can some one send me a sample code how to do this? | It's perfectly fine to just iterate over an IList if that is what you're asking.
foreach(var item in MethodThatReturnsIList())
{
// Do whatever
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "c#, unit testing"
} |
What does util.generic_utils.deserialize_keras_object() function in keras do
In Keras library, `activattion.get()` calls `activattion.deserialize()` function which in turn calls `util.generic_utils.deserialize_keras_object()` function. Can someone explain what happens in `deserialize_keras_object()` function | As one may read here `deserialize_keras_object` is responsible for creation of a `keras` object from:
* configuration dictionary - if one is available,
* name identifier if a provided one was available.
To understand second point image the following definition:
model.add(Activation("sigmoid"))
What you provide to `Activation` constructor is a `string`, not a `keras` object. In order to make this work - `deserialize_keras_object` looks up defined names and check if an object called `sigmoid` is defined and instantiates it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "machine learning, neural network, keras, keras layer, keras 2"
} |
finding instance of text in sql files after WHERE clause
I have a VS2008 solution with a database project, in it is a folder that holds a whole bunch of sql stored procedures (we are talking 100's).
Due to a change that has been made to the ANSI_NULLS setting for all the sprocs I need to update all instances of '= null' to 'is null'.
I cannnot do a "find and replace all" on .sql files as most instances of this string are located in the sproc declarations, i.e., "@dtDate DateTime = null" (which i dont't want to change). However all other instances such as "if (@dtDate = null)" I do want to change as it is no longer valid.
What is a good way to replace all instances of the text "= null" to "is null" that occur after a particular word (e.g., "WHERE") in all .sql files in a database project folder?
Thanks very much | I ended up using a little bit of regex in the VS2008 find dialog.
create(.|\n)*select(.|\n)*= null
This found instances of "= null" after the select statement (missing instances in the declarations). I then just went through each instance manually - worked OK. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, regex, visual studio 2008"
} |
How does Databinding work with Structured Software
I've been doing some Web-Projects lately that rely on heavy Data-Binding and have been quite happy with the results. Databinding Webforms works mostly the way I need it and I spared myself tons of code.
One thing that still feels weird is that I have application logic and database logic mixed throughout the application. Datasources query directly to the database..
Also, there is no way (I could think of) that would enable me to unit-test this system. By having the DA logic everywhere I can't really momck out database calls and provide fake data. (Although I am still learning how to do that on normal projects as well).
So, how was this meant to work initially? How do I use databinding without sacrificing structure and testability? | It's very much possible!
Here's an article about it. (focuses on winforms however)
A common pitfall.
This however focuses on winforms, webforms is another story, and it's difficult to test properly.
If you like unit testing, why not have a look at asp.net mvc | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, data binding, webforms, design patterns"
} |
How do you hide the sidebars in Eclipse so you can just see the code?
I'm new to Eclipse. One of the things I like _most_ about it is the fantastic indexing, and the symbols/function outline at the right. One of the things I like _least_ about it is how small the code area is due to all of the side-bars (one each in Eclipse CDT at the left, right, and bottom makes the code area quite small).
Is there a quick way to toggle between hiding and showing the sidebars? | After some tinkering around I accidentally discovered it! **Just double-click on your open file-name tab and it will maximize to full-screen. Double-click again to toggle it back to your normal "perspective".** This applies to the left, right, and bottom sidebars too: just double-click on any of their tabs and they will maximize. Do it again to toggle back to normal size. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "eclipse"
} |
How do you make DISPLAY variable undefined?
I am using Ubuntu, but I think this applies to all Linux.
What's the command to set DISPLAY to be undefined in the shell? | You want the `unset` command: `unset DISPLAY` | stackexchange-unix | {
"answer_score": 9,
"question_score": 5,
"tags": "shell, environment variables"
} |
Jquery fadeToggle on each element separately
I'm making a tumblr theme, and I'm trying to achieve a Jquery effect in which when I click `.cari`, `.inpo` will fadeToggle. But, the problem is that there are more than 1 div with the class `.cari` and more than 1 div with the class `.inpo` and when one of the divs with the class `.cari` is clicked, all the divs with the class `.inpo` will fadeToggle. What should I do to make each `.inpo` fadeToggle only when its own `.cari` is clicked? I'm pretty sure there are similar questions asked here, but I am sorry though I cannot understand the solutions/answers. I am very new to Jquery/Javascript, so it'd be nice if the answer is to be simple and easy to understand. Sorry and thank you!
Image: <
Hopefully, I made it easy to understand what I'd like to achieve. | It depends on your exact layout of your divs but here's an example
<div class="cari">?</div>
<div class="inpo">{block:Date}<a href="{Permalink}">{TimeAgo}{block:NoteCount} ({NoteCountWithLabel}){/block:NoteCount}</a>{/block:Date}</div>
<div class="cari">?</div>
<div class="inpo">{block:Date}<a href="{Permalink}">{TimeAgo}{block:NoteCount} ({NoteCountWithLabel}){/block:NoteCount}</a>{/block:Date}</div>
If your layout is like that
$(".cari").click(function () {
$(this).next().fadeToggle();
});*
Basically _this_ is the exact element in question (.inpo) so it grabs the next element and toggles just that one.
Jsfiddle example | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery"
} |
h2 sql, create table with multi-column primary key?
How can i create a multi-column primary key within the CREATE TABLE statement using the **h2** database? From my investigations, the code to do so in mySQL and Apache Derby databases is:
CREATE TABLE SAMP.SCHED(
CLASS_CODE CHAR(7) NOT NULL,
DAY SMALLINT NOT NULL,
STARTING TIME,
ENDING TIME,
PRIMARY KEY (CLASS_CODE, DAY));
But this doesn't work in h2, it results in a 'org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement'
Any help is much appreciated. Thanks | From here:
* <
this should work:
ALTER TABLE SAMP.SCHED ADD PRIMARY KEY (CLASS_CODE, DAY) | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 14,
"tags": "sql, h2"
} |
Creating a weird matrix
So I'm making a documentation about Coding Theory and I'm almost over, but I'll have to create a matrix and I have no idea how to create this specific one, any help would be appreciated. ,
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "reactjs, import"
} |
Signature pad Storing the signature in Database
I have develop a signature using Html and java script where user can perform a signature,.
help will be appreciated :)
Thanks. | It all depends on what sort of DB you want to use to store the signature.
If you're using Rails and Amazon's S3 service you can use Active_Storage to assign the signature to a user.
< <
I'm using < on the front end for capturing the user's input. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "database, storage, signature, pad"
} |
Undefined value using Laravel in JavaScript
The following code should display the availability of the selected record in the `alert` call, but it always results in `undefined`. How should the `availability` value be computed?
{!! Form::open(array('url'=>'admin/products/toggle-availability', 'class'=>'form-inline update-form', 'data-recordid'=>$product->id))!!}
{!! Form::select('avail', array('1'=>'In Stock', '0'=>'Out of Stock'), $product->availability) !!}
{!! Form::submit('Update') !!}
{!! Form::close() !!}
<script> type="text/javascript">
$(document).ready(function(){
$(".update-form").submit(function(s){
s.preventDefault();
var recordID = $(this).data('recordid');
var availability = $('input[name=avail]').val();
alert(availability);
});
});
</script> | I already solve :)`
View
<select id ="availability">
Jquery
var availability = $('#availability option:selected').val();
` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "javascript, php, laravel"
} |
ReplaceAll java throws exception
why does this code throw an exception?
file = file.replaceAll(Pattern.quote("/"),File.separator);
Message: String index out of range: 1
File: null Class: java.lang.String Methode: charAt Line: -1
File: null Class: java.util.regex.Matcher Methode: appendReplacement Line: -1
File: null Class: java.util.regex.Matcher Methode: replaceAll Line: -1
File: null Class: java.lang.String Methode: replaceAll Line: -1 | The second parameter of `replaceAll` is _also_ a pattern to some extent. In particular, backslash has a special meaning. However, you don't just want to use `Pattern.quote` as that will quote more than you need to. You want to use `Matcher.quoteReplacement`:
file = file.replaceAll(Pattern.quote("/"),
Matcher.quoteReplacement(File.separator));
Alternatively - and rather more simply - don't use regular expressions at all:
file = file.replace("/", File.separator); | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "java, regex"
} |
Finding the value of $x$ when $2^{\frac{1}{\cos^2(x)}}\sqrt{y^2 - y +\frac{1}{2}} \leq 1$
> Find the value of $x$ when $2^{\frac{1}{\cos^2(x)}}\sqrt{y^2 - y +\frac{1}{2}} \leq 1$.
I don't know how to start thinking at this question. Please help me. Thank you! | Hint:
We have two unknowns with one inequality.
$$y^2-y+\dfrac12=\left(y-\dfrac12\right)^2+\dfrac12\ge\dfrac12$$
Now for real $x,\sec^2x\ge1\implies2^{\sec^2x}\ge2$
$$\implies2^{\sec^2x}\left(y^2-y+\dfrac12\right)\ge2\cdot\dfrac12$$
What is the intersection with given condtion? | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "trigonometry"
} |
How to return the number of different values in pandas dataframe as an integer
I want to count how many different values exists in a pandas dataframe column and return it as an INTEGER. I need to store that number in a variable so I can use it later.
I tried this:
`count = pd.Series(table.column.nunique())`
I get the expected result, but as pandas series not as integer, so I can't use it later in my function.
I've also looked for something that could convert it into numeric, but I havn't found anything. | Does this solve your issue?
table['column'].nunique() | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, pandas groupby"
} |
Zero knowledge proofs for a Merkle Tree
Say I have a publicly available Merkle tree, and I want to prove the existence of a leaf (containing a number, maybe) in the tree. I could give the path along with the siblings, for a normal Merkle proof, but this reveals the leaf itself.
How can I do this in zero knowledge, i.e., proving that the leaf exists, but not revealing which leaf? | The "path" is only a witness for your proof; you don't actually want to _give_ the path to the verifier. Turns out that going from a NP-problem with witness to an actual zero-knowledge proof is not that trivial.
What you could do: one of your leaves $L_1, \dots, L_{n}$ has the value of your commitment $x$. You might write something like
$$\bigvee^{n}_{i=1}\left(L_i=x\right).$$
This is a satisfaction problem, so it's suited to be fed in a bunch of ZK libraries.
* * *
Lately, I've been playing with rank-1 constraint systems (r1cs), such as provided by libsnark or in a little time by dalek's ``bulletproof'' library. These provide non-interactive, fast, compact zero-knowledge proves.
You said your leaves could contain numbers. This translates very nicely in a r1cs system!
$$\prod^n_{i=1}(L_i-x)=0$$
You simply prove that one of the roots of the above polynomial equals zero, which is true when $x$ represents a leaf. | stackexchange-crypto | {
"answer_score": 3,
"question_score": 4,
"tags": "zero knowledge proofs, hash tree"
} |
What determines the number of hearts Wolf Link has?
When Amiiboing Wolf Link in, what determines the number of hearts he has? I heard it was defined by your Twilight Princess HD savefile on WiiU, but does that mean if you play on Switch you are stuck on minimum hearts? | It's based on Twilight Princess HD Cave of Shadows save data that you save to the Amiibo itself. It does not use the normal save file from the game but the save data you save to the Amiibo after completing the Cave of Shadows so the fact that it is a different system does not play into effect.
The exact hearts you get are based on what you save to the the Amiibo once you complete a section the amount of hearts wolf link currently has still full. So easiest way to get 20/20 hearts saved is:
* Get 20 Hearts normally
* Head to the Cave of Shadows
* Get to floor 6 with Full Health
* Now save to the Ammibo | stackexchange-gaming | {
"answer_score": 5,
"question_score": 6,
"tags": "zelda breath of the wild, amiibo"
} |
Why do browsers automatically redirect to urls in location?
When a response to a certain request is redirection, with status code 3XX and location header, it seems that the browser automatically redirects to the other page (by URLs included in location header).
But when I send the same request via cURL or postman, the response comes with the 3XX but no redirect occurs.
So I concluded that the redirection from the first case is not a basic response but an additional function that browsers.
If so where I can find the settings about this? If not, what is the main cause of this redirection? | The browser is trying to give the user a good experience. If the web site returns a redirect, then the best user experience is for it to go ahead and do the redirect. `cURL` and `wget` will also follow the redirects if you enable the option, but since those tools are mostly for diagnostics, the default is to have one request, one response. It's up to the consumer to decide what to do with that response.
I'm not sure what you mean by "basic response". The RFC does not require a redirect. The request receives a response, and it's up to the recipient to decide what to do next. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect, browser"
} |
Where to set the OAuth redirect_uri in ASP.NET 4.5 webforms application
I can't find anywhere how to set the OAuth2 redirect_uri in an ASP.NET 4.5 webforms application. By default it's set to localhost and of course I get this error from google:
The redirect URI in the request: did not
match a registered redirect URI
And this from Facebook:
Given URL is not allowed by the Application configuration.: One or more of the
given URLs is not allowed by the App's settings. It must match the Website URL
or Canvas URL, or the domain must be a subdomain of one of the App's domains.
And I get this error from my website domain (not from the localhost). | I was testing the built in external login logic for authentication, and I got this error even though my Google API credentials were correct. For example the redirect URI was set to:
`
The odd thing was that the default CallbackPath for the Google Authentication is "/signin-google" but I had to set this anyway in App_Start/Startup.Auth, so I added this line and it worked:
> **CallbackPath = new PathString("/signin-google")**
so...
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "YOUR CLIENT ID",
ClientSecret = "YOUR CLIENT SECRET",
CallbackPath = new PathString("/signin-google")
}); | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 8,
"tags": "c#, asp.net, .net, webforms, oauth 2.0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.