INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Has anyone had any success brewing 11.5l in a 30l container?
I am keen to start home brewing but I don't want to make 23l of beer at a time. I'd like to brew smaller batches of different beers.
I have looked at the starter brewery kits available locally and they are all 30l containers for brewing 23l.
I have spoken to a brew master and he assured me it is possible to brew half, say 11.5l in a 30l container but oxidation and temperature are very tricky to get right.
Has anyone successfully brewed 11.5l in a 30l container and if so what brands did you use? | I brew 12.5L batches in 30L plastic fermenters. Have done 15 batches or so without any issue. The "fermenters" are generic 30L water containers from various hardware stores. | stackexchange-homebrew | {
"answer_score": 2,
"question_score": 2,
"tags": "first time brewer, brewing"
} |
Models of intuitionistic linear logic that reflect the resource interpretation
I am interested in models of intuitionistic linear logic, that is, the logic that you get if you take classical linear logic and restrict the set of operators to $\otimes$, $1$, $\multimap$, $\times$, $\top$, $+$, $0$, and $!$. I know what categorical models of this logic are. However I am looking for something more concrete, something that reflects the interpretation that intuitionistic linear logic is about resources.
Intuitionistic linear logic corresponds to a variant of the λ-calculus that cannot only deal with values (which can be duplicated and destroyed at will), but also with resources (which can neither be duplicated nor destroyed by default). The ordinary simply typed λ-calculus can be given a semantics where the meaning of a type is the set of its inhabitants. Can something similar be done for the linear λ-calculus such that the idea of computing with resources is directly expressed? | I think the Petri net semantics for linear logic probably best captures this intuition that it is a logic about resource manipulation. The idea is that Petri nets model the movement of tokens (i.e., resources) through a network. Here's the money quote from Lokhorst 1997.
> Petri nets are models of dynamic processes in terms of types of resources, represent ed by places which can hold to arbitrary nonnegative multiplicity, and how these resources are consumed or produced by actions, represented by transitions. They are usually described in terms of multisets.
Lokhorst, Gert-Jan C. 1997. Deontic linear logic with Petri net semantics. Technical report, FICT (Center for the Philosophy of Information and Communication Technology). Rotterdam. < | stackexchange-mathoverflow_net_7z | {
"answer_score": 5,
"question_score": 8,
"tags": "lo.logic, lambda calculus, linear logic, intuitionism"
} |
Laravel + PostgreSQL Ltree
How to write the migration file to add the field type 'ltree' (PostgreSQL)
Schema::create('table', function (Blueprint $table) {
....
$table->ltree('path');
}
Does not work.
Thanks! | Look to the manual of the functions available: <
Laravel's goal is compatibility, so unless there is equivalent structures in all supported databases, they aren't likely to support it natively.
You can run SQL statements manually using `DB::statement('CREATE TABLE ...')`
Just keep in mind that your application will be locked to postgres which may not be ideal. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, postgresql, laravel, laravel 5.1, ltree"
} |
Get matched sublist from list comprehension
cache = [['a', 'b'], ['c', 'd']]
val = 'a'
if val in [x for [x,y] in cache]:
print(y)
else:
print('Not found')
In the above code, I wish to have `b` returned as the answer. However, the result is `d`. How can I retrieve the matched item from this expression? Pardon me if my terminology is incorrect, I just started learning Python and list comprehensions. I prefer to use this shorthand notation as I'm not comfortably familiar with lambda expressions just yet. Another curiosity, why is the result `d`? | The problem is the the expression `[x for [x,y] in cache]` is valued as `['a','c']` before you look for `a` in it. and therefore, `a` is not related to `b` in it.
`y` contains the value of `d` because it the last value the was stored in `y` while iterating over `cache`
I think what you want is something like this:
cache = [['a', 'b'], ['c', 'd']]
val = 'a'
ys = [y for [x,y] in cache if val == x]
if ys:
print(ys[0])
else:
print('Not found') | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, list comprehension, python 2.x"
} |
Descendants of Latin vs. Greek?
From Latin there descend half a dozen (or more) modern languages. Greek, by contrast, has simply changed over time but without branching into separate languages.
Why the difference? Both were spoken over pretty wide areas, after all, and I'd have expected that the various koines would eventually have diverged. | Tsakonian is considered a separate Hellenic language, deriving mostly from Doric Greek and not mutually intelligible by standard Greek speakers. Cappadocian and certain Pontic dialects are considered different languages sometimes, but this is debatable. Greek did change mainly in terms of phonology and (partially) grammar, but not that much in terms of core vocabulary. I think Blazec V. demonstrated this few years ago with a glottochronological example (I can get back to you with the title).
Greek was indeed spoken in a great area, but was replaced (unlike Latin) by other languages such as Arabic, which was closer to the native tongue of the former Greek speakers in those areas. | stackexchange-linguistics | {
"answer_score": 7,
"question_score": 9,
"tags": "historical linguistics, latin, greek"
} |
SLF4J version of Logging Event
I have a Log4J Serializer that uses a Log4J pattern to generate the serialized form.
However, I am migrating to Log4j2, and trying to use SLF4j in my java project except for at runtime when I want to use Log4j2. Is there anyway to refactor the LoggingEvent class in log4j to use a class in slf4j. I have read here about a SLF4J LoggingEvent, but it is an abstract interface and I do not believe is what I need.
My end goal is to use slf4j for all of my logging, i.e. :
org.slf4j.logger
logger.debug("test"); logger.info("Hello World");
Then in my spring-boot app use log4j2 at **runtime**. | Have you tried to use **log4j-slf4j-impl** lib of log4j2? When I upgraded (log4j -> log4j2) I had to add to my gradle file these libs:
runtime group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8'
runtime group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.8'
runtime group: 'org.apache.logging.log4j', name: 'log4j-web', version: '2.8'
runtime group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.8'
However I must admit, I dont use spring-boot, but I hope my hint helps you
Cheers | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, log4j, slf4j, log4j2"
} |
Pygame, trying to rotate sprite
I'm trying to rotate of sprite for my game written in pygame
I don't get any consol error, but my sprite stay exactly the same and doesn't rotate :(
Any idea ?
perso.image = pygame.image.load("sprites/[shadow]main_char_sprite.png").convert_alpha()
perso.image = pygame.transform.scale(perso.image, (53,60))
perso.rect = perso.image.get_rect()
perso.rect.x = 200
perso.rect.y = 200
perso.add(perso_group)
while 1:
screen.fill(white)
pygame.transform.rotate(perso.image,30) ########not working :(
all_group.add(statique_group, zombie_group, perso_group)
all_group.draw(screen)
pygame.display.flip() | The documentation for the transform functions says:
> All these functions take a Surface to operate on and return a new Surface with the results.
So you need to assign the return value of `rotate` to the variable:
perso.image = pygame.transform.rotate(perso.image,30)
However, the documentation also says:
> Some of the transforms are considered destructive. These means every time they are performed they lose pixel data. Common examples of this are resizing and rotating. For this reason, it is better to retransform the original surface than to keep transforming an image multiple times.
So you may want to keep the original, and keep increasing the rotation angle instead. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, pygame, sprite"
} |
Set new state to an existing array state
If I have a state that looks like this
this.state = {
names: [
"Snap, Crackle, Pop"
]
}
Is it possible to create a new state by referring to an index number of an existing array?
Something like this is suppose? This is just an example.
this.state = {
names: [
"Snap, Crackle, Pop"
],
myName: this.state.names[0]
} | I would set it in `componentDidMount`:
componentDidMount() {
const { names, myName } = this.state;
if (!myName) this.setState({ myName: names[0] });
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, react native"
} |
400 bad request when access ASP.net web api via computer name on IISExpress
I'm getting a 400 bad request error message when accessing an ASP.net web api via a url that uses the computer name. When I use localhost it works fine. I'm using the iisExpress for visual studio 2012.
Any help is appreciated! Thanks in advance! | I found the answer to this from another post on here. I had to update my IISExpress' applicationhost.config file and add a binding with my computer name on it.
The link to the other post is here: Configure IIS Express for external access to VS2010 project | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "asp.net mvc, asp.net web api"
} |
In a pandas dataframe column, remove last 4 digit if it's 2017
In a pandas dataframe, there is a column X, with numbers like 12342017, 23456782017, WC456123, ER2017124. I want to remove the last four digit if it's '2017'
So, my desired output should be 1234,2345677,WC45612,ER2017124 | Use `Series.str.replace` with `$` for regex for end of string, also if possible mix numbers with strings first convert to strings:
df = pd.DataFrame({'X': ['12342017', '23456782017', 'WC456123', 'ER2017124']})
df['X'] = df['X'].astype(str).str.replace('2017$','')
print (df)
X
0 1234
1 2345678
2 WC456123
3 ER2017124 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "string, pandas, text, replace, strip"
} |
Where can I practice web-security or network-security?
> **Possible Duplicate:**
> Servers for penetration testing
I'm in a process of learning security of networks and websites. I already practised code reviewing but I want to perform exercise.
Is there any online resources to get our hands dirty instead of just looking at code and word for learning web security or network security? | I would recommend that you have a look at some of the wargames out there. For example one of my personal favourites is Over the Wire where they provide several games of varying difficulty. Certainly makes for a much more entertaining and thrilling learning experience.
Another one more specifically targeting web-hacking is Hack This Site split into varying levels of difficulty. | stackexchange-security | {
"answer_score": 1,
"question_score": 0,
"tags": "appsec, network, web application"
} |
How to use GROUP with DATEPART?
I am using the following script to count the number of ShopId for one year.
I need also to breakdown the result by month for a year.
So end result should be
MONTH 1
SHOPID 5 100
SHOPID 4 90
MONTH 2
SHOPID 1 150
SHOPID 4 80
* * *
SELECT ShopId, Count(ShopId) as Interest
FROM dbo.Analytics
WHERE DateCreated >= '2014' AND DateCreated < '2015'
GROUP BY ShopId ORDER BY Interest DESC
* * *
Table structure
CREATE TABLE Analytics
(
DateCreated dateTime2(2),
ShopId int
);
What Should I change in my script? Shall I use DATEPART near GROUP BY | You can use **DatePart**.
Try like this
SELECT DatePart(mm,datecreated) 'Month',ShopId, Count(ShopId) as Interest
FROM dbo.Analytics
WHERE year(DateCreated) = '2015'
GROUP BY Datepart(mm,datecreated),ShopId
ORDER BY Interest DESC
DatePart will return Month Number only. If you need Result would have Month Name then you should use **DateName**
Try this
SELECT Select DateName( month , DateAdd( month , DatePart(mm,datecreated) , -1 ) ) 'Month',ShopId, Count(ShopId) as Interest
FROM dbo.Analytics
WHERE year(DateCreated) = '2015'
GROUP BY DateName( month , DateAdd( month , DatePart(mm,datecreated) , -1 ) ),ShopId
ORDER BY Interest DESC | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "sql, sql server"
} |
Why "example link" doesn't work inside an unnumbered list?
This is the text of the message:
This X is an example link
<ul>
<li>
This Y is an example link
</li>
</ul>
And this is how it looks:
This X is an example link
* This Y is an example link
Update (this way it seems to work)
- This X is an example link
* This X is an example link
**But why not in unnumbered list?** | From the editor help section on raw HTML (emphasis mine):
!post editor html help
> Block-level HTML elements have a few restrictions:
>
> 1. They must be separated from surrounding text by blank lines.
> 2. The begin and end tags of the outermost block element must not be indented.
> 3. **Markdown can't be used within HTML blocks.**
>
So, you either need to construct the `<a>` HTML yourself, or, more simply, use the Markdown syntax for unordered lists:
This X is an example link
- This Y is an example link
...produces...
This X is an example link
* This Y is an example link | stackexchange-meta | {
"answer_score": 6,
"question_score": 1,
"tags": "support, markdown"
} |
How to not die?
I want something like this:
or function() { echo mysql_error().'<br>'; } // doesn't work
Instead of:
or die(mysql_error());
I want to continue the execution of the script, not to "die". Can't I use the anonymous function that way? I just woudn't like to name it.
**EDIT/TIP:** For creating anonymous functions, there's a lambda-style function called create_function... | or print mysql_error();
though printing it out is almost bad as dying.
In the perfect world it would be
$res = mysql_query($query) or trigger_error(mysql_error().$query);
always do it that way. You'll get not only filename and line number (which is MIGHTY helpful when you have plenty of queries on the page) but also will keep sensitive information secret on the production server, where you will turn displaying errors off and logging - on. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "php"
} |
Google Maps API Static Map off-road marker
When I place a marker with geocode on a off road position, Google always put the marker on the road. Example:
<
In the normal Google maps you see the original position (the green arrow) and the position where the marker is placed: <
How can I get the marker off the road? So I want my marker to be at the place of the green arrow in my Google Maps API.
Maybe it is not possible with the Static Map, but if so, is it possible with V3 API? | Use a LatLng(52.112683,5.138950) instead of the address: | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "google maps, google maps markers, google maps static api"
} |
emberjs analogue of rails partial
I am porting my rails view to emberjs. It seems that there are view and outlet helper for template separation. Since outlet is for state change, I am planning to use view helper to mimic rails partial. Am I right? | Declaring views just to use them as partials is probably overkill. What might suit you best is the `{{template}}` helper in handlebars. If you've got a precompiled template in your Ember.TEMPLATES hash, you can do `{{template "sometemplate"}}` to inject that template, similar to a rails partial.
There's also a syntax particularly for partials in vanilla Handlebars, but I don't think it's well supported in Emberland and I never see anyone use it, and template does the same thing afaik.
## Update 1/19/2013
There is now a {{partial}} helper you can use to insert insert template partials, whose filename's (and therefore `Ember.TEMPLATES` names) must begin with an underscore. Thanks to @brg for the heads up. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "ember.js"
} |
Intersect all possible combinations of list elements
I have a list of vectors:
> l <- list(A=c("one", "two", "three", "four"), B=c("one", "two"), C=c("two", "four", "five", "six"), D=c("six", "seven"))
> l
$A
[1] "one" "two" "three" "four"
$B
[1] "one" "two"
$C
[1] "two" "four" "five" "six"
$D
[1] "six" "seven"
I would like to **calculate the length of the overlap between all possible pairwise combinations of the list elements** , i.e. (the format of the result doesn't matter):
AintB 2
AintC 2
AintD 0
BintC 1
BintD 0
CintD 1
* * *
I know `combn(x, 2)` can be used to get a matrix of all possible pairwise combinations in a vector and that `length(intersect(a, b))` would give me the length of the overlap of two vectors, but I can't think of a way to put the two things together.
Any help is much appreciated! Thanks. | `combn` works with list structures as well, you just need a little `unlist`'ing of the result to use `intersect`...
# Get the combinations of names of list elements
nms <- combn( names(l) , 2 , FUN = paste0 , collapse = "" , simplify = FALSE )
# Make the combinations of list elements
ll <- combn( l , 2 , simplify = FALSE )
# Intersect the list elements
out <- lapply( ll , function(x) length( intersect( x[[1]] , x[[2]] ) ) )
# Output with names
setNames( out , nms )
#$AB
#[1] 2
#$AC
#[1] 2
#$AD
#[1] 0
#$BC
#[1] 1
#$BD
#[1] 0
#$CD
#[1] 1 | stackexchange-stackoverflow | {
"answer_score": 19,
"question_score": 12,
"tags": "r, list, combinations, intersect, combn"
} |
Request access for Contacts (Calendar, Reminders, Facebook etc) customized message
How can I set my own customized message when asking the user to grant access for Contacts (Reminders, Facebook etc)?
As you can see from below picture is the Path app asking for access to Contacts:
!enter image description here | From the iOS 6 release notes:
> In iOS 6, there are improved privacy controls for Calendar, Reminders, Contacts, and Photos. Users will see access dialogs when an app tries to access any of those data types. The user can switch access on and off in Settings > Privacy. Developers can set a “purpose” string for each class of isolated data. iOS displays this string to users to help them understand why their data is being requested. These strings can be added using Xcode’s Project editor, which is in the Info tab. The relevant key names begin with the string “Privacy -”.
!Editing Privacy Settings in Xcode | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "objective c, cocoa touch, ios6"
} |
libGL.so.1 not found: Qt GUI app in docker with centos
I am trying to run a Qt app in docker. I have a very limited Linux experience. The OS is centos. Qt version is 5.9.1. The overall idea is to run it in Xvbf. ( _I have already run firefox in DISPLAY:1(Xvbf) inside docker under centos_ )
When I try "docker run -it myTestGuiApp", I get an error libGL.so.1: cannot open shared object file: No such file or directory.
What is missing here?
Thanks in advance. | You probably have a missing library. You might need to install this : `yum install mesa-libGL`
Just add this line in your dockerfile : `RUN yum install mesa-libGL`
If this doesn't work, copy here your dockerfile. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "qt, docker, centos"
} |
Multiline Textbox Column in DataGridView
I want to have a multiline textbox to display data in a DataGridView. I found a solution here but that is not working for me. Here is my code that I am trying to fix the problem with:
myDataGridView.Columns["Column1"].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
I noticed that I can scroll inside of the textboxes, but their height is not correct so I cannot see all of the data at once. I want their height to be such that I can see all of their content at once.
Thanks in advance for any advice! | I found the problem. When I set "AutoSizeRowsMode" to "AllCells" that caused the row height to default to what I wanted. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": ".net, winforms, datagridview"
} |
Does portability come to the cost of unchanging variable sizes in C#?
Is this true? For performance-intensive applications using C# on 64-bit systems, I found this surprising in my book:
> C# strictly specifies a range and behavior for each value type. Because of portability requirements, C# is uncompromising on this account. For example, an int is the same in all execution environments. There is no need to rewrite code to fit a specific platform. Although strictly specifying the size of the value types may cause a small loss of performance in some environments, it is necessary in order to achieve portability. | Portability is 'more' _guaranteed_ by the unchanging variable sizes in C# (or really, the .NET/CLR/ECMA-355 specifications, of which C# is just one language).
This is just one of many guarantees that ensure that _code_ (and the resulting MSIL) are portable across compilation and run-time systems. On the other hand, making assumptions about the size of `int` in C is rather _unportable_.
The "cost" is only in certain implementations that must still provide the guarantee to correctly execute the resulting MSIL - and one requirement is a 64-bit `long` value. Not all systems have an associated "cost" and on an AMD64 system there is effectively zero "extra work" to do. Also, C# is not a 'bare metal' language.. and is not always the [most] appropriate language to use. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#"
} |
Powershell here-string expansion
**Here-strings**
There are some examples regarding Powershell 'here-string' but I have hardly come across 'here-string' expansion. so I posted this to be of some help.
When you want to add some literal with line breaks, both single and double quotes do not need to be escaped and no need for line breaks like `"`r`n"`. 'here-strings' comes to the rescue in PowerShell. They should start with
@"
and line break and should end with line break
"@
For example: |Result:
|
@" |
Hello world! 09/25/2014 11:39:56 | Hello world! 09/25/2014 11:39:56
'(this will appear as is)' | '(this will appear as is)'
! | !
"@ | | Here is how to introduce CmdLet and a date variable to show current date like so:
For example the following is what we want to achieve:
Hello world! 09/25/2014 11:39:56
'(this will appear as is)'
!
Here is how:
@"
Hello world! $(Get-Date)
'(this will appear as is)'
!
"@
Or with variable:
$myDate = Get-Date
@"
Hello world! ${myDate}
'(this will appear as is)'
!
"@ | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 11,
"tags": "powershell, powershell 3.0"
} |
Display a complete application in Windows 7 taskbar?
On Windows 7, is it possible to create an application to be displayed in the taskbar? What I have in mind is a small widget like a media player or a weather widget, etc.
Something like the mockup below:
!enter image description here
Any idea? | Yes it's possible. What you are looking for is a toolbar or sometimes referred to as "desk band":
< | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "winapi, windows 7, taskbar, windows shell"
} |
CSS vertical-align:middle on div inside anchor
I'm trying to get a div with css property `display:table-cell; vertical-align:middle` to behave as it "should". My expectation is that text inside these divs would be vertically aligned regardless of whether it's wrapped in an anchor or not.
Here's a jsfiddle: <
What am I doing wrong that prevents the vertical-align property from rendering the text out centered vertically, in the same way the header does in this example. | There is no need to use `display: table-cell` or even `float` anywere in this example.
To vertically center the text in the header, set the **line-height** of the `<h2>` to match the height of `#h2wrap`. Or remove **height** from `#h2wrap` and increase its top and bottom **padding** instead.
To vertically center the images, labels and the buttons within the `<a>` tags, set their **display** to **inline-block** and add a `vertical-align: middle`. You will have to explicitly set their widths and also eliminate the extra spaces caused by inline-block, but I believe this would be the easiest solution. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "css"
} |
Nutch : get current crawl depth in the plugin
I want to write my own HTML parser plugin for nutch. I am doing focused crawling by generating outlinks falling only in specific xpath. In my use case, I want to fetch different data from the html pages depending on the current depth of the crawl. So I need to know the current depth in HtmlParser plugin for each content that I am parsing.
Is it possible with Nutch? I see CrawlDatum does not have crawl_depth information. I was thinking of having map of information in another data structure. Does anybody have better idea?
Thanks | Crawl.java has NutchConfiguration object. This object is passed while initializing all the components. I set the property for crawl-depth before creating new Fetcher.
conf.setInt("crawl.depth", i+1);
new Fetcher(conf).fetch(segs[0], threads,
org.apache.nutch.fetcher.Fetcher.isParsing(conf)); // fetch it
The HtmlParser plugin can access it as below:
LOG.info("Current depth: " + getConf().getInt("crawl.depth", -1));
This doesn't force me to break map-reduce. Thanks Nayn | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "nutch"
} |
Open link with jquery
I'm totally not good at jQuery, but this is getting hilarious. Searching the web for 2 hours, trying to found how to open a link with jQuery, without any result.
I have tried this example: <
What I want is from the example above, change this code (and get it to work):
<a href="#">An anchor</a>
to
<a href="my_site.php">An anchor</a>
How can I do this? | $('a').attr('href', 'my_site.php');
however I advise you to give you link an id so it does not do this to ALL links, so
<a id="linkness" href="#" >An anchor</a>
$('#linkness').attr('href', 'my_site.php'); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, hyperlink"
} |
Jess bind this instance of java object
I want to do something like that in Jess:
(bind ?instance (this))
The only way I get it working is by using "new Object" instead of "this".
How can I get it working? | Presumably you are passing some Jess code to the Rete.exec() method, and want a reference to the object that's making the call. You just have to inject it into Jess yourself. Either use Rete.store() to store the object in Jess, then use (fetch) to retrieve it from storage in the Jess code, or use the methods of the global context object -- see Rete.getGlobalContext() -- to set a variable to refer to the Java object, then use the variable in the Jess code. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jess"
} |
What is the success / failure ratio of online petitions?
Ok I see a similar question has been answered and there have been successes: Have any of the "We the People" petitions ever resulted in policy changes?
However, what is the success / failure ratio based on an online petition from change.org or whitehouse.gov? What is the ratio of petitions that have met the threshold and effected change, versus those that met the petition threshold and did not have an effect? Has anyone done a study or collected data? | I follow this closely and, to my knowledge there has never been a study on the success/failure rate of White House petitions.
The real effect is that the White House uses these petitions to rationalize that which it has already decided on. Note the large number of signatures required in a short time. That requires an organized campaign, part of a large lobbying effort.
I have yet to see a petition acted on that was not already being acted on in the absence of the petition. | stackexchange-politics | {
"answer_score": 2,
"question_score": 1,
"tags": "data sources, petition"
} |
How to install ROracle package?
I am trying to install ROracle package using `install.packages("ROracle")` but every time i am getting this message `"Package which is only available in source form, and may need compilation of C/C++/Fortran: ‘ROracle’"`
These will not be installed
I am not able to find the solution for this, How can i resolve this issue? | from a past post. How to install ROracle package on Windows 7?
Download binary from oracle: <
The run the following command in r, substituting the file path:
setwd('xxxxx') # set to path of download
install.packages('ROracle_1.2-1.zip', repos = NULL)
Then load the library and use the package - you may have to change XXXX to whatever is in your TNS Names:
library('ROracle')
drv <- dbDriver("Oracle")
con <- dbConnect(drv, "USER GOES HERE", "PASSWORD GOES HERE", dbname='XXX')
test connection:
dbReadTable(con, 'DUAL')
was able to install from source and download the pre compiled addin directly from oracle | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 9,
"tags": "roracle"
} |
Localization for Async Python Telegram bot
We have asynchronous python application (telegram bot), and we want to add localization: user selects language when he starts dialog with bot, then bot translates all messages for him.
Django allows to change language for every request, it is working normally, because Django create separate process for each request. But it will not work in async bot — there is only one process and we should handle multiple users with different languages inside of it.
We can do simple thing — store user's preferences in Database, load the preferred language from DB with each incoming message, and them pass this settings to all inside functions — but it is quite complicated, because our bot is complex and there can be more than dozen included function calls.
How we can implement language switching in the asynchronous application with elegant way? | Okay, we solved problem using `with` that provide us with context to all inner function calls. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "python, asynchronous, localization, internationalization, gettext"
} |
ROUND in SQL statement vs rounding the scalar result
This is more of a style question than a coding problem. I have a function that returns the total for a requisition based on multiplying the quantity * cost for each line item on that requisition. The result can only have two decimal places because it is a dollar amount.
Here is my current SQL statement:
SELECT SUM(Quantity * Cost)
FROM LineItems
WHERE RequisitionID = @requisitionID
And here is my return statement in vb:
Return CDec(FormatNumber(selectCommand.ExecuteScalar, 2))
Is there any advantage to using the `ROUND()` function in the SQL statement rather than rounding the scalar result?
The code works just fine like it is, but I want to find the most efficient solution. Thanks! | I'd rather do the rounding on the scalar result because you can still manipulate the record returned by the scalar command.
It offers flexibility for me because who knows there are some future changes on the code. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql, vb.net"
} |
Outputting specific lines by number
I want to read lines 25 to 55 from a file, but the range seems to be only outputting a single number and 6 lines, when it should be 30 lines.
hamlettext = open('hamlet.txt', 'r')
for i in range (25,55):
data = hamlettext.readlines(i)
print(i)
print(data)
Output:
54
['\n', 'Mar.\n', 'O, farewell, honest soldier;\n', "Who hath reliev'd you?\n"] | Use the builtin `enumerate` function:
for i, line in enumerate(hamlettext):
if i in range(25, 55):
print(i)
print(line) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "python, range, readlines"
} |
Bitrise: How to add second "Git Clone Repository" step to a workflow?
I'm using Bitrise for CI/CD.
The `Git Clone Repository` build step uses the environment variable `GIT_REPOSITORY_URL` as an input to determine where to clone from.
I'd like to add a second step to clone another repository, but it seems like it is not possible to specify a different url to clone from.
If there is, can somebody tell me how to do that, or, alternatively, does anyone have an alternative approach? | I found a way that works for me: In our company project, Bitrise CI first runs the `Activate SSH key`step, then the `Git Clone Repository` (which of course needs the first one for authentication) step from their library.
Now when this is done, I still can't use another `Git Clone Repository` because of the limitation described in the question, but it's very easy to access another repository that uses the same credentials in a script. So that's what I did. My second repo is accessible with the same SSH key, so all I needed was a `script`build step that does this:
git clone [email protected]:myrepo [my\desired\location]
to get my second repo. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "continuous integration, continuous deployment, bitrise"
} |
Slider change event firing on slider build
I am using jquery slider. I set a function to be on called on slider change.
The problem I have it the function is being called when the slider is initially built. I dont want the change function to fire on event build. Just on change.
here is my code
$('.sliderClass').slider({
range: true,
step: 5,
values: [0, 5],
min: 0,
max: 100,
change: function (e, ui) {
myFunction(e, ui);
}
});
var myFunction = function (e, ui){
//do stuff
};
this code is being called on document ready. | I figure it out using this link
<
$('.sliderClass').slider({
change: function(e, ui) {
if(e.originalEvent==undefined) {
} else {
myFunction(e, ui);
}
}}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, jquery ui"
} |
Open a sub window with link?
I'm using Vaadin7, and I looking for how to open a sub-window using link.
I'm trying this, but not work.
> public class MyWindow extends Window{
>
>
> public MyWindow(){
> super("MyWindow");
> center();
> setModal(true);
> setClosable(false);
> setDraggable(false);
> setResizable(false);
> }
>
>
> }
>
> public class OpenMyWindow extends Window{ private Link link;
>
>
> public MyWindow(){
> super("OpenMyWindow");
> center();
> setModal(true);
> setClosable(false);
> setDraggable(false);
> setResizable(false);
>
> link = new Link("Open Window", new ExternalResource("MyWindow");
> VerticalLayout v = new VerticalLayout();
> setContent(v);
> v.addComponent(link);
> }
>
>
> }
Any idea how to do work ?
thanks. | You shouldn't use a link for opening a sub window. Use a button instead. If it has to look like a link, then you can style the button as a link.
Button button = new Button("Click Me!");
button.setStyleName(Button.STYLE_LINK);
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
// open your sub window here
Window sub = new Window("Subwindow");
v.addWindow(sub);
}
});
v.addComponent(button);
Hope that helps. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, vaadin7"
} |
Image Rendering using Cocos2D
Hi i'm developing an iPhone app with cocos2D framework for image rendering . How we can split the image into layer for example consider an house image here i want to spilt the roof of the house ,door,wall etc and i want to change there respective colors or images can any one help me in this.! I needed some example code also for it . Please help me | Use different layer for different depth of rendering.
You can read more about Cocos2D programming here: Click Here
Get Cocos2D SDK and run some sample test applications. DOWNLOAD SDK HERE | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "iphone, ios"
} |
Calculate inside map in es6
I need to calculate the total for a specific field inside map
{agent.reviews.map((a, i) => {
return (
<p style={{fontSize: 15}} key={a.id}>Knowledge Rating:
{a.local_knowledge_rating}</p>
)
})}
Returns
Knowledge Rating: 1
Knowledge Rating: 2
But I need to achieved is to get the total instead
Knowledge Rating: 3
Any ideas?
"users": [
{
"name": "someee",
"reviews": [
{
"id": 1,
"local_knowledge_rating": 1,
},
{
"id": 2,
"local_knowledge_rating": 2,
}
],
}
] | You can do something like below
Declare below method outside render and pass reviews array to it as param
The below approach will sum the rating for every user
sumRating = reviews => {
let total = 0;
agent.reviews.forEach(a => {
total+= a.local_knowledge_rating;
});
return total;
}
<p style={{fontSize: 15}}>Knowledge Rating: {this.sumRating()}</p>
There are many other ways to implement the same. The above approach is one of them | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "reactjs, ecmascript 6"
} |
Android - Volume Buttons used in my application
I need to use volume buttons to control a variable parameter in my application. I use `Activity.onKeyDown` to get notified when the button is pressed but the media volume is also increased.
Android is doing something like below when I press the volume key:
1. increase media / ringtone volume
2. pass the event to my application
Is there a way to avoid increasing the system volume and use volume key only for my application? | You need to capture all actions:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
} | stackexchange-stackoverflow | {
"answer_score": 109,
"question_score": 44,
"tags": "android"
} |
Variants of Szemeredi's regularity lemma
I've noticed that the name 'Szemeredi's regularity lemma' is used for several closely related yet different statements about graphs.
Specifically, I'm interested in the distinction between two of them:
**Variant 1** Given $\varepsilon>0$ and $l>0$, there exists an $L=L(\varepsilon,l)$ such that any graph $G$ can be partitioned into sets $V_1,\ldots,V_k$ of as-equal-as-you-can-get sizes for some $l\leq k\leq L$, such that at most $\varepsilon {k\choose 2}$ of the pairs $(V_i,V_j)$ are not $\varepsilon$-regular.
**Variant 2** As above, except that we have an additional "junk" part $V_0$ of size $\leq \varepsilon |G|$, and the $V_i$ have equal sizes. In this case we consider only regular pairs $(V_i,V_j)$ for $1\leq i<j\leq k$.
Can anybody with more experience of using the lemma weigh in? Specifically, under what parameters are these two equivalent, and what are the benefits of using one over the other? Cheers! | I think this recent arXiv paper < explains precisely the relationship between these two versions of the regularity lemma. | stackexchange-mathoverflow_net_7z | {
"answer_score": 3,
"question_score": 3,
"tags": "co.combinatorics, graph theory"
} |
File Getting Corrupted after upload node FS
Hi i am using html5 filereader and node fs to upload the file to server which i am able to do so far, but the result file is larger than the original one. here is my code.
var f = document.getElementById('file').files[0],
r = new FileReader();
console.log(f); //for checking file info
r.onloadend = function(e) {
var data = e.target.result;
var fs = require('fs');
try {
fs.writeFileSync(f.name, data, 'utf-8');
console.log('saved sucessfully!');
} catch (e) {
alert('Failed to save the file !');
}
}
r.readAsBinaryString(f);
} | Got it to work. I had to just convert data as ArrayBuffer
here is my final working code:
var fs = require('fs');
var f = document.getElementById('file').files[0],
r = new FileReader();
// console.log('srcPath='+f.path);
// console.log('savPath='+f.name);
r.onloadend = function(e) {
var data = e.target.result;
try {
fs.writeFileSync('uploads/' + f.name, Buffer.from(new Uint8Array(this.result)));
console.log('saved sucessfully!');
} catch (e) {
alert('Failed to save the file !');
}
//send your binary data via $http or $resource or do anything else with it
}
r.readAsArrayBuffer(f);
console.log('binary=' + r); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, node.js, html, electron, filereader"
} |
Ошибка при указании соединения для controluser в конфигурации
!Error
Прошу помощи у гуру MySQL. Такую вот ошибку выдает pma. Что делать? | В снимках экрана ошибка "`Access denied for user root (using password: NO)`" и фигурирует "`controluser`".
Вам необходимо правильно установить имя пользователя и пароль для `controluser`'а. Они используются для соединения с хранилищем конфигурации phpMyAdmin (configuration storage), где хранятся настройки для дополнительный функций.
Хранилище конфигурации не обязательно, phpMyAdmin может работать без него. Поэтому у вас есть два пути:
* Выключить хранилище конфигурации: `$cfg['Servers'][$i]['pmadb'] = null;` в `config.inc.php`.
* Настроить `controluser`'а: создать пользователя в MySQL, предоставить ему определённый набор привилегий, затем добавить его имя и пароль в `config.inc.php`:
$cfg['Servers'][$i]['controluser'] = '<ИМЯ_ПОЛЬЗОВАТЕЛЯ>';
$cfg['Servers'][$i]['controlpass'] = '<ПАРОЛЬ>'; | stackexchange-ru_stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "mysql, sql, база данных, phpmyadmin"
} |
How to pass empty variables to a function in Lua
I've tried to pass empty values to a function but failed. Here is my setup;
function gameBonus.new( x, y, kind, howFast ) -- constructor
local newgameBonus = {
x = x or 0,
y = y or 0,
kind = kind or "no kind",
howFast = howFast or "no speed"
}
return setmetatable( newgameBonus, gameBonus_mt )
end
I want only to pass "kind" and want the constructor to handle the rest. Like;
local dog3 = dog.new("" ,"" , "bonus","" )
Or I want only to pass "howFast";
local dog3 = dog.new( , , , "faster")
I tried both with `""` and without, gives error:
> **unexpected symbol near ','** | `nil` is the type and value to represent empty in Lua, so instead of passing an empty string `""` or nothing, you should pass `nil` like this:
local dog3 = dog.new(nil ,nil , "bonus", nil )
Note that the last `nil` can be omitted.
Take the first parameter `x` as an example, the expression
x = x or 0
is equivalent to:
if not x then x = 0 end
That is, if `x` is neither `false` nor `nil`, sets `x` with the default value `0`. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 7,
"tags": "variables, lua, function parameter"
} |
How can I open the command line in Firefox Quantum?
There’s a command line built into Firefox, which allows various options such as taking screenshots and restarting the browser. It used to open with `Shift`+`F2`, but since the upgrade to Firefox 57, that no longer does anything.
I have seen the command line since the upgrade (it was open in one Firefox window, and remained open after the upgrade), so I know that it does still exist in Firefox Quantum. However, I have since closed that window, and cannot get it back. Is there now a different keyboard shortcut to reveal the command line?
The Mozilla documentation for the command line still says `Shift`+`F2`.
I am using Firefox Quantum 57.0 on Ubuntu 17.10. | The Graphical Command Line Interface (GCLI) has now been removed from Firefox. Much of its functionality is now in the Web Developer Console.
There are two ways to access the Web Developer Console:
* Tools → Web Developer → Web Console
* `Ctrl` \+ `Shift` \+ `K` | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 4,
"tags": "firefox"
} |
MySQL bug: Does not allow column name keys...Anyone know why?
I banged my head against the wall for hours trying to understand why I could not complete an OOP insert statement into a MySQL insert table.
In my table I had a column named keys which was not getting inserted into.
I tried a lot of solutions, but then i renamed the column and the error sorted itself out.
Can anybody please tell me why this is occuring?
I am using wampserver 2.4. | It's a reserved word. You have to backtick it if you want to use it:
Like this:
insert into `keys` values (val1, val2) etc... | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysql"
} |
Problem when posting back to mvc 3.0 facebook app
I have setup a facebook app, configured it to point to my localhost and created a tab in facebook to point to the local app.
All works fine and the initial load renders my page fine and the user is authenticated when I check FacebookWebContext.Current.IsAuthenticated().
My problem is that when I post data back, the facebook context is lost and FacebookWebContext.Current.IsAuthenticated() returns false.
Not sure if I am missing something here, but surely I should be able to post back to controller actions and stay authenticated? | you need to manually maintain the signed request for post backs.
<% if(!string.IsNullOrEmpty(Request.Params["signed_request"])) { %>
<input type="hidden" name="signed_request" value="<%= Request.Params["signed_request"] %>" />
<% } %>
Refer to this discussion on more information <
You could also use this html helper extensions method
@FacebookSignedRequest()
instead of
<input type="hidden" name="signed_request" value="<%= Request.Params["signed_request"] %>" /> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "facebook c# sdk"
} |
Webpage layout order for my webapp - does it matter if the Sidebar is programmatically displayed before the main content?
OK that's the worst title I could ever possibly think up. But I'm not too sure how to phrase it!
What I mean is, is it inefficient for the browser, search engine optimisation, or any other important factors, if programmatically my `float:right`ed sidebar appears in the markup before the main content div, which is set to `float:left`?
To the user, the main content appears on the left, and the sidebar on the right. In the source code it appears like so:
<div id="sidebar">This is where my sidebar goes </div>
<div id="content">This is where my content goes </div>
Will this affect SEO or other factors in my page? | Yes, put your content first.
WordPress has a nice discussion about content structure and SEO. You want to put content as close to the beginning of the served HTML file as possible. Robots and screen readers will get to what they want earlier, and I'd guess that the browser would start rendering content according to its place in the served file as well. CSS makes positioning things out of order more or less trivial, so why not give the HTML content all the help it can get? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "xhtml, seo, html"
} |
Sending large file to PIPE input in python
I have the following code:
sourcefile = open(filein, "r")
targetfile = open(pathout, "w")
content= sourcefile.read():
p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)
p.communicate(content)
sourcefile.close()
targetfile.close()
The data in sourcefile is quite large, so it takes a lot of memory/swap to store it in 'content'. I tried to send the file directly to stdin with stdin=sourcefile, which works except the external script 'hangs', ie: keeps waiting for an EOF. This might be a bug in the external script, but that is out of my control for now..
Any advice on how to send the large file to my external script? | Replace the `p.communicate(content)` with a loop which reads from the `sourcefile`, and writes to `p.stdin` in blocks. When `sourcefile` is EOF, make sure to close `p.stdin`.
sourcefile = open(filein, "r")
targetfile = open(pathout, "w")
p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)
while True:
data = sourcefile.read(1024)
if len(data) == 0:
break
p.stdin.write(data)
sourcefile.close()
p.stdin.close()
p.wait()
targetfile.close() | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "python"
} |
Get the immediate values from the adjacent columns based on the value of another column
I am trying to get the immediate next adjacent column values based on the values of another column. I tried by adding serial numbers and VLOOKUP() but I'm getting some mismatches.
The data is in columns A to C and the output required should be in column D.
Based on the column C, if the value is NA, I need the date from the next row for the same ID. If the next ID is different, I need the same date in column D.
Thanks
, you can nest them to get the result you want. See formula for cell D2:
=IF(C2="NA",IF(B3=B2,A3,A2),"") | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "excel, if statement, excel formula"
} |
ASMX service returns only part of the list items, not all of existing items
I can see that there are 50 items on site in list1, but ASMX-service returns me 34 items. When I call `GetList("list1")` service returns me a description of the list. This description contains an attribute `ItemsCount` which value equals to a real count of list items (50 in this case).
Here is my code:
XElement ndQuery = new XElement("Query", "");
XElement ndViewFields = new XElement("ViewFields", "");
XElement ndQueryOptions = new XElement("QueryOptions", "");
ndQueryOptions.Add(new XElement("IncludeMandatoryColumns") { Value = "FALSE" });
XElement list = client.GetListItems(
"list1",
null,
ndQuery,
ndViewFields,
null,
ndQueryOptions,
null); | If you don't include a query, the web service will query the default view. Either change the default view to include all items, or write a caml query that includes all items. | stackexchange-sharepoint | {
"answer_score": 4,
"question_score": 2,
"tags": "2010, list, web services"
} |
Is $f(z)=\frac{|z|^{3/2}e^{i3\arg(z)}-1}{|z|e^{2i\arg(z)}-1}$ bounded for $|z|\in (0,1)$?
Let $f:B(0,1)\setminus\\{0\\}\to\mathbb{C}$ denote the function defined by $$f(z)=\dfrac{|z|^{3/2}e^{3i\arg(z)}-1}{|z|e^{2i\arg(z)}-1}.$$ Is f bounded above on $B(0,1)\setminus\\{0\\}$? I believe it should be, but I cannot seem to show this. It can be seen that such a function has the following form: $$ f(z) = \frac{|z|^3e^{6i\arg(z)}-1}{|z|e^{2i\arg(z)}-1} \cdot \frac{|z|^{3/2}e^{3i\arg(z)}-1}{\left(|z|^{3/2}e^{3i\arg(z)}\right)^2-1} = \frac{1+|z|e^{2i\arg(z)}+|z|^2e^{4i\arg(z)}}{1+|z|^{3/2}e^{3i\arg(z)}}, $$ but I cannot see where this would help. Any hints would be much appreciated. Here when considering balls and boundedness we are considering the Euclidean metric. | If we choose $z=-r, 0<r<1$ we have that $\arg z =\pi$ so $f(z)=f(-r)=\frac {r^{3/2}+1}{1-r}$
But as $r \to 1$ the expression above goes to $+\infty$ so indeed $f$ is superior unbounded | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "complex analysis, metric spaces"
} |
Java 11 Convert List of Strings to Map<UUID,String>
I am trying to convert the list of strings to Map as below but am getting a compilation error `no instance(s) of type variable(s) K, T exist so that UUID conforms to Function<? super T, ? extends K>`, can someone please help me with it?
List.of("john","jack", "jill")
.stream()
.collect(Collectors.toMap(UUID.randomUUID(), name ->name)); | Map<UUID, String> collect =
List.of("john", "jack", "jill")
.stream()
.collect(Collectors.toMap(k -> UUID.randomUUID(), name -> name)); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "java, collections, java stream, java 11"
} |
Expressing an ellipse with polar coordinates
We have the following ellipse:
$2(x+1)^2+(y+1)^2 \le 16$
So the polar coordinates will be:
$x = -1 + A\cos(\phi)$
$y = -1 + r\sin(\phi)$
Where $0 \le r \le 4$ and $0 \le \phi \le 2\pi$.
This is pretty easy, however I have trouble determining the coefficient for $x$, $A$ since we get $\frac{2(x+1)^2}{4}$. How do we determine the coefficient so that it is true when $0 \le r \le 4$? | Since$$2(x+1)^2+(y+1)^2\leqslant16\iff\frac{(x+1)^2}8+\frac{(y+1)^2}{16}\leqslant1,$$the expression of the ellipse in polar coordinates is $x=2\sqrt2r\cos\phi$ and $y=4r\sin\phi$, with $0\leqslant r\leqslant1$ and $0\leqslant\phi\leqslant2\pi$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "polar coordinates"
} |
Python, pythonic expression
Is there pythonic expression for this snippet?
# linux.cmd is a dict
cmd = linux.cmd.get(k, k)
if not cmd:
cmd = k
The value of `linux.cmd.get[k]` could be `False`. | All you need is the first line, sice the second paramter to dict.get() is the default value anyway. That construct returns k if k is not in dict. IF dict can return a value that evaluates to false add a " or k" to the end of the first line. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "python"
} |
Unable to bind a combobox value to a label
I am trying to bind my combobox text/value to a label. I am able to bind a slider to the label but when I use the same method to bind a combobox, it shows no results. Please advice. Thanks.
<!--Works-->
<Slider Name="slider2" Width="144"/>
<Label Content="{Binding Value, ElementName=slider2}"/>
<!--Not working-->
<ComboBox Name="secondaryTable" Width="120">
<ComboBoxItem Content="A"/>
<ComboBoxItem Content="B"/>
<ComboBoxItem Content="C"/>
</ComboBox>
<Label Content="{Binding Value, ElementName=secondaryTable}"/> | You need to bind to **`SelectedItem.Content`** property.
<Label Content="{Binding SelectedItem.Content, ElementName=secondaryTable}"/>
**OR**
**`Text`** property of ComboBox.
<Label Content="{Binding Text, ElementName=secondaryTable}"/> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, wpf, xaml"
} |
¿Cómo hacer que mediante una combinación de teclas un usuario pueda abrir una sección privada?
Se me ha ocurrido una idea un poco loca pero no se si se puede hacer. Quisiera saber si se puede programar que un usuario estando en una web, pueda abrir una sección privada solo con la combinación de dos teclas por ejemplo: `ctrl+a`. Así por ejemplo mis clientes podrían abrir un login sin que este estuviera especificado en la web de forma visible.
Sería entonces que lo que se abre es un archivo de nombre por ejemplo loginclients.php o un html o una ruta del tipo < | Podrías usar la librería jQuery.Hotkeys que permite capturar eventos del teclado.
Podrías hacer algo así:
$(document).bind('keydown', 'ctrl+a', function(){
//alert("Has pulsado ctrl+a");
var win = window.open(" '_blank');
win.focus();
});
$(document).bind('keydown', 'ctrl+l', function(){
alert("Has pulsado ctrl+l");
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Teclado Shortcuts</title>
</head>
<body>
<script src="
<script src="
</body>
</html>
Ejecuta el código y da click en la region donde se ejecuta el script, luego presiona `ctrl+a` o `ctrl+l` y se lanzará un `alert()` diciendo que tecla pulsaste, es un ejemplo básico pero espero te sirva.
Para ver el script que abre una nueva pestaña, funcionando correctamente te dejo un jsbin en el siguiente Link < | stackexchange-es_stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "javascript"
} |
Blank space below the status bar
In app delegate I use `[[UIScreen mainScreen] bounds]` (which is by default) to set frame for the window.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
But when I try to launch the app, I see blank space between my view and the status bar. !enter image description here
If I set the frame this way
CGRect bounds = [[UIScreen mainScreen] bounds];
self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0.0, -20.0, bounds.size.width, bounds.size.height)];
It'll be ok, but it won't detect taps at the bottom 20 points of the screen.
What's wrong here? Please help.
P.S. I don't use IB, don't set frame for any view except window (because it doesn't help). | Solved by setting the property `wantsFullScreenLayout` of the root view controller to `YES`.
P.S. It's not my first app where I write `application:didFinishLaunchingWithOptions:` from scratch, but I never had this problem... | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "iphone, ios, statusbar, uiwindow, cgrect"
} |
Why two favicons in facebook
Today when I logged into facebook, I saw two favicons in address bar near to the identity portion (I don't know exact name of this part. If somebody know, just edit my question) like the screenshot below;
!enter image description here
But there is only one favicon in the login page;
!enter image description here
Why is this so? What will be the possible reason? I use Firefox 13.0 in Windows 7. | The squared area is SSL certificate information. SSL certificate contains company information (Facebook), I suppose that Firefox retrieves favicon from the company's website address, in this case facebook.com).
P.S. it doesn't matter what "level" of answer you want to receive, each kind of question belongs to its particular domain. Moderators: please move this question as well as my answer if its possible to superuser.com
!enter image description here | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "firefox, browser, favicon"
} |
how can i check session and redirect in android?
In my application, a user can post comments only after logging in. So when a user clicks on comment activity, he/she will be redirected to login page and after successful login, he/she should redirect to that activity.
In this situation, I used `startactivityfor result()`, but it shows the page loading again. So when I click back button (using `finish()`), it again shows the same page.
I want to load the page only once.
Does anybody knows how to accomplish this? | Use sharedpreferences to save the state of users login, When the user enters ur loginscreen, if he is already logged in before, set flag as true and direct him to main page else false and ask him to log in again | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android"
} |
Shared application resources in MEF
In order to dynamically add functionality to an application, I heavily rely on MEF which is a great tool to provide interfaces for third party assemblies (plugins). But now, I not only want a common interface for plugins that I can access from my main application but also offering a interface to the plugins through which they can access various resources (such as objects) from my main application. How could this be done? I'm thinking about something like a plugin API, but I'm not sure if MEF offers such an option.
There are two options that I had in mind for this task:
* **Pass objects as parameters on plugin instantiation**
Drawback: If I pass lets say e.g. a logging object instance which I use elsewhere, a third party plugin could easily call Dispose, making it unusable for the whole application or other plugins. Very dangerous!
* **Declare globally accessible static methods** | Instead of constructing your plugins or having static instances somewhere, you might want to use injection...
You can actually inject other objects to your plugin. Most commonly by `[ImportingConstructor]`.
If you other objects do not implement any MEF exports, you might not be able to use this MEF feature, if this is the case you can also combine e.g. Unity injection with your MEF plugins so that your Plugins can use the unity container to resolve certain things. This is a little bit tricky but there are certain solutions out there. There is an old but still valid blog post you might want to read: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, api, plugins, mef"
} |
How to parse this json in azure data factory in copy operation
{"Properties"::\"{\"receivedPushNotificationMessage\""Received push notification: {\n aps = {\n alert = \\\"Network programmer push\\\";\n };\n channelToken = \\\"eyJ0eXAiO\",\"time\":\"2019-02-26_11-32-03-AM\"}"},{"AppBuild":"321"}, | JSON format is supported in file type dataset.
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "json, azure, blob, azure data factory, jsonpath"
} |
Validate a form by using jQuery or struts2
I'm wondering if jQuery is enough for validation (eg: validate a login form.) Why we use Struts2 to do this?
Regards Liam | It is not a recipe but for security reasons, you should validate your application from the server and the cliente side
in this question that i made speak about some points of security. So hopefully read this to get some considerations for client and server side validations | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jquery, struts2"
} |
sending String from C# to MFC through SendMessage
I know how to PInvoke a method that wants a CString by using LPCTSTR instead and setting up the DllImport to call with the LPstr conversion.
However, how would I do it with SendMessage where LPARAM is an IntPtr?
Would this work?
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam,
[MarshalAs(UnmanagedType.LPStr)] String lParam); | You can declare it simply like this:
[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr SendMessage(
IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
The default marshalling is as an pointer to null-terminated character array. If you really want the ANSI version, then that's the default. And you should use `SetLastError` in case you want to capture the error code in case of failure.
I trust you know that it cannot work if the window is in a different process. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "c#, mfc, pinvoke"
} |
Extend DataSet Class Not Working
I've created a dataset using the dataset designer. One of my tables is called `Users` and so there is a class called `UsersDataTable`. In this class are some properties, namely `Connection`. So I created a `Partial Class UsersDataTable`, but none of the routines, properties, or variables from the `UsersDataTable` class in the designer codebehind file are visible to me.
I'm simply trying to extend the class to add my own routines but leverage the connections and strong typing of the designer-generated class. I've tried creating my own partial classes and testing them to see if I have the problem with other classes and I don't. Only with these dataset designer-generated classes can I not access items in the other half of the partial class.
I'm working in .Net 4. What might I be doing wrong? | It seems as though I've just extended my class using the wrong identifiers:
There is a `Namespace` and inside of the namespace is the `Partial Public Class`. Therefore my code of:
Partial Public Class myData
Partial Public Class UsersTableAdapter
Public Function DoSomething() As String
Return "Testing..."
End Function
End Class
End Class
was wrong...What I needed was:
Namespace myDataTableAdapters
Partial Public Class UsersTableAdapter
Public Function DoSomething() As String
Return "Testing..."
End Function
End Class
End Namespace | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, partial classes, dataset designer"
} |
Multiple background colors on div's background
Hey there I'm struggling with creating multiple colour background with CSS. I tried `gradient` but it makes shades which I doesn't want. I want to create this with CSS:
!Example of what I want to create with CSS
Does anyone know how to create this without getting shades that I got when I used `gradient`.
Here is my html code.
<div id="head">
<h1>Mira's place</h1><br>
<h2><span id="quote">Mira is creating huge game named Rock Paper!</span></h2>
<ul>
<li>Home</li>
<li>Games</li>
<li>Applications</li>
<li>Contact</li>
</ul>
</div> | Don't know, what you mean with shades. Does the following not look like you wanted to? (Some modifications may be needed, but it shows the way to go)
background: linear-gradient(135deg, #ffffff 0%,#ffffff 25%,#0011ff 25%,#0011ff 35%,#ffffff 35%,#ffffff 65%,#ff0000 65%,#ff0000 75%,#ffffff 75%,#ffffff 100%);
Here is the Fiddle. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "css"
} |
Windows Phone 8 Silent Mode
I am not sure if this is possible in WP8, but I am trying to tweak the audio playback settings and would like to know if anyone else has been able to accomplish this.
What I am looking to do is have the phone enter a "silent mode," where absolutely no sounds will emit from its speakers, yet retain a volume setting so that if I plug in headphones or an audio cable, it will still output sound across the wire.
Currently, even with my phone on vibrate, I have to hold down the Lumia 920's side rocker switch to bring system volume all the way down to zero if I want the phone to be truly silent. When I want to listen and plug in a cable, I then have to bring the volume back up.
If I forget to bring the volume back down when I am done listening, and then launch a games or another app with sound, the app will play sound out of the phones speakers when in vibrate mode with no headphones plugged in. | iOS devices have a separate volume setting for headphones and the built-in speakers. This is being determined from whether you have a 3.5mm AUX cable plugged in or not.
Windows Phone 8 does not have anything of the sort, as far as I can tell. I have looked for it as part of my quest for a mute mode.
You will potentially have better luck with wireless accessories, though. A connected Bluetooth headset could offer separate volume controls through their hardware. But I have not tested this. You can probably test this in a store. | stackexchange-windowsphone | {
"answer_score": 6,
"question_score": 8,
"tags": "settings, 8.0, audio, nokia lumia 920, volume"
} |
Line Number for all non-blank lines?
Kind of amused here, I'm trying to pass the prereqs to get into the Udacity Course on High Performance Computer Architecture by Georgia Institute of Technology For the life of me I can't figure out what they want,
Question reads,
> To list the contents of a file, with line numbers for non-blank line shown use the command with an option: ________ ___ filename.
I've tried `nl`. It didn't work. Most bizarre question ever.
;
$ nl ./foo.py
1 a = 5
2 a = a + 1
3 print "foobarbaz" + str(a); | stackexchange-unix | {
"answer_score": 1,
"question_score": 2,
"tags": "text processing, cat, nl"
} |
Unable to reference other JS code after migrating Parse
After migrating from Parse.com to Parse Server on Heroku, I am unable to run cloud-code like this:
var foo = require('cloud/test.js')
Before switching, this worked fine. | it turns out:
require('./test.js')
is the correct way to do this (due to server on heroku being linux based, as I was told) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, heroku, parse platform, parse cloud code, parse server"
} |
Angular frequency. Wrong interpretation at Wikipedia?
This and this articles mention that the angular frequency is:
number of oscillations per unit of time
But this doesn't seem to be correct since the angular frequency is the _speed of wave rotation_ , and Wiki actually says about the _wave frequency_. Is this correct or I simply don't understand something? | If something does a complete rotation per second, everyone agrees it has an angular frequency of 2π radians per second. It is well-known that one complete oscillation is equal to the angle of 2π radians, so the article as written isn't necessarily wrong as 1 oscillation per second is equivalent to 2π radians per second (just different units). However, it could possibly be clearer:
Angular frequency specifies the rate of angular change and is equal in value to 2π radians times the number of oscillations per unit of time. | stackexchange-physics | {
"answer_score": 4,
"question_score": 2,
"tags": "waves, frequency"
} |
Symfony 1.4 - How to set default values on sfWidgetFormChoice (checkboxes)
The following code creates a field with multiple checkboxes. How do I set the default values of these checkboxes?
new sfWidgetFormChoice(array(
"choices" => $choices,
"label" => "Label",
"multiple" => true,
"expanded" => true
)); | You can set the defaults manually:
$countries = array(
'Spain',
'England',
'France'
);
$this->widgetSchema['countries'] = new sfWidgetFormChoice(array('choices' => $countries, 'multiple' => true, 'expanded' => true));
// Form will render with Spain and England pre-selected
$this->widgetSchema['countries']->setDefault(array(0,1));
If the object to which the form is related is not new, the defaults will pre-selected based on stored values, so you may need to add a `$this->getObject()->isModified()` check around the last line. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "symfony 1.4, symfony forms"
} |
How to download and update local images under monotouch app
I have a question regarding how to update local images embedded as content in the application.
My application is built using 30 images stored as "Content" (embedded in the app) for a image gallery that I have to show. Every 2 days the application check server info to see if the images have been changed in the database, in that case then I have to compare files and if any file has changed then I have to download it and update the local image.
I have read the the best way to store images for this kind of porposses is under "Library" folder of the application, but the images that comes with the app are built as "Content" (embedded)...
Any clue on the best way to do that in monotouch?
Thanks. | Resources, like images, that you bundle inside your .app becomes part of your application. Since the application is signed you **cannot** update (or remove) those files as it would invalidate the signature (there's also file permissions that won't allow this to happen).
_note: it can work in the iOS simulator since it does not require (or check) for application signatures, however it won't works for application on devices._
What you can do is:
1. Bundle default images with your applications;
2. Download new images (when needed) and install them outside your application (in the appropriate directory);
3. Have your application checks if there are downloaded images (or if images needs to be downloaded) and fallback to the images that ships with your application; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "ios, xamarin.ios"
} |
PHP Generate Array with number of month and year display
I have two dates of the form:
> Start Date: 2010-12-24
> End Date: 2011-10-06 (today)
Now I need to generate an array for this group by month from the above start date and end date:
$arr_month['oct_11'] = array(
'month' => 'October 2011'
);
.
.
.
$arr_month['feb_11'] = array(
'month' => 'Feb 2011'
);
$arr_month['jan_11'] = array(
'month' => 'January 2011'
);
$arr_month['dec_10'] = array(
'month' => 'December 2010'
);
As you can see the table should be got 11 rows in the table if I use this array to generate a table. | $start_date = '2010-12-24';
$end_date = '2011-10-06';
function getMonthArray($start_date, $end_date){
$start_timestamp = strtotime(str_replace('-', '/', $start_date));
$end_timestamp = strtotime(str_replace('-', '/', $end_date));
$start_month_timestamp = strtotime(date('F Y', $start_timestamp));
$current_month_timestamp = strtotime(date('F Y', $end_timestamp));
$arr_month = array();
while( $current_month_timestamp >= $start_month_timestamp ) {
$arr_month[strtolower(date('M_y', $end_timestamp))] = date('F Y', $end_timestamp);
$end_timestamp = strtotime('-1 month', $end_timestamp);
$current_month_timestamp = strtotime(date('F Y', $end_timestamp));
}
return $arr_month;
}
$arr_month = getMonthArray($start_date, $end_date);
**Demo** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays, datetime, datediff"
} |
Displaying labels from a shapefile?
I downloaded a Nigeria shapefile and loaded it via the add vector layer where I picked out the three .shp files within the zip file and displayed them on the layers panel. I can see the shapes displayed on the canvas.
On the canvas there are no state names or local government names so I thought those attributes may be in a .csv file, included in the zip file. I tried to add it as a delimited text file but the file doesn't contain any coordinates.
Nothing is displayed on the canvas, no state names or anything. How do I make the attributes within the .csv file to be displayed on the canvas?
I'd like to mention that I'm a beginner in GIS and I just downloaded the QGIS software only a couple of hours ago. | You will have to tell QGIS how to label the features. The layer attribute table (do a right-click in the layer list, select attribute table) will show the attributes for the features. If you have a "name" attribute or such, you'll need to use the "label" tab of the layer properties (double-click a layer name in the layer list, or right-click and choose properties at the bottom; the label tab is the third from the top).
See < for a documentation, but it may be outdated somewhat - still, the main concepts will still apply, although maybe the dialogues are different. | stackexchange-gis | {
"answer_score": 4,
"question_score": 5,
"tags": "qgis, shapefile"
} |
How does the presence of chlorine atoms in PVC make it flame resistant?
In a paper that I'm reading, it states that:
> The presence of chlorine atoms in polyvinyl chloride make it flame resistant
and I'm just wondering why the presence of chlorine atoms will make it flame resistant. To the best of my knowledge, burning something is just providing a material with enough activation energy such that it can react with oxygen to produce products such as carbon dioxide and water. If so why does the chlorine prevent this process in any way? | PVC is not truly flame resistant, it does decompose on relatively gentle heating (around 150 °C) However, the process produces significant volumes of hydrogen chloride, that is not flammable and isolates the plastic from the flame. This makes makes PVC **self-extinguishing** or fire-retardant. | stackexchange-chemistry | {
"answer_score": 2,
"question_score": 7,
"tags": "polymers, combustion"
} |
how to do custom keras layer matrix multiplication
Layers:
* Input shape `(None,75)`
* Hidden layer 1 - shape is `(75,3)`
* Hidden layer 2 - shape is `(3,1)`
For the last layer, the output must be calculated as `( (H21*w1)*(H22*w2)*(H23*w3))`, where `H21,H22,H23` will be the outcome of Hidden layer 2, and `w1,w2,w3` will be constant weight which are not trainable. So how to write a lambda function for the above outcome
def product(X):
return X[0]*X[1]
keras_model = Sequential()
keras_model.add(Dense(75,
input_dim=75,activation='tanh',name="layer1" ))
keras_model.add(Dense(3 ,activation='tanh',name="layer2" ))
keras_model.add(Dense(1,name="layer3"))
cross1=keras_model.add(Lambda(lambda x:product,output_shape=(1,1)))([layer2,layer3])
print(cross1)
> NameError: name 'layer2' is not defined | Use the functional API model
inputs = Input((75,)) #shape (batch, 75)
output1 = Dense(75, activation='tanh',name="layer1" )(inputs) #shape (batch, 75)
output2 = Dense(3 ,activation='tanh',name="layer2" )(output1) #shape (batch, 3)
output3 = Dense(1,name="layer3")(output2) #shape (batch, 1)
cross1 = Lambda(lambda x: x[0] * x[1])([output2, output3]) #shape (batch, 3)
model = Model(inputs, cross1)
Please notice that the shapes are totally different from what you expect. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "machine learning, keras, keras layer, keras 2"
} |
Prompt to reload an externally modified file in Textmate 2?
Im finding myself using TextMate 2 more and more for development these days
One thing that is bugging me is that it does not seem to reload a file when it is changed externally.
This is a big problem since I use terminal to switch git branches a lot, and it often results in accidentally saving an older version over the new branch
Sadly the TM team seem to have disabled the Issue tracker on github, and documentation just seems scattered far and wide over the web in tiny scraps.
Any ideas? | Right now it reloads the file silently whenever the file on Disk is changed. There is currently no option for a prompt.
Regarding the closed issue tracker: As an alternative, you can always send a mail to the Textmate users list if you find a problem. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "textmate, textmate2"
} |
Output Array Items
I'm using Salesforce.com Toolkit for PHP and I'm trying to output something I think is very simple.
THIS IS WORKING EXAMPLE CODE
$query = "SELECT ID, Phone FROM Contact LIMIT 5";
$response = $mySforceConnection->query($query);
foreach ($response->records as $record) {
echo $record->ID." - ".$record->Phone;
}
I'VE TWEAKED THE QUERY AND NOW WANT TO JUST OUTPUT THE NAME AND THE COUNT. HOWEVER THE CODE BELOW DOES NOT WORK
$query = "SELECT owner.name, count(type) FROM Task LIMIT 5";
$response = $mySforceConnection->query($query);
foreach ($response->records as $record) {
echo $record->owner.name; //DOES NOT WORK
}
THIS IS WHAT I GET WHEN I **print_r ($record);**
stdClass Object ( [Id] => [any] => Array ( [0] => First Last [1] => 2177 ) )
I just want to be able to output "First Last - 2177" | foreach ($response->records as $record)
{
echo implode(' - ', $record->any);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "php, database, arrays, salesforce, soql"
} |
Name For Stack With Unique Values
I'm using `.NET 3.5` to create an application that requires a `Stack<T>` with unique values. I realize I could call `Contains()` before every `Push()`, but it makes sense semantically that I roll my own "unique stack" (`UniqueStack<T>` or maybe `HashStack<T>`?). I'm having a hard time to determine a strong name for this data structure.
I hate the fact that `Stack<T>` doesn't implement some `IStack<T>`...
Thoughts are appreciated. | * ExclusiveStack?
* DistinctStack?
Personally, I like your UniqueStack or UniqueItemStack | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, .net, data structures"
} |
How to avoid of using anonymous callback function for marker click event listener?
I know there's lots of ways to do the click event handling for google map markers, I've been using those methods and they always work well.
But just curious that if we could do the same thing in a better way, I'm thinking about this because it's possible that there could be 100,000 markers in a new project (of course they will not be shown on the map at the same time, but the markers' instances do exist)
google.maps.event.addListener(marker, 'click', clickhandler); function clickhandler(event) { /* HERE */ }
in the clickhandler's scope, we only have the latLng information, and I guess it's not reliable to search markers by latLng which are float numbers, so The problem is, what is the best way to find which marker was clicked? | When ever I am trying to reference one element out of a group elements (say, elements with the same class), using `this` can help find the right element that triggered the event. Just to make sure `this` wil work, I check with `console.log`.
`google.maps.event.addListener(marker, 'click', clickhandler); function clickhandler() { console.log(this); }`
This should log the marker object. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "google maps, google maps api 3, google maps markers"
} |
For the vector field: $F = (x^2 + y^2 +3x)i - (2xy + y)j$, find the scalar field $f(r)$ such that $\nabla f = (\nabla \cdot F)\cdot F$.
For the vector field: $F = (x^2 + y^2 +3x)i - (2xy + y)j$, find the scalar field $f(r)$ such that $\nabla f = (\nabla \cdot F)\cdot F$.
Now I have found that F is irrotational however I am unsure how to progress since I cannot make sense of the question.
Computing the divergence of F yields a scalar field so how can we then find the dot product of that with F?
Unless they simply mean that F is 'multiplied' by a scalar?
Just want to make sure before I continue.
Thanks a million!!
My Attempt:
$\nabla \cdot F = \frac{\partial (x^2 + y^2 +3x)}{\partial x} + \frac{\partial (2xy +y)}{\partial y} = (2x - 2y -1)$
Which means:
$(\nabla \cdot F) \cdot F = (2x - 2y -1) [(x^2 + y^2 +3x)i - (2xy + y)j]$
But seems odd? | All you have to do is solve the following equations,
$$ (f_x,f_y) = \bigg(\left(\frac{\partial}{\partial x}, \frac{\partial}{\partial y}\right) \bullet (x^2+y^2+3x,-2xy-y)\bigg) \cdot (x^2+y^2+3x,-2xy-y)$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "ordinary differential equations, multivariable calculus"
} |
How to remove "href" with Jquery?
<a id="a$id" onclick="check($id,1)" href="javascript:void(0)" class="black">Qualify</a>
After "href" is removed, is "Qualify" still clickable? | Your title question and your example are completely different. I'll start by answering the title question:
$("a").removeAttr("href");
And as far as not requiring an href, the generally accepted way of doing this is:
<a href"#" onclick="doWork(); return false;">link</a>
The return false is necessary so that the href doesn't actually go anywhere. | stackexchange-stackoverflow | {
"answer_score": 127,
"question_score": 62,
"tags": "jquery, href"
} |
ST_Length (GEOM, true) for calculating distances in Geographic Reference System
I use (1) ST_Length (ST_Transform (geom, 3395)) to get distances in meters from points in Geographic Reference Systems EPSG: 4326. The thing is I found that with (2) ST_Length (geom, true) you can get also the distance in meters but using the spheroid.
If I am right, is the option (2) more accurate if the GIS project use a Geographic Reference System for Global data, especially near to the poles?
ST_Length reference: <
EPSG:3395 reference: < | You can if your data is stored in a geography column, or cast from geometry to geography. If you run ST_Length against geometry it will return the units the data is stored in (feet, meters, degrees), if you run ST_Length against geography it will return the answer in meters.
See this workshop for details on the difference. | stackexchange-gis | {
"answer_score": 2,
"question_score": 2,
"tags": "coordinate system, postgis 2.0, length"
} |
PyCharm: limit cache size
When I search for this online, all I get are hits for increasing the cache size. According to `ncdu`, my PyCharm cache is 55GB. How can I prevent this from _ever_ happening again? | There is no way to limit caches, use File | Invalidate cache to clear them manually | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "intellij idea, pycharm"
} |
CreateReadStream creates an extra newline delimiter in chunks?
I have a simple question on readStream in node's fs module. Here is the simple code:
fs = require('fs');
readStream = fs.createReadStream('somefile.d');
readStream.on('data', function(chunk) {
console.log(chunk.toString());
});
'somefile.d' is:
a1
a2
a3
a4
Question: Why is there an extra newline at the end of the output? I tried an od -c to get an octal dump and yes there is an extra newline. Is that put by toString? **More importantly, why is chunk delimited by newline? The data event is triggered for every line.** I have not specified any option and there is no option to read chunks separated by any specific character. I know that there is the carrier module, for example, to get around this issue.
Any explanation will be appreciated.
~
~
~ | Not sure I fully understand, but if you're talking about the actual output of the program, as-written it looks like your only output is coming from `console.log`. `console.log` terminates its write with a line ending. If you want to write to stdout without a line terminator, you could just do:
`process.stdout.write(chunk)`
should send them out as-is. You could also pipe the readstream directly to stdout if you wanted to:
`readStream.pipe(process.stdout);` | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "javascript, node.js"
} |
FourierParameters default differs from documentation?
Running Mathematica 11.2.0 I see in the documentation that FourierParameters defaults to {0,1}, yet when I try a Fourier transform with the default options, vs those values explicitly, I get different results. It looks like the defaults actually appear to be {0,-2Pi} :
FourierTransform[Sinc[t], t, \[Omega]]
FourierTransform[Sinc[t], t, \[Omega], FourierParameters -> {0, 1}]
FourierTransform[Sinc[t], t, \[Omega], FourierParameters -> {0, -2 Pi}]
These give respectively
$$\frac{1}{2} \pi \text{sgn}(2 \pi \omega +1)+\frac{1}{2} \pi \text{sgn}(1-2 \pi \omega )$$
$$\frac{1}{2} \sqrt{\frac{\pi }{2}} (\text{sgn}(1-\omega )+\text{sgn}(\omega +1))$$
$$\frac{1}{2} \pi \text{sgn}(2 \pi \omega +1)+\frac{1}{2} \pi \text{sgn}(1-2 \pi \omega )$$
Is FourierParameters configurable somehow, and is Mathematica finding a default FourierParameters value that differs from the documentation? | You can check the default options of any symbol with `Options`. For me, `Options[FourierTransform]` outputs:
> {Assumptions :> $Assumptions, GenerateConditions -> False, FourierParameters -> {0, 1}}
Which coincides with the documentation. Furthermore, the output I get without parameters matches the results for `FourierParameters -> {0, 1}`.
If you `Unprotect[FourierTransform]`, you can change the default options simply by setting them, e.g.:
Unprotect[FourierTransform];
Options[FourierTransform] = {Assumptions :> $Assumptions, GenerateConditions -> False, FourierParameters -> {0, -2 Pi}};
However, this is difficult to actually recommend. | stackexchange-mathematica | {
"answer_score": 3,
"question_score": 2,
"tags": "fourier analysis"
} |
Count number of times text is repeated in a spreadsheet (excel)
I have a spreadsheet with this kind of data:
`
B1 and copied down:
`=COUNTIF(Data!$A$1:$A$7,Data!B1)+COUNTIF(Data!$B$1:B1,Data!B1)`
C1 and copied down:
=COUNTIF(Data!$A$1:$A$7,Data!C1)+COUNTIF(Data!$B$1:$B$7,Data!C1)+COUNTIF(Data!$C$1:C1,Data!C1) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "excel formula"
} |
How to add quotes around each list element after .add?
I have a List
private List<string> additionalHeaderMeta = new List<string>();
and I want to output it to a csv file. All that is working find but it turns out some of the elements I am adding to additionalHeaderMeta might have commas in them sometimes which obviously messes up a csv file. How can I put quotes around each element after the element has been added?
I tried
additionalHeaderMeta.Select(i => "\"" + i + "\"");
But no luck there. | If you want to modify the list in place, simply loop over it.
for (int index = 0; index < list.Count; index++)
list[index] = /* modify item here */
What you have done is create a query definition which would be lazily evaluated, but you would actually need to iterate over the query. Use the query if you want to actually leave the list unmodified, but simply want to project the data into the modified form.
var query = additionalHeaderMeta.Select(i => "\"" + i + "\"");
foreach (var item in query)
do whatever
To simply replace your list with another entirely, use `ToList()` on the query and assign the result back to your original list.
additionalHeaderMeta = additionalHeaderMeta.Select(i => "\"" + i + "\"").ToList(); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, list, anonymous methods"
} |
Remove tables from html files in python
I am looking to remove all tables from from html files, i.e. I want a copy of the html files without include any tables in them [not to extract the tables from the files, or reformat it etc].
I was considering using regex, of the form:
html_without_tables = re.sub(r"(?s)(?i)\<table .*\<\/table\>, " ", table)
However, there are countless posts saying don't parse html with regex, which makes me somewhat reluctant (although not really sure what problems would induce). I am guessing Beautifulsoup must be able to do it, but not sure how. | Using BeautifulSoup, this is basically as easy as finding all `table` tags and calling `.extract()` on each:
for table in soup.find_all("table"):
table.extract() | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, html, regex, beautifulsoup"
} |
Can this equation have more than one solution?
Consider the following equation:
$\left[\array{1 & 0.1353 & 1 \\\0.3678 & 0.3678 & 1 \\\ 0.1353 & 1 & 1 \\\ 0.3678 & 0.3678 & 1}\right]\left[\array{w_1\\\w_2\\\w_3}\right]=\left[ \array{ 0\\\1 \\\ 0 \\\ 1}\right]$
The $4$ by $3$ matrix on the LHS, is not a square matrix and has infinite left inverses, but I think there is only one solution for $[w_1 w_2 w_3]^T$ because the rows $2$ and $4$ of the matrix are the same and have similar values on the RHS, so in fact we have $3$ linear equations for $3$ unknowns, so we have only one solution for this equation.
Am I right or I have made a mistake? | Yes, because rows two and four are the same on both sides, you can simplify your system to $$ \begin{pmatrix}1 & .1353 & 1\\\\.3678 & .3678 & 1 \\\ .1353 & 1 &1 \end{pmatrix} \begin{pmatrix} w_1 \\\ w_2\\\ w_3 \end{pmatrix}=\begin{pmatrix} 0\\\1\\\0 \end{pmatrix} $$ If the $3\times 3$ matrix has nonzero determinant, then you have a unique solution. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra, matrices, inverse"
} |
Count of dataframe column above a threshold
I have a dataframe where I want to find the count of all ID above a threshold. For example
index DEVICE_ID DIFF
0 12 3
1 12 4
2 12 5
3 12 3
4 13 2
5 13 4
6 13 1
7 14 3
8 14 6
If 'Diff' is greater than or equals to 4, give me the count of the IDs starting from that index for each unqiue ID, so the above dataframe will result in:
{12:3, 13:2, 14:1} - For ID 12, the diff column is 4 on index 1 so we count the amount of 12's from and including index 1 till 3
Sorry for the badly worded question. | Using `df.shift()`
df['T_F']=(df.DIFF>=4)
df[df.T_F != df.T_F.shift(1)].groupby('DEVICE_ID')['DEVICE_ID'].count().to_dict()
{12: 3, 13: 2, 14: 1} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "python 3.x, pandas, dataframe"
} |
VBA Convert Negative Numbers to Postive
after the function that filters my results below zero, I have to write it as a positive result, i.e. without "-". However, I get the error "Object variable or With block not set" . What I doing wrong ?
Dim cl As Range
cl = wbMe.Sheets("pochodne").Range("T35").Copy
If cl.Value < 0 Then
cl.Value = -cl.Value
End If | Objects need to be "set", so try:
Dim wbMe As Excel.Workbook
Dim cl As Excel.Range
Set wbMe = ThisWorkbook
Set cl = wbMe.Worksheets("pochodne").Range("T35")
If cl.Value < 0 Then
cl.Value = -cl.Value
End If
That works here. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "excel, vba"
} |
My published CrystalReports desktop app (VB.NET) wont run without installed CRforVS on the clients computer
The published program run correctly on my developer computer, but wont run on the client computer without the CrystalReports SDK (CRforVS). The CR runtime is installed, but dont solved the problem.
The CR SDK needs an installed Visual Studio (VS) on the target computer, but I dont want setup theese programs (VS, CRforVS) on the clients computer.
Any idea? | I checked the Windows Event Log, and find a FileNotFoundException. After debugged the code in developer environment (VS) on the client computer, I found the concrete message: "log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
The solution is for the problem, that I set the Target CPU from "AnyCPU" to "x64" on Compile tab in the Project Properties in the VS.
Now it works fine!
.css({"color": "white"});
$("div").children().css({"color": "white"});
I am not able to add an id to the span.
I am using oracle apex 4.2 | With CSS, everything is specificity. Is the span element on it's own or is it wrapped inside a div? You can always increase specificity in order to increase the priority in CSS styles. For example, you can try:
$('span.fielddata').css({"color": "white"});
or, if it's inside a div:
$('div .fielddata').css({"color": "white"}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, html, css, oracle apex"
} |
A summation including binomial coefficients
I'm trying to solve a problem. It led to such a summation :
$$f(n)=\sum_{i\, =\, \left\lceil\, n/2 \,\right\rceil}^{\infty} {\binom{i + k}{i}\binom{2i}{n}{(-a)}^i}$$
Where $k$ is a nonnegative integer, $a$ is a non-negative real number and both are given.
How can I find it as a closed form function of $n$? | I am not sure that it coud simplify since it is almost the definition of the gaussian hypergeometric function.
If $n=2m$, you would get $$(-a)^m \binom{k+m}{m} \, _2F_1\left(m+\frac{1}{2},k+m+1;\frac{1}{2};-a\right)$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "sequences and series, combinatorics, summation, binomial coefficients, analytic combinatorics"
} |
How to set the Mapbox symbol layer textfield with GeoJSON property value?
I want to create a symbol layer with the textfield set to a property from my GeoJSON file. For instance, in my GeoJSON file each Feature has a property called "rlabel" and I would like to set the value of this label as the symbol layers textfield. How do I do this?
String geojsonString = loadJsonFromDownloadedFile(...);
source = new GeoJsonSource("source-id", geojsonString);
SymbolLayer symbolLayer = new SymbolLayer("symbol-layer-id", "source-id");
symbolLayer.setProperties(
PropertyFactory.textField( ??? ) // what goes here?
);
style.addLayer(symbolLayer);
Thanks | Try the following code:
PropertyFactory.textField(get("rlabl"))
Specifically the `get()` method is `com.mapbox.mapboxsdk.style.expressions.Expression.get()` This class has a lot of matchers. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, android, mapbox, mapbox android"
} |
Is it possible to create an error log in java that extends to all classes?
Is it possible to create an error log in java that extends/works to all classes in a package?
So when I handle exceptions in various classes, I can simply log that error into one single file. | Take a look at the numerous Java logging frameworks available, in particular:
* Log4j
* slf4j
Both of these allow you to customize (at config time and runtime) which statements to log, where to log them (the console, a single file, many files, files per error level) and how to format them. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, error log"
} |
Libraries from Cocoapod are not found by Xcode compiler
I have a project that has the Podfile with the following configuration
source '
platform :ios, '9.0'
target 'CDA' do
pod 'RestKit', '~> 0.27.0'
pod 'ZBarSDK', '~> 1.3.1'
end
I use the Pod install command and I get the following result
!Text
But when I try to build the project on Xcode, I received the following error:
!Text
For some reason, the compiler was not able to find the libraries from cocoapod. How can I fix this error? | I found a way to fix the problem.
I follow the guide on this site <
What fix the problem for me is the step number 5.
I add the Libraries direct to build now and at the moment it works now for me, all builds are working now. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "xcode, cocoapods"
} |
Ground states in the shell model for odd-even nuclei
> I understand that even-even nuclei (Z and N number) have zero spin because of pairing.
>
> Even-odd nuclei have the spin of the odd nucleon, and parity is given by $(-1)^L$ \- so my question is, how do we work out the state which this odd nucleon is in?
As an example: $^3_2 \text{He}$ the odd nucleon, is a neutron which is the state $1\text{s}_\frac{1}{2}$ ($l=0,$ $s=1/2$) so the answer for the ground state spin-parity is $\frac{1}{2}^+$... Or with $^9_4 \text{Be}$ the most energetic neutron is the $1\text{p}_{\frac{3}{2}}$ giving $\frac{3}{2}^-$ but how is this worked out? I assume it is something to do with the nucleons occupying all the lowest energy states and finding the highest energy spare nucleon - How will I know which quantum numbers are the lowest energy?
Edit: for example, do I need to refer to this table? < | > How will I know which quantum numbers are the lowest energy?
In general that is a difficult question from first principles. Simulation can often answer it, but the problem can be pretty involved and demanding.
However, as a practical matter the configuration and energy levels of many nuclei are known from extensive experiments. For example an online level diagram and a table of level data for Gd-157 from < . | stackexchange-physics | {
"answer_score": 1,
"question_score": 2,
"tags": "homework and exercises, nuclear physics"
} |
Prev not working inside div
I am trying to change the colour of my label when the texbox has focus
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
This is my javascript
$(':text').focus(function () {
$(this).prevAll("label").last.css("color", "blue");
});
`$(this).prevAll()` is always empty. But `$(this).next()` and `$(this).nextAll()` has a span
Please help I would really appreciate any assistance | `$(this).prevAll("label")` is empty because `prevAll("label")` will look for label siblings of the text box. You should do something like this instead:
$(':text').focus(function () {
$(this).parent("div").prev().find("label").css("color", "blue");
});
`next()` and `nextAll()` is returning a span because the following code will be rendered as a span, which is the next element after the textbox.
<%: Html.ValidationMessageFor(model => model.FirstName) %> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery"
} |
How to set each value in a current_group() to its absolute value before summing the group?
I have an XSLT file that sets up a group. I want to sum one of the fields that are in the group but I would like all of the the negative numbers in the grouping to be positive before summing.
I tried using the abs() and translate functions on the current-group()/Transaction_Credit_Amount field but an get an error. The errors say that a sequence of one or more than one item is not allowed as the first argument to translate() or abs().
Here is the original line of code I am trying to change so that all of the Transaction_Credit_Amount values are positive before summing.
<xsl:value-of select="format-number(sum(current-group()/Transaction_Credit_Amount,'-',''), '#0.#############')"/>
The expected result is the summation of the absolute values of all Transaction_Credit_Amount values. | You should be able to use `current-group()/Transaction_Credit_Amount/abs(.)` to get a sequence of numbers of the absolute values and of course you can then sum them with `sum(current-group()/Transaction_Credit_Amount/abs(.))`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "xslt"
} |
How to customize <pagination-controls> color?
I am using **angular pagination** and I want to customize this **blue** color into **another** , Can anyone help me.
 > a {
background-color: red !important;
border-color: black !important;
}
::ng-deep ul > li.disabled > span {
background-color: brown !important;
border-color: black !important;
}
::ng-deep ul > li.active > a {
background-color: green !important;
border-color: red !important;
}
Working example: Stackblitz | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angular, colors, pagination, customization"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.