text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How to put the char with the smallest ASCII value at the end of the String recursively?
Given the method:
public String moveSmallest(String s) {}
how to find the char with the smallest ASCII value, place it at the end of the String, and return that String, recursively?
Reading Find a char.., Move the char.., Move to end.. didn't really answer: what is the algorithm I need, and how do I implement it.
No global vars, accumulators, helper methods, or any additional structures can be used.
This question is closely connected (in nature) to How to pass a partial solution to the next recursive call.
Attempt to find the min char:
if (s.length() == 0) {
return s;
} else if (s.length() > 1) {
char c = s.charAt(0) > moveSmallest(s.substring(1)).charAt(s.length()-1) ? s.charAt(0) : moveSmallest(s.substring(1)).charAt(s.length()-1);
}
A:
Well, if you really want to use recursion, here it is.
Move smallest letter to the end:
public static String moveSmallestToTheEnd(String s) {
if (s.length() <= 1)
return s;
if (s.length() == 2)
return s.charAt(0) < s.charAt(1) ? String.valueOf(s.charAt(1)) + s.charAt(0) : s;
String suffix = s.substring(1);
String res = moveSmallestToTheEnd(suffix);
return s.charAt(0) < res.charAt(res.length() - 1) ? suffix + s.charAt(0) : s.charAt(0) + res;
}
Output:
a -> a
ab -> ba
ba -> ba
abc -> bca
bac -> bca
bca -> bca
bcdae -> bcdea
bcae -> bcea
Move higest letter to the beginning:
public static String moveHighestToTheBeginning(String s) {
if (s.length() <= 1)
return s;
if (s.length() == 2)
return s.charAt(0) < s.charAt(1) ? String.valueOf(s.charAt(1)) + s.charAt(0) : s;
String prefix = s.substring(0, s.length() - 1);
String res = moveHighestToTheBeginning(prefix);
return s.charAt(s.length() - 1) > res.charAt(0) ? s.charAt(s.length() - 1) + prefix : res + s.charAt(s.length() - 1);
}
Output:
a -> a
ab -> ba
ba -> ba
abc -> cab
bac -> cba
bca -> cba
bcdae -> ebcda
bcae -> ebca
| {
"pile_set_name": "StackExchange"
} |
Q:
how do i/can i access a sessionid cookie through javascript?
I've installed the cookie extension for jquery, and am attempting to access the session id cookie.
I currently have two cookies for my session - see screenshot below:
however, $.cookie() only lists one:
> $.cookie()
Object {csrftoken: "fFrlipYaeUmWkkzLrQLwepyACzTfDXHE"}
> $.cookie('sessionid')
undefined
can i/how do i access the sessionid cookie from javascript?
A:
The session id cookie should be marked as HTTP Only, preventing access from javascript. This is a security issue, preventing session hijacking via an xss vulnerability.
You can see in your screenshot that the cookie is indeed marked as HTTP.
If you want to learn more about the flag see here. Originally implemented by IE, most browsers support the flag nowadays, and session cookies not marked http-only are considered a security flaw. Also see here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any generic KVM over IP cards/chips for motherboards without any such capability?
I have a remote server that doesn't have any IP KVM capabilities, meaning I can't remotely power cycle it or access the BIOS. I saw that ASUS offers something for their motherboards here:
http://www.asus.com/Server_Workstation/Accessories/ASMB5iKVM/
But is there anything like this available for other motherboards? Even something that I could stash away somewhere in a hard drive bay that simply plugs into the board would be great.
A:
You'll need to check with your specific motherboard vendor to see what's available. There won't be anything generic that works with everything unless it was going to be able to physically push the power button on the server.
| {
"pile_set_name": "StackExchange"
} |
Q:
AJAX quantity Validation
I want to do a quantity validation using Jquery. I want to check for following
1) that the number is a whole number
2) that it not letter
3) that they is not decimal
4) that the max number is 99.
My current Jquery
$(document).ready(function()
{
$('#button').click(function()
{
var pid = $('#pid').val();
var length = $('#length').val();
var Qty = $('#Qty').val(); // this is the quantity
var Category = $('#Category').val();
#Qty = preg_replace('#[^0-9]#i', '', $Qty); // filter everything but numbers
if ($Qty >= 100) { $Qty = 99; }
if ($Qty < 1) { $Qty = 1; }
if ($Qty == "") { $Qty = 1; }
$.ajax({
url: 'cart.php',
type: 'POST',
data: { pid:pid, length:length, Qty:Qty, Category:Category },
success: function(data)
{
}
})
});
});
A:
Please note that any validation you do with JavaScript (with or without jQuery) should be repeated in your PHP code (obviously the syntax won't be the same), because you can't ever completely trust what is submitted by the browser (the user might have used dev tools to bypass your client-side validation).
Having said that, to answer your question on how to do the validation you've described with jQuery, given a variable Qty holding the user input you can test whether it is an integer between 1 and 99 using the following code:
if (!/^[1-9]\d?$/.test(Qty)){
alert('Add meaningful error message here');
return false;
}
The regex I've shown, ^[1-9]\d?$, allows the first character in the string to be a digit between 1 and 9, and then an optional second character that is any digit (0-9). Which works out to all of the numbers between 1 and 99. (Actually that was just plain JS, not jQuery.)
In the context of your existing code:
$(document).ready(function () {
$('#button').click(function () {
var pid = $('#pid').val();
var length = $('#length').val();
var Qty = $('#Qty').val(); // this is the quantity
var Category = $('#Category').val();
if (!/^[1-9]\d?$/.test(Qty)){
alert('Add meaningful error message here');
return false; // don't continue
}
$.ajax({
url: 'cart.php',
type: 'POST',
data: {
pid: pid,
length: length,
Qty: Qty,
Category: Category
},
success: function (data) {
}
});
});
});
Note that the PHP code that you showed in your question (that you later edited into the middle of your JS) doesn't make sense because it actually changes the value entered by the user to force it to meet the rules. E.g., user types "15.0" so your code removes the decimal to leave "150" and then decides that that is too big and makes it "99". So the user thinks they've sent you "15.0" and you've changed it to "99".
Note also that if you know that 99 is the largest permitted number then you can add maxlength="2" to the input element in question so that the user can't type more than two characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't get ApiGateway Lambda:InvokeFunction permissions working in CloudFormation
I'm trying to set up a CloudFormation template that will create a lambda function and an APIGateway that can access it. However, despite setting up the Lambda:InvokeFunction permission as shown below (and trying every permutation under the sun as recommended on other SO questions), I get the message Execution failed due to configuration error: Invalid permissions on Lambda function.
The only way I can get it to work is if I go into the AWS console and manually un-set and re-set the APIGateway's destination to the lambda.
I've also tried the CLI to no effect:
aws lambda add-permission --function-name $updatedFunction.FunctionName --statement-id "AllowExecutionFromAPIGateway" --action "lambda:InvokeFunction" --principal "apigateway.amazonaws.com" --source-arn $api.StackId
Does anyone have any insight into why these permissions wouldn't work?
...
"Get":{
"Type":"AWS::Lambda::Function",
"Properties":{
"Code":{
"S3Bucket":"webapistack-bucket-org0oolyde9v",
"S3Key":"webapi/webapistack-636349410359047808.zip"
},
"Tags":[
{
"Value":"SAM",
"Key":"lambda:createdBy"
}
],
"MemorySize":256,
"Environment":{
"Variables":{
"AppS3Bucket":{
"Fn::If":[
"CreateS3Bucket",
{
"Ref":"Bucket"
},
{
"Ref":"BucketName"
}
]
}
}
},
"Handler":"webapi::webapi.LambdaEntryPoint::FunctionHandlerAsync",
"Role":{
"Fn::GetAtt":[
"GetRole",
"Arn"
]
},
"Timeout":30,
"Runtime":"dotnetcore1.0"
}
},
"GetPutResourcePermissionTest":{
"Type":"AWS::Lambda::Permission",
"Properties":{
"Action":"lambda:invokeFunction",
"Principal":"apigateway.amazonaws.com",
"FunctionName":{
"Ref":"Get"
},
"SourceArn":{
"Fn::Sub":[
"arn:aws:execute-api:WS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/ANY/*",
{
"__Stage__":"*",
"__ApiId__":{
"Ref":"ServerlessRestApi"
}
}
]
}
}
},
...
"ServerlessRestApi":{
"Type":"AWS::ApiGateway::RestApi",
"Properties":{
"Body":{
"info":{
"version":"1.0",
"title":{
"Ref":"AWS::StackName"
}
},
"paths":{
"/{proxy+}":{
"x-amazon-apigateway-any-method":{
"x-amazon-apigateway-integration":{
"httpMethod":"POST",
"type":"aws_proxy",
"uri":{
"Fn::Sub":"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Get.Arn}/invocations"
}
},
"responses":{
}
}
}
},
"swagger":"2.0"
}
}
}
A:
Your AWS::Lambda::Permission seems to be incorrect.
The FunctionName you are referencing is the logical ID, the spec, however, requires the physical ID or ARN.
The SourceArn pattern of the Sub is missing some characters on the Region replacement.
Since I'm not sure whether the "ANY"-operation is valid for the ARN, I would replace it with "*", just to be sure.
Here a changed version of the permission:
"GetPutResourcePermissionTest":{
"Type":"AWS::Lambda::Permission",
"Properties":{
"Action":"lambda:invokeFunction",
"Principal":"apigateway.amazonaws.com",
"FunctionName":{
"Fn::GetAtt": [ "Get" , "Arn" ]
},
"SourceArn":{
"Fn::Sub":[
"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/*/*",
{
"__Stage__":"*",
"__ApiId__":{
"Ref":"ServerlessRestApi"
}
}
]
}
}
},
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress Shortcode Returning "Array"
I am making a custom shortcode which basically is just meant to return my custom post type, here's my code:
function shortcode_slider($atts, $content=null){
extract(shortcode_atts( array('id' => ''), $atts));
$return = $content;
$return .= query_posts( array( 'post_status' => 'publish' , 'post_type' => 'slider' ) );
return $return;
}
add_shortcode('slider', 'shortcode_slider');
The shortcode works ok apart from one thing - when it returns all of the posts it also returns "array" at the top of the list - any idea why this would happen?
Also, I want to be able to use the "id" input to be able to specify a category, e.g.
$return .= query_posts( array( 'post_status' => 'publish' , 'post_type' => 'slider', 'category' => $id ) );
but I am unsure of the correct syntax for this.
Any help is much appreciated.
A:
First of all, don't use query_posts.
Please, check:
When should you use WP_Query vs query_posts() vs get_posts()?
When to use WP_query(), query_posts() and pre_get_posts
In a shortcode case, I'd go with get_posts. It will return what you need and won't mess with the loop.
It is worth noting that you don't really need to extract the attributes, using $atts['id'] does the work.
Follows a working shortcode, see comments:
add_shortcode( 'slider', 'shortcode_slider' );
function shortcode_slider( $atts, $content=null )
{
// Initialize variable and check for shortcode content
$return = '';
if( $content ) {
$return = $content;
}
// Shortcode attribute: title="Lorem Ipsum"
if( isset( $atts['title'] ) )
{
$return .= '<br><h2>' . $atts['title'] . '</h2>';
}
// Get our custom posts
// 'category' is the category ID or a comma separated list of ID numbers
$sliders = get_posts( array(
'post_status' => 'publish',
'post_type' => 'slider',
'numberposts' => 10,
'order'=> 'ASC',
'orderby' => 'title',
'category' => $atts['id']
) );
// Auxiliary variable, don't print <br> in the first element
$first = '';
// Iterate through the resulting array
// and build the final output
// Use $slide->post_author, ->post_excerpt, as usual
// $slide->ID can be used to call auxiliary functions
// such as get_children or get_permalink
foreach( $sliders as $slide )
{
$link = get_permalink( $slide->ID );
$return .=
$first
. '<a href="' . $link . '">'
. $slide->post_title
. '</a>
';
$first = '<br>';
}
return $return;
}
Shortcode applied in a default post type:
Custom post types:
Result:
Useful links:
WordPress Shortcodes: A Complete Guide
How to Add Shortcodes to Your WordPress Plugin
| {
"pile_set_name": "StackExchange"
} |
Q:
Why would one number theorems, propositions and lemmas separately?
When it comes to numbering results in a mathematical publication, I'm aware of two methods:
Joint numbering: Thm. 1, Prop. 2, Thm. 3, Lem. 4, etc.
Separate numbering: Thm. 1, Prop. 1, Thm. 2, Lem. 1, etc.
Every piece of writting advice I have encountered advocates the use of 1. over 2., the rationale being that it makes it easier to find the result based on the number. It seems that 1. is more popular than 2., although 2. still exists, especially in books. I can only imagine that people using 2. must have a reason, but I have not yet to encounter one. I hope it is not too opinion-based to ask:
What is the rationale for separately numbering theorems, propositions and lemmas, like in 2.?"
A:
If the paper contains three main theorems, each generalizing the previous, it is nice to be able to discuss them like this:
While the extension of Theorem 1 to Theorem 2 uses only complex analysis, in Theorem 3 we will have to employ some Ramsey theory.
A:
This is a slight elaboration of François Dorais's comment. If you have a small number of theorems/lemmas/propositions—let's say, small enough that readers can reasonably be expected to hold all the theorems in their head at once—then the second method of numbering can help readers grasp the flow of the paper and can even serve as a mnemonic aid.
A secondary consideration, similar to what Fedor Petrov said, is that the reader may want to skim through and just look at the main theorems. If you adopt the first method of numbering, then readers might accidentally skip from (say) Theorem 8 to Theorem 17 without realizing that they missed Theorem 14.
One famous book that uses the second method of numbering is Serre's Course in Arithmetic. Serre uses the "Theorem" designation very sparsely in that book, and the numbering system helps make the Theorems stand out.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I add an ImageView as a ListView Header?
Can anyone help me to find out how to add an ImageView as a header to a ListView?
My code is here:
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View snapshot = inflater.inflate(R.layout.map_snapshot, null);
ListView channelsList = (ListView) findViewById(R.id.channelsList);
channelsList.addHeaderView(snapshot);
By now it shows nothing.
A:
Try inflating your header view passing the parent (ListView) as parameter:
ListView channelsList = (ListView) findViewById(R.id.channelsList);
View snapshot = inflater.inflate(R.layout.map_snapshot, channelList, false);
Then, just add it to the ListView:
channelsList.addHeaderView(snapshot);
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a variable across c++ programs (compilations)
this type of question has been asked several times over here and elsewhere but it seems that I don't get any of the solutions to work. What I've 'accomplished' so far is that a variable can be used by two different applications (one application calls the other one via system command) but the value is NOT passed from the main app to the secondary one.
code corresponds to this:
#ifndef avis_h
#define avis_h
#include "string"
using namespace std;
extern int fnu;
#endif
that's the header file avis_h.
The main program goes like this:
#include "stdafx.h"
...
#include "iostream"
#include "avis_h.h"
int fnu;
int main(){fnu=3;system (app2);}
where app2 is the secondary application:
#include "stdafx.h"
...
#include "iostream"
#include "avis_h.h"
int fnu;
int main(){cout<<fnu;Sleep(10);}
instead of the number 3 the number 0 is displayed. I've tried alternative ways but none worked so far. Can somebody please tell me how I get that value passed correctly from the main program to the secondary program?
A:
You can't share variables between independent applications like that.
You can pass it as a parameter to the system command:
//commandLine is app2 + " " + the parameter
system (commandLine);
Breakdown:
std::stringstream ss;
ss << app2;
ss << " ";
ss << fnu;
std::string commandLine = ss.str();
system(commandLine.c_str());
and don't forget to:
#include <sstream>
#include <string>
and retrieve it via argv in the second application.
Or you can use IPC, but that's overkill in this particular case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue regarding fetching data from DB using LINQ and .NET
Actually I don't have the idea that whether I should use some technique in storing data so that I can fetch according to my requirement or just need to search a query returning data according to my requirement. I want to store some data that is linked with eachother some rough data is given below
Name Reference City
Mian Null GUj
Hamza Mian Khi
Adam Mian Lhr
Jamil Adam Lhr
Musa Jamil Khi
Subhan Musa ISL
I want the solution that when I enter some name its fetches data of that person and its all childs and sub childs.
Ex:
If I enter Adam acoording to above table info it should return Adam, Jamil, Musa, Subhan.
A:
Well you must have a foreign key for the parent.
Here is an example
select * from person parent
left join person child on child.Parent_ID = parent.ID
where parent.Name like 'Adam'
I think this should work for you, you could also left join the sub children of the sub children.
Or you can write query that search recursive.
Please see this article for more info
recursive-select
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone - Decrypting an AES-encrypted message with a different key than the one used to encrypt
I'm just coding basic "encrypt" and "decrypt" methods for AES on iPhone, using CCrypt.
I've been running a few tests and I was really struck about finding that, sometimes, if you try to decrypt an encrypted text using a key different than the one that was used to encrypt the plain text CCrypt would not return any errors.
Here is an example:
- (void) testDecryptTextWithTheWrongKey {
NSData *encryptKey = [Base64 decodeBase64WithString:@"+LtNYThpgIlQs2CaL00R6AuG2C/i6U1Vt1+6wfFeFMk="];
NSData *decryptKey = [Base64 decodeBase64WithString:@"yg7BvhM8npVGpAFpAESDn3IRWpe6qeQWaa1rwHiTsyU="];
NSString *plainText = @"The text to be encrypted";
NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *encrypted = [LocalCrypto encryptText:plainTextData key:encryptKey error:&error];
assertThat(error, nilValue());
assertThat(encrypted, notNilValue());
error = nil;
NSData *decrypted = [LocalCrypto decryptText:encrypted key:decryptKey error:&error];
assertThat(error, notNilValue());
assertThat(decrypted, nilValue());
}
My encrypt and decrypt methods defined in LocalCrypto simply call an internal "executeCryptoOperation" method indicating that they want to encrypt or decrypt:
+ (NSData *) executeCryptoOperation:(CCOperation)op key:(NSData *) key input:(NSData *) input error:(NSError **)error {
size_t outLength;
NSMutableData *output = [NSMutableData dataWithLength:input.length + kCCBlockSizeAES128];
CCCryptorStatus result = CCCrypt(op, // operation
kCCAlgorithmAES128, // Algorithm
kCCOptionPKCS7Padding | kCCOptionECBMode, // options
key.bytes, // key
key.length, // keylength
nil, // iv
input.bytes, // dataIn
input.length, // dataInLength,
output.mutableBytes, // dataOut
output.length, // dataOutAvailable
&outLength); // dataOutMoved
if (result == kCCSuccess) {
output.length = outLength;
} else {
*error = [NSError errorWithDomain:kCryptoErrorDomain code:result userInfo:nil];
return nil;
}
return output;
}
Well, my question is: is it normal that CCrypt returns kCCSuccess when we try to decrypt the encrypted text with a different key than the one used during the encrpytion? Am I missing something or doing something wrong?
It is true that even when CCrypt returns success for the decryption, I can't get a proper NSString out of the resulting data but I would certainly expect CCrypt to return some sort of error in this situation (as Java would probably do).
If this is the normal behavior, how am I supposed to know if the decrypt operation returned the real plain text or just a bunch of bytes that don't make any sense?
There is a similar question here, but the answer doesn't really convince me: Returning wrong decryption text when using invalid key
Thanks!
A:
There are cipher algorithms which include padding (like the PKCS#5 padding in your Java implementation), and there are ones which don't.
If your encryption algorithm used padding, the corresponding decryption algorithm expects that there will be well-formed padding in the decrypted plaintext, too. This serves as a cheap partial integrity check, since with a wrong key the output likely will not have a right padding. (The chance that a random n-byte block (n=16 for AES) has a valid PKCS#5 padding is 1/256 + 1/(256^2) + ... + 1/(256^n), which is only slightly more than 1/256.)
It might be that your objective-C CCCrypt function does not check that the padding is valid, only its last byte (or even only some bits of this last byte), to see how many bytes were padded (and are now to be cut off).
If you want to make sure that the key is right, encrypt some known part of the plaintext, and error out if it is not in the decrypted part. (But don't do this with ECB mode, see below.)
If you also want to make sure that the data was not modified, also use a MAC, or use a combined authenticated encryption mode of operation for your block cipher.
Another note: You should not use ECB mode, but instead a secure mode of operation (about any other mode indicated in this article and supported by your implementation will do - standard nowadays is CBC or CTR mode). Some modes (like CFB, OFB and CTR) don't need padding at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display a .phtml Block in another Theme
I'd like to display a block which is currently working on my custom theme on base theme section.
<?php echo $this->getLayout()->createBlock('fblogin/fblogin') ->setTemplate('fblogin/bt_fblogin.phtml')->toHtml() ; ?>
I'm using a one-page checkout plugin and it is installed in base theme folder, How can i Display the above block there.?
A:
You need to copy file from base to your theme.
and add below code to your phtml file where you want to add
<?php echo $this->getLayout()->createBlock('fblogin/fblogin')->setTemplate('fblogin/bt_fblogin.phtml')->toHtml(); ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Different usage of « Qui sait », depending on a negative or positive context
J'ai rencontré de nombreuses phrases avec l'expression « Qui sait », et tout porte à croire que :
Est-ce que l'on emploie la construction « Qui sait si ... ne ... pas » quand tout laisse prévoir que quelque chose de désagréable se produira ?
Dans un contexte négatif :
Qui sait si elle ne va pas le larguer du jour au lendemain ?
(Plutôt que de dire carrément) : Qui sait, elle va peut-être le larguer du jour au lendemain ?
Quand il s'agit d'un changement favorable, en revanche, je remarque une tendance à éviter la construction négative, ainsi qu'à ne pas utiliser la conjonction « si ».
Dans un contexte positif :
Qui sait, voir l'intérieur fera peut-être resurgir quelques souvenirs ?
(Plutôt que de dire) : Qui sait si voir l'intérieur ne fera pas resurgir quelques souvenirs ?
A:
Qui sait si / si ne pas = expression d'un doute.
Qui sait si elle viendra ? Il y a une possibilité qu'elle vienne, avec un doute.
Qui sait si elle ne chantera pas une chanson ? Il y a une possibilité qu'elle chante une chanson.
Globalement:
qui sait si + positif : on doute si cela va arriver.
qui sait si + négatif : cela peut arriver (par surprise).
Qui sait, + affirmation = peut-être que l'affirmation est vraie.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using JQuery Tabs as Main Navigation
A JQuery UI Tab that inherits from a JQuery Theme and redirects (HTTP GET) to a new page is the goal.
I'm 90% there using the following code, but the compromise has been to put the target URL in the anchor TITLE (the Tab widget expects the HREF to be a local page selector).
This works, but for SEO purposes I'd like the HREFs to be actual URLs to ensure search engines will follow and index them.
Thoughts?
<script>
$(function () {
$("#tabs").tabs();
$(".nav-link")
.click(function () {
window.location = this.title;
});
});
</script>
<div id="tabs">
<ul>
<li><a href="#tabs-1" title="home.html" class="nav-link">Home</a></li>
<li><a href="#tabs-2" title="contact.html" class="nav-link">Contact Us</a></li>
</ul>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
</div>
A:
If you make sure that you follow certain HTML structure, you can do something like,
<div id="tabs">
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="contact.html">Contact Us</a></li>
</ul>
<!-- Make sure that your DIVs are called 'tabs-0', 'tabs-1' etc. 'tabs-0' will be referred by first link, tabs-1 will be referred by second link, so on and so forth. -->
<div id="tabs-0"></div>
<div id="tabs-1"></div>
</div>
If your HTML structure looks like this, you can do:
<script>
$(function() {
var tabId = '#tabs';
$(tabId + ' a').each(
function(index, val)
{
$(this).attr('href', tabId + '-' + index);
}
);
$("#tabs").tabs();
});
</script>
Now, search engine will see those links where as user will see your regular tab behavior.
| {
"pile_set_name": "StackExchange"
} |
Q:
node-cron with timezones
i have a node(v0.7.3-pre) server with node-cron(0.3.2) and node-time(0.8.2):
var cronJob = require('cron').CronJob;
var cronJ = new cronJob({
cronTime: "00 29 16 6 * *",
onTick: function() {
console.log("Tick");
},
start:true,
timeZone: "America/Los_Angeles"
});
console.log(cronJ);
it runs, but the Cron is allways working with the server time(UTC), and the returned cron is:
{ _callbacks: [ [Function] ],
onComplete: undefined,
cronTime:
{ source: '00 29 16 6 * *',
zone: undefined,
second: { '0': true },
minute: { '29': true },
hour: { '16': true },
dayOfWeek:
...
the zone is set as undefined, am i missing something?
A:
Because an error in node-cron module. I already send a pull request that will fix it. You can change this lines in your local copy of this module.
You also can use several function parameters to initialize cronJob instead of one object:
var cronJob = require('cron').CronJob;
var cronJ = new cronJob("00 29 16 6 * *", function() {
console.log("Tick");
}, undefined, true, "America/Los_Angeles");
console.log(cronJ);
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the norm on a sequence space have to be monotone?
Let $\rho:[0,+\infty)^{\mathbb{N}}\to[0,+\infty] $ satisfy the following properties:
$\rho(\lambda u)=\lambda\rho( u)$, for every $u\in [0,+\infty)^{\mathbb{N}}$ and $\lambda\ge 0$;
$\rho(u+v)\le \rho( u)+\rho( v)$, for every $u,v\in [0,+\infty)^{\mathbb{N}}$.
Define $\|\cdot\|:\mathbb{R}^{\mathbb{N}} \to[0,+\infty] $ by $\left\|\{u_n\}_{n\in\mathbb{N}}\right\|=\rho(\{|u_n|\}_{n\in\mathbb{N}})$.
Assume that we know that $E=\{u\in \mathbb{R}^{\mathbb{N}}, \|u\|<+\infty\}$ is a linear space and $\|\cdot\|$ is a norm on $E$. Does it follow that $\rho$ is monotone?
By monotonicity I mean that $\rho(\{u_n\}_{n\in\mathbb{N}})\le \rho(\{v_n\}_{n\in\mathbb{N}})$, once $0\le u_n\le v_n$, for all $n$, and $\rho(\{u_n\}_{n\in\mathbb{N}}), \rho(\{v_n\}_{n\in\mathbb{N}})<+\infty$.
Remark 1. It is not hard to show monotonicity, if we consider complex sequences instead of real.
Remark 2. It is very possible that $\rho(\{v_n\}_{n\in\mathbb{N}})<+\infty$, $\rho(\{u_n\}_{n\in\mathbb{N}})=+\infty$, and $0\le u_n\le v_n$, for all $n$.
Remark 3 I can show
$E$ is a Banach space $\Rightarrow$ $\rho$ is monotone $\Rightarrow$ $E$ is a normed space $\Rightarrow$ $\rho$ is "finitely" monotone.
By the latter i mean, that $\rho(\{u_n\}_{n\in\mathbb{N}})\le \rho(\{v_n\}_{n\in\mathbb{N}})$, once $0\le u_n\le v_n$, for all $n$, and the set$\{\frac{u_n}{v_n}, n\in \mathbb{N}\}$ is finite.
A:
For $f\in\mathbb R^{\mathbb N}$ define $\|f\|$ to be the infimum of the reals $B$ such that the graph of $f$ is contained in a finite union of lines of the form $Y=mX+c$ with $|m|,|c|\leq B.$ The infimum is $\infty$ if no such $B$ exists. The indicator function of $[1,\infty)$ has norm $1$ because any line except $Y=1$ has a finite intersection with its graph. But it is bounded by $x\mapsto \tfrac 12(x+1)$ which has norm $\tfrac12.$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return Json as part of my view in C# MVC
My question is: How can I combine the two of these action results into one? There really seems no point in having the first one only to do one line. But I cant see a way out. Any ideas would be appreciated. The remaining I provide for background.
I am trying and successful in returning a partial view with the Json results I require but I am using two ActionResults of the same name (one with parameter one without) to achieve this. If I continue in this manner, I will have to repeat all my ActionResults twice. The problem I have with this is that the first action result does nothing more than literally this:
[HttpGet]
public ActionResult MyResults()
{
return PartialView();
}
That is used to return the view. Within the view I have some JQuery/Ajax which in turn calls another action result of the same name but with parameters. This action result effectively populates a Json object which is then parsed and rendered into the view above as a table. Effectively this actionresult does all the work. It looks something like:
[HttpPost]
public ActionResult MyResults(DataTablePrameters param)
{
//Get the full list of data that meets our needs
var fullList = _myResultsRepository.GetListByID(Id);
//Count the records in the set
int count = fullList.Count();
//Shorten the data to that required for the page and put into object array for Json
var result = from r in fullList.Skip(param.iDisplayStart).Take(param.iDisplayLength)
select new object[]
{
r.field1,
r.field2,
r.field3
};
//Return Json data for the Datatable
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = param.iDisplayLength,
iTotalDisplayRecords = count,
aaData = result
});
}
Those of you not familiar with it, will not be aware that I am using DI/IOC and for brevity I have not included the details of this. But that is not my question. Also the above code used Datatables from the following site:
http://datatables.net/index
Which are actually quite good. And again, using all the above, my code works well. So I don't have problems with it. I know its somewhat inefficient because it loads the resultset into a variable does a count, then skip...take and so on but again, it works and this is not my question.
So again my only question is, how can I combine the two of them into one view. There really seems no point in having the first one only to do one line. But I cant see a way out. Any ideas would be appreciated.
A:
Assuming that the separation of POST and GET access is not desired with just one action left, wouldn't just making "param" optional do the trick?
public ActionResult MyResults(DataTablePrameters param = null) {
if(param == null)
return PartialView();
// Repository action...
return Json([...]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do i overload operator "[]" for vector containing my own class objects
So i got a class WayPoint (inside the namespace HHN).
And i got a class WayPointContainer.
The container got a private vector variable to store objects from the type "HHN::WayPoint"
What i want to do now is i want to overload the operator[] so i can
easy access the objects inside the vector like so:
WayPoint p1("name",1.5,2.0);
WayPointContainer c1;
c1[0] = p1 // This would add the WayPoint p1 to the vector of the container on index 0
WayPoint p2 = c1[0] // This would get the WayPoint from the vector at index 0 and copy it to p2
...
I found different implementations but they were for other types then vector or did not use a complex type inside the vector.
Here is my WayPointContainer.h
#include <vector>
#include <iostream>
#include "WayPoint.h"
#ifndef SRC_WAYPOINTCONTAINER_H_
#define SRC_WAYPOINTCONTAINER_H_
class WayPointContainer {
private:
std::vector<HHN::WayPoint>* pContainer{ nullptr };
public:
WayPointContainer();
WayPointContainer(const WayPointContainer& orig);
virtual ~WayPointContainer();
WayPointContainer& operator=(const WayPointContainer& rhs);
HHN::WayPoint& operator[](int idx) const;
void Add(const HHN::WayPoint& arg);
int Size() const;
void Print() const;
};
#endif /* SRC_WAYPOINTCONTAINER_H_ */
Here is my WayPointContainer.cpp
#include <vector>
#include "WayPointContainer.h"
#include <iostream>
using namespace std;
//Default Konstruktor
WayPointContainer::WayPointContainer() {
//Heap bereich ... new ... pContainer
pContainer = new std::vector<HHN::WayPoint>;
}
//Destruktor
WayPointContainer::~WayPointContainer() {} //TODO
//Copy Konstruktor
WayPointContainer::WayPointContainer(const WayPointContainer& orig) {
pContainer = orig.pContainer;
}
WayPointContainer& WayPointContainer::operator=(const WayPointContainer& rhs) {
if(&rhs == this) {
return *this;
}
if ( pContainer != rhs.pContainer) {
pContainer = rhs.pContainer;
}
return *this;
}
HHN::WayPoint& WayPointContainer::operator[](int idx) const {*
//invalid initialization of reference of type 'HHN::WayPoint&' from expression of type 'std::vector<HHN::WayPoint>'
return pContainer[idx];
}
void WayPointContainer::Add(const HHN::WayPoint& arg) {
pContainer->insert(pContainer->begin(), arg);
}
int WayPointContainer::Size() const {
int i = pContainer->size();
return i;
}
void WayPointContainer::Print() const {
for (auto waypoint = pContainer->begin(); waypoint != pContainer->end(); ++waypoint) {
cout << waypoint->Name();
}
}
The method i am struggling with:
HHN::WayPoint& WayPointContainer::operator[](int idx) const {*
//invalid initialization of reference of type 'HHN::WayPoint&' from expression of type 'std::vector<HHN::WayPoint>'
return pContainer[idx];
}
The Code i implemented there got the invalid initialization error described above.
So i expect to use the []-operator as described at the top but right now its not implemented or implemented with an error.
(I am also missing the Destructor for the vector "pContainer" inside the destructor of the WayPointContainer. So if thats something you know feel free to add it but thats not my question just a bonus.)
If you want i can also provide the code i got for the WayPoint class and my main.cpp i use to test it.
A:
The error message is quite clear about the immediate problem in your operator implementation
invalid initialization of reference of type 'HHN::WayPoint&' from expression of type 'std::vector<HHN::WayPoint>'
pContainer[idx] dereferences pContainer with an offset of idx, thus the result is of type std::vector<HHN::WayPoint>.
There are two ways to solve the problem:
You either dereference the pointer and apply idx on it:
return (*pContainer)[idx];
You don't use a pointer to hold your std::vector<HHN::WayPoint> class member at all (recommended solution):
class WayPointContainer {
private:
std::vector<HHN::WayPoint> container;
// ...
};
In that case you won't need to deal with memory de-/allocation for the pointer, and can simply write your operator overload as
HHN::WayPoint& WayPointContainer::operator[](int idx) const {
return container[idx];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap affix does not work when navigating back
I have used Bootstrap affix to create a fixed position div that behaves similar to the "How to Format" and "Similar Questions" div that appears when you ask a new question in Stackoverflow. It works fine when I load the page the first time, but if I scroll quite far down the page, navigate away, and then return to the page with the back button, the affixed div will sometimes be affixed in the wrong place, and sometimes the fixed positioning will break and it will simply return to its normal place in the document.
Is there something wrong with how I am implementing affix?
Document layout (#engage is the affixed div). It should not scroll over #title or #footer:
Javascript
$('#engage').affix({
offset: {
top: $('#donation-content').offset().top,
bottom: function () {
return (this.bottom = $('.footer').outerHeight(true))
}
}
});
CSS
#engage.affix {
position: fixed;
top: 0;
}
@media(max-width:767px){
#engage.affix {
position: static;
}
}
You can find example code at http://www.bootply.com/pxyz1hsefA. Errors tend to happen if you scroll to the bottom of the page, click on "Go somewhere else", then click on the back button. Violent scrolling up and down will also tend to break it.
Edit:
Adding an .affix-bottom class to the css with absolute positioning goes some way to fixing it. At least now when it's 'broken' the div just sticks to the bottom of its scrolling range. When I scroll back to the top, it resumes it's correct fixed position again. But it's still not what I'd call stable.
#engage.affix-bottom {
position: absolute;
}
A:
I think that the problem I was experiencing was due to a mismatch between the top and bottom offset values, leading to the affix plugin not knowing what state it should be in. It may be a bug in the affix plugin or how it is applied (read more at https://github.com/twbs/bootstrap/issues/4647). It also seems to manifest differently in different browsers.
In my case I could only solve it by removing the bottom offset:
$('#engage').affix({
offset: {
top: $('#donation-content').offset().top
}
});
This does mean that the fixed div can overlap the footer in some situations, which is not ideal but it is more stable. I am marking this as the accepted answer for now, because it does solve the problem, though it does leave unfortunate side-effects.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking PropTypes of inner React component as part of wrapper component
I have Component B that contains Component A. Component A has propTypes defined to validate its properties. I'd like to have a property in Component B that represents the properties in Component A, validate them and reference them. I can't seem to figure that out. Here's what I have so far (abstracted for simplicity of this discussion):
class ComponentB extends PureComponent {
static propTypes = {
componentAProperties: PropTypes.shape(ComponentA.propTypes)
compBProp1: PropType.number,
compBProp2: PropType.string,
compBProp3: PropType.object
}
render() {
const {componentAProperties, ...others} = this.props
return (
<ComponentB {...others}>
<ComponentA {...componentAProperties} />
</ComponentB
)
}
}
class ComponentA extends PureComponent {
static propTypes = {
compAProp1: PropTypes.string,
compAProp2: PropTypes.number,
compAProp3: PropTypes.oneOf(['cat', 'dog', 'mouse'])
compAProp4: PropTypes.bool,
compAProp5: PropTypes.object
}
render() {
const {...others} = this.props
return <ComponentA {...others} />
}
}
The line in ComponentB containing PropTypes.shape(ComponentA.propTypes) does not throw any warning, but I can still pass bogus property values to ComponentA, so I feel like there's still something missing. That is, I can write
<ComponentB componentAProperties={{compAProp2: 'hello'}} />
without warning or error even though compAProp2 is defined as a number.
(Note: I tested PropTypes.ComponentA, ComponentA.PropTypes and ComponentA.propTypes as the componentAProperties value, and all of them threw the console warning, "Failed prop type: ComponentB: prop type componentAProperties is invalid; it must be a function, usually from the prop-types package, but received object.)
I read that there are custom validators you can write, but those seem to work for only PropTypes.arrayOf() and PropTypes.objectOf() whereas ComponentA's propTypes are a shape.
Other Questions I Referenced:
React composition component proptypes
Why not: I want a specific property to reference the inner component, not just to spread the inner component's properties.
Should wrappers component remind propTypes of wrapped components?
Why not: The suggested answer doesn't work. It throws a warning, "Failed prop type: : prop type <inner component> is invalid; it must be a function, usually from the prop-types package, but received object.
A:
From what i see, your approach is already correct.
So i try it right away in JSFiddle.
I have fixed your "abstracted" code example so that it works without essentially changing anything.
Here is the fiddle: https://jsfiddle.net/gejimayu/cnhw4vzy/2/
I take this as an example.
<ComponentB componentAProperties={{compAProp2: 'hello'}} />
As you can see, if you open browser's console, you will see a proptype warning.
So there is nothing wrong with your approach.
However, if i change the prop-type package to the production build, it won't show any warning.
Hence i think it must have something to do with production/development build.
Proptypes will only show warning on development build.
So please do change your environment build to development if you wish to see any warning.
In addition to that, please use prop-type package if you haven't. https://www.npmjs.com/package/prop-types
React "native" support for prop-types has been stopped.
https://reactjs.org/docs/typechecking-with-proptypes.html
Hope it helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find text ending with words defined in array
For instance, I want to see whether each cell from B10 till the end of the B colomn is ending with "@yahoo.com", "@gmail.com", "@rediffmail.com". If not then, it should color that particular cell.
Here is what I tried:
Here are the cons:
Its searching entire sheet, instead a column.
Its coloring entire row, instead that particular cell
I want to highlight the cell, which do not end with above domains.
A:
you can use this:
1) variant using array to store search keys:
Sub test()
Dim cl As Range, Data As Range
Dim searchTerms, k, trigger%
searchTerms = Array("yahoo.com", "gmail.com", "rediff.co")
Set Data = Range("B10:B" & [B:B].Find("*", , , , xlByRows, xlPrevious).Row)
For Each cl In Data
trigger = 0
For Each k In searchTerms
If LCase(cl.Value2) Like "*" & LCase(k) Then
trigger = 1
Exit For
End If
Next k
If trigger = 0 Then
cl.Interior.ColorIndex = 7
Else
cl.Interior.Pattern = xlNone
End If
Next cl
End Sub
2) variant using the range with searching keys:
Sub test2()
Dim cl As Range, Data As Range
Dim k As Range, searchTerms As Range, trigger%
Dim S1 As Worksheet, S2 As Worksheet
Set S1 = Sheets("Sheet1") ' change to sheetname with data for comparing
Set S2 = Sheets("Sheet2") ' chanfe to sheetname with search keys
Set Data = S1.Range("B10:B" & S1.[B:B].Find("*", , , , xlByRows, xlPrevious).Row)
Set searchTerms = S2.[A1:A3] '"yahoo.com", "gmail.com", "rediff.co"
For Each cl In Data
trigger = 0
For Each k In searchTerms
If LCase(cl.Value2) Like "*" & LCase(k.Value2) Then
trigger = 1: Exit For
End If
Next k
If trigger = 0 Then
cl.Interior.ColorIndex = 7
Else
cl.Interior.Pattern = xlNone
End If
Next cl
End Sub
3) variant using scripting.dictionary and range with search terms:
Sub test3()
Dim cl As Range, Data As Range, Cnt As Long
Dim S1 As Worksheet, S2 As Worksheet
Dim searchTerms As Object, WrdArray() As String
Set searchTerms = CreateObject("Scripting.Dictionary")
searchTerms.comparemode = vbTextCompare
Set S1 = Sheets("Sheet1") ' change to sheetname with data for comparing
Set S2 = Sheets("Sheet2") ' chanfe to sheetname with search keys
For Each cl In S2.[A1:A4] '"yahoo.com", "gmail.com", "rediff.co", "internal.yahoo.com"
If Not searchTerms.exists(cl.Value2) Then
searchTerms.Add cl.Value2, Nothing
End If
Next cl
Set Data = S1.Range("B10:B" & S1.[B:B].Find("*", , , , xlByRows, xlPrevious).Row)
Cnt = 0
For Each cl In Data
WrdArray() = Split(cl.Value2, "@")
If Not searchTerms.exists(Split(cl.Value2, "@")(UBound(WrdArray()))) Then
cl.Interior.Color = vbYellow: Cnt = Cnt + 1
Else
cl.Interior.Pattern = xlNone
End If
Next cl
If Cnt > 0 Then
Msgbox "Total count of incorrect entries is [" & Cnt & _
"] all discrepancies have been highlighted with Yellow!"
End If
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing view in TabSpec
In my app I'm using the following code to build my TabActivity -
contactsTabSpec = mTabHost.newTabSpec(getString(R.string.contacts))
.setIndicator(chatHeaderView).setContent(R.id.contactList);
the contactList is a ListView that must be build in my TabActivity implementation (can not be build in regular Activity).
Some of the actions in my app required to change the contactList with groupList in the same tab.
How it can be done with out using intents?
A:
You must have an adapter for the contact list, which your displaying on the ListView. When you need to update the list based on your action, just call adapter.notifyDataSetChanged() method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby on Rails, Datepicker search between two dates
I am a new ROR user trying to implement a DateTime picker to select dates for a search function.
My problem is that when I enter two dates (date from, and date to) in the DatePicker, I get inconsistent results from the search. Sometimes I get no results, and sometimes I get all the results. I am also using the bootstrap-datepicker-rails gem as well as the ransack gem.
This is what my view looks like
<div class="field">
<%= f.label :departure_date_gteq, "Departure Date Between" %>
<%= f.search_field :departure_date_gteq, "data-provide" => "datepicker" %>
<%= f.label :return_date_lteq, "and" %>
<%= f.search_field :return_date_lteq, "data-provide" => "datepicker" %>
</div>
The two database columns I am referencing are departure_date, and return_date. The date stored is datetime and looks like this,
departure_date
2016-08-07 00:00:00.000000
return_date
2016-08-14 00:00:00.000000
I enter 2016-08-06 and 2016-08-15 in the DatePickers and I am returned all the results.
Could my search form DatePicker be sending data that cannot be correctly compared to the DateTime in the database?
Am I using the 'gteq' and 'lteq' calls correctly?
EDIT #1
@Michael Gaskill, you are correct that the problem is the date formatting. When I enter a date manually, I get the correct search results. I just need to figure out how to correct the formatting before its passed to the controller.
Here is what my controller looks like.
class HomeController < ApplicationController
def index
@search = Sailing.search(params[:q])
@sailings = @search.result
... Other calls ...
end
end
Here is the full piece of code in my view that generates sailings content. Note that I'm using search_for_for which is part of the ransack gem.
<%= search_form_for @search, url: root_path, method: :post do |f| %>
<div class="field">
<%= f.label :cruise_ship_name_or_cruise_ship_company_or_destination_identifier_cont, "Cruise Ship Name" %>
<%= f.text_field :cruise_ship_name_or_cruise_ship_company_or_destination_identifier_cont %>
</div>
<div class="field">
<%= f.label :departure_date_gteq, "Departure Date Between" %>
<%= f.search_field :departure_date_gteq, "data-provide" => "datepicker" %>
<%= f.label :return_date_lteq, "and" %>
<%= f.search_field :return_date_lteq, "data-provide" => "datepicker" %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
Thanks.
A:
You need to convert the string-formatted dates entered in the form (either via the DatePicker or manually-entered) to Date or DateTime values. When you query the database, use this DateTime#strptime to convert:
MyTable.where(date_field_to_search: DateTime.strptime(date_value_from_ui, "%F %T")
You can check out the formats available as the second argument to strptime, using the instructions at DateTime:strftime. Note that strftime and strptime are used to convert back and forth between DateTime and formatted String values.
In your Sailing#search(params[:q]) example, you can either implement the solution in Sailing#search (if you have access to change that code) or prior to calling Sailing.search.
Here is how you might implement this in Sailing#search:
class Sailing
def search(args)
datetime = args[:date_field_to_search]
if datetime.kind_of?(String)
datetime = DateTime.strptime(datetime, "%F %T")
end
# other search functionality
end
end
or, prior to calling Sailing#search:
datetime = params[:q][:date_field_to_search]
if datetime.kind_of?(String)
datetime = DateTime.strptime(datetime, "%F %T")
end
Sailing.search(params[:q].merge({ date_field_to_search: datetime })
| {
"pile_set_name": "StackExchange"
} |
Q:
How to align words backwards in CSS
I'm trying to create a list with a few items. I am using Flexbox and because I want the list in the middle of the screen I use justify-content:center however that puts everything to the center even some things I don't want to, like the headers. Then when I try to use flex-direction:row-reverse it simply won't do what I expect.
Remember that I want the text to be in the center of the screen.
A:
Like the comments suggest, you can simply make use of text-align
.center-div {
width: 200px;
display: block;
margin: 0 auto;
}
.center-text {
text-align: right;
}
<div class="center-div">
<div class="center-text">
Example <br>
Example second <br>
Example third <br>
</div>
</div>
JSFiddle here
| {
"pile_set_name": "StackExchange"
} |
Q:
When to use the abverbial form of maximal: maximally?
Could the following sentence considered to be a correct use case of the adverbial form of the word maximal in English?
Use underflow to set the maximally possible value of used datatype.
When should one use maximal, and when should one use maximally?
A:
In the example you have given, maximum would be the right word:
Use underflow to set the maximum possible value of the data type used.
Maximally is usually found as an adverb that modifies an adjective, such as maximally efficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
The model item passed into the dictionary is of type... ut this dictionary requires a model item of type
I'm new to exploring MVC3 and came up with a problem.
I'm editing my Master view and want the login boxes to be visible on every page when a user isn't logged in. I've done this by using this code:
@if (Request.IsAuthenticated)
{
<text>Welcome <strong>@User.Identity.Name</strong>!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else
{
Html.RenderPartial("../Account/LogOn");
}
This works when going to my normal Index method of the HomeController.
However, when going to the Index method of my NewsController I get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[LeagueSite.Models.News]', but this dictionary requires a model item of type 'LeagueSite.Models.LogOnModel'.
I understand what the problem is but don't really know a sollution for it.
The view LogOn looks like this (standard MVC3 logon view):
@model LeagueSite.Models.LogOnModel
@{
ViewBag.Title = "Log On";
}
<h2>Login</h2>
<p>
Please enter your user name and password. @Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
`
Any tips/ideas?
A:
Quick and dirty: instead of Html.RenderPartial use Html.RenderAction:
Html.RenderAction("LogOn", "Account");
and in the LogOn action of the Account controller ensure to return a PartialView or you will get a stack overflow and Cassini will crash:
public ActionResult LogOn()
{
return PartialView();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the meaning of ぴっと。
Here is the sentence :
1年たったらここんとこをピッとおせばレーダーに反応がでるとおもうわ!
I didn't find any information about ぴっと in the dictionaries I searched in...
A:
It's a sound effect (beep) of a button press. This is a sample from youtube.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cant move an html image and I dont know why
This is my code. I have done the CSS and the HTML code so that this logo image that I have moves to the right.
However, the image remains still. What am I doing wrong?
HTML CODE:
#logo {
width: 200px;
height: 200px;
position: absolute;
top: 0px;
right: 200 px;
border: 25px black;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="template.css">
</head>
<body>
<div id="logo">
<img src="LogoSIEM.PNG" alt="logo" style="width:200px;height:200px">
</div>
</body>
</html>
A:
Change right: 200 px; to right: 200px;
The space before px is invalid, so it doesn't recognize it as being 200px from the right.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need to stream Excel file to web clients
I have a method that converts a SQL query into a DataView and now I'm trying to convert a DataView to an Excel document that can be streamed from an asp.net site.
I've tried generating a .csv file but Excel would mess up the format.
Then tried OpenXML it appears super slow.
I just need to write out some basic table data so it can be modified in Excel and re-imported.
A:
For creating an excel file you could use the Infragistics Excel engine. There is an example of how to create an excel file from a DataTable here: http://help.infragistics.com/NetAdvantage/ASPNET/Current/CLR3.5/?page=ExcelEngine_Populating_a_Worksheet_from_a_DataSet.html
You could then load the data again from the excel file format as well. If you want to test this you could do so with a trial of NetAdvantage for ASP.NET if you don't already have this:
http://www.infragistics.com/dotnet/netadvantage/aspnetdownloads.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
How to apply "quick fix" to multiple errors at once in IntelliJ?
In IntelliJ, pressing Alt+Enter on an error pops up a dialog that shows a fix which gets applied when you press Enter. Is there a way to do that action on multiple errors of the same type in the a file?
A:
First press Alt+Enter, then →, select Fix all 'xxx' problems in File, Enter. Here's what it should look like:
| {
"pile_set_name": "StackExchange"
} |
Q:
Do hard rock singers use distortion effects on their vocals?
I've been wondering how hard rock/metal singers (e.g. Layne Staley, James Hetfield, Dave Grohl) manage to achieve such a 'gritty' sound with their vocals. Do professional rock singers ever use distortion effects to enhance the 'grit', either in concert or when recording? Or would that sound too 'artificial' or 'fake' (or be considered 'cheating')?
If they do use electronic distortion, what sort of equipment would typically be used to achieve the effect? Would they use similar distortion to an electric guitar, or something more specialized?
A:
There are many aspects to hard rock singing, and each singer (hell, each song) has a different approach. I know that even death metal vocalists can do their scary vocals without doctoring them in the studio, and I know some really "clean"-sounding singers have to fix uo the tone in the studio. So it depends a lot.
In hard rock, a lot of the "aggresiveness" of the tone does in fact come from the singer. Particularly, volume and punchiness are all by the singer, along with simply each singer's own vocal differences. Often, microphones themselves lend to the effort by changing the sound a little (even unintentionally). In the studio, they can doctor vocals to sound unintelligible or whatever, but I've never heard of any hard rock singer that didn't sound "hard rock" without using any effects.
Frank Sinatra considered his instrument to be not his voice, but his microphone.
A:
It depends, is the answer. And it also depends on what you call "distortion" - do you mean it in the sense that a guitarist would, or just that the sound is changed?
Microphones are the first potential source of distortion. Sometimes you want a "smooth" mic, but sometimes you want one which puts a bit more "grit" inio the sound. Mics are fairly consistent as they come from the manufacturer, but mics from different manufacturers and of different construction will produce a noticeably different sound.
After that, you have the mic preamp. On solid-state electronics, turning the gain up so that the signal clips (reaches the maximum voltage possible) causes hard edged distortion which can sound pretty nasty. I've used it as an impromptu effect in the past though for someone jacking an electric guitar in directly, but it's not normal.
On valve-based electronics though, for starters they distort everything. Your basic distortion level is higher than on solid-state. However that distortion is initially mostly in even harmonics. As you push the gain up, a valve preamp doesn't go straight into saturation but instead just progressively distorts more, adding more odd harmonics as it gets crunchier. This is more commonly referred to as "overdrive". It's still distortion, but it's under a degree of control, and subjectively it sounds appealing to us.
Mostly a sound engineer would try to keep mic preamps out of this region, and stay within the most linear range of the preamp. The Rolling Stones though famously pushed all their mic inputs into overdrive, because they wanted that sound. Some other recordings used it more by accident, or couldn't get away from it because their gear was inherently not that good (for example, "Louie Louie" by the Kingsmen).
Muse use distortion on vocals as an effect - check their cover of "Feeling Good", amongst others. It's an effect though, not a key part of Matt Bellamy's normal vocal sound.
You certainly can add some in, and if you think it sounds good then fine. But ultimately though it all does have to start with a good voice.
A:
The "gritty" sound in rock singer's voices is their natural voice, albeit a technique that gives the sense of screaming or growling. Something else that should be considered is that there are many hard-rock style singers who are smokers, which can significantly affect a singer's voice.
Note: Increasing your risk for lung cancer is not worth it to achieve a specific sound in your music.
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterate through nested objects to form a string
I have the following array, containing multiple nested objects (the nesting level could be infinite) :
var logicRules = [
{
'operator' : null,
'conditionString' : 'x == y'
},
{
'operator' : 'and',
'conditionString' : 'x > y'
},
{
'operator' : 'or',
'rules' : [
{
'operator' : null,
'conditionString' : 'x <= y'
},
{
'operator' : 'and',
'conditionString' : 'x > y'
},
{
'operator' : 'and',
'rules' : [
{
'operator' : null,
'conditionString' : 'x < y'
},
{
'operator' : 'or',
'conditionString' : 'x != y'
}
]
},
{
'operator' : 'and',
'conditionString' : 'x == y'
}
]
},
{
'operator' : 'and',
'conditionString' : 'x >= y'
}
];
If I perform processCondition(logicRules) (see function below), the goal is to end up with a string like this :
if(x == y && x > y || (x <= y && x > y && (x < y || x != y)) && x >= y){ doSomething(); }
I will later eval() this string. And yes many front-end and back-end precautions are taken to make sure the eval() is safe to execute.
Below is my latest effort to achieve my goal. And yes I'm aware it is completely off in some parts. I just can't figure out how to solve it and it's driving me nuts.
function processCondition(rules){
var fullConditionString = "if(";
_processConditionsRecursive(rules);
function _processConditionsRecursive(logicRules, isGrouped){
var groupedConditionString = (typeof isGrouped != "undefined" && isGrouped) ? "(" : "";
for (var key in logicRules) {
if (logicRules.hasOwnProperty(key)) {
if(typeof logicRules[key].rules != "undefined" && logicRules[key].rules.length){
groupedConditionString += '(' + _processLogicRulesRecursive(logicRules[key].rules, true) + ')';
}else{
groupedConditionString += " " + logicRules[key].conditionString + " ";
}
}
}
groupedConditionString += (typeof isGrouped != "undefined" && isGrouped) ? ")" : "";
fullConditionString += groupedConditionString;
return groupedConditionString;
}
fullConditionString += '){ doSomething(); }';
return fullConditionString;
}
(!) I can do the operator separation myself no problem. Right now I'm mostly just worried about grouping conditions in brackets.
Thank you so very much!
A:
You could do this using recursive function with reduce method.
var rules = [{"operator":null,"conditionString":"x == y"},{"operator":"and","conditionString":"x > y"},{"operator":"or","rules":[{"operator":null,"conditionString":"x <= y"},{"operator":"and","conditionString":"x > y"},{"operator":"and","rules":[{"operator":null,"conditionString":"x < y"},{"operator":"or","conditionString":"x != y"}]},{"operator":"and","conditionString":"x == y"}]},{"operator":"and","conditionString":"x >= y"}]
function process(rules) {
return rules.reduce((r, e, i) => {
let nested = ''
let op = '';
let cond = '';
if (e.rules) {
nested = process(e.rules);
}
if (e.conditionString) {
cond = e.conditionString
}
if(i === 0) op = '';
else if (e.operator === 'and') op = '&&';
else if (e.operator === 'or') op = '||';
r += (op ? ` ${op} ` : '') + cond + (nested ? `(${nested})` : '')
return r;
}, '')
}
const result = process(rules);
console.log(result)
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery get next input element value in
I have some piece of an html table which reads like
<table>
<tr>
<td>
<input type="text" class="myclass" name="first_ele[]" value="100" />
</td>
<td>
<input type="text" class="anotherclass" name="secon_ele[]" value="" />
</td>
</tr>
</table>
I have a piece of jquery that will get the value of the element that contains class "myclass" on keyup and I am getting the proper value.
I need to get the value of the next input element.
FYI , The table gets rows added dynamically.
My issue is I don't know how to point to the next available input element.
my jquery to get the element which has the class "myclass" is as follows.
$('.tInputd').keyup(function(){
var disc = $(this).val();
});
your help is greatly appreciated.
A:
Try
$('.myclass').on('keyup', function () {
var disc = $(this).closest('td').next().find('input').val();
});
or
$('.myclass').on('keyup', function () {
var disc = $('.anotherclass').val();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript for loop skips last element
i have array from which am deleting certain elements on base of certain conditions and when i delete element i restart for loop because index is refreshed.
var k;
for( k=0 ; k < this.j_data.length;k++){
if(condition === true){
this.j_data.splice(k, 1);
k = 0; // restart
}
}
my array this.j_data have two element both should be deleted by splice however after first element deleted , the last one is skipped by loop.
any idea what am missing
A:
thanks to @Jaromanda X
k++ occur first so k=-1 fix the issue
var k;
for( k=0 ; k < this.j_data.length;k++){
if(condition === true){
this.j_data.splice(k, 1);
k = -1; // restart
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to know what made a behavior change?
I'm writing a network description for a a listbox logic.
It's really simple: I have a behavior for the (Maybe) current selected item, and I want it so that whenever the user adds a new item to the list, the current selected item will select the just-created value.
It's also possible for the user to remove items from the list, and cause various of other changes, so I have to know when a new item is created; I can't just select the last item on every change.
I don't really have any code to show for it because all my speculations on what to do can't even be written with the API*, but I have the context of Frameworks t and (simplified):
bDb :: Behavior t [Entry] -- Created with accumB.
bSelected :: Behavior t (Maybe Entry) -- Created with accumB.
eAddEntry :: Event t () -- User clicked an add button. Created with fromAddHandler.
* Well, I did think about using eAddEntry to select the last entry, but that's so bad and even if it will work it's just a race between the adding of new item and the selecting of it.
How can I go about it?
A:
I gave Cactus's suggestion in the comments a try, and it turns out it couldn't been done (I'd have to bind changes in the middle of let block where the selection behavior, and the list behavior is, but they depend on each other).
So I decided to start again from scratch but over-do it this time, and wrap the entire state in it's own data-type which the network will merely drive. So really all the network will do is call functions on the network according to events, and that's it. It turned out much superior imo, because there's no applicative-style mess, all the functionality is really just simple functions, and it's more modular (I could decide to just not use FRP at all for example, and the changes would be extremely minor -- just switch the firing with the functions; although I'd still have to find where to put the state, which would probably be something impure like IORef).
It's so clean, it looks something similar to this:
data DbState = DbState Database SelectedItem LastAction Etc Etc
emptyState :: DbState
stateRemove, stateAdd :: DbState -> DbState
and the behavior is just:
let bDb = accumB emptyState $ unions
[stateAdd <$ eAddEntry
,stateRemove <$ eRemoveEntry
]
Prior, I had length lines filled with lambdas, <$>, <*>, etc. all over.
And now I just rectimate' and see the changes through that LastAction.
I also added error-checking extremely trivially like that.
| {
"pile_set_name": "StackExchange"
} |
Q:
BigDecimal Substract with negative result
I have this code:
public BigDecimal getDifference() {
BigDecimal total = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_DOWN);
for (Order order : orders) {
BigDecimal originalCost= order.getOriginalValue();
BigDecimal nweCost= order.getNewValue();
BigDecimal diff = newValue.substract(originalValue);
total.add(diff);
}
return total;
}
I am testing with originalCost > newCost but total is always 0. I took a snapshot of the debugger at the line total.add(diff):
Does anybody know what I am doing wrong?
Thanks.
A:
total = total.add(diff);
Immutable type, like String.
Some IDEs give a warning.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional formatting based on a value, if value is found then format all the column
I have this table on excel that I would like to color when the value "do" is found... The "hard part" (for me) is to color also the rows that are under that value, untile row n.39
Here is a picture of my current table:
Here is the code I used to create the Table so far...
Sub FillCal()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim contatore As Integer
contatatore = -1
Dim StartD As Date, EndD As Date
Dim prova As Integer
Dim rngMerge As Range, rngCell As Range, mergeVal As Range
Dim i As Integer
Dim wks As Worksheet
Dim GiornoSingolo As String
Set wks = ThisWorkbook.Sheets("Foglio1") ' Change Sheet1 to your worksheet
Worksheets("Foglio1").Range("D2:XZ39").Clear
strInterval = "d"
StartD = Foglio1.Cells(2, 2)
EndD = Foglio1.Cells(3, 2)
For Row = 4 To EndD - StartD
'Cells(4, Row) = Format(StartD + Row - 1, "d mmmm yyyy")
contatore = DatePart(strInterval, StartD + Row - 1)
Cells(3, Row).NumberFormat = 0
Cells(3, Row).Value = contatore
Cells(3, Row).VerticalAlignment = xlCenter
Cells(3, Row).HorizontalAlignment = xlCenter
Cells(3, Row).BorderAround ColorIndex:=1
GiornoSingolo = Format(StartD + Row - 1, "ddd")
prova = Application.WorksheetFunction.WeekNum(StartD + Row - 1, 2)
'Cells(6, Row).NumberFormat = 0
Cells(4, Row) = Left(GiornoSingolo, 2)
Cells(4, Row).VerticalAlignment = xlCenter
Cells(4, Row).HorizontalAlignment = xlCenter
Cells(4, Row).BorderAround ColorIndex:=1
'GiornoSingolo = Left(StartD + Row - 1, "ddd")
'GiornoSingolo = Left(Text(StartD + Row - 1, "ddd"), 1)
'Cells(6, Row) = Left(StartD + Row - 1, "DDD")
Cells(2, Row) = Format(StartD + Row - 1, "MMMM' yy")
Cells(2, Row).BorderAround ColorIndex:=1
Cells(5, Row).BorderAround ColorIndex:=1
Cells(6, Row).BorderAround ColorIndex:=1
Cells(7, Row).BorderAround ColorIndex:=1
Cells(8, Row).BorderAround ColorIndex:=1
Cells(9, Row).BorderAround ColorIndex:=1
Cells(10, Row).BorderAround ColorIndex:=1
Cells(11, Row).BorderAround ColorIndex:=1
Cells(12, Row).BorderAround ColorIndex:=1
Cells(13, Row).BorderAround ColorIndex:=1
Cells(14, Row).BorderAround ColorIndex:=1
Cells(15, Row).BorderAround ColorIndex:=1
Cells(16, Row).BorderAround ColorIndex:=1
Cells(17, Row).BorderAround ColorIndex:=1
Cells(18, Row).BorderAround ColorIndex:=1
Cells(19, Row).BorderAround ColorIndex:=1
Cells(20, Row).BorderAround ColorIndex:=1
Cells(21, Row).BorderAround ColorIndex:=1
Cells(22, Row).BorderAround ColorIndex:=1
Cells(23, Row).BorderAround ColorIndex:=1
Cells(24, Row).BorderAround ColorIndex:=1
Cells(25, Row).BorderAround ColorIndex:=1
Cells(26, Row).BorderAround ColorIndex:=1
Cells(27, Row).BorderAround ColorIndex:=1
Cells(28, Row).BorderAround ColorIndex:=1
Cells(29, Row).BorderAround ColorIndex:=1
Cells(30, Row).BorderAround ColorIndex:=1
Cells(31, Row).BorderAround ColorIndex:=1
Cells(32, Row).BorderAround ColorIndex:=1
Cells(33, Row).BorderAround ColorIndex:=1
Cells(34, Row).BorderAround ColorIndex:=1
Cells(35, Row).BorderAround ColorIndex:=1
Cells(36, Row).BorderAround ColorIndex:=1
Cells(37, Row).BorderAround ColorIndex:=1
Cells(38, Row).BorderAround ColorIndex:=1
Cells(39, Row).BorderAround ColorIndex:=1
Next Row
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Here is the output :
A:
You can use this code (I used a (for loop) for a better coding experience ) :
Sub FillCal()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim contatore As Integer
contatatore = -1
Dim StartD As Date, EndD As Date
Dim prova As Integer
Dim rngMerge As Range, rngCell As Range, mergeVal As Range
Dim i As Integer
Dim wks As Worksheet
Dim GiornoSingolo As String
Set wks = ThisWorkbook.Sheets("Foglio1") ' Change Sheet1 to your worksheet
Worksheets("Foglio1").Range("D2:XZ39").Clear
strInterval = "d"
StartD = Worksheets("Foglio1").Cells(2, 2)
EndD = Worksheets("Foglio1").Cells(3, 2)
For Row = 4 To EndD - StartD
'Cells(4, Row) = Format(StartD + Row - 1, "d mmmm yyyy")
contatore = DatePart(strInterval, StartD + Row - 1)
Cells(3, Row).NumberFormat = 0
Cells(3, Row).Value = contatore
Cells(3, Row).VerticalAlignment = xlCenter
Cells(3, Row).HorizontalAlignment = xlCenter
Cells(3, Row).BorderAround ColorIndex:=1
GiornoSingolo = Format(StartD + Row - 1, "ddd")
prova = Application.WorksheetFunction.WeekNum(StartD + Row - 1, 2)
'Cells(6, Row).NumberFormat = 0
Cells(4, Row) = Left(GiornoSingolo, 2)
Cells(4, Row).VerticalAlignment = xlCenter
Cells(4, Row).HorizontalAlignment = xlCenter
Cells(4, Row).BorderAround ColorIndex:=1
'GiornoSingolo = Left(StartD + Row - 1, "ddd")
'GiornoSingolo = Left(Text(StartD + Row - 1, "ddd"), 1)
'Cells(6, Row) = Left(StartD + Row - 1, "DDD")
Cells(2, Row) = Format(StartD + Row - 1, "MMMM' yy")
For ii = 2 To 39
Cells(ii, Row).BorderAround ColorIndex:=1
Next ii
If Cells(4, Row).Text = "do" Then
For i = 4 To 39
Cells(i, Row).Interior.ColorIndex = 9
Next i
End If
Next Row
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Find distance from point to line in not standart coordinate system
I have point $M(0,0,0)$ and line
$$x=3t-7$$
$$y=-2t+4$$
$$z=3t+4$$
$e_1=(x_1,y_1,z_1),e_2=(x_2,y_2,z_2),e_3=(x_3,y_3,z_3)$ - our basis vectors, and
$e_i*e_j=g_{ij}$
$$g_{11}=g_{22}=g_{33}=2;$$
$$g_{12}=1;g_{23}=1;g_{13}=0 $$
How to find distance from given point to given line?
Well, at first we know that $|e_1|=|e_2|=|e_3|=\sqrt2$. Also we know that $e_1*e_3=0=>e1$ is perpendicular to $e_3$. And using formula
$$cos\alpha=\frac{e_i*e_j}{|e_i|*|e_j|}$$
We can find angles between vectos. Finally, we have the system
$$x_1x_2+y_1y_2+z_1z_2=1$$
$$x_2x_3+y_2y_3+z_2z_3=1$$
$$x_1x_3+y_1y_3+z_1z_3=0$$
I have no idea what should I do or use next. Have any thoughts?
A:
If you write the coordinates of a point as $(x_1,x_2,x_3)$, then the square of its distance from the origin using the given metric is $$\sum_{\lambda=0}^3\sum_{\mu=0}^3 g_{\lambda\mu} x_\lambda x_\mu = 2(x_1^2+x_1x_2+x_2^2+x_2x_3+x_3^3).†$$ Plug in the coordinates of an arbitrary point on the line to get the distance squared as a function of $t$ and minimize (and don’t forget to take the square root at the end).
You can also do this without using calculus. The line can be expressed as $(-7,4,4)^T+t(3,-2,3)^T$, so if you translate by $(7,-4,-4)^T$ so that the line passes through the origin, the problem is equivalent to finding the distance from this point to the translated line. This is a matter of computing the orthogonal rejection of $\mathbf p$ from the direction vector $\mathbf v=(3,-2,3)^T$ of the line, using the inner product induced by $g$: $$\mathbf p_\perp = \mathbf p - {\mathbf p^T G \mathbf v \over \mathbf v^T G \mathbf v}\mathbf v$$ and the distance is then $$\sqrt{\mathbf p_\perp^T G \mathbf p_\perp}.$$ Here, $G$ represents the matrix with entries given by the components $g_{\lambda\mu}$ of the metric.
† You might also see this written more simply as $g_{\lambda\mu}x^\lambda x^\mu$, where the coordinates use superscripts instead of subscripts and the Einstein summation convention is in force.
| {
"pile_set_name": "StackExchange"
} |
Q:
Combining multiple Django templates in a single request
I am wondering if someone can help me figure out the best approach to the following problem. I'm building a web application which uses Django templating to construct its web UI component. There are a number of common HTML elements such as the header / footer, HTML head, masthead etc. I'd like to code these once and "include/combine" them with other templates representing the core application functionality.
Is this possible using Django Templates? If so how might I go about accomplishing that?
A:
You can use django's extends tag. Say you had a header and footer. You could make a template, called, say, foo.django:
<h1>My HTML Header</h1>
<!-- an so on -->
{% block content %}
{% endblock %}
<!-- html footer -->
Then, you can make another template, say, bar.django:
{% extends "foo.django" %}
{% block content %}
This overrides the content block in foo.django.
{% endblock %}
...which will then render:
<h1>My HTML Header</h1>
<!-- an so on -->
This overrides the content block in foo.django.
<!-- html footer -->
There's good instructions on django templates at http://www.djangobook.com/en/1.0/chapter04/.
A:
The {% extends %} and {% include %} methods are good for page elements which don't need extra information in the context.
As soon as you need to insert more stuff into the context from the database, template tags come handy. As an example, the contrib.comments app included with Django defines a {% get_comment_list %} template tag for retrieving comments attached to a given model instance. Here's how you would use it:
<div>
{% load comments %}
{% get_comment_list for my_instance as comment_list %}
{% for comment in comment_list %}
<p><a href="{{ comment.url }}">{{ comment.name }}</a> wrote:</p>
{{ comment.comment }}
{% endfor %}
</div>
You could save this in a separate template and {% include %} it in other templates.
For your own content you can write your own custom template tags. Follow the documentation. Whenever possible, it's convenient to write tags using the simple tag mechanism. You'll find handy ready-made template tags on djangosnippets.org and the blogosphere.
A:
Try the {% include %} tag.
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include
| {
"pile_set_name": "StackExchange"
} |
Q:
How to receive multiple JSON object and an Uri Parameter in WebAPI Controller
I came over the following scenario when trying out ASP.NET Web API2. I have a WebAPI2 Controller:
[HttpPost]
[Route("api/service/receiver/{date}")]
public IHttpActionResult receiver([FromUri] string date, [FromBody List<car> cars)
}
Now I can call this with the following jQuery:
<script>
var carsData = [{ "model": "Audi" }, { "model": "BMW" }, { "model": "Audi" }];
var uri = 'api/service/receiver/20180107';
$.ajax({
type: "POST",
url: uri,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(carsData),
dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
</script>
This works fine, but I have no clue how to post multiple complex Objects or maybe a complex JSON object and multiple additional parameters.
I tried:
[HttpPost]
[Route("api/service/receiver/{date}")]
public IHttpActionResult receiver([FromUri] string date, [FromBody List<car> cars, [FromBody] List<company> companies)
}
and also
[HttpPost]
[Route("api/service/receiver/{date}")]
public IHttpActionResult receiver([FromUri] string date, [FromBody List<car> cars, string company)
}
and then in the jQuery Call I changed the data line
data: JSON.stringify({ cars: carsData, companies: compData }),
and also to
data: JSON.stringify({ cars: carsData, company: "theCompany" }),
But then i receive a 404 or null. How can this be done?
A:
First of, "FromBody" refers to from the body of the HTTP request. Basically, the body of the received request is taken and converted into an object (by default by deserializing JSON). MVC.NET will take the entire body and make an object. This is the reason you can't have two [FromBody].
Based on your jQuery, what you are trying to do is pass { cars: carsData, companies: compData } and { cars: carsData, company: "theCompany" } both of which entire objects sent as the body. Each of these objects have two properties (cars and companies) and (cars and company) respectively. Since you are passing these as whole objects to the body, MVC will need to deserialize the body into an entire string as well.
You will have to make a new class:
class MyCarData {
public List<car> cars { get; set; }
public List<company> companies { get; set; }
}
You can then use [FromBody] MyCarData in your controller to access it as a whole.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enumerate members of COM object in C#?
I connect to some program via COM and receive System.__ComObject. I know several methods of it, so I can do like this:
object result = obj.GetType().InvokeMember("SomeMethod", BindingFlags.InvokeMethod, null, obj, new object[] { "Some string" });
and like this
dynamic dyn = obj;
dyn.SomeMethod("Some string");
Both methods works fine. But how can I determine inner type information of com object and enumerate through all its members?
I tried this:
[ComImport, Guid("00020400-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDispatch
{
void Reserved();
[PreserveSig]
int GetTypeInfo(uint nInfo, int lcid, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(TypeToTypeInfoMarshaler))] out System.Type typeInfo);
}
...
IDispatch disp = (IDispatch)obj;
Type t;
disp.GetTypeInfo(0, 0, out t);
But the t is null at the end. Can anyone help me?
A:
I've just published a CodeProject article about how to do Reflection with IDispatch-based COM objects. The article provides a small C# DispatchUtility helper class that's easy to include in other projects. Internally, it uses a custom declaration of IDispatch and .NET's TypeToTypeInfoMarshaler to convert IDispatch's ITypeInfo into a rich .NET Type instance.
In your example, you could call DispatchUtility.GetType(obj, true) to get back a .NET Type instance, which you could then call GetMembers on.
FWIW, DispatchUtility's declaration of IDispatch.GetTypeInfo is nearly identical to yours. However, when calling GetTypeInfo, it passes in LOCALE_SYSTEM_DEFAULT (2048) rather than 0 for the lcid parameter. Perhaps GetTypeInfo returned a failure HRESULT for your disp.GetTypeInfo(0, 0, out t) call. Since you declared it with [PreserveSig], you'd need to check its result (e.g., by calling Marshal.ThrowExceptionForHR).
Here's a version of the DispatchUtility class with most comments removed:
using System;
using System.Runtime.InteropServices;
using System.Reflection;
public static class DispatchUtility
{
private const int S_OK = 0; //From WinError.h
private const int LOCALE_SYSTEM_DEFAULT = 2 << 10; //From WinNT.h == 2048 == 0x800
public static bool ImplementsIDispatch(object obj)
{
bool result = obj is IDispatchInfo;
return result;
}
public static Type GetType(object obj, bool throwIfNotFound)
{
RequireReference(obj, "obj");
Type result = GetType((IDispatchInfo)obj, throwIfNotFound);
return result;
}
public static bool TryGetDispId(object obj, string name, out int dispId)
{
RequireReference(obj, "obj");
bool result = TryGetDispId((IDispatchInfo)obj, name, out dispId);
return result;
}
public static object Invoke(object obj, int dispId, object[] args)
{
string memberName = "[DispId=" + dispId + "]";
object result = Invoke(obj, memberName, args);
return result;
}
public static object Invoke(object obj, string memberName, object[] args)
{
RequireReference(obj, "obj");
Type type = obj.GetType();
object result = type.InvokeMember(memberName,
BindingFlags.InvokeMethod | BindingFlags.GetProperty,
null, obj, args, null);
return result;
}
private static void RequireReference<T>(T value, string name) where T : class
{
if (value == null)
{
throw new ArgumentNullException(name);
}
}
private static Type GetType(IDispatchInfo dispatch, bool throwIfNotFound)
{
RequireReference(dispatch, "dispatch");
Type result = null;
int typeInfoCount;
int hr = dispatch.GetTypeInfoCount(out typeInfoCount);
if (hr == S_OK && typeInfoCount > 0)
{
dispatch.GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, out result);
}
if (result == null && throwIfNotFound)
{
// If the GetTypeInfoCount called failed, throw an exception for that.
Marshal.ThrowExceptionForHR(hr);
// Otherwise, throw the same exception that Type.GetType would throw.
throw new TypeLoadException();
}
return result;
}
private static bool TryGetDispId(IDispatchInfo dispatch, string name, out int dispId)
{
RequireReference(dispatch, "dispatch");
RequireReference(name, "name");
bool result = false;
Guid iidNull = Guid.Empty;
int hr = dispatch.GetDispId(ref iidNull, ref name, 1, LOCALE_SYSTEM_DEFAULT, out dispId);
const int DISP_E_UNKNOWNNAME = unchecked((int)0x80020006); //From WinError.h
const int DISPID_UNKNOWN = -1; //From OAIdl.idl
if (hr == S_OK)
{
result = true;
}
else if (hr == DISP_E_UNKNOWNNAME && dispId == DISPID_UNKNOWN)
{
result = false;
}
else
{
Marshal.ThrowExceptionForHR(hr);
}
return result;
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00020400-0000-0000-C000-000000000046")]
private interface IDispatchInfo
{
[PreserveSig]
int GetTypeInfoCount(out int typeInfoCount);
void GetTypeInfo(int typeInfoIndex, int lcid, [MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(System.Runtime.InteropServices.CustomMarshalers.TypeToTypeInfoMarshaler))] out Type typeInfo);
[PreserveSig]
int GetDispId(ref Guid riid, ref string name, int nameCount, int lcid, out int dispId);
// NOTE: The real IDispatch also has an Invoke method next, but we don't need it.
}
}
A:
You cannot get a Type for the COM object. That would require you creating an interop library for the COM component. Which is certainly the low pain point if the COM server has a type library, just add a reference to it or run the Tlbimp.exe utility. If it is present then the type library is usually embedded inside the DLL. When you got that, both the editor and the Object Browser get a lot smarter about the method and properties available on the COM class.
Seeing the IDispatch cast work makes it quite likely that a type library is available as well. It is pretty trivial for the COM server author to create one. Another tool you can use to peek at the type library is OleView.exe, View + Typelib.
If that doesn't work then you can indeed dig stuff out of IDispatch. Your declaration looks fishy, the 3rd argument for IDispatch::GetTypeInfo is ITypeInfo, a COM interface. No need for a custom marshaller, ITypeInfo is available in the System.Runtime.InteropServices.ComTypes namespace. You can dig the IDispatch declaration out of the framework code with Reflector.
And of course, there's no substitute for decent documentation. You should be able to get some when you got a license to use this component.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a selected option in AngularJs
I have spent hours on this script, I want to output the text and not the value of a select option in angularjs in html by data binding, but when I try I'm alway getting the value and not the text. How can I accomplish this. Here is the Fiddle
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.typeofwritings = [{
value: '5',
text: 'Writing from scratch'
}, {
value: '3',
text: 'Editing or Proofreading'
}
];
$scope.type_writing = $scope.typeofwritings[0].value;
$scope.pieces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
$scope.piece = 1;
$scope.calculate = function(){
$scope.calculation = ($scope.piece * $scope.type_writing);
}
$scope.calculate();
}]);
})(window.angular);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Return selected input in Angular Js</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="app.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" novalidate action="formsubmitted.php" method="post">
<table width="465" border="0">
<tbody>
<tr>
<td width="186"><label for="type_writing">Type of Writing:</label></td>
<td width="269"><select ng-change="calculate()" ng-model="type_writing" ng-options="o.value as o.text for o in typeofwritings" ng-init="type_writing='5'" name="type_writing" id="type_writing">
</select>
</td>
</tr>
<tr>
<td><label for="num_pieces">Number of Pieces:</label></td>
<td><select ng-change="calculate()" ng-model="piece" ng-options="o as o for o in pieces" name="num_pieces" id="num_pieces"></select></td>
</tr>
<tr>
<td> </td>
<td><strong>Order Cost</strong> For <strong>{{type_writing}}</strong> with <strong>{{piece}}</strong> pages<div style="color:#D76D25; font-size:24px;">${{calculation}}</div></td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
A:
Here is your solution, you should properly define your ng-options
Fiddle: https://jsfiddle.net/4zj4a9z7/2/
<title>Return selected input in Angular Js</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="app.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" novalidate action="formsubmitted.php" method="post">
<table width="465" border="0">
<tbody>
<tr>
<td width="186"><label for="type_writing">Type of Writing:</label></td>
<td width="269"><select ng-change="calculate()" ng-model="type_writing" ng-options="o as o.text for o in typeofwritings" ng-init="type_writing='5'" name="type_writing" id="type_writing">
</select>
</td>
</tr>
<tr>
<td><label for="num_pieces">Number of Pieces:</label></td>
<td><select ng-change="calculate()" ng-model="piece" ng-options="o as o for o in pieces" name="num_pieces" id="num_pieces"></select></td>
</tr>
<tr>
<td> </td>
<td><strong>Order Cost</strong> For <strong>{{type_writing.text}}</strong> with <strong>{{piece}}</strong> pages<div style="color:#D76D25; font-size:24px;">${{calculation}}</div></td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
<script>
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.typeofwritings = [{
value: '5',
text: 'Writing from scratch'
}, {
value: '3',
text: 'Editing or Proofreading'
}
];
$scope.type_writing = $scope.typeofwritings[0].value;
$scope.pieces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
$scope.piece = 1;
$scope.calculate = function(){
$scope.calculation = ($scope.piece * $scope.type_writing.value);
}
$scope.calculate();
}]);
})(window.angular);
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Rlang: find the data pronoun in a set of quosures
I have a set of quosures which are being used to generate sets of summary statistics using dplyr.
I want to know which data columns are being used.
The data columns are prefixed by .data[["ColumnName"]].
So for example we have:
my_quos <- rlang::list2(
"GenderD" = rlang::quo(length(.data[["TeamCode"]])),
"GenderMaleN" = rlang::quo(.data[["S1IsMale"]])
)
I've started tackling this problem by using rlang::call_args() to break a command up into its components:
my_args_test <- rlang::call_args(my_quos[[1]])
str(my_args_test)
List of 1
$ : language .data[["TeamCode"]]
The columns should all be sat as data pronouns. Is there a quick way to check if the item within the list is a data pronoun? I had tried:
is(my_args_test[[1]], "rlang_data_pronoun")
But this returns false. Checking the string as text beginning with .data[[ might be an option I guess (but I suspect that is more fallible).
Also is there a way to cleanly return the parameter passed to the data pronoun rather than parsing the string? In other words the goal is to ideally return our output to be:
c("TeamCode", "S1IsMale")
From the original my_quos.
A:
This can be done in two steps. First, you want to extract expressions captured by your quosures and convert them to Abstract Syntax Trees (ASTs).
## Recursively constructs Abstract Syntax Tree for a given expression
getAST <- function( ee ) { as.list(ee) %>% purrr::map_if(is.call, getAST) }
## Apply function to expressions captured by each quosure
asts <- purrr::map( my_quos, quo_get_expr ) %>% purrr::map( getAST )
str(asts)
# List of 2
# $ GenderD :List of 2
# ..$ : symbol length
# ..$ :List of 3
# .. ..$ : symbol [[
# .. ..$ : symbol .data
# .. ..$ : chr "TeamCode"
# $ GenderMaleN:List of 3
# ..$ : symbol [[
# ..$ : symbol .data
# ..$ : chr "S1IsMale"
From here, we see that the pattern matching .data[["somename"]] is a length-3 list where the first entry is [[, the second entry is .data and the last entry is what you're trying to extract. Let's write a function that recognizes this pattern and returns the third element upon recognition (NOTE: this function shows how to match an item against .data pronoun, which was your other question):
## If the input matches .data[["name"]], returns "name". Otherwise, NULL
getName <- function( x )
{
if( is.list(x) && length(x) == 3 && ## It's a length-3 list
identical( x[[1]], quote(`[[`) ) && ## with [[ as the first element
identical( x[[2]], quote(.data) ) && ## .data as the second element
is.character(x[[3]]) ) return(x[[3]]) ## and a character string as 3rd
NULL
}
Given this function, the second step is simply to apply it recursively to your list of ASTs to extract column names used.
getNames <- function( aa ) {
purrr::keep(aa, is.list) %>%
purrr::map(getNames) %>% ## Recurse to any list descendants
c( getName(aa) ) %>% ## Append self to the result
unlist ## Return as character vector, not list
}
getNames(asts)
# GenderD GenderMaleN
# "TeamCode" "S1IsMale"
| {
"pile_set_name": "StackExchange"
} |
Q:
What are materialized views?
Can someone explain to me what views or materialized views are in plain everyday English please? I've been reading about materialized views but I don't understand.
A:
Sure.
A normal view is a query that defines a virtual table -- you don't actually have the data sitting in the table, you create it on the fly by executing.
A materialized view is a view where the query gets run and the data gets saved in an actual table.
The data in the materialized view gets refreshed when you tell it to.
A couple use cases:
We have multiple Oracle instances where we want to have the master data on one instance, and a reasonably current copy of the data on the other instances. We don't want to assume that the database links between them will always be up and operating. So we set up materialized views on the other instances, with queries like select a,b,c from mytable@master and tell them to refresh daily.
Materialized views are also useful in query rewrite. Let's say you have a fact table in a data warehouse with every book ever borrowed from a library, with dates and borrowers. And that staff regularly want to know how many times a book has been borrowed. Then build a materialized view as select book_id, book_name, count(*) as borrowings from book_trans group by book_id, book_name, set it for whatever update frequency you want -- usually the update frequency for the warehouse itself. Now if somebody runs a query like that for a particular book against the book_trans table, the query rewrite capability in Oracle will be smart enough to look at the materialized view rather than walking through the millions of rows in book_trans.
Usually, you're building materialized views for performance and stability reasons -- flaky networks, or doing long queries off hours.
A:
A view is basically a "named" SQL statement. You can reference views in your queries much like a real table. When accessing the view, the query behind the view is executed.
For example:
create view my_counter_view(num_rows) as
select count(*)
from gazillion_row_table;
select num_rows from my_counter_view;
Views can be used for many purposes such as providing a simpler data model, implement security constraints, SQL query re-use, workaround for SQL short comings.
A materialized view is a view where the query has been executed and the results has been stored as a physical table. You can reference a materialized view in your code much like a real table. In fact, it is a real table that you can index, declare constraints etc.
When accessing a materialized view, you are accessing the pre-computed results. You are NOT executing the underlaying query. There are several strategies for how to keeping the materialized view up-to-date. You will find them all in the documentation.
Materialized views are rarely referenced directly in queries. The point is to let the optimizer use "Query Rewrite" mechanics to internally rewrite a query such as the COUNT(*) example above to a query on the precomputed table. This is extremely powerful as you don't need to change the original code.
There are many uses for materialied views, but they are mostly used for performance reasons. Other uses are: Replication, complicated constraint checking, workarounds for deficiencies in the optimizer.
Long version: -> Oracle documentation
| {
"pile_set_name": "StackExchange"
} |
Q:
Ignore all folders but one
I read many posts from StackOverflow about this, but I can't get it working in my case.
I would like to ignore all directories except for one.
I added something like this to my .gitignore:
app/design/frontend/base/default/template/
!app/design/frontend/base/default/template/mymodule/
but it looks like the negation doesn't work at all.
There are many subfolders under the path app/design/frontend/base/default/template/, and within the app/design/frontend/base/default/template/mymodule folder there are some files if it makes any difference.
Can somebody tell me what I'm doing wrong here?
A:
Put the whitelist item on top of the ignore item:
!app/design/frontend/base/default/template/mymodule/
app/design/frontend/base/default/template/
If that still doesn't work, you may have to include the template directory itself, but ignore all files beneath it except mymodule:
app/design/frontend/base/default/template/*
!app/design/frontend/base/default/template/mymodule/
For more information, see the gitignore man page.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the look and feel of exposed filters in a block
I have view which has exposed filters. I have configured those filters to block.
But now I want to change the look and feel of the exposed filters .
How to do this.
A:
If you want more control over your exposed form template, you an write a template file for it. This article will help you to define template file.
Otherwise you can change the appearance with css, And you can use form alter in case of alter any elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write the set of all natural numbers, that can be divided by two?
I would like to write as a mathematical expression such sentence:
x is the set of all natural numbers that can be divided by 2 without the remainder.
$\{x \in \mathbb N: What \ here? \} $
Thanks in advance,
Regards,
Misery
A:
A very typical shorthand when writing the set of natural numbers divisible by $a$ is to write $a\mathbb N = \{an \in \mathbb N\;|\; n \in \mathbb N\}$. Clearly every natural number of the form $an$ where $n\in \mathbb N$ is divisible by $a$ and every such number arises in this way. This follows the usual notation for cosets.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the remaining area of equilateral triangle if 3 circle sectors of radius R1, R2, R3 are given.
An equilateral triangle of side length $S$ is given. and from the three corners of the triangle, three circle sector is being drawn which has a radius of $R_1$, $R_2$, $R_3$. Find the area of the triangle which is not covered by any of these circle sectors.
So if
$R_1+R_2 < S$ and $R_2+R_3 < S$ and $R_3+R_1 < S$
then
we can find the circle sector area using formula and then we can subtract it from triangle area to get the answer. but I'm stuck at the point where these sectors intersect/overlap! how to get the answer if the sector intersects/overlaps like the above figure?
A:
Let $V_1,V_2,V_3$ be the vertices of the triangle at which the sectors of radii $R_1,R_2,R_3$, respectively, are centered.
Let $P$ be the point of intersection, inside the triangle, of the sectors with radii $R_2$ and $R_3$. Let $T$ be the point on the side $V_2V_3$ such that $PT$ is perpendicular to $V_2V_3$. Then you can decompose the overlapping area of those two sectors as:
a sector of radius $R_2$ centered at $V_2$, but extending from the side $V_1V_2$ only as far as $P$;
the right triangle $V_2PT$;
a sector of radius $R_3$ centered at $V_3$, but extending from the side $V_1V_3$ only as far as $P$;
the right triangle $V_3PT$.
Once you know the length of $PT$ (which should be possible given $R_2$, $R_3$, and $S$), you will be able to calculate all of these areas.
| {
"pile_set_name": "StackExchange"
} |
Q:
Augmenting data structure for matrix
Given a square matrix of size n (data structure) with operation as follow
read(i,j) returns the element
write(i,j,x) write the new element
initalize() set matrix to zero
and the read and write are performed in (worst case) constant time.
How can I augment it so that the following operations performed in (worst case) constant time?
emptyrow(i) if the ith row is empty then return true
emptycol(j) if the jth col is empty then return true
My first thought is that I don't need to augment. I can simply use a for loop and read(i,j) to get my result, and at worst case will just be constant time n. Am I on the right track or I still need to somehow augment the data structure. Any help is appreciated, thanks.
A:
Consider storing the data structure as an n × n matrix for the entries, plus two extra arrays: a rowCount array counting how many 1s are in each row of the matrix, and a colCount array containing how many 1s are in each column of the array.
To perform an initialize() operation, you create the matrix and the rowCount / colCount arrays and initialize everything to 0. This takes time O(n2). To perform a read(i, j), just read from the matrix in time O(1). To perform a write(i, j, x), write x to position (i, j), and if you changed a 0 to 1 or a 1 to 0, make the appropriate increments/decrements of the rowCount and colCount arrays. This also takes time O(1). Finally, to perform emptyRow(i) or emptyCol(j), just return whether rowCount[i] or colCount[j], respectively, is zero. This also takes time O(1).
You could speed up to construction O(1) if you use hash tables for everything and treat "empty" to mean 0, though you now have average-case O(1) guarantees for the remaining operations rather than worst-case guarantees. Depending on the circumstances, that might be a good trade-off.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sort array with objects on property of objects
I would like to sort an array of objects by a property of the specific object. This is my array with objects:
As you can see I have an array $all_studies with 2 objects. How can I now sort on the graduationYear property of the objects? So I would like to have an array with objects and the the order with object 2010 first, then 2014, ... (in this case the order is already correct but this won't always be the same ..).
This is what I've tried but with no succes:
$all_studies = usort($all_studies, "sort_objects_by_graduationyear");
function sort_objects_by_graduationyear($a, $b) {
if((int)$a->graduationYear == (int)$b->graduationYear){ return 0 ; }
return ($a->graduationYear < $b->graduationYear) ? -1 : 1;
}
But I just get true back. I've never used the usort function so I don't really know how to work with it. Can someone help me?
A:
The function usort returns "true" on success. So, good news :).
If you want to check if the sort is done, you only have to check your $all_studies object after the usort.
$status = usort($all_studies, "sort_objects_by_graduationyear");
print_r($all_studies);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I output the result of a dynamic module to the rest of a notebook?
I have a long-ish code which stores the grey values of an image's pixels in a matrix called data and then does some numerical analysis using those values. At one point in the code, I need to ask the user to select a region of the image to serve as a reference for the analysis of the rest of the image. To do so, I've indexed the pixels (from 1 to rows x cols, which is the number of pixels in the image) and I'm using a dynamic module where the user can draw a polygon on the image and the coordinates of the pixels inside the polygon are stored in a vector; my code for this is a variation of Heike's code here. This is my code for the dynamic module:
points=ConstantArray[0,{rows*cols,2}];
For[j=1,j<=rows,j++,
For[l=1,l<=cols,l++,
points[[(j-1)cols+l,1]]=l;
points[[(j-1)cols+l,2]]=j];];
selection[region_,pt_]:=Round[(
Total@Mod[
(#-RotateRight[#])&@(ArcTan@@(pt-#)&/@region),
2Pi,
-Pi
]/2/Pi
)];
DynamicModule[
{plot, pos},
plot=Legended[
ListDensityPlot[
data,
PlotRange->Full,
ColorFunction->"Rainbow",
ImageSize->Large
],
BarLegend[
{"Rainbow",{Min[data],Max[data]}},
LegendMarkerSize->575
]
];
Manipulate[
pos=Pick[Range[Length[points]],selection[region,#]&/@points,1];
Show[
plot,
Epilog->{
{Transparent,Point[points[[pos]]]},
{Transparent,Point[Complement[points,points[[pos]]]]},
{EdgeForm[Red],FaceForm[{Red,Opacity[0.35]}],Polygon[region]}
}
],
{{region,{}},Locator,LocatorAutoCreate->All},
Row[{
Button["confirm",MANY OPERATIONS GO HERE],
Button["undo",region=Drop[region,-1]],
Button["reset",region={};pos={}]
}]
]
]
Now, pos (the vector where the selected pixels' indices are stored) does not work outside of the dynamic module; if I close the module and then ask Mathematica to tell me what's stored in pos, all I get is pos. Therefore, as you can see, all of the code for the analysis that takes place after the user draws the polygon is inside what the "confirm" button does.
The problem with this approach is that the code is really long and involves many operations and numerical solutions of equations and so on. This is a problem because Mathematica (10.4.1.0) doesn't seem able to handle so many operations inside a dynamic module; it stops without notice after a certain number of operations and throws an "internal error" message on the error-message window.
I've tested the code without the dynamic module (filling pos with an arbitrary amount of arbitrary integers beforehand), and the code works fine. The problem is clearly the dynamic module.
In order to avoid this, I'd like to output the result of the dynamic module (i.e. the numbers stored in pos) to the rest of the code. I thus have two questions:
How do I do this?
How can I a avoid forcing the user to run two separate pieces of code instead of just one? If I write ; after the dynamic module, the module doesn't appear at all; if I don't add it, I don't know how to add code after the dynamic module without starting a new input section.
Thanks a lot in advance.
A:
DynamicModule automatically scopes its variables, so you'll want a top-level symbol that tracks the value. Try this:
DynamicModule[{plot, pos},
plot =
Legended[
ListDensityPlot[data, PlotRange -> Full,
ColorFunction -> "Rainbow", ImageSize -> Large],
BarLegend[{"Rainbow", {Min[data], Max[data]}},
LegendMarkerSize -> 575]];
Manipulate[
$externalPos = pos =
Pick[
Range[Length[points]],
selection[region, #] & /@ points, 1
];
Show[plot,
Epilog -> {{Transparent, Point[points[[pos]]]}, {Transparent,
Point[Complement[points, points[[pos]]]]}, {EdgeForm[Red],
FaceForm[{Red, Opacity[0.35]}],
Polygon[region]}}], {{region, {}}, Locator,
LocatorAutoCreate -> All},
Row[{Button["confirm", MANY OPERATIONS GO HERE],
Button["undo", region = Drop[region, -1]],
Button["reset", region = {}; pos = {}]}]],
Initialization :> (
$externalPos = pos
)]
Where $externalPos is your position list. Note that I have it in the Initialization getting assigned to pos instead of removing pos altogether. That's because DynamicModule will save the state, so we want to preserve that.
One other thing is that I see you're using a For loop. Generally we try to avoid this as For is clunkier than Do or Table. I think you can just replace that with:
points =
Flatten[
Table[
{j, l},
{l, cols},
{j, rows}
],
1
];
| {
"pile_set_name": "StackExchange"
} |
Q:
Alter with custom media field data
I have used the following code to add some custom fields to my media attachment details...
function aj_attachment_field_audio_url( $form_fields, $post ) {
$form_fields['aj-audio-url'] = array(
'label' => 'Audio File URL',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'aj-audio_url', true ),
'helps' => 'Add Audio URL',
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'aj_attachment_field_audio_url', 10, 2 );
function aj_attachment_field_audio_url_save( $post, $attachment ) {
if( isset( $attachment['aj-audio-url'] ) )
update_post_meta( $post['ID'], 'aj_audio_url', esc_url( $attachment['aj-audio-url'] ) );
return $post;
}
add_filter( 'attachment_fields_to_save', 'aj_attachment_field_audio_url_save', 10, 2 );
?>
I'm now lost as to how to alter my img tags to include the new information with a data-audio_url="".
Basically anytime there is an image (added to content wysiwyg) with that field I would like to add that to the img tag.
Any help would be appriciated.
Thanks you
A:
Using get_image_tag() will probably get your where you want. The below is not tested, but should work.
function get_image_tag( $id, $alt, $title, $align, $size ) {
//Getting the meta data
$aj_audio_url = get_post_meta( $id, 'aj_audio_url', true );
//If not empty add the audio_url
if ( ! empty( $aj_audio_url ) ) {
$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . ' data-audio_url="' . $aj_audio_url . '"/>';
return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
}
}
Get more info and examples here:
https://developer.wordpress.org/reference/functions/get_post_meta/
| {
"pile_set_name": "StackExchange"
} |
Q:
Including interface functions in cfc from cfml files on lucee or railo
I'm trying to add a interface to a cfc that includes some functions in a cfml file however it throws a error with the message "component [...] does not implement the function [..] of the interface" the function it's complaining about is implemented in the included cfml file, i've tested this in both railo 4 and lucee 5 and get the same error in both but it works in coldfusion 11 does anyone know if there is a workaround or fix for this in lucee or railo?
Below is example code that reproduces the error.
int.cfc
interface {
public numeric function func() output="false";
}
comp.cfc
component implements="int" {
include "inc.cfm";
}
inc.cfm
<cfscript>
public numeric function func() output="false"{
return 2;
}
</cfscript>
index.cfm
<cfscript>
cfc = createObject("component", "comp");
writedump(cfc.func());
</cfscript>
A:
One possible workaround i've found is to replace the original cfc that includes the cfml file with an empty cfc that implements the interface but also extends the original cfc renamed to something else, by replacing original cfc you can keep the same type while also adding the interface. So the updated parts of the example with the question would look like this
comp-to-extend.cfc
component implements="int" {
include "inc.cfm";
}
comp.cfc
component extends="comp-to-extend" implements="int" {}
| {
"pile_set_name": "StackExchange"
} |
Q:
cordova telephonenumber plugin returns empty string
I'm trying to use the telephonenumber plugin from the following git repository: https://github.com/macdonst/TelephoneNumberPlugin.git and I keep getting an empty string instead of the phone number. there is no error, the success function is called.
I'm using Cordova 3.0, here's the code how I use the plugin:
var telephoneNumber = cordova.require("cordova/plugin/telephonenumber");
telephoneNumber.get(function(result) {alert(result);}, function() {alert("FAILED!");});
and yes, I'm calling it after deviceready event :) I even setup a timer that calls it every few seconds, but all I get is empty string as result. any ideas?
thanks!
A:
Not all the phones can return the phone number, in fact, most of them can't.
Go to settings app, and on the device info there should be a field for the phone number. If the phone number is empty there, there is nothing you can do.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finite-dimensional representations of the integers
Two questions.
How do I find all finite-dimensional linear representations of $\mathbb{Z}$, the additive group of the integers? I know that all finite-dimensional differentiable representations of the reals under addition are given by sending $t$ to $\exp(tA)$ where $A$ is a linear operator on the vector space of given dimension. So I can restrict those representations to the subgroup $\mathbb{Z}$, but are there more?
What about the integers $\mod m$ under addition? How do I find all their finite-dimensional linear representations?
A:
Figuring this out for $\Bbb Z$ is easy because the group $\Bbb Z$ is generated by the single element $1$. In particular, for any representation $\rho:\Bbb Z \to \Bbb C^{n \times n}$, the following holds:
$\rho(1)$ is an invertible matrix
for any $k \in \Bbb Z$, we have
$$
\rho(k) = \rho(k \cdot 1) = \rho(1)^k
$$
Thus, every representation of $\Bbb Z$ can be written in the form
$$
\rho(k) = A^k
$$
where $A$ is an invertible matrix. Moreover, if we can find a matrix $B$ for which $\exp(B) = A$ (which we can, as long as $A$ is invertible), then this becomes
$$
\rho(k) = \exp(kB)
$$
so indeed every representation has the form you mentioned.
$\Bbb Z_m$ also is generated by $1$, but it has the additional property that $m \cdot 1 = 0$. Thus, the representations of $\Bbb Z_m$ are precisely those of the form
$$
\rho(k) = A^k
$$
for which $A^m = I$ ($I$ is the identity matrix). If $C$ is one of the "logarithms of the identity" (i.e. $\exp(C) = I$), then we can get the representation
$$
\rho(k) = [\exp(C/m)]^k = \exp[(k/m)C]
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Emergency plan for Soyuz missions
Recent ISS Cargo delivery via Progress ship was a failure, and it seems that Russian mission control lost the cargo ship completely.
Since Progress ship is basically the same design as Soyuz:
What are the procedures for unlikely event when you lost communication with the ground? Is it better for astronauts and cosmonauts to try to reach ISS manually or go to abort and land?
Assume both variants of "lost communication":
Communication via radio is OK (you can hear the crew), but you cannot upload any commands to on-board computer
Communication is completely silent. Crew does not have any chance of contacting the mission control, but the ship functions "normally" otherwise.
A:
What are the procedures for unlikely event when you lost
communication with the ground? Is it better for astronauts and
cosmonauts to try to reach ISS manually or go to abort and land?
Back in the Apollo days, the astronauts would always have a "PAD" read up to them, hours or even days before any major manoeuvre. For any burn, the ground would read up to them the angles to point the ship, the precise timing and thrust setting (if appropriate). The astronauts would write this down on paper.
That way, if communication was lost, they would always be able to execute the velocity change well enough to carry on.
For present flights to the ISS in low earth orbit, they would launch with all of the required burns known in advance, and I guess they would be able to make their own way if necessary provided the launch went as planned.
(Note however, loss of communication is a different problem to the case of a vehicle spinning out of control, as is happening with the unmanned Progress vehicle.)
EDIT: "PAD", from http://www.hq.nasa.gov/alsj/apollo.glossary.html :
Preliminary Advisory Data: the crew had pre-printed forms on which
they could write lift-off times and other data they would need in the
event that communications was lost with Houston. Before and after each
rest period, the CapCom would read up a list of lift-off times
covering the next 10 to 12 hours and, prior to launch, a longer list
of data was read up.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are there no wheeled animals?
In physics, "almost everything is already discovered, and all that remains is to fill a few unimportant holes." (See Jolly.) Therefore, on Physics SE, people are veering off into different directions: biology, for example.
Thus, it happens that a question about bicycles generates some discussion about evolution in biology and animals with wheels.
Three explanations are offered for the apparent lack of wheely animals (also on Wikipedia, where, by the way, most Physics SE questions are answered perfectly).
Evolutionary constraints: "[A] complex structure or system will not evolve if its incomplete form provides no benefit to an organism."
Developmental and anatomical constraints.
Wheels have significant disadvantages (e.g., when not on roads).
Now, I suggest that all three can be "solved".
With time.
With a symbiotic relationship between a wheel-like animal and a "driver"-like animal, although this gets awfully close to a "driver"-animal to jump onto an actual (man-made) wheel. (So, perhaps, you can suggest a better loophole around this constraint.)
Roads are presumably not the only ecological niche where animals with wheels could thrive. I'm thinking of frozen lakes, although there skates would be better than wheels.
What, therefore, is the explanation for there not being any wheeled animals?
Please consider, in your answer, the counterfactual: What assumption of yours would be falsified once a wheely animal is discovered?
A:
Wheels are possible on the molecular level — bacterial flagella are rotating cores inside a molecular motor, but wheels larger than the flagellum have not really been found.
A single animal with a wheel is an improbable* development that would require a single animal have two separable parts (axle/wheel and body).
[*read as: pretty much impossible]
It's hard to imagine how such a thing could evolve. A wheel and axle would need to be made of living tissue, otherwise it would be vulnerable to wear and tear. Wheels also have problems going over uneven terrain, which is really all terrain animals live in. It's difficult to imagine what sort of selection conditions would be strong enough to push animals away from legs.
If you include driver-vehicle symbionts where the 'car' and 'wheel' are actually two animals, then they have evolved. Parasites can have all sorts of symbiotic control over their victims including as means of transport. The Jewel Wasp is one which is the most suggestive of what you may be thinking. The wasp stings its victim (a cockroach) in the thorax to immobilize the animal and then again just behind its head. After this, the wasp can ride the beetle, steering it by holding its antennae back to its nest where the roach is immobilized to feed the wasp larvae there.
(see section "Pet cockaroaches" in this reference.)
As to the three schools of thought you added to the question, I would probably rather say there were two strong arguments against. The first is whether there is an evolutionary path to wheels (argument 1 in your question), which I doubt. Given even a large amount of evolutionary time you will not see a naked human being able to fly on their own power. Too many structural characteristics of the body plan have been made to all be reversed so that wings or other means of aerial conveyance will show up. The same can be said for wheels when the body plans have fins/legs/and wings already.
Argument 3, which I also tend to agree with, is perhaps more convincing. By the time a pair of animals makes a symbiotic relationship to do this, or a single macroscopic animal evolves wheels, they will literally develop legs and walk away. When life came onto the land this happened, and since then it's happened several times. It's sort of like saying that the random movement of water molecules might line up to run a stream uphill. There's just such a strong path downwards, that the statistical chances of you seeing it happen are nil.
This is a hypothetical case, but arguing this in a convincing way I think you would need to lay out: a) an environment whose conditions created enough of a selective advantage for wheels to evolve over legs or other similar adaptations we already see. Perhaps based on the energy efficiency of wheels; b) some sort of physiological model for the wheels that convey a reasonable lifestyle for the wheel.
There are lots of questions that would need to be satisfied in our thought experiment. Here are some: "the symbiotic wheel would be spinning constantly; if it died the driver creature would be completely defenseless"; "if the ground were bumpy, all these wheeled animals would get eaten"; "the wheel symbiont — how would it eat while its spinning all the time? Only fed by the driver? Even symbionts such as barnacles or lampreys on the flanks of sharks still have their own ability to feed."
For many similar questions the same sort of discussion ensues where there are many disadvantages which outweigh advantages for animals. e.g.
"why are all the flying animals and fish and plants even more similar to airplanes than helicopters?"
Sorry if I seem negative, but way back in grad school I actually did go over some of these angles.
UPDATE: First Gear found in a Living Creature.
A european plant hopper insect with one of the largest accelerations known in biology has been found to have gears! (There's a movie on the article page.
)
The little bug has gears in its exoskeleton that synchronize its two jumping legs. Once again selection suprises.
The gears themselves are an oddity. With gear teeth shaped like
cresting waves, they look nothing like what you'd find in your car or
in a fancy watch. There could be two
reasons for this. Through a mathematical oddity, there is a limitless
number of ways to design intermeshing gears. So, either nature evolved
one solution at random, or, as Gregory Sutton, coauthor of the paper
and insect researcher at the University of Bristol, suspects, the
shape of the issus's gear is particularly apt for the job it does.
It's built for "high precision and speed in one direction," he says.
The gears do not rotate 360 degrees, but appear on the surface of two joints to synchronize them as they wind up like a circular spring. The gear itself is not living tissue, so the big solves the problem of regenerating the gear by growing a new set when it molts (i.e. gears that continually regenerate and heal are still unknown). It also does not keep its gears throughout its lifecycle. So the arguments here still stand; the exception still supports the rule.
A:
In your question, you mention frozen lakes and rightly say that skates would be far easier than wheels, but you could have used salt flats as an example.
I think the reason there are no actual wheels is a mixture of ontogenetic and phylogentic barriers, maintenance (nutrition), lubrication and control (nerve connections). There would have to be severe and sustained evolutionary incentives to go from something simple, cheap and extant (legs) to something way more difficult and complex.
However, there are several species of plants and animals that use rolling as a form of locomotion. Tumbleweeds are a good example of plants, and for animals, there are spiders, caterpillars and salamanders.
It only takes a small evolutionary development to take something like this from a passive motion (rolling down hill to escape predators) to active (perhaps creating waves of flexion to roll like... ahem, caterpillar tracks).
A:
Shigeta's molecular answer is spot on. However, at the large scale level I think the key problem with a biological wheel needs to be spelled out clearly: how does an organism with separate parts maintain these parts? Let's suppose that an organism evolves a fully rotational joint, how do they then provide nutrients to the tissue on the other side? If they don't provide nutrients how does self-repair in this tissue continue without nutrients?
Mind you, I'm not sure that the biological problems with a wheel are the real answer. I'm not sure how a wheel evolves. What's the functional intermediate? How does a semi-connected wheel out-perform a limb? Remember than evolution is canalised by what has gone before.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting number of days from timedelta column in pandas
I have a Dataframe that stores aging value as below:
Aging
-84 days +11:36:15.000000000
-46 days +12:25:48.000000000
-131 days +20:53:45.000000000
-131 days +22:22:50.000000000
-130 days +01:02:03.000000000
-80 days +17:02:55.000000000
I am trying to extract the text before days in the above column. I tried the below:
df['new'] = df.Aging.split('days')[0]
The above returns
AttributeError: 'Series' object has no attribute 'split'
Expected output:
-84
-46
-131
-131
-130
-80
A:
IMO, a better idea would be to convert to timedelta and extract the days component.
pd.to_timedelta(df.Aging, errors='coerce').dt.days
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int64
If you insist on using string methods, you can use str.extract.
pd.to_numeric(
df.Aging.str.extract('(.*?) days', expand=False),
errors='coerce')
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int32
Or, using str.split
pd.to_numeric(df.Aging.str.split(' days').str[0], errors='coerce')
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int64
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble installing tower module - ws module crashes
I'm new to node.js and I have installed it by running the installation from the node website. I've had a play installing packages globally (e.g. should) but now I'm trying to install the tower module on my Mac, like so:
sudo npm install tower -g
It install a bunch of stuff and then crashes, with output
npm http 304 https://registry.npmjs.org/tinycolor
npm http 304 https://registry.npmjs.org/zeparser/0.0.5
> [email protected] install /usr/local/lib/node_modules/tower/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws
> node install.js
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
node.js:520
var cwd = process.cwd();
^
Error: EACCES, permission denied
at Function.startup.resolveArgv0 (node.js:520:23)
at startup (node.js:54:13)
at node.js:611:3
npm ERR! [email protected] install: `node install.js`
npm ERR! `sh "-c" "node install.js"` failed with 11
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the ws package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node install.js
npm ERR! You can get their info via:
npm ERR! npm owner ls ws
npm ERR! There is likely additional logging output above.
If I read that correctly it's the ws (websockets?) module crashing.
In researching this problem a blog suggested I add the node path to my .bashrc so I have done that.
Any suggestions?
A:
After much experimentation the only thing that worked for me was to enable the OSX root account, and then:
su
npm install -g tower
sudo did not work but su did.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get mathjax to display double digit or negative power to values?
$x^-3$
$x^15$
$x^1^5$
This sucks. What am I doing wrong?
A:
L.Dutch already told you to use curly braces ({}) around the number. So you'd write x^{15} to get $x^{15}$.
This applies more generally as well. For example, \sqrt xy will render as $$\sqrt xy$$ but \sqrt{xy} renders as $$\sqrt{xy}$$ and correspondingly \sqrt \sin xy gives you $$\sqrt \sin xy$$ which is probably not what you meant, while \sqrt{\sin{xy}} becomes $$\sqrt{\sin{xy}}$$
As a general rule, any time you need to group multiple symbols in LaTeX (which Mathjax uses), those symbols need to be surrounded by {}.
A:
Use {...} to input more than 1 character.
$3^{15}$ will be given by 3^{15}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this code lead to an access violation?
This function works perfectly fine, or so the compiler/debugger tells me
void GUIManager::init(ToScreen* tS)
{
toScreen = tS;
loadFonts();
GUI_Surface = SDL_SetVideoMode( toScreen->width, toScreen->height, 32, SDL_SWSURFACE );
components.push_back(&PlainText("Hello, World!", font, -20, -40));
}
In here, the first function call raises an access violation error.
The debugger doesn't show any problems.
I don't get the chance to debug components[0], since the program halts here.
void GUIManager::draw()
{
// This line here is the problem
components[0].draw(GUI_Surface);
// This line here is the problem
SDL_BlitSurface(GUI_Surface, NULL, toScreen->Screen_Surface, NULL);
}
In case it's needed, this is my 'components'
boost::ptr_vector<GUIComponent> components;
Just let me know if any other code is needed. Perhaps that of PlainText, or GUIComponent
A:
Instead of pushing pointer to temporary, which ends its lifetime just after this line:
components.push_back(&PlainText("Hello, World!", font, -20, -40));
You should push dynamic object, which will exist as long as components:
components.push_back(new PlainText("Hello, World!", font, -20, -40));
See doc: http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_sequence_adapter.html#modifiers
void push_back( T* x );
Requirements: x != 0
Effects: Inserts the pointer into container and takes ownership of it
Throws: bad_pointer if x == 0
Exception safety: Strong guarantee
| {
"pile_set_name": "StackExchange"
} |
Q:
How to combine several rows into one with a total figure
Hope someone can help with this. as you can see from the table below I have a staff member with 5 "Contract" what I would like to do is add together all the "Hours" relating to "Contract" 1, and the same for contract 2, 3, 4 & 5.
for example I just want one line for contract 1 with a total of 8.5.
If you are able to help with this it would be much appreciated, Thank you.
A:
this should be a simple group by select.
Something like:
select CarerCode, Contract, ContractHours, SUM(Hours) TotalHours
from YOUR_TABLE
group by CarerCode, Contract, ContractHours
| {
"pile_set_name": "StackExchange"
} |
Q:
SELECT'ing a relationship with Postgres as a list
I have some tables that I'm joining in a query with Postgres (9).
However, as it's a many to many relationship, I'm getting lots of records where I have a record for table A, and then the items for table B (as expected). For instance:
Car, Ford
Car, BMW
Car, VW
Bike, Yamaha
Bike, BMW
Bike, Honda
What I'm after is getting the relationship as a list:
Car, "Ford, BMW, VW"
Bike, "Yamaha, BMW, Honda"
Is this possible with Postgres in a normal query, or do I need to do something more magic?
A:
select a.type,
string_agg(b.name, ',');
from a
join b on a.id = b.type_id
You will need to replace the column and table names with the real ones (which you have not provided so I can't use the correct ones here).
| {
"pile_set_name": "StackExchange"
} |
Q:
imacros - ignore code if tag not found
URL GOTO=my site
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:login ATTR=NAME:name CONTENT=name
SET !ENCRYPTION NO
TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:login ATTR=NAME:password CONTENT=pass
TAG POS=1 TYPE=BUTTON FORM=NAME:login ATTR=ID:s1
WAIT SECONDS=3
ONDOWNLOAD FOLDER=* FILE=image.jpg WAIT=YES
TAG POS=1 TYPE=IMG ATTR=HREF:*captcha* CONTENT=EVENT:SAVEPICTUREAS
WAIT SECONDS=3
TAB OPEN
TAB T=2
SET !EXTRACT_TEST_POPUP NO
URL GOTO=site of service
WAIT SECONDS=3
TAG POS=1 TYPE=INPUT:TEXT FORM=... ATTR=NAME:username CONTENT=...
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:... ATTR=NAME:password CONTENT=...
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:... ATTR=NAME:pict CONTENT=image.jpg
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ACTION:... ATTR=VALUE:Send
WAIT SECONDS=3
TAG POS=6 TYPE=TD ATTR=* EXTRACT=TXT
SET !CLIPBOARD {{!EXTRACT}}
tab close
TAB T=1
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:login ATTR=ID:recaptcha_response_field CONTENT={{!CLIPBOARD}}
TAG POS=1 TYPE=BUTTON FORM=NAME:login ATTR=ID:s1
WAIT SECONDS=3
I use this code to solve the CAPTCHA ..
Sometimes there is no CAPTCHA ..
I want to make this code only works if there is CAPTCHA ..
In the case of non-appearance of CAPTCHA (or image to save) ignores the following lines ..
I heard that this is possible through Javascript ..
But I can not find a way to do that ..
Any Help? ..
A:
Yes, you can use JavaScript.
Basically, what you need to do is check whether the captcha field do exists or not. Maybe something like this one.
function isCaptchaExists() {
var macro = "TAG POS=1 TYPE=IMG ATTR=HREF:*captcha* EXTRACT=HTM";
var retcode = iimPlayCode(macro);
return retcode < 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Questions migrated correctly?
I saw this particular situation once before but wanted to question it today. This question was migrated from Stack Overflow to Super User, but it would serve better value at Ask Ubuntu.
When I commented on this my comment was deleted. So how does one decide where a question should be migrated to? Why when a question is flagged to recommend a move to a better location it doesn't list all the choices? I was under the impression that content should be migrated to the best site and also limit an overwhelming amount to Stack Overflow.
A:
Five users (or at least 4 I think) migrated the question to Super User.
migrated to superuser.com by martin clayton, Björn Kaiser, Linuxios, spajce, Tom Mar 9 at 16:30
The "problem" there is that Ask Ubuntu is not a migration target regular users can select on SO. Super User is. If it is an appropriate question there, there really is no problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Importing and exporting breakpoints in visual studio code
Does visual studio code support exporting and importing of breakpoints? If so, how to import and export breakpoints in visual studio code.
A:
It appears that there is still not a way to do this. The GitHub issue has been closed - no work appears to have been done there.
screenshot of GitHub issue
I also checked the VS Code extension gallery to search for "breakpoint" / "break point", etc.
Nada.
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel Formula Result is not Cell Value
in Excel i try to get the count of Rows where 2 criterias match.
I do this with this function
=COUNT(IF(Data!J$5:Data!J$1000="RC Corp",IF(Data!AD$5:Data!AD$1000="Expected Allowances / Provisions", 1)))
Data is here a different Worksheet in my Workbook. In the cell it shows me the Result 1.
But when i watch the Formula, it tells me "Formula Result = 2" the correct result is 2. But it always shows 1.
I also tried to update the cell manually with f9 but nothing changes.
Thanks for your help.
A:
For Excel 2007+ use
=COUNTIFS(Data!J$5:Data!J$1000,"RC Corp",Data!AD$5:Data!AD$1000,"Expected Allowances / Provisions")
For Older then 2007 use
=SUMPRODUCT((Data!D:D="RC Corp")*(Data!AD:AD="Expected Allowances / Provisions"))
| {
"pile_set_name": "StackExchange"
} |
Q:
Resolving singularities in one fell swoop
From what I understand, resolution of singularities (in characteristic 0) is proved and implemented inductively. You repeatedly blow up your variety along subsets of your singular locus in a way that decreases the "severity" of your singular locus.
At the end of "On the problem of resolution of singularities in positive characteristic" (link), Hauser says:
"From Hironaka’s theorem it follows (at least in characteristic zero) that there does exist another ideal structure on the singular locus of a variety so that the induced blowup with this center resolves the singularities in one single stroke. Formidable!"
So in contrast to the usual inductive way of resolving singularities, there is a way of resolving singularities "all at once."
Question: What does Hauser mean by "another ideal structure" on the singular locus?
The following was my initial thought. If $k$ is a field of characteristic 0 and $X$ is a variety over $k$ with singular locus $Z$, we want some ideal sheaf $\mathcal{I}$ such that $\mathcal{O}_X/\mathcal{I}$ has support $Z$, and such that blowing up $X$ at $\mathcal{I}$ is smooth. Actually constructing $\mathcal{I}$ is presumably difficult, since it should compensate for any difficulties that arise from resolving $Z$.
However, blow-ups are determined by their center, so this initial thought isn't right. For example, there are isolated singular points that require multiple blow-ups to be resolved. How could such a singular point ever be resolved by a single blow-up? Perhaps there's a larger center containing the singular locus that one should blow up?
Edit: As Donu points out, if a singular locus can be resolved, it can be resolved by a single blow-up for entirely formal reasons. So the locus cut out by an ideal that resolves our singular locus in one fell swoop should contain, but need not be equal to, our singular locus. This answers the previous paragraph.
The question then becomes whether the singular locus determines the "resolving ideal" in any tractable way.
A:
The reasons for this are rather formal. Any projective birational morphism of varieties is the blow up of some ideal, see chap II, theorem 7.17, of Hartshorne. So although the statement you quote sounds striking, I don't think it is a terribly useful.
Let me add a few more remarks, even though it won't answer your modified question. Blowing up a complicated ideal or closed subscheme would hard understand geometrically. What makes Hironaka, and various other resolution proofs, useful is not just that the resolution exists, but that it can be achieved by blowing up along a succession of smooth centres.
| {
"pile_set_name": "StackExchange"
} |
Q:
What case should a name use after the preposition 'with'?
See for example the following sentence:
В Париж с Константином Коровиным
Why the -ом on the first name and -ым on the last name? Are there any other words besides "with" that would see this pattern?
A:
Nice question! The difference is that Константин is a first name, while Коровин is a surname. According to the rules, surnames ending with the suffixes -ин / -ын get the ending -ым in the instrumental case. Константин, on the contrary, has the usual ablative index -ом.
Interestingly, if a surname becomes a city name, the above rule is not applicable any more: Голицын — За Голицином.
A:
Why the -ом on the first name and -ым on the last name?
The last names with this paradigm (ending in -ов, -ев, -ёв, -ин, -ын and their female counterparts) developed from posessive adjectives and decline like those, though keeping the old short form paradigm: Коровина, Коровину rather than **Коровиного, **Коровиному.
Actually, Коровин is a contraction of Коровин сын: a son of a person named, dubbed, nicknamed, or otherwise yclept корова (cow).
Until quite recently, it was the way to write the patronymics (Иван Петров сын Сидоров), and it's still used in Bulgarian.
Note that this paradigm is only valid for last names of this origin.
Names originated from other languages (Асприн, Толкин etc.) are declined as nouns (Асприном, Толкином).
Russian names which have not originated from posessive adjectives (Литвин, Мордвин) also decline as nouns (Литвином, Мордвином). However, the names' origins in this case are not obvious from sg. nom., so these last names can decline as posessive adjectives as well, and only the name bearer may know the right form.
The name of Ivan Ivanovich Sakharine, the antagonist in "Tintin's adventures", is declined Сахариным, not Сахарином in Russian translation (though both versions are grammatically possible). It's believed it should be an old aristocratic family name originated from the word сахар (sugar), not quite a recent nick originated from сахарин (saccharin).
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - TypeError: Can't mix strings and bytes in path components
The following code:
import os
directory_in_str = 'C:\\Work\\Test\\'
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.lower().endswith(".xml"):
with open(os.path.join(directory, filename), 'r') as handle:
for line in handle:
print(line)
else:
continue
is giving me this error:
Traceback (most recent call last):
File "c:\Work\balance_search2.py", line 9, in <module>
with open(os.path.join(directory, filename), 'r') as handle:
File "C:\ProgramData\Anaconda3\lib\ntpath.py", line 114, in join
genericpath._check_arg_types('join', path, *paths)
File "C:\ProgramData\Anaconda3\lib\genericpath.py", line 151, in _check_arg_types
raise TypeError("Can't mix strings and bytes in path components") from None
TypeError: Can't mix strings and bytes in path components
Can anyone help me fix it please.
A:
Just remove this line: directory = os.fsencode(directory_in_str). There is no need to encode the directory name.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a translucent audio-reactive overlay with Processing?
I've researched this question far and wide, but I can't find any useful answers. Basically, I want to create a translucent (or semi-transparent) audio-reactive overlay which can be transposed onto a generic video file. The idea is to give the video the appearance of pulsating with the audio track.
I think I can achieve this effect with Processing and the minim library, but I don't know how to formulate the sketch. The output should be 1920x1080 and the pulsating overlay should produce a sense of vibrant luminosity (e.g. a light color with 30-50% brightness and perhaps 25-50% opacity).
I'm updating this challenge with the sketch provided by @george-profenza (with modifications to use video instead of cam input):
import processing.video.*;
Movie movie;
PGraphics overlay;
import ddf.minim.*;
Minim minim;
AudioInput in;
void setup(){
size(320,240);
movie = new Movie(this, "input.mp4");
movie.play();
// setup sound
minim = new Minim(this);
in = minim.getLineIn();
// setup overlay
overlay = createGraphics(width,height);
// initial draw attributes
overlay.beginDraw();
overlay.strokeWeight(3);
overlay.rectMode(CENTER);
overlay.noFill();
overlay.stroke(255,255,255,32);
overlay.endDraw();
}
void draw(){
//update overlay based on audio data
overlay.beginDraw();
overlay.background(0,0);
for(int i = 0; i < in.bufferSize() - 1; i++)
{
overlay.line( i, 50 + in.left.get(i)*50, i+1, 50 + in.left.get(i+1)*50 );
overlay.line( i, 150 + in.right.get(i)*50, i+1, 150 + in.right.get(i+1)*50 );
}
overlay.endDraw();
//render video then overlay composite
image(movie,0,0);
image(overlay,0,0);
}
// update movie
void movieEvent(Movie m){
m.read();
}
Presumably this sketch works, but unfortunately, the underlying processing.video (GStreamer 1+) library seems to be malfunctioning on Ubuntu (and there doesn't appear to be a way to update the library with one of the community provided forks, according to issue #90 on GitHub.
If anyone can suggest a way to fix this problem or has another solution, I'd be appreciative.
A:
That's a wide question. I'll cover a few aspects:
translucent (audio-reactive) overlay: look into PGraphics. It's like layers in Processing. You can draw into PGraphics (with translucency, etc.), then render in what order you want. See commented example bellow
audio-reactive: you can use minim is use loudness, FFT data or some other software that can do more advanced audio analysis from which you can export data for Processing to read.
1920x1080 output: In my personal experience, at the time of this writing I had the surprise of seeing ok, but not super crisp 1080p video playback within Processing (I would experience staggering every once in a while, tested on a macbook with 16GB RAM and on a PC also with 16GB RAM). Doing sound analysis and overlay graphics on top may degrade performance even further, the main issue being sync between audio and composited graphics, that is you want to do this realtime.
If you simply want to output a video that has beautiful generative audio-responsive graphics, but doesn't need to be in real-time I recommend taking a more "offline" approach:
pre-analysing the audio data so only what you need to drive the visuals is there (can be as simple as loudness)
prototyping visuals at low-res with realtime audio and no video to see if looks/feels fine
rendering the video + visuals (with sound mapped properties) frame by frame at 1080p to then render with audio synched (can be with After Effects, ffmpeg, etc.)
For reference here is a very basic proof of concept sketch that demonstrates:
using overlay graphics
updating overlay graphics to be audio reactive (Minim MonitorInput sample)
compositing video + overlays
Note the low-res video size.
import processing.video.*;
Capture cam;
PGraphics overlay;
import ddf.minim.*;
Minim minim;
AudioInput in;
void setup(){
size(320,240);
// setup video (may be video instead of webcam in your case)
cam = new Capture(this,width,height);
cam.start();
// setup sound
minim = new Minim(this);
in = minim.getLineIn();
// setup overlay
overlay = createGraphics(width,height);
// initial draw attributes
overlay.beginDraw();
overlay.strokeWeight(3);
overlay.rectMode(CENTER);
overlay.noFill();
overlay.stroke(255,255,255,32);
overlay.endDraw();
}
void draw(){
//update overlay based on audio data
overlay.beginDraw();
overlay.background(0,0);
for(int i = 0; i < in.bufferSize() - 1; i++)
{
overlay.line( i, 50 + in.left.get(i)*50, i+1, 50 + in.left.get(i+1)*50 );
overlay.line( i, 150 + in.right.get(i)*50, i+1, 150 + in.right.get(i+1)*50 );
}
overlay.endDraw();
//render video then overlay composite
image(cam,0,0);
image(overlay,0,0);
}
// update video (may be movieEvent(Movie m) for you
void captureEvent(Capture c){
c.read();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do we say bar mitzvah instead of ben mitzvah?
I've heard somewhere that there is a source explaning why do we say "bar mitzvah" instead of "ben mitzvah". I assume that this source it's not dealing with common knowledge on this (such as the development of this term, etc), but rather conceptually. Anybody knows the source and/or the explanation to this?
A:
R. Yitshak Osterlits writes (1) that this is because בר also means 'outside' in Aramaic. The one becoming Bar Mitsvah, is still an outsider to the realm of mitsvot, since he is only now entering it.
A similar explanation is cited by R. Sh'muel Friedman. (2)
(1) Z'khor L'Avraham (Holon) (2002-2003) p. 118.
(2) Mevaqshei Torah (45) (2007) p. 46.
| {
"pile_set_name": "StackExchange"
} |
Q:
In VB, calculating the 5th working day of every month
In VB, what coding could I use to calculate the 5th working day of every month? And if the 5th day is a holiday to go up one day.
A:
You would need a list of holiday dates with which to compare. You would need to build and store that list separately. You did not say what variant of VB (VBA? VB.NET?) but in VB.NET you could do:
Dim datevalue As DateTime = New DateTime(DateTime.Year, DateTime.Month, 1)
Dim dayIsFound As Boolean = False
Dim workDays As Integer
workDays = 1
While Not dayIsFound
If ( dateValue.DayOfWeek <> DayOfWeek.Saturday _
And dateValue.DayOfWeek <> DayOfWeek.Sunday _
And Not HolidayList.Contains( dateValue ) _
workDays = workDays + 1
End If
If index >= 5 Then
dayIsFound = True
Else
dateValue = dateValue.AddDays(1)
End If
End While
Technically, it is possible to build an algorithm that determines the major holidays based on Federal guidelines (in the US) but it is complicated and may not conform to the holidays of the company to whom you are building this component.
| {
"pile_set_name": "StackExchange"
} |
Q:
APT unable to locate sun-java5-jdk
I have following Ubuntu:
Ubuntu 12.04.1 LTS
With following apt installed:
apt 0.8.16~exp12ubuntu10.2 for i386 compiled on Jun 15 2012 14:41:15
This is content of sources.list:
deb http://archive.ubuntu.com/ubuntu precise main universe restricted multiverse
deb-src http://archive.ubuntu.com/ubuntu precise universe main multiverse restricted
deb http://security.ubuntu.com/ubuntu/ precise-security universe main multiverse restricted
deb http://archive.ubuntu.com/ubuntu precise-updates universe main multiverse restricted
deb http://archive.ubuntu.com/ubuntu precise-backports universe main multiverse restricted
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner
# deb http://extras.ubuntu.com/ubuntu precise main
# deb-src http://extras.ubuntu.com/ubuntu precise main
I made:
sudo apt-get clean
sudo apt-get update
I didn't had errors.
When I do:
sudo apt-cache search ^sun-java
I have only:
sun-javadb-client - Java DB client
sun-javadb-common - Java DB common files
sun-javadb-core - Java DB core
sun-javadb-demo - Java DB demo
sun-javadb-doc - Java DB documentation
sun-javadb-javadoc - Java DB javadoc
And finally when I do:
sudo apt-get install sun-java5-jdk
I have:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package sun-java5-jdk
But!!! The package is existing in the repository (!!!):
http://archive.ubuntu.com/ubuntu/pool/multiverse/s/sun-java5/
Any ideas?
Thank you for ahead.
A:
The reason why you can't install sun-java5-jdk is because it doesn't exist in the repository anymore. It was removed because of a security risk.
If you need to use Java, you could install OpenJDK.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tracking AppView events in GA via Google Tag Manager from iOS
I am trying to get GA Screens working via Google Tag Manager on iOS. I've configured GTM Tag with the tracking type App View and I am able to see that events are coming but screen name is always (not set)
I was trying to set different variables/parameters in GTM but haven't succeeded so far. Any ideas?
Thanks.
A:
That was very complicated and absolutly not documented from google side. You have to configure your tag as App View and add field &cd and set it's value to your screen name. It can be tracked then in real time.
Look here for some more context: google documentation for google analytics
| {
"pile_set_name": "StackExchange"
} |
Q:
Dojo syntax for Eclipse Aptana plugin
Using Aptana plugin for Eclipse version 3.7. Working on Dojo-powered project.
Aptana would mark every line that has Dojo tags (e.g. data-dojo-type) as incorrect syntax. What is the workaround to stop Eclipse from marking those tags as syntax errors?
Is there any way to at least add Dojo-tags as exceptions?
A:
This is valid solution for the problem: In Preferences > Aptana Studio > Validation > HTML Tidy Validator > Attributes >> Proprietary attributes --> ignore
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP to INSERT new Row to DB with 1 variable and all others default?
I have a DB with about 10 columns. I want to be able to have a form that inputs the first column's variable, and use the pre-defined default on the remainder.
Here is my current form on locationbuilder.php:
<form method="post" action="builder.php" id="locationbuld">
Location Name <input type="text" name="locationname"/><br/>
<input type="submit"/>
</form>
builder.php
$propertyname = $_POST['locationname'];
$loadCP = $conn->query("INSERT INTO properties (propertyName) VALUES ('$propertyname')");
header("Location: locationbuilder.php");
When I run the form, it goes through and redirects back just fine, but it doesn't insert the new row. I'm assuming it's because I have about 9 undetermined columns, but I'm not 100% sure how to remedy this.
Thanks!
Also, in case it helps, here is my create table I used so you can see the data/columns:
$cp = "CREATE TABLE properties (
id INT(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
propertyName VARCHAR(40) NOT NULL,
location VARCHAR(15) DEFAULT 'South Side',
propertyType VARCHAR(8) DEFAULT 'Business',
businessType VARCHAR(20) DEFAULT 'None',
ownerName VARCHAR(30) DEFAULT 'None',
gangHQFor VARCHAR(30) DEFAULT 'None',
drugFront VARCHAR(3) DEFAULT 'No',
productionType VARCHAR(10) DEFAULT 'None',
productionQuantity INT(4) DEFAULT '0',
weeklyCost INT(15) DEFAULT '0',
dailyIncome INT(15) DEFAULT '0',
available VARCHAR(3) DEFAULT 'Yes',
confiscated VARCHAR(3) DEFAULT 'No',
confiscatedTime VARCHAR(20) DEFAULT '0'
)";
$conn->query($cp);
A:
I don't know how's you are creating your connection object $conn. So i gave this code, try this and tell:-
Your table must be like this:-
TABLE properties(some default values are changed) =
id INT(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
propertyName VARCHAR(40) NOT NULL,
location VARCHAR(15) DEFAULT 'South Side',
propertyType VARCHAR(8) DEFAULT 'Business',
businessType VARCHAR(20) DEFAULT 'None',
ownerName VARCHAR(30) DEFAULT 'NULL',
gangHQFor VARCHAR(30) DEFAULT 'NULL',
drugFront VARCHAR(3) DEFAULT 'No',
productionType VARCHAR(10) DEFAULT 'NULL',
productionQuantity INT(4) DEFAULT '0',
weeklyCost INT(15) DEFAULT '0',
dailyIncome INT(15) DEFAULT '0',
available VARCHAR(3) DEFAULT 'Yes',
confiscated VARCHAR(3) DEFAULT 'No',
confiscatedTime VARCHAR(20) DEFAULT '0'
And code :-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('host name','user name','password','database name') or die(mysqli_connect_error());
$propertyname = mysqli_real_escape_string($conn,$_POST['locationname']);
$loadCP = mysqli_query($conn,"INSERT INTO properties (propertyName) VALUES ('$propertyname')") or die(mysqli_error($conn));
if($loadCP){
header("Location: locationbuilder.php");
}else{
echo "some error occur.Please try again";
}
?>
Note:- change credentials value and other variables value accordingly. Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create objects in jsps using struts tags?
I am developing a struts based application on google app engine. I am using google's user service to allow users to log into my application.
When the user is signed into his google account and opens my application, my application must not ask to sign in again. Suppose the homepage of my application is index.jsp, it should say
Welcome user [email protected]
To do so, I have to check whether there is a current user or not like this
<%
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if(user == null)
//login link
else
//Welcome message
%>
But I am not supposed to use scriptlets in my application. I have to achieve this using struts tags.
Any help is greatly appreciated. Thank you all in advance and good day.
A:
First of all, you need to register the user logged in the session. You must create an action where you will put the code that does the checking account with Google:
public LoginAction {
@Action(...)
public String login () {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
ActionContext.getContext().getSession().put("user", user);
return "success";
}
}
Then you will have the user available on any jsp. The jsp code would be something like:
<s:if test="#session.user == null">
//login link
</s:if>
<s:else>
//Welcome message
</s:else>
When the user logs off, you just have to remove the session object.
And if you need to log off the user if he does in his Google account, you will need an interceptor that will check if it is still logged all the time.
| {
"pile_set_name": "StackExchange"
} |
Q:
TimerCallback function based on Standard Template LIbrary without Boost
Are there TimerCallback libraries implemented using STL. I can't bring in Boost dependency into my project.
The timer on expiry should be able to callback the registered function.
A:
There's no specific timer in the standard library, but it's easy enough to implement one:
#include <thread>
template <typename Duration, typename Function>
void timer(Duration const & d, Function const & f)
{
std::thread([d,f](){
std::this_thread::sleep_for(d);
f();
}).detach();
}
Example of use:
#include <chrono>
#include <iostream>
void hello() {std::cout << "Hello!\n";}
int main()
{
timer(std::chrono::seconds(5), &hello);
std::cout << "Launched\n";
std::this_thread::sleep_for(std::chrono::seconds(10));
}
Beware that the function is invoked on another thread, so make sure any data it accesses is suitably guarded.
| {
"pile_set_name": "StackExchange"
} |
Q:
regular expression matches in Python
I have a question regarding regular expressions. When using or construct
$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> for mo in re.finditer('a|ab', 'ab'):
... print mo.start(0), mo.end(0)
...
0 1
we get only one match, which is expected as the first leftmost branch, that gets accepted is reported. My question is that is it possible and how to construct a regular expression, which would yield both (0,1) and (0,2). And also, how to do that in general for any regex in form r1 | r2 | ... | rn .
Similarly, is it possible to achieve this for *, +, and ? constructs? As by default:
>>> for mo in re.finditer('a*', 'aaa'):
... print mo.start(0), mo.end(0)
...
0 3
3 3
>>> for mo in re.finditer('a+', 'aaa'):
... print mo.start(0), mo.end(0)
...
0 3
>>> for mo in re.finditer('a?', 'aaa'):
... print mo.start(0), mo.end(0)
...
0 1
1 2
2 3
3 3
Second question is that why do empty strings match at ends, but not anywhere else as is case with * and ? ?
EDIT:
I think I realize now that both questions were nonsense: as @mgilson said, re.finditer only returns non-overlapping matches and I guess whenever a regular expression accepts a (part of a) string, it terminates the search. Thus, it is impossible with default settings of the Python matching engine.
Although I wonder that if Python uses backtracking in regex matching, it should not be very difficult to make it continue searching after accepting strings. But this would break the usual behavior of regular expressions.
EDIT2:
This is possible in Perl. See answer by @Qtax below.
A:
I don't think this is possible. The docs for re.finditer state:
Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string
(emphasis is mine)
In answer to your other question about why empty strings don't match elsewhere, I think it is because the rest of the string is already matched someplace else and finditer only gives matches for non-overlapping patterns which match (see answer to first part ;-).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set Mercurial upstream
I created local hg repository for new project: hg init ; hg addremove,
then I created empty upstream repo, and pushed first version there: hg push https://remoterepo.
Now, I want to set that https://remoterepo as default upstream, so I can just do hg push/pull without giving it.
I was surprised Google did not give me a straight answer with "set mercurial upstream", and I didn't find a direct answer here at SO either. So, for the benefit of all the people using SO as a howto, what's the right way to do this?
A:
You can do that by adding the upstream URL to /project/.hg/hgrc like this:
[paths]
default = ssh://[email protected]/repos/something
upstream = ssh://[email protected]/repos/something_else
and now upstream is an alias for repo something_else which you can then pull from or push to:
hg pull upstream
hg push upstream
Reference
hg help urls:
URLs can all be stored in your
configuration file with path aliases
under the [paths] section like so:
[paths]
alias1 = URL1
alias2 = URL2
...
You can then use the alias for any
command that uses a URL (for example
hg pull alias1 will be treated as
hg pull URL1).
Two path aliases are special because
they are used as defaults when you do
not provide the URL to a command:
default
default-push
| {
"pile_set_name": "StackExchange"
} |
Q:
How to identify which file implicitly relies on linkage with a library?
I am working on en embedded project. I have integrated open source sub-projects in it (i.e. code I did not write).
Compilation is fine but I have linkage errors:
gcc-arm-none-eabi-7-2018-q2-update/bin/../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/fpv4-sp/hard/libc.a(lib_a-abort.o):
In function `abort': abort.c:(.text.abort+0xa): undefined reference to `_exit'
gcc-arm-none-eabi-7-2018-q2-update/bin/../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/fpv4-sp/hard/libc.a(lib_a-signalr.o):
In function `_kill_r': signalr.c:(.text._kill_r+0x10): undefined reference to `_kill'
gcc-arm-none-eabi-7-2018-q2-update/bin/../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/fpv4-sp/hard/libc.a(lib_a-signalr.o):
In function `_getpid_r': signalr.c:(.text._getpid_r+0x0): undefined reference to `_getpid' collect2: error: ld returned 1 exit status
I also had errors about undefeined reference to _exit but I fixed these by searching & replacing calls to exit(1).
I tried to search & replace calls to abort() but I still have these errors.
I found some similar questions resolved by adding linker options -specs=nosys.specs but this is not what I want.
I want to modify the code so that I can handle errors gracefully without brutally exiting the entire program and to do that I have to find which code relies on this link.
A:
I tried to search & replace calls to abort() but I still have these errors.
I think you are asking: "how to find code that calls abort (after replacing all calls that you can find)?"
If that is indeed your question, use -y linker option. For example:
gcc main.o foo.o bar.o -Wl,-y,abort
/usr/bin/ld: bar.o: reference to abort
/usr/bin/ld: //lib/x86_64-linux-gnu/libc.so.6: definition of abort
P.S. Your build of .../v7e-m/fpv4-sp/hard/libc.a is highly unusual: generally if it defines abort and exit, it should also define _exit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript use mouseMove event to move objects does not work when mouse suddenly moves quick
I'm trying to build a drag and drop feature for shapes in a svg using svelte framework. Here is the structure of the svg
<svg>
<g
on:mousedown={mouseDownHandler}
on:mousemove={mouseMoveHandler}
on:mouseup={mouseUpHandler}>
<circle />
</g>
But with this structure, if I move the mouse quickly, it could accidentally move out of the <g> before it can be updated with the current mouse location, and the mouseMoveHandler will stop responding.
I tried something like memorizing the selected element in mouseDownHandler, hoping that even if the mouse is no longer within the group, it could still use the current mouse location to move. But it did not work as I expected.
I suspect that this mouseMoveHandler is only activated while the mouse is within the group, is it correct? Any suggestions for how to overcome this problem?
Thanks
Update:
I am aware that adding the handlers to the parent group would solve the problem. The reason why I wish to do so is because there are different types of elements, and I would like to do different things with them. Right now I have everything in one big mouseMoveHandler under the svg and everything works fine, but it's getting really ugly as I add more features to the handler. This is why I wish to have different handlers for different elements.
A:
When you're implementing drag and drop (in any situation, not just Svelte or SVG), never apply the 'move' handler to the element itself. Always apply it (and the 'up' handler) to window. The 'down' handler should be responsible for noting the start coordinates and registering the 'move'/'up' handlers, nothing more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ternary operator as a command?
In the source-code for nanodns, there is an atypical use of the ternary operator in an attempt to reduce the size of the code:
/* If the incoming packet has an AR record (such as in an EDNS request),
* mark the reply as "NOT IMPLEMENTED"; using a?b:c form to save one byte*/
q[11]?q[3]|=4:1;
It’s not obvious what this line does. At first glance, it looks like it is assigning a value to one of two array elements, but it is not. Rather, it seems to be either or’ing an array element, or else, doing nothing (running the “command” 1).
It looks like it is supposed to be a replacement for this line of code (which is indeed one byte longer):
if(q[11])q[3]|=4;
The literal equivalent would be this:
if (q[11])
q[3]|=4;
else
1;
The ternary operator is typically used as part of an expression, so seeing it used as a standalone command seems odd. Coupled with the seemingly out of place 1, this line almost qualifies as obfuscated code.
I did a quick test and was able to compile and run a C(++) program with data constants as “command”, such as void main() {0; 'a'; "foobar"; false;}. It seems to be a sort of nop command, but I cannot find any information about such usage—Google isn’t very amenable to this type of search query).
Can anyone explain exactly what it is and how it works?
A:
In C and C++ any expression can be made into a statement by putting ; at the end.
Another example is that the expression x = 5 can be made into a statement: x = 5; . Hopefully you agree that this is a good idea.
It would needlessly complicate the language to try and "ban" some subset of expressions from having ; come after them. This code isn't very useful but it is legal.
A:
Please note that the code you linked to is awful and written by a really bad programmer. Particularly, the statement
"It is common practice in tiny C programs to define reused expressions
to make the code smaller"
is complete b***s***. That statement is where things started to go terribly wrong.
The size of the source code has no relation to the size of the compiler executable, nor any relation to that executable's memory consumption, nor any relation to program performance. The only thing it affects is the size of the source code files on the programmers computer, expressed in bytes.
Unless you are programming on some 8086 computer from mid-80s with very limited hard drive space, you never need to "reduce the size of the code". Instead, write readable code.
That being said, since q is an array of characters , the code you linked is equivalent to
if(q[11])
{
(int)(q[3] |= 4);
}
else
{
1;
}
Where 1 is a statement with no side effect, it will get optimized away. It was only placed there because the ?: operator demands a 3rd operator.
The only difference between if statements and the ?: operator is subtle: the ?: implicitly balances the type between the 2nd and 3rd operand.
To increase readability and produce self-documenting code, the code should get rewritten to something like
if (q[AR_INDEX] != 0)
{
q[REPLY_INDEX] |= NOT_IMPLEMENTED;
}
As a side note, there is a bug here: q[2]|=128;. q is of type char, which has implementation-defined signedness, so this line is potentially disastrous. The core problem is that you should never use the char type for bit-wise operations or any form of arithmetic, which is a classic beginner mistake. It must be replaced with uint8_t or unsigned char.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to split a string in the controller of codeigniter?
I am using codeigniter framework. I am getting the date from the view.i want to send them into 2 fields. like "2016-06-19" to one field and "2015-06" into another field. How can i get it done?? If anyone has an idea it would help me.
Here is my controller function.
function add() {
$reservation_model = new Reservation_model();
$reservation_service = new Reservation_service();
$newDate=$this->input->post('date',TRUE);
$splitted= split("-", $newDate, 1);
$reservation_model->set_date(trim($this->input->post('date',TRUE)));
$reservation_model->set_date_half($splitted);
$reservation_model->set_title(trim($this->input->post('selected_hall', TRUE)));
$reservation_model->set_type(trim($this->input->post('selected_time', TRUE)));
$reservation_model->set_description(trim($this->input->post('name', TRUE)));
$reservation_model->set_advanced_payment_status(trim($this->input->post('optionsRadios', TRUE)));
//$reservation_model->set_advanced_payment_status(trim($this->input->post('no', TRUE)));
$reservation_model->set_paid_amount(trim($this->input->post('paid_amount', TRUE)));
$reservation_model->set_fax(trim($this->input->post('fax', TRUE)));
$reservation_model->set_telephone_number(trim($this->input->post('telephone', TRUE)));
$reservation_model->set_address(trim($this->input->post('address', TRUE)));
$reservation_model->set_menu_no(trim($this->input->post('selected_menu_number', TRUE)));
$reservation_model->set_menu_price_per_plate(trim($this->input->post('menu_price', TRUE)));
$reservation_model->set_is_deleted('0');
//$this->db->last_query();
echo $reservation_service->add_reservation($reservation_model);
}
date is my original date. it should be like "2015-06-19". date_half is my other date field. it should be like "2015-06"
A:
It is more general PHP question then CI question.
I would do it by date and strtotime functions.
$splitted = date('Y-m', strtotime($this->input->post('date',TRUE)));
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET MVC binding DropDownList and Checkbox to ViewModel
I have a huge job offer post form, and I wanted to increase priority of properties by clicking checkbox next to them.
For example:
Salary X
TeamSize O
SomeTechnology X
Where X is checked and O isn't.
I've came across a problem where I need to have a drop down list and checkbox next to it, and then bind it to the viewModel. I couldn't make the last step working though.
HomeController
public ActionResult CandidateRegister()
{
CandidateRegisterViewModel viewModel = new CandidateRegisterViewModel();
viewModel.SelectedEmploymentTypeViewModel = new SelectedEmploymentTypeViewModel()
{
EmploymentType =
new SelectList(
Enum.GetValues(typeof(Enums.EmploymentType)).Cast<Enums.EmploymentType>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList(), "Value", "Text"),
Selected = false
};
return View(viewModel);
}
ViewModels
public class CandidateRegisterViewModel
{
public SelectedEmploymentTypeViewModel SelectedEmploymentTypeViewModel { get; set; }
}
public class SelectedEmploymentTypeViewModel
{
public SelectList EmploymentType { get; set; }
public bool Selected { get; set; }
public int? SelectedEmployment { get; set; }
}
EmploymentType enum
public enum EmploymentType
{
[Display(Name = "Full Time")]
FullTime,
[Display(Name = "Part Time")]
PartTime,
Contract,
Internship,
Other
}
CandidateRegister View
@model SourceTreeITMatchmaking.Models.CandidateRegisterViewModel
<div class="white-container sign-up-form">
@using (Html.BeginForm("CandidateRegister", "Candidates"))
{
<section>
<h6 class="bottom-line">Essentials:</h6>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-7" style="padding-left: 0;">
@Html.DropDownList("SelectedEmployment", Model.SelectedEmploymentTypeViewModel.EmploymentType)
@Html.CheckBox("Selected", Model.SelectedEmploymentTypeViewModel.Selected)
</div>
</div>
</div>
</section>
</div>
<hr class="mt60">
<div class="clearfix">
<input type="submit" class="btn btn-default btn-large pull-right" value="Register candidate!">
</div>
}
This is what I tried so far.
Yet again, what I want to achieve is that I have a drop down list of my EmploymentType enum, checkbox next to it and then bind it to SelectedEmploymentTypeViewModel so I could put it in CandidateRegisterViewModel (which has a number of other properties, like Address etc.)
I hope You could help me a little :) Thanks in advance!
A:
The reason that you can not bind it to view model is that your input names are incorrect. Either change them to:
@Html.DropDownList("SelectedEmploymentTypeViewModel.SelectedEmployment", Model.SelectedEmploymentTypeViewModel.EmploymentType)
and
@Html.CheckBox("SelectedEmploymentTypeViewModel.Selected", Model.SelectedEmploymentTypeViewModel.Selected)
Or a much better solution would be using a strongly typed helpers:
<div class="row">
<div class="col-sm-12">
<div class="col-sm-7" style="padding-left: 0;">
@Html.DropDownListFor(m=>m.SelectedEmploymentTypeViewModel.SelectedEmployment , Model.SelectedEmploymentTypeViewModel.EmploymentType)
@Html.CheckBoxFor(m=>m.SelectedEmploymentTypeViewModel.Selected)
</div>
</div>
</div>
Also if you have multiple nested models you can create editor templates for them:
@model SourceTreeITMatchmaking.Models.SelectedEmploymentTypeViewModel
<section>
<h6 class="bottom-line">Essentials:</h6>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-7" style="padding-left: 0;">
@Html.DropDownListFor(m=>m.SelectedEmployment , Model.EmploymentType)
@Html.CheckBoxFor(m=>m.Selected)
</div>
</div>
</div>
</section>
Save it in Views/Shared/EditorTemplates/SelectedEmploymentTypeViewModel.cshtml
And then in your main view you can use them like this:
@model SourceTreeITMatchmaking.Models.CandidateRegisterViewModel
<div class="white-container sign-up-form">
@using (Html.BeginForm("CandidateRegister", "Candidates"))
{
@Html.EditorFor(m=>m.SelectedEmploymentTypeViewModel)
<hr class="mt60">
<div class="clearfix">
<input type="submit" class="btn btn-default btn-large pull-right" value="Register candidate!">
</div>
}
This way you will be able to cleanup your main view and to encapsulate and reuse the editor templates wherever they needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I use my rails3 generator in all my projects?
I wrote a generator that I'd like to use in my Rails3 projects using Thor (which I absolutely love).
How would I go about using my generator in all my rails3 projects?
i.e. how do I install it?
If the answer is to make a gem out of it - could you please describe the rails3 process of doing so?
Thanks!
A:
Yep, make a gem!
In terms of loading your generator it's pretty much as simple as putting your generator files in lib/generators/#{generator_name}/ in the gem. See the generators guide for a little more explanation of how they're loaded.
Check out some gems which do this such as rails3-generators gem. rspec-rails, machinist for examples.
In terms of actually building your gem, check out jeweler
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the black pin called that mourners wear?
What is the name of the black pin that one wears at a funeral, and are there any customs around them to know about? It's a black circle, pinned, and there's a black ribbon affixed to it.
A:
There is a Jewish practice to tear one's clothes when in mourning. In recent times, it has become common for non-Orthodox Jews to tear a black ribbon pinned to their clothes rather than the clothes themselves in order to avoid damaging an article of clothing.
I am not sure whether using the ribbon satisfactorily fulfills the obligation according to the letter of Jewish law, but at least Chabad.org seems to imply very strongly that it does not.
How shallow, how disappointing, how pitiably trivial, therefore, to symbolize these authentic sentiments not by an act of historic and religious significance, but by the little black ribbon or button--invented by enterprising American undertakers!
As far as a name goes, I don't think there is any special name for this. I think it is generally just called a black ribbon. I have heard some people refer to it as a "keriah ribbon" after the custom of keriah (tearing).
| {
"pile_set_name": "StackExchange"
} |
Q:
Crankset for SRAM Apex Groupset
I have SRAM Apex Shifters, FD, RD, and Brakes.
Can I use a SRAM Force BB30 Crankset?
Thanks
Paul
A:
Can I use a SRAM Force BB30 Crankset?
Unfortunately, you will not be able to use the BB30 on your bicycle. You will need to search for a Sram Force GXP Crankset. You will also need to verify if your particular Bianchi is Italian threaded or not as not all Bianchi are.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery selector multi-class objects
Hey all, I've been trying to get a series of objects to appear that have multiple classes associated with them
<div class="Foo Bar">
Content
</div>
<script>
alert($('.Foo').length);
</script>
The selector above is returning 0. This is unfortunately one of those questions that is completely impossible to ask to google (at least as far as I can tell).
How can I make this query work?
To be more specific, I have a table that looks like this:
<table>
<tr class="Location2">
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr class="Location3 Territory4">
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</table>
When I script:
alert($('.' + (Var that = 'Territory4')).length));
I get 0.
I'm well versed in HTML and CSS and I know I shouldn't use tables etc etc, but this is a special case.
A:
EDIT: Based on updated question.
Your code throws a syntax error. Bring the variable assignment out of the selector.
var that = 'Territory4';
alert( $('.' + that).length );
The selector is correct. I'm guessing that your code is running before the DOM is fully loaded.
Try this: http://jsfiddle.net/QWNPc/
$(function() {
alert($('.Foo').length);
});
Doing:
$(function() {
// your code
});
is equivalent to doing:
$(document).ready(function() {
// your code
});
which ensures that the DOM has loaded before the code runs.
http://api.jquery.com/ready/
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get fireworks?
What are the requirements for making fireworks appear at the end of a level in the original Super Mario Bros.?
A:
From the Super Mario Wiki:
At the end of every level in Super Mario Bros., with the exception of a castle level, fireworks would go off when Mario or Luigi entered the tiny castle (if the last number of the timer is 1, 3, or 6 at the end of the level). If the last number was 1, one firework would go off; if the last number was 3, three fireworks would go off and so forth. Each explosion would award the player with 500 points.
The page also details the appearance of fireworks in numerous other Mario titles.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read atom feed in .NET
I write code given below to read Atom feed.
string strUrL = "http://loluyede.blogspot.com/atom.xml";
WebRequest objWR = WebRequest.Create(strUrL);
WebProxy objWP = new WebProxy("strAddress", 1978);
objWP.Credentials = new NetworkCredential("username", "password");
objWR.Proxy = objWP;
StreamReader objSR = new StreamReader(objWR.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
AtomFeed feed = AtomFeed.Load(objSR);
at the end of the statement following error comes
ERROR In Code:
The type initializer for 'Atom.Utils.DefaultValues' threw an exception.
ERROR on Page
Server Error in '/WebAppUI' Application.
--------------------------------------------------------------------------------
Value cannot be null.
Parameter name: stream
Anybody suggest me what i have to do.
A:
The solution is much simpler:
string strUrl = "http://loluyede.blogspot.com/atom.xml";
Stream responseStream = WebRequest.Create(strUrl).GetResponse().GetResponseStream();
StreamReader objSR = new StreamReader(responseStream, System.Text.Encoding.UTF8);
string strTheWholeFeedAsString = objSR.ReadToEnd();
To get it fully up and running you should change from AtomFeed to ASP.Net RSS Toolkit (free from codeplex).
Good luck!
EDITED on 2010-09-12:
Given the fact, that the AtomFeed project is discontinued and written for .NET v1.1 therefore too old, I've created a sample application fetching your feed using RSS Toolkit. Feel free to download the source codes from http://www.isource.ro/StackOverflow/RssReaderTest.zip.
If you have questions don't hesitate to ask.
| {
"pile_set_name": "StackExchange"
} |
Q:
Alternatives to WebResponse/HttpWebResponse
I'm trying to write a simple program to return the status code from a website. Currently using the HttpWebRequest and HttpWebResponse classes. However the way they work just seems horrible to me, the status code is only returned if its 200/OK, and all other codes give a webexception.
While I can read the response from the exception and get the status code I was wondering if there are any other alternatives that don't cause exceptions. As I understand exceptions are costly and should be reserved for rare occasions when there are serious problems. Not that it matters for my application but I'd rather avoid exceptions unless absolutely necessary.
So are there any other options?
Edit:
Here's some code
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create("http://www.randomsite.com");
request.Method = "HEAD";
try
{
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Console.WriteLine("Status: " + response.StatusCode);
response.Close();
}
catch (WebException ex)
{
HttpWebResponse httpResponse = (HttpWebResponse) ex.Response;
if (httpResponse != null)
{
Console.WriteLine("Status: " + httpResponse.StatusCode);
}
}
A:
While exceptions are costly, they are many powers of ten less costly than a web request. So just wrap HttpWebResponse to give you back the status code and forget about the cost.
| {
"pile_set_name": "StackExchange"
} |
Q:
Share on Instagram/WhatsApp without UIDocumentInteractionController
Is there any way to share an UIImage to Instagram and WhatsApp without using UIDocumentInteractionController?
I want to set a button for IG that won't open the OpenIn menu, and won't make me select an app from the menu.
Same goes for Whatsapp...
Or perhaps a way to use UIDocumentInteractionController but somehow setting the selected app to be (for example) Instagram without prompting the user to choose IG app from the OpenIn menu.
Thanks in advance
Haim
A:
No, there is no way to share an image without UIDocumentInteractionController. Perhaps Whatsapp or Instagram will provide an API for this in the future.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error: XHR error (404 Not Found) loading ....@angular/Http(…)
I ran into problem when I try to bootstrap the HTTP_PROVIDERS in the main.ts file and the actual error is :
Error: XHR error (404 Not Found) loading http://localhost:3000/node_modules/@angular/Http(…)
Without bootstrapping the HTTP_PROVIDERS, I don't have any problem to start the application. Here are information of my app.
Do you see anything wrong with the way I use the HTTP_PROVIDERS?
Here is the package.json
{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
"lite": "lite-server",
"postinstall": "typings install",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
},
"license": "ISC",
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.1",
"systemjs": "0.19.27",
"es6-shim": "^0.35.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"angular2-in-memory-web-api": "0.0.7",
"bootstrap": "^3.3.6"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.2.0",
"typescript": "^1.8.10",
"typings":"^0.8.1"
}
}
Here is the system.config.js
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'@angular': 'node_modules/@angular'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
var packageNames = [
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'@angular/router-deprecated',
'@angular/testing',
'@angular/upgrade',
];
// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
Here is the tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
A:
I think that you import the following:
import { ... } from '@angular/Http';
instead of
import { ... } from '@angular/http';
http must be in lowercase. Http corresponds to the class in the @angular/http module to execute HTTP requests.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understand DMARC Email Record
I want to understand my DMARC record. I've done some reading online but I don't understand why in the <policy_evaluated> tag , spf fails but after when they are detailed it actually passes.
<record>
<row>
<source_ip>2607:f8b0:400c:c05::230</source_ip>
<count>1</count>
<policy_evaluated>
<disposition>none</disposition>
<dkim>pass</dkim>
<spf>fail</spf> <-- here
</policy_evaluated>
</row>
<identifiers>
<header_from>xxxxx</header_from>
</identifiers>
<auth_results>
<dkim>
<domain>xxxxx</domain>
<result>pass</result>
<selector>default</selector>
</dkim>
<spf>
<domain>xxxxx</domain>
<result>pass</result> <-- here
</spf>
</auth_results>
</record>
Also on a different record I have a soft fail :
<auth_results>
<dkim>
<domain>xxxxx</domain>
<result>pass</result>
<selector>default</selector>
</dkim>
<spf>
<domain>xxxxx</domain>
<result>softfail</result> <-- here
</spf>
</auth_results>
A:
The probable cause of the discrepancy between <policy_evaluated><spf> & <auth_results><spf><result> is that your envelope "mail from" & your header "from" are not on the same domain. <policy_evaluated><spf> is the SPF alignment test, which verifies that both the "From" field in the message header & the RFC 5321 "MAIL FROM" are from the same domain, whereas <auth_results><spf><result> only tests whether or not the sending MTA is an authorised sender for the domain in the domain in the RFC 5321 "MAIL FROM".
There's a good answer here: DMARC -spf and DKIM record queries
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can I apt-get install rapidsvn but not see it within the Ubuntu Software Center GUI?
I went to install Rapid SVN from the Ubuntu Software Center today as I have done before - it wasn't there.
I can install this using the command:
sudo apt-get install rapidsvn
Why can I apt-get install rapidsvn but not see it within the Ubuntu Software Center GUI?
A:
Ubuntu Software Center is focused on end-user applications and indeed will not "find" many individual packages. There is a bug report on this
Obviously, this requires you to use the terminal to find and install specific packages. You also may use the powerful Synaptic Package Manager to be able to manage your installed software at the level of the individual installation packages.
| {
"pile_set_name": "StackExchange"
} |
Q:
Template ASP.NET MVC view
Here is the code in my view for users ratings display:
<div class="leftBlock">
<div class="leftBlockHead">
<div class="textHead">
<b>Users rating</b>
</div>
</div>
<div id="leftBlockContent">
@foreach (var user in Model)
{
<div class="list">
@user.Login @user.Rating
</div>
}
</div>
</div>
The problem is I use the same html structure for some other blocks. So I don't want to repeat this code, I need some kind of template which will take block title and @foreach as arguments. What are the ways to implement it?
A:
I have finally used Templated Razor Delegates.
Here is my partial view:
@model LeftColumnBlockViewModel
<div class="levo_blok1">
<div class="levo_blok1_head">
<div class="text_head">
@Model.Title
</div>
</div>
<div id="levo_blok1_content">
@Model.Content(null)
</div>
</div>
Here is the view model for it:
public class LeftColumnBlockViewModel
{
public string Title { get; set; }
public Func<dynamic, object> Content { get; set; }
public LeftColumnBlockViewModel(string title, Func<dynamic, object> content)
{
Title = title;
Content = content;
}
}
and here is the usage:
@Html.Partial(MVC.Shared.Views._LeftColumnBlock,
new LeftColumnBlockViewModel(
Battles.CurrentBattles,
@<text>
@foreach (var currentBattle in Model.CurrentBattlesViewModels)
{
<div class="list">
@currentBattle.Budget / @currentBattle.BetLimit% / @[email protected]
</div>
}
</text>))
| {
"pile_set_name": "StackExchange"
} |
Q:
What's important to know while using new { attribute = value } with Html.Helper actions
I've difficult to used new { attributes} in an HtmlHelper function. I'd like, for instance, to widen a TextBox. Should I use new { width = "50px"}, new { width = "50"}, or new { width = 50}, etc.
How many atttribues can I use?
What's the general rules?
Thanks helping
A:
When adding HtmlAttributes in such a way it is important to keep in mind that the attributes you specify will get rendered as the html element's attributes. E.g. if you have:
<%= Html.TextBoxFor(... , new { width = "50px" }) %>
it will get rendered as
<input type="text" ... width="50px" />
In other words - exactly what you specify. Thus if you feel that it's difficult to decide what to write in the Helper, try to think what you want your Html to look like first, and go from there. You might want something like:
<%= Html.TextBoxFor(... , new { style = "width:50px;attribute2:value2;" }) %>
to get
<input type="text" ... style="width:50px;attribute2:value2;" />
But generally it is considered a good practice to separate layout from markup, so it's quite common to just apply a css-class to the element (note the @ before the class name - it is required due to class being a keyword in C#):
<%= Html.TextBoxFor(... , new { @class = "mytextbox" }) %>
Where mytextbox is defined in a css file and specifies your width and other properties:
.mytextbox { width: 50px; attribute2: value2; ... }
| {
"pile_set_name": "StackExchange"
} |
Q:
Indent/outdent on a MBP keyboard in VSC?
Unable to get the keyboard shortcuts for indent/outdent to work in VSC.
The documented defaults of ⌘] / ⌘[ don't work (not possible with just 2 keys on MBP).
(https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf)
To just get a square bracket [ ] with the MBP you need to use the ALT+8 or 9 keys. So I tried those with the command key ⌘ and nothing. Anyone know the solution. I run up against these sorts of problems all the time with MBP.
A:
I assume VSC stands for Visual Studio Code:
Indent: Mark the lines you want an press Tab
Outdent: Mark the lines you want an press Shift+Tab
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.