text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Refer to Numbered Section in moderncv Class using \ref
I would like to refer back to a numbered section in the moderncv class using \ref but I am unable to do so.
I read the post titled
Using \ref in moderncv class
and I was able to get the following:
\documentclass[11pt,a4paper]{moderncv}
\moderncvstyle{banking}
\moderncvcolor{blue}
\usepackage[margin=1in]{geometry}
\usepackage{etoolbox}
\newcounter{secnumber}
\newcommand{\numbersec}{\refstepcounter{secnumber}\thesecnumber~}
\patchcmd{\section}{\sectionstyle{#1}}{\sectionstyle{\numbersec #1}}{}{}
\renewcommand\sectionstyle[1]{{%
\refstepcounter{secnumber}%
\sectionfont
\textcolor{color1}{\thesecnumber.\quad#1}%
}}
\firstname{First Name}
\familyname{Last Name}
\begin{document}
\makecvtitle
\section{A Section}
\label{sec.one}
Text goes here
\section{Another Section}
\label{sec.two}
Text goes here
\section{Yet Another Section}
\label{sec.three}
Recall in section \ref{sec.one} that we mentioned ...
\end{document}
This provides the following output:
As we can see, the section number is not appearing in the position where I use the \ref command.
I attempted to solve this issue by reading the post titled Using \ref in moderncv class
however I was not successful.
Is it possible to use \ref and refer back to a numbered section which has been labelled in the moderncv class?
Note: I realize this might be an unusual request, however the reason for asking this question is because I have already have CV made using the moderncv class and I need to also write a supplementary document which requires numbered sections. I would like to use the moderncv class (with modifications) for this supplementary document in order to maintain visual and styling consistency between the CV and supplementary document. The reason for requiring referencing in the supplementary document is to avoid repeating information by requesting the reader to refer back to a certain numbered section.
A:
The problem is due to the rather convoluted code used to produce the number. If we simplify that code, then the \label commands will work as you would expect them to do. Instead of incrementing the counter inside the \sectionstyle macro, we prepend it to the \section command. This allows the label to be accessed properly whether the \label command is inside the \section{...} command (as I suggested in my comment) or immediately after it (as you would expect it to work.)
\documentclass[11pt,a4paper]{moderncv}
\moderncvstyle{banking}
\moderncvcolor{blue}
\usepackage[margin=1in]{geometry}
\usepackage{etoolbox}
\newcounter{secnumber}
\pretocmd{\section}{\refstepcounter{secnumber}}{}{}
\renewcommand\sectionstyle[1]{{%
\sectionfont
\textcolor{color1}{\thesecnumber.\quad#1}%
}}
\firstname{First Name}
\familyname{Last Name}
\begin{document}
\makecvtitle
\section{A Section}
\label{sec.one}
Text goes here
\section{Another Section}
\label{sec.two}
Text goes here
\section{Yet Another Section}
\label{sec.three}
Recall in section \ref{sec.one} that we mentioned and in section \ref{sec.two} ... and in section \ref{sec.three} we see
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to catch invalid Elasticsearch queries?
Given an invalid query, Elasticsearch's Java API (1.1.0) throws a SearchPhaseExecutionException. This exception has no "cause", but a "message" like this one:
Failed to execute phase [query_fetch], all shards failed; shardFailures {[bwUSN171Ru6rY1-su5-48A][f2f0i20hrf][0]: SearchParseException[[f2f0i20hrf][0]: from[-1],size[0]: Parse Failure [Failed to parse source [{"size":0,"query":{"bool":{"must":{"term":{"count":""}}}}}]]]; nested: NumberFormatException[For input string: ""]; }
How can I distinguish invalid queries from other errors, other than doing a string search for SearchParseException, or validating the query first?
A:
I would suggest to use validate query before query execution in that case:
ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
validateQueryRequest.source(jsonContent);
validateQueryRequest.explain(true);
ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
ValidateQueryResponse response = future.get(); // typical java future as response
System.out.println(response.isValid()); // true or false
System.out.println(response.getQueryExplanation().size()); // size of explanations why the query is incorrect
QueryExplanation.getError() provides something like that (for the query where I'm trying to use text with number field range):
org.elasticsearch.index.query.QueryParsingException: [bill_d20160227t123119] Failed to parse; java.lang.NumberFormatException: For input string: "TEST"
More about validation API you will find at https://www.elastic.co/guide/en/elasticsearch/reference/current/search-validate.html
Hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Firebird with Rails 4.2
I am trying to update my rails application from version 4.1.6 to 4.2.0.
Almost all are going well, except that I have two database connections (one is the default Postgres and other is used for reading data from another legacy application). The second uses Firebird (fb) adapter.
In Rails 4.2 I cannot do anything with this second (fb) database. All commands result in this error:
NoMethodError: undefined method `compile' for #
To reproduce the case, I created a new application from scratch using adapter 'fb' and a simple model called Foo with two string columns. After I called from rails console the command Foo.count
the result is the same.
Here is the full call stack for the problem
I tried to investigate the sources but I could not determine where is the problem. I think it has due to some changes/optimizations in activerecord in version 4.2 but I don't know exactly.
Thanks in advance by any help.
A:
Gem activerecord-fb-adapter version 1.0.1 has now support for rails ~>4.2, according this closed issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Execute on enter-key-press
I have this code
<script>
function cA( url )
{
document.myform.action = url;
}
</script>
<input type="whatever" name="whatever" id="whatever" />
<button class="whatever-button" id="defaultAction" value="Go for it" name="whatever" type="submit" onClick="cA('whatever.php#anchor')" >Go for it
</button>
When you click the Go for it-Button, whatever.php#anchor is being loaded. How do I need to change the input tag's elements for it to execute the same cA('whatever.php#anchor') as the button click?
So when a user presses enter in the field, the site whatever.php#anchor should be loaded or more specifically, cA('whatever.php#anchor') be executed.
The page has more buttons, so making one button the default button does not work.
PS:
Wrapping all in one form does not work as the page's structure is
<form>
<script>
function cA( url )
{
document.myform.action = url;
}
</script>
<input type="whatever1" name="whatever1" id="whatever1" />
<button class="whatever1-button" id="defaultAction1" value="Go for it" name="whatever1" type="submit" onClick="cA('whatever.php#anchor1')" >Go for it
</button>
<input type="whatever2" name="whatever2" id="whatever2" />
<button class="whatever2-button2" id="defaultAction2" value="Go for it" name="whatever2" type="submit" onClick="cA('whatever.php#anchor2')" >Go for it
</button>
<input type="whatever3" name="whatever3" id="whatever3" />
<button class="whatever3-button" id="defaultAction3" value="Go for it" name="whatever3" type="submit" onClick="cA('whatever.php#anchor3')" >Go for it
</button>
...
</form>
A:
You can try this:
<input type="whatever" name="whatever" id="whatever" onkeydown="if (event.keyCode == 13) {cA('whatever.php#anchor');}" />
Check this post for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Woocommerce remove bank account number on order thank you page
I am using woocommerce site and I have enabled the direct bank transfer payment method. I want to remove the account number of order thank you page but want to show in emails. Same function is called in both cases.
How can I differentiate it to show the account number only in email.. not on thank you page. I have tried it like:
global $pagename;
if($pagename == "checkout"){
//remove bank account number
}else{
//show bank account number
}
But its Not working.. can anyone give me suggestions...
Also i used this.
add_action('woocommerce_before_template_part', 'thankyou_bacs');
function thankyou_bacs() {
/* get bacs payment gateway class */
$methods = WC()->payment_gateways->payment_gateways();
$bacs_class = $methods['bacs'];
unset($bacs_class->account_details[0]['account_name']);
unset($bacs_class->account_details[0]['account_number']);
}
working great for checkout page, but hiding these details from email too. :( :(
A:
You could try to use conditional is_page('checkout') or is_checkout(), first.
Then you can use remove_action() for removing your hooked function from checkout page only…
This way you don't have to edit templates.
---- Update ----
USING CSS:
You can also use CSS to hide just account number targeting one of this selectors/classes. For example, in one of my e-commerce, this are the css selectors to target:
.woocommerce-checkout ul.order_details.bacs_details
.woocommerce-checkout ul.order_details.bacs_details > li.iban
.woocommerce-checkout ul.order_details.bacs_details > li.bic
With: display:none;
---- update2 ----
Using your hook with a conditional:
1) Inside:
add_action('woocommerce_before_template_part', 'thankyou_bacs');
function thankyou_bacs() {
if(is_checkout()){
/* get bacs payment gateway class */
$methods = WC()->payment_gateways->payment_gateways();
$bacs_class = $methods['bacs'];
unset($bacs_class->account_details[0]['account_name']);
unset($bacs_class->account_details[0]['account_number']);
}
}
1) Ouside:
if(is_checkout()){
add_action('woocommerce_before_template_part', 'thankyou_bacs');
function thankyou_bacs() {
/* get bacs payment gateway class */
$methods = WC()->payment_gateways->payment_gateways();
$bacs_class = $methods['bacs'];
unset($bacs_class->account_details[0]['account_name']);
unset($bacs_class->account_details[0]['account_number']);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
S3 ACL Public-Read on Swisscom Cloud
AFAIK Swisscom does not support Uploads into the S3 Service with a public-read status. The only way to share a file is via presigned url. Is this correct? Already asked here:
How to serve user-uploaded files on Swisscom Application Cloud?
In the docs, it's written though that PUT Object ACLis supported. According to the Amazon Specs this should include public-read as well.
What is the current case now? What is the best workaround if it's not possible to store public readable binaries? For example to serve images for a website stored on Swisscom S3?
A:
Swisscom Dynamic Storage currently does not support static web pages, which means every http request has to be signed. Workaround are shareable URLs with a very long expiration date so called Pre-signed Object URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't acquire add-in without personal account
I have developed an Outlook add-in that I have published in the store (https://appsource.microsoft.com/da-dk/product/office/WA104381386 ). The add-in is targeted Office365 work accounts.
However when users try to acquire the add-in they are asked to switch from their work account to a personal account.
I want the users to be able to get the add-in just with their Office365 account without having to switch to (and possible create) a personal account.
Not sure if this is something that I can configure in the add-in manifest or in the Seller Dashboard, but so far not been able to find any documentation on this.
Steps to reproduce:
Create a brand new test tenant (or use existing)
From within Outlook (web) opened settings -> Manage add-ins
Search for MeetingRoomMap -> click ‘get it’ (transferred to
https://appsource.microsoft.com/da-dk/product/office/WA104381386 )
Click free trial
Transferred to login page that only accepts personal account (account from tenant not accepted) – see screenshot attached.
If I choose ‘Get it now’ instead of ‘free trial’, I get this message: “Change to your personal account. If you want to proceed you must enter the email attached to your personal account”.
I’m not able to get the add-in without entering a personal account (screenshot in Danish).
A:
Unfortunately, purchasing add-in licenses is currently only available via Microsoft Accounts.
Users will be able to acquire trial licenses with their O365 Accounts via the Outlook store, but they will have to swap to MSA for the full purchase.
If you're looking to handle purchase for O365 accounts, I'd recommend reading our GTM guidance on freemium setups.
https://dev.office.com/blogs/gtm-how-to-monetize-with-office-add-ins-and-apps
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i send e-mail with SendGridAPICliente. Azure Website
I`m trying to send an e-mail with SendGrid but i got some errors.
I was making this tutorial but after install SendGrid i cant creat any instance of SendGridMessage.
I am using .NET Framework 4.5.2
var test = new SendGirdMessage();
I got this error:
Error 3 The type or namespace name 'SendGridMessage' could not be
found (are you missing a using directive or an assembly
reference?)
Then i already try to use SendGridAPIClient, this i can creat but that aren`t sending the e-mail.
I follow this tutorial With Mail helper class.
Could some one help me to send e-mail from azure?
A:
You should use the version 2 of SendGrid to that tutorial. To use this version you have that install the SendGrid C-Sharp 6.3.4 or bellow.
In Package Management Console write:
Install-Package SendGrid -version 6.3.4
| {
"pile_set_name": "StackExchange"
} |
Q:
Relation between runge domain and polynomial convexity
Are these concepts the same? Just to state the definitions
Definition 1 A domain $\Omega \in \mathbb{C}^n$ is a Runge domain if every function $f \in H(\Omega)$ can be approximated, uniformly on compact subsets of $\Omega$, by polynomials in $\mathbb{C}^n$.
Here $H$ stands for the space of holomorphic functions. While the definition of polynomial convexity is stated as
Definiton 2 Let $\mathcal{P}$ denote the set of holomorphic polynomials on $\mathbb{C}^n$. Let $K$ be a compact set in $\mathbb{C}^n$ and let
$\|P\|_K = \sup\limits_{z\in K}|P(z)|$ be the sup-norm of $P \in \mathcal{P}$ on $K$. The set
$$
\hat{K}
= \{ z \in \mathbb{C}^n : |P(z)| \leq \|P\|_K \ , \ P \in \mathcal{P} \}
$$
is called the polynomially convex hull of $K$. If the compact subsets $K \subset \omega$ have compact polynomial hulls $\hat{K}$, then we have a polynomial convex domain.
I have a book that gives an example [Wermer] which shows a domain $\Omega\in\mathbb{C}^2$ which is biholomorphic to a bidisc, but which is not a runge domain.
However another paper says the following:
"On the other hand , biholomorphic images of polydiscs can fail to be polynomically convex, see [Wermer]"
Just for completeness sake, here is the theorem both papers refers to
Theorem 1 [Wermer]> There is a bounded domain in $\mathbb{C}^2$ which analytically
(holomorphic) equivalent to the bidisk, but which is not a runge
domain
So one paper refers says that the domain is not Runge, while the other says that it fails to be polynomically convex.
Hence my question is as follows: Is being a Runge domain equivalent to being polynomically convex?
A:
The concepts are not equivalent:
The open subset $\Omega=\mathbb C^2\setminus\{0\}\subset \mathbb C^2$ is Runge but not polynomially convex: indeed for $K$ the unit sphere $||Z||=1$ centered at the origin $\hat K$ is the non compact set $0\lt||Z||\leq 1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get data from dict by using for-loop in Python
My input is
[['apple',{'john':3,'anna':4,'kitty':6}],['pear',{'john':4,'anna':3,'kitty':3}]]
Expected output:
{
'key':['apple','pear'],
'value':[
{
'name':'john',
'data':[3,4]
},
{
'name':'anna',
'data':[4,3]
},
{
'name':'kitty',
'data':[6,3]
}
]
}
The key is a list which conclude the first part of each item, such as 'apple' 'pear', and the value is another list.
How should I do it?
A:
You can achieve this with the help of collections.defaultdict:
from collections import defaultdict
value, key = defaultdict(list), []
for x in l:
key.append(x[0])
for k, v in x[1].items():
value[k].append(v)
To get the result:
In [15]: {'key': key, 'value': [{'name': k, 'data': v} for k, v in value.items()]}
Out[15]:
{'key': ['apple', 'pear'],
'value': [
{'data': [4, 3], 'name': 'anna'},
{'data': [6, 3], 'name': 'kitty'},
{'data': [3, 4], 'name': 'john'}]}
For a more efficient (?) version, subclass defaultdict to customize the default __missing__ hook to call the default_factory with missing key as a parameter (I copied this text and the implementation from the other answer of mine). Then you'll be able to do this in a single pass:
from collections import defaultdict
class mydefaultdict(defaultdict):
def __missing__(self, key):
self[key] = value = self.default_factory(key)
return value
# pass 'name' to the dictionary
value = mydefaultdict(lambda name: {'name': name, 'data': []})
key = []
for x in l:
key.append(x[0])
for k, v in x[1].items():
value[k]['data'].append(v)
The result is then
In [24]: {'key': key, 'value': value.values()}
Out[24]:
{'key': ['apple', 'pear'],
'value': [
{'data': [4, 3], 'name': 'anna'},
{'data': [6, 3], 'name': 'kitty'},
{'data': [3, 4], 'name': 'john'}]}
In Python 3, you'll have to call list(value.values()) instead of just value.values() to get a list object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I reading zero volts phase to earth?
When i measured the voltage reading on the socket I got an unusual reading
phase to neutral is 220V (expected reading )
phase to earth is 0V (unusual) ??
neutral to earth is oV (expected reading)
I do not understand why the phase to earth reading shows 0.... Could you please explain the underlying problem
A:
That is a simple "open ground", or "open earth" situation. The safety connection to "earth" is open somewhere in the circuit.
This is a problem that should be corrected. May I ask what prompted you to make these measurements?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change ContentDialog transition?
Windows Phone 8.1 introduced a new transition for dialogs and flyouts that looks like a Venetian blind. I don't like this; I preferred the way it looked in Windows Phone 8 where it sort of swiveled/tilted in. Is there any way to change this?
I've tried things like:
<ContentDialog.Transitions>
<TransitionCollection>
</TransitionCollection>
</ContentDialog.Transitions>
But it doesn't change the transition.
A:
You cannot override the transitions in the ContentDialog, etc. They are designed to be easy ways to get standard behaviour and will always use the PopupThemeTransition.
If you want non-standard behaviour then you can write a custom control which uses your own TransitionCollection. I couldn't find any existing samples exactly of this, but check out Callisto's CustomDialog for the general concept. It mimics the Windows MessageDialog with contents in a horizontally centred bar over a full-screen dimming window, but it shouldn't be hard to shift the UI to match Windows Phone's top-docked panel.
Once you're in your own control you can use whichever transitions you like. I don't have a WP8 device handy to see what the transition was, but the PaneThemeTransition with Edge="Left" sounds like it matches your description. If not then once you have transitions going you can swap it for one you like or remove all transitions and apply your own Storyboarded animation. I'd either stick with a standard transition which makes sense for the user or do a full customisation since the theme transitions could change again.
Creating a panel that looks right is pretty easy. The tricky part is in how to show the control. If you include it in your Xaml so it's part of the visual tree to start with then you can just show it. If it's not in the visual tree then you need to either add it to the visual tree or host it in a Popup.
Here's a quick and dirty UserControl which hosts itself in a Popup and uses a PaneThemeTransition to slide in from the right.
<UserControl
x:Class="App199.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App199"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400"
PointerReleased="UserControl_PointerReleased">
<UserControl.Transitions>
<TransitionCollection>
<PaneThemeTransition Edge="Left"/>
</TransitionCollection>
</UserControl.Transitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition x:Name="statusBarRow" Height="0" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row ="1" Background="Black">
<Ellipse Height="100" Width="100" Fill="Yellow" />
<TextBlock>Lorem Ipsum</TextBlock>
<Rectangle Height="100" Width="100" Fill="Red" />
</StackPanel>
<Border Grid.Row="2" Background="#7F000000" />
</Grid>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace App199
{
public sealed partial class MyUserControl1 : UserControl
{
Popup hostPopup;
public MyUserControl1()
{
this.InitializeComponent();
hostPopup = new Popup();
hostPopup.Child = this;
Loaded += MyUserControl1_Loaded;
Unloaded += MyUserControl1_Unloaded;
}
void MyUserControl1_Loaded(object sender, RoutedEventArgs e)
{
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void MyUserControl1_Unloaded(object sender, RoutedEventArgs e)
{
HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}
public void Show()
{
this.Height = Window.Current.Bounds.Height;
this.Width = Window.Current.Bounds.Width;
var occRect = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().OccludedRect;
statusBarRow.Height = new GridLength(occRect.Height);
hostPopup.IsOpen = true;
}
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (hostPopup.IsOpen)
{
hostPopup.IsOpen = false;
e.Handled = true;
}
}
private void UserControl_PointerReleased(object sender, PointerRoutedEventArgs e)
{
hostPopup.IsOpen = false;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding Return Values in C#
So this question follows on from a previous post that I am just trying to understand in full before I move on to more complicated C# stuff.
My question relates specifically to the return value of a function.
Consider the following function code:
public static void DisplayResult(int PlayerTotal, int DealerTotal){
if (PlayerTotal > DealerTotal) {
Console.WriteLine ("You Win!");
Console.ReadLine ();
}
else if (DealerTotal > PlayerTotal) {
Console.WriteLine ("Dealer Wins!");
Console.ReadLine ();
} else {
Console.WriteLine ("It is a Draw!");
Console.ReadLine ();
}
I could be wrong of course but I believe that the "void" keyword in the first line of code means that the function code result does NOT return a value.
What I am trying to understand is - the function calculates a result. It distributes text (eg: "you win!" etc) based on the result. Is the result of the function not considered a value?
By my own (novice) logic, I would have thought one of two things:
The return value of this function is a string because it is the output of the calculated result.
The return value of this function is an int because it calculates int results.
I hope this makes sense. I think understanding this concept will make it easier for me in future to write functions without second guessing return values. If anyone has an example of a function that actually DOES return a value it would also be appreciated.
A:
A bit of terminology first: C# doesn't have functions, it has methods.
Return values give some value to the method's caller. They aren't related to the statements executed within that method, except for the return statement. The method's signature dictates what (if any) type is returned by that method.
public void NoReturnValue()
{
// It doesn't matter what happens in here; the caller won't get a return value!
}
public int IntReturnValue()
{
// Tons of code here, or none; it doesn't matter
return 0;
}
...
NoReturnValue(); // Can't use the return value because there is none!
int i = IntReturnValue(); // The method says it returns int, so the compiler likes this
A:
A void method, as you have surmised, is one that returns no value. If you wrote:
var myResult = DisplayResult(3, 7)
you would get an error because there is no returned value to assign to myResult.
Your method outputs text to the console. This is a "side effect" of the method, but has nothing to do with its return value.
Also, the fact that your method interacts with ints has nothing to do with what its return value is either.
As a final point. The most basic thing to keep in mind is that a return value is a value that comes after the return keyword:
return "All done!";
Anything that doesn't involve the return keyword is not a return value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create GUID for each item created or added to a list.Using JSOM
Trying to create a unique ID(not sequential which is preferably an alpha numeric unique ID) for each row item added.
The same I have tried using an EXCEL formula, but how to integrate it with SharePoint list using JSOM and script editor web part. Also need to know how to bind the code to sharepoint list.
formula used in EXCEL sheet
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",
A:
The following example for your reference.
1.Create a custom list, add text field "GUID".
2.Add the code below into script editor web part in new form page.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function (){
var fieldTitle="GUID";
$("input[title='"+fieldTitle+"']").val(buildGuid());
$("input[title='"+fieldTitle+"']").attr("disabled", "disabled");
})
function buildGuid(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
</script>
If you add item, we can see the GUID in the "GUID" field.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make a non-member function which uses an overridden function?
In this code I try to overload += operation basically. Everything looks okay in non-member parts but when i write a non-member function, (+ operation in this part) It gives invalid abstract return type error and says += operation is pure within vector1d. How can I solve this problem?
class AbstractBase{
public:
virtual AbstractBase &operator+=(const AbstractBase &other)=0;
private:
}
////
class Vector1d:public AbstractBase{
public:
Vector1d &operator+=(const Vector1d &other);
private:
int size_;
vector<double> data_;
}
//non member func
Vector1d operator+(const Vector1d& vec1, const Vector1d& vec2);
///
Vector1d &Vector1d::operator+=(const Vector1d &other){
cout<<"sum operator is called"<<endl;
for(int i = 0; i < other.size_ ; i++)
data_.at(i) += other.data_.at(i);
return *this;
}
Vector1d operator+(const Vector1d& vec1, const Vector1d& vec2){
return (Vector1d) vec1 += vec2;
};
A:
Use the C++11 override contextual keyword when overriding. That will move your error closer to where you made your mistake. Which is that you did not override.
You are told this elsewhere, but it is confusing.
This:
virtual AbstractBase &operator+=(const AbstractBase &other)=0;
Has a different signature than this:
Vector1d &operator+=(const Vector1d &other);
And the second does not override the first. It just overloads. (They are different!)
You are violating the LSP in addition (see here), which basically states your design has fundamental errors. I lack information on how to fix that problem. LSP violation does not cause build breaks.
To fix your build break, simply do:
Vector1d &operator+=(const AbstractBase &other) override; // and maybe final
(The return types do not match exactly; this is ok, and the override keyword checks it, because of covariant return type rules in C++. Covariance does not apply to const& arguments (aka, in) in any sensible language (contravariance could sensibly, but C++ does not supply that for free, and you are not trying to do that anyhow).)
And for the body:
Vector1d &Vector1d::operator+=(const AbstractBase &other_abstract){
auto& other = dynamic_cast<Vector1d const&>(other_abstract); // can throw
std::cout<<"sum operator is called"<<std::endl;
for(int i = 0; i < other.size_ ; i++)
data_.at(i) += other.data_.at(i);
return *this;
}
This now throws a bad cast if the abstract type does not match the type you expect. Which is horrible, but it builds.
The LSP error is that your abstract base += implies any two objects with the same abstract base can be +='d. Your implementation does not agree, quite sensibly. This means your class heirarchy is junk and should be thrown out and possibly not replaced. But that is a wider problem than I can cover in a SO answer about your technical build break.
A:
Fundamentally, you never override operator+=(const AbstractBase &other).
You provide a new operator+= that takes a const Vector1d&, but this only allows using += with the derived type.
The base class operator += can be used with any AbstractBase so when you override this, you need to preserve the signature so that the derived implementation also works with any AbstractBase.
This may not makes sense for your class hierarcy, so think carefully about the utility of the abstract base class' operator+=.
A:
Even if Vector1d inherits from AbstractBase
Vector1d &operator+=(const Vector1d &other);
doesn't have the same signature as
AbstractBase &operator+=(const AbstractBase &other)=0
Consequently it cannot be a candidate for the override.
| {
"pile_set_name": "StackExchange"
} |
Q:
Auto Refresh Div Using jQuery from 5 Seconds to Zero
How to create a countdown counter in Drupal 7 that says:
Your download will start in 5 seconds...
During page load and it countdown the number to 5, 4, 3, 2, 1
And change the value to
Your download will start shortly...
When finished?
I found so many tutorials about this but not specific to what I am looking for.
I am also moving this question from Drupal stackexchange as suggested by Chapabu.
A:
25 jQuery countdown scripts here: http://www.tripwiremagazine.com/2013/04/jquery-countdown-scripts.html and the according StackOverflow-Question including excellent answers: How can I make a jQuery countdown
| {
"pile_set_name": "StackExchange"
} |
Q:
Whats the difference between [01], [0-1] and [0,1] in linux globbing?
Title, is there a reason to use one and not the other in X case?
[root@localhost ~]# ls 192.168.[0,1].1
192.168.0.1 192.168.1.1
[root@localhost ~]# ls 192.168.[01].1
192.168.0.1 192.168.1.1
[root@localhost ~]# ls 192.168.[1].1
192.168.1.1
[root@localhost ~]# ls 192.168.[01].1
192.168.0.1 192.168.1.1
[root@localhost ~]# ls 192.168.[0-1].1
192.168.0.1 192.168.1.1
[root@localhost ~]# ls 192.168.[10].1
192.168.0.1 192.168.1.1
[root@localhost ~]# ls 192.168.[01].1
192.168.0.1 192.168.1.1
A:
The expression [...] is part of the filename expansion set. The three examples you give are all different, but in some cases two of them can be equivalent:
[01]: this matches the character 0 or 1
[0,1]: this matches the character 0 or 1 or ,
[0-1]: this is a range expression, any character that falls between those two characters (0 and 1) will be matched. This depends on the current locale and the values of LC_COLLATE and LC_ALL. If LC_ALL=C, the range [0-1] and the set [01] will be equivalent.
This pattern is used in a filename expansion, this implies that if you would have a file named 192.168.,.1 it would have been matched with [0,1].
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting f:setPropertyActionListener value with a f:param value
I'm trying to use the setPropertyActionListener tag to set a value in my backing bean. However, it doesn't work as I expected.
Context: userService is an instance of my backing bean, which contains an int member, reqID. This, in turn, is the key to a map of objects that belong to a class called User. I'm trying to create a page that will list all instances of User, and provide a button to visit a separate view that shows that particular User's information. To do this, I'm attempting to set userService.reqID to the id of the chosen User so it can generate a reference to that user for the next view (which is done in the call userService.toUserInfo).
If I use the xhtml snippet below:
<ui:define name="content">
<h:form>
<h:panelGrid>
<ui:repeat value="#{userService.UserList.getUserList()}" var="user">
<li>
<h:outputText value="#{user.name}" />
<h:commandButton value="View details of #{user.name}" action="#{userService.toUserInfo}">
<f:param name="id" value="#{user.id}" />
<f:setPropertyActionListener target="#{userService.reqID}" value="#{id}"/>
</h:commandButton>
</li>
</ui:repeat>
</h:panelGrid>
</h:form>
</ui:define>
The tag does not appear to evaluate id correctly and I get a Null Pointer Exception.
Earlier, I tried changing my setPropertyActionListenerTag so it read out as:
<f:setPropertyActionListener target="#{userService.reqID}" value="id"/>
which gave me an error, because the tag was sending the string "id" as opposed to the int value of the parameter.
Is there some way to force f:setPropertyActionListener to evaluate the expression under value? Or is there another tag that will allow me to do this?
Also, is ui:param used appropriately here?
A:
The <f:param> (and <ui:param>) doesn't work that way. The <f:param> is intented to add HTTP request parameters to outcome of <h:xxxLink> and <h:xxxButton> components, and to parameterize the message format in <h:outputFormat>. The <ui:param> is intented to pass Facelet context parameters to <ui:include>, <ui:decorate> and <ui:define>. Mojarra had the bug that it also behaves like <c:set> without a scope. This is not the intented usage.
Just use <c:set> without a scope if it's absolutely necessary to "alias" a (long) EL expression.
<c:set var="id" value="#{user.id}" />
Put it outside the <h:commandLink> though. Also in this construct, it's kind of weird. It doesn't make the code better. I'd just leave out it.
<f:setPropertyActionListener ... value="#{user.id}" />
See also:
Setting ui:param conditionally
what is the scope of <ui:param> in JSF?
Defining and reusing an EL variable in JSF page
Unrelated to the concrete problem, if you're using EL 2.2 (as you're using JSF 2.2, you undoubtedly are as it requires a minimum of Servlet 3.0, which goes hand in hand with EL 2.2), then just pass it as bean action method argument without <f:setPropertyActionListener> mess. See also a.o. Invoke direct methods or methods with arguments / variables / parameters in EL and How can I pass selected row to commandLink inside dataTable?
<h:commandButton ... action="#{userService.toUserInfo(user.id)}">
On again another unrelated note, such a "View user" or "Edit user" request is usually idempotent. You'd better use <h:link> (yes, with <f:param>) for this. See also a.o. Creating master-detail pages for entities, how to link them and which bean scope to choose and How to navigate in JSF? How to make URL reflect current page (and not previous one).
Oh, that <h:panelGrid> around the <ui:repeat><li> doesn't make sense in HTML perspective. Get rid of it and use <ul> instead. See also HTMLDog HTML Beginner tutorial.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using interfaces in java
Suppose there in an interface Displaceable and a class Circle which implements Displaceable. Displaceable has a method named move() which of course is implemented in Circle.
What would happen in the following scenario?
Circle a = new Circle(..);
Displaceable b = a;
b.move()
Would the object refer to the Circle's move method?
A:
Yes, b.move() would be the same as calling a.move() in your scenario. This is polymorphism in action.
A:
Yes.
Displaceable b says what can be done to b. The compiler can (and does) check whether that method is available on that type (Displaceable) at compile time.
How this is done is not necessarily clear at compile time. It's up to the implementation, at run-time, to just do it (move).
At compile time, the promise (I can move!) is checked. At runtime, the code has to prove that it really can :)
Even if Displaceable were a class and not an interface, and implemented move itself, the actual move called run-time would still be the implementation (if that implementation, Circle, would have overridden the Displaceable implementation).
The only time there is a compile-time binding of a call (to e.g. move) to the actual implementation is when a method is defined as being static. That's also why static methods can't be defined in interfaces, as they don't hold implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recalling software keyboard only in English [without the option of choosing other languages]?
How can I have the android keyboard just in English [without the option of choosing the other languages] when recall it to fill a box (For example EditText)? I want to do this by programming not by changing the android setting.
A:
You can use Below code :
<EditText
android:id="@+id/nameText"
android:layout_width="177dp"
android:layout_height="wrap_content"
android:inputType="text"
android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ" />
Or :
EditText state = (EditText) findViewById(R.id.txtState);
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(state.getText().toString());
boolean bs = ms.matches();
if (bs == false) {
if (ErrorMessage.contains("invalid"))
ErrorMessage = ErrorMessage + "state,";
else
ErrorMessage = ErrorMessage + "invalid state,";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the default location of data in HDFS to some permanent location?
I am running Hadoop in a pseudo-distributed single node cluster and I have a problem in changing the default location of data from /var/lib/hadoop-0.20/cache/hadoop/dfs/data to some permanent location which does not get cleared every time I reboot. I am new to Hadoop ecosystem.Any help will be highly apprciated. Thanks :)
A:
Setting dfs.data.dir in hdfs-site.xml should help.
By default it is set to ${hadoop.tmp.dir}/dfs/data, that's why /var/lib/hadoop-0.20/cache/hadoop/dfs/data in your case.
You cand find more information about HDFS configuration options in hdfs-default.xml docs.
You need to create a permanent directory where hdfs user has write privilege. lets say /home/poulami/hadoopData/data then you will need to add following in hdfs-site.xml
<property>
<name>dfs.data.dir</name>
<value>/home/poulami/hadoopData/data</value>
<final>true</final>
</property>
| {
"pile_set_name": "StackExchange"
} |
Q:
Маскирование фонов CSS
Добрый день уважаемые. Подскажите как реализовать маскирование фонов в CSS ?
Необходимо добиться что б на выходе получить красный круг (5штук) с чёрным обводом. Эффект как-будто в диве с классом el дырка и через него просвечивает нижний фон. Я пробовал через clip-path но оно обрезает наружное, а мне надо то что внутри что б вырезало
.block{
width: 100px;
height: 500px;
background-color: red;
}
.el{
width: 100px;
height: 100px;
background-color: black;
/* -webkit-clip-path: circle(50% at 50% 50%);
clip-path: circle(50% at 50% 50%); */
}
<div class="block">
<div class="el">
<svg>
<defs>
<clipPath id="clipping">
<circle cx="50" cy="50" r="50" />
</clipPath>
</defs>
</svg>
</div>
</div>
A:
А может попробовать маски для этой цели. Сделаем из круга маску и сквозь нее будем смотреть на подложку.
В первом варианте у меня красный квадрат подложка, а во втором растровое изображение.
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200" viewBox="0 0 200 200">
<defs>
<mask id="mask">
<g stroke="gray" stroke-width="4" fill="white">
<circle cx="50%" cy="50%" r="45%" />
</g>
</mask>
</defs>
<g mask="url(#mask)">
<rect width="100%" height="100%" fill="red" />
</g>
</svg>
Теперь цветы. Фотка Yoksel и идеи её по использованию масок
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300" viewBox="0 0 300 300">
<defs>
<mask id="mask">
<g stroke="gray" stroke-width="12" fill="white">
<circle cx="50%" cy="50%" r="25%" />
</g>
</mask>
</defs>
<g mask="url(#mask)">
<image xlink:href="http://img-fotki.yandex.ru/get/6208/5091629.73/0_63193_9ffa75d7_L" width="100%" height="100%"></image>
</g>
</svg>
Вот в качестве маски шестиугольник
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300" viewBox="0 0 300 300">
<defs>
<mask id="mask">
<g transform="scale(2.95) translate(18 0)" stroke="gray" stroke-width="4" fill="white">
<path d="M48.9 60.9 16.9 60.9 1.2 33.4 17.1 6.1 48.7 6.2 64.4 33.6z" />
</g>
</mask>
</defs>
<g mask="url(#mask)">
<image xlink:href="https://img-fotki.yandex.ru/get/5106/yoksel.5a/0_44b5e_4da2ba62_orig" width="100%" height="100%"></image>
</g>
</svg>
Отличная статья о масках от Yoksel
A:
Такое ощущение, что недавно отвечал на такой же вопрос на SO.
Чёрная часть маски убирается из элемента, а белая остаётся:
html, body {
height: 100%;
margin: 0;
background: linear-gradient(to top, red, blue);
}
svg {
display: block;
width: 150px;
}
<svg viewBox="0 0 150 150">
<mask id="circles" maskUnits="objectBoundingBox">
<rect x="0" y="0" width="100%" height="100%" fill="white" />
<circle cx="40" cy="40" r="15" fill="black" />
<circle cx="80" cy="40" r="15" fill="black" />
<circle cx="70" cy="80" r="15" fill="black" />
</mask>
<rect x="0" y="0" width="100%" height="100%" fill="green" style="mask: url(#circles)" />
</svg>
| {
"pile_set_name": "StackExchange"
} |
Q:
${d^2\over dx^2}$ notation problem
How would I figure out the following problem.
Find
$\frac{d^2}{dx^2}$ $[(x^3-1)\frac{d^2}{dx^2}(6x-x^5)$
This is what I did
I took the derivative of $(6x-x^5)$ and got $(-20x^3)$
I did $(x^3-1)(-20x^3)$ and got $(-20x^6+20x^3)$
Then I took the derivative of that twice and got
$(-600x^4+120x)$
But did I do this correctly?
A:
Assuming you mean to close the left bracket on the right of the entire expression:$$\frac{d^2}{dx^2}\left[(x^3-1)\frac{d^2}{dx^2}(6x-x^5)\right]$$
Then your result is correct, but I suspect you meant that you took the derivative twice (sequentially), of $(6x - x^5)$, getting $$d/dx (6 - 5x^4) = -20x^3.$$
Then you correctly multiplied $(x^3 - 1)(-20x^3)$.
And then took the derivative of that product, twice, to get your answer: $-600x^4 + 120x$
Nice job.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert string to object by splitting the string javascript
I need to convert the full strings to array, object combination.
Example,
let string = {'user-0-residences-0-pincode': 678987};
// Expecting output will be
{
user: [
{
residences: [
{
pincode: 678987
}]
}]
}
A:
As per your requirement, you can try the following code
let string = { "user-0-residences-0-pincode": 678987 };
let output = null, temp;
Object.keys(string)[0]
.split("-0-")
.reverse()
.forEach(val => {
if (output === null) {
output = {};
output[val] = Object.values(string)[0];
} else {
temp = [];
temp.push(output);
output = {}
output[val] = temp;
}
});
console.log(output);
| {
"pile_set_name": "StackExchange"
} |
Q:
Configurar o caminho de saída do compilador no NetBeans
Alguém saberia configurar no Netbeans, para que quando eu compilar um projeto, gere o executável em uma pasta determinada? Nas propriedades do projeto, tem a opção vinculador, que acredito que seja a saída do programa, lá esta este diretório:
${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/meu_prog
Alguém sabe o que significa essas macros? Como mudar este diretório?
A:
Sim, é neste local que muda o destino do arquivo, só que o separador de diretórios é / e não \.
Se houver um diretório com o mesmo nome do arquivo de saída, pode precisar outros ajustes como colocar o .exe no final do nome na configuração de execução (Propriedades -> Executar -> Comando Executar).
A documentação do que significa está no arquivo Makefile, ou pelo menos pistas para as que não estão exatamente iguais às listadas. No projeto, fica numa pasta chamada "Arquivos Importantes" ou "Important Files" na versão em inglês.
CND_DISTDIR: diretório de distribuição, onde os arquivos finais estarão;
CND_CONF: Não diz, mas é a configuração usada, parece equivalente a ${CONF}: Tem valor Debug, Release ou outro nome que você crie nas propriedades de projeto;
CND_PLATFORM: a plataforma alvo, pelo que vi é o nome do compilador (definido por você) e o sistema operacional host que está construindo o programa. Pode ser Cygwin_4.x-Windows, ou Arduino-Windows, Arduino-Linux, AVR-Linux, etc.
Você também pode, sem alterar o destino do programa, copiar o mesmo para o local que quiser, adicionando o comando na seção .build-post do Makefile. Se quiser executar/debugar no novo local mudar as configurações dos comandos Executar e Depurar. Exemplo: depois das linhas
.build-post: .build-impl
# Add your post 'build' code here...
No Windows, adicione a linha:
${CP} ${CND_ARTIFACT_PATH_${CONF}}.exe ${USERPROFILE}/Desktop/
No Linux, a linha é:
${CP} ${CND_ARTIFACT_PATH_${CONF}} ${HOME}/Desktop/
Importante: Esta linha começa com um caractere [Tab], do contrário não funciona.
Importante 2: Nem sempre o ${USERPROFILE}/Desktop/ funciona. Por exemplo: No Windows eu mudei a pasta do meu desktop, e este caminho não copia o arquivo para o meu desktop. (Porque mudei é outra história) No Linux o ambiente que uso nem usa a pasta Desktop.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I get this error when I try to use db_change_field()?
My Drupal installation has a table with a field title of type varchar and length of 255.
For some custom process, I need to increase the length to 500 characters.
I tried doing so with the following code:
function mymodule_schema_alter(&$schema){
if( isset($schema['field_data_field_document_title']) ){
db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value',
array(
'length' => 11,
)
);
}
}
Originally I had that code in my .module file. When I flushed caches I could verify using the DEVEL module that my field length changed. But in phpmyadmin the field length remained 255.
Then I migrated the function to the .install file. I execute run updates and get the following error:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL' at line 1: ALTER TABLE {field_data_field_document_title} CHANGE field_document_title_value field_document_title_value DEFAULT NULL; Array ( ) in db_change_field() (line 3020 of /var/www/Intranet/includes/database/database.inc).
I could really use some help, please.
A:
The error you get is because you aren't using db_change_field() with the correct arguments. For example, if you look at block_update_7003(), you will see it calls the function as follows.
db_change_field('block', 'weight', 'weight', array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Block weight within region.',
), array(
'indexes' => array(
'list' => array('theme', 'status', 'region', 'weight', 'module'),
),
));
The last argument is the full array defining the field, not just the part that you need to change.
As the description for block_update_7003() says, its purpose is changing the weight column to normal int. If your code were correct, block_update_7003() should use the following call.
db_change_field('block', 'weight', 'weight', array(
'type' => 'int',
));
Also, hook_schema_alter() should be used to alter the schema, not adding or removing database fields. Drupal doesn't use that hook, but the example code is clear enough.
function hook_schema_alter(&$schema) {
// Add field to existing schema.
$schema['users']['fields']['timezone_id'] = array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Per-user timezone configuration.',
);
}
The description of the hook is probably not clear, since it doesn't say in which way the schema should be changed, but since is talking of $schema, the idea behind that hook is that it alters what returned from hook_schema(), which is what an alter hook normally does: Change the values returned from another hook.
It is then hook_install() or hook_update_N() that effectively changes the database table.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does your organization approach usability?
I have a good friend (my old college roommate, actually), who critiques my personal projects every once in awhile. He is a usability engineer at a large bank, and I'm constantly amazed at what kinds of things he catches/suggestions he makes. Back when I was in college, I always knew usability was important on some level, but I didn't really care all that much. These days, I've come to realize that a good usability expert is worth their weight in gold.
I have two parts to my question:
Does your organization have a team dedicated to usability? If so, how do they fit into your development process?
Can you recommend any usability "checklists" for software engineers who do not have access to usability experts to run through when developing UIs themselves? I googled the subject and found a few guides, but they were very long. I'm looking for something small, that I can tack to a tackboard and refer to without having to browse through an online book.
A:
First - congratulations! You've come to realize what far too few project leaders realize - that usability is an extremely important aspect of software. If people don't want to use your software, or can't figure out how to use it, then all of its technical prowess means nothing. And if they don't love your software, they'll jump to the next best thing when it becomes available.
In my organization, we fluctuate from having a dedicated usability guru, to being very proactive about usability among our engineers. Having a leader with a sense for usability helps, even if he's not officially a UI guy.
I asked a similar question to yours, Easily digestable UI tips for developers. The answers there are probably what you're looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace M for N in words finished on M, but the M it self
Problem: I need to replace 'm' for 'n' in all words finished on 'm', but not the 'm' it self.
Example text: Bombom has an m.
Expected return: Bombon has an m.
Current PHP code: $txt = preg_replace('/(m)(?=\\s|$)/i', 'n', $txt);
But it returns: Bombon has an n.
Bonus one: I want "Word" to be [a-zA-ZÀ-ÿ], so, 3m should not be replaced for 3n.
Bonus two (for another similar problem): Tell me how to replace Use Q for Iraq and Qatar for Use Q for Irak and katar (replace all occurences except when alone).
A:
As you are looking for a m which appears only at the end of a word, i.e it should be followed by a word boundary but preceded by a letter. You can use negative lookbehind like this.
Regex: /(?<=[A-Za-z])m\b/
Explanation:
m\b matches the m followed by a word boundary. So Bombom and m should match. But we need only Bombom. So use negative lookbehind.
(?<=[A-Za-z]) looks for a letter before matched m.
And then replace it with n.
It doesn't matches 3m since m is preceded by a digit.
Regex101 Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
run named .exe in subdirectory in windows cmd
I feel stupid for asking this, but here goes. In linux/mac, you can run an executable file in the shell, simply by writing its name. Can you do something similar in windows command line?
Example: I am in directory dir. I want to run a file a.exe in dir/subdir without changing directory to subdir, or writing subdir/a.exe. Is this possible?
A:
You can using one of the following:
"subdir/a.exe"
subdir\a.exe
A:
It is possible. All you need to do is ensure that the directory in which a.exe resides is included on the path.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a RegExp for node/mongo that will find data that DOESN'T contain the RegExp
I want to search a mongo database with a RegExp, but instead of returning data with the matched RegExp I want to return data that does not have the RegExp.
For example:
Find all data that does not contain a new RegExp("mediaType").
I have really bad knowledge of RegExp so I'm not sure how to go about this.
A:
To find elements matching a regexp (e.g. pattern) you can use:
db.coll.find({ fieldName: { $regex: /pattern/ } });
To find elements NOT matching the same regexp you can use:
db.coll.find({ fieldName: { $not: /pattern/ } });
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving that there are no other positive integer solutions to $y = \frac{3(x-5)}{(x-7)}$
Given the equation, $y = \frac{3(x-5)}{(x-7)}$, how do I find the set of solutions $(x, y)$ given $x, y \in \mathbb{Z^+}$, and prove that no other solutions exist.
I am able to do the first part by simply choosing arbitrary $x$ values. For example, integer solutions include the following: $(1, 2), (4, 1), (8, 9), (9, 6), $ etc.
How do I formally prove that these are solutions, and that no other solutions in the positive integers exist for this equation?
A:
We have: $y = 3+ \dfrac{6}{x-7}\implies x-7 \mid 6\implies x-7 = 1,-1,2,-2,3,-3,6,-6\implies x = ...., y = ....$
| {
"pile_set_name": "StackExchange"
} |
Q:
Solved - sudo into user instead of root with rundeck
i'm configuring a server for some bioinfo analysis on Centos7 and i installed rundeck.
Rundeck seems to launch scripts as its own account name and i decided to use the sudo bypass to make it access my scripts.
using visudo i can make sudo with rundeck change to root having some commands without password.
As soon as i put the user bioinfo instead of root, the system asks for a password for the same commands.
here is the part of the sudoers file :
root ALL=(ALL) ALL
bioinfo ALL=(ALL) ALL
rundeck ALL=(bioinfo) NOPASSWD:/home/bioinfo/singularity_data/Bionano3.5,/usr/local/bin/singularity,/bin/*
i dont know what's different between root and bioinfo as they have the same rights.
Would anyone have an idea on what would make it not working with bioinfo when it works fine with root ?
I tried my configuration running as root
su - rundeck
and then doing a
sudo whoami
if root => root
if bioinfo => ask for password
Thank you
A:
For the user bioinfo to be able to run sudo commands without typing in a password you need to modify the bioinfo entry in sudoers to include NOPASSWD:
bioinfo ALL=(ALL) NOPASSWD: ALL
Please note that doing this allows the user to run any sudo command without having to type the password in.
If the user is a member of a group (%wheel or %users for example) that is also specified in sudoers, the last entry takes precedence - so put this entry underneath.
If you are want one user to be able to run things as another user without needing a password:
rundeck ALL=(bioinfo) NOPASSWD:/home/bioinfo/singularity_data/Bionano3.5,/usr/local/bin/singularity,/bin/*
then you need to invoke commands in the format sudo -u bioinfo <cmd> otherwise it thinks you're still trying to invoke as root
| {
"pile_set_name": "StackExchange"
} |
Q:
jxTable Initial sort order
I'd like to initially sort a table. I tried following code:
tableModel = createTableModel(model);
rowSorter = new TableRowSorter<>(tableModel);
rowSorter.setSortKeys(Arrays.asList(getDefaultSort()));
rowSorter.sort();
final JXTable table = new JXTable();
table.setAutoCreateRowSorter(false);
table.setRowSorter(createSorter());
When I click the default sort column it works fine, so there seems to be no problem with the actual sorting. But the UI doesn't sort initially with the above code, the UI shows no sort indicator (that small triangle in the column header). What do I missing?
A:
The problem might be that the RowSorter is set before the TableModel is set. I had this problem once.
| {
"pile_set_name": "StackExchange"
} |
Q:
No hyphens in biblatex
How can I suppress hyphenation in biblatex?
(I know that only one sentence usually is considered bad question quality, but why over-complicate a simple (?) problem)
A:
It's a good idea to disable hyphenation in bibliographies, but it will only yield acceptable results if you also disable justification, that is, if you set your bibliography with no hyphenation plus ragged-right (to suppress awkward stretching and shrinking of inter-word space). The command that switches to a right rag and (implicitly) turns off hyphenation is \raggedright.
Now, biblatex has a command called \bibsetup:
\bibsetup: Arbitrary code to be executed at the beginning of the bibliography, intended for commands which affect the layout of the bibliography.
So let's append \raggedright to whatever else is already contained in \bibsetup:
\documentclass[10pt,DIV=5]{scrartcl}
\usepackage[style=authoryear]{biblatex}
\usepackage{filecontents}
\begin{filecontents}{testbib.bib}
@INCOLLECTION{Cahn97,
author = {Cahn, Michael},
title = {Die Rhetorik der Wissenschaft im Medium der Typographie: Zum Beispiel die Fußnote},
year = {1997},
pages = {91-109},
crossref = {RHW97}}
\end{filecontents}
\appto{\bibsetup}{\raggedright}
\bibliography{testbib.bib}
\begin{document}
\cite{Cahn97}
\printbibliography
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
gulp-sass, watch stops when invalid property name
watch stops when error messages occur.
stream.js:94
throw er; // Unhandled stream error in pipe.
^
source string:51: error: invalid property name
How I can keep watch running and just to tell me where is the error located.
grunt could deal with errors and doesn't need to stop,
styleSheet.scss:41: error: invalid property name
otherwise, I need to keep typing "gulp" in the command-line when an error occurs.
A:
This answer has been appended to reflect recent changes to Gulp. I've retained the original response, for relevance to the OPs question. If you are using Gulp 2.x, skip to the second section
Original response, Gulp 1.x
You may change this default behavior by passing errLogToConsole: true as an option to the sass() method.
Your task might look something like this, right now:
gulp.task('sass', function () {
gulp.src('./*.scss')
.pipe(sass())
.pipe(gulp.dest('./'));
});
Change the .pipe(sass()) line to include the errLogToConsole: true option:
.pipe(sass({errLogToConsole: true}))
This is what the task, with error logging, should look like:
gulp.task('sass', function () {
gulp.src('./*.scss')
.pipe(sass({errLogToConsole: true}))
.pipe(gulp.dest('./'));
});
Errors output will now be inline, like so:
[gulp] [gulp-sass] source string:1: error: invalid top-level expression
You can read more about gulp-sass options and configuration, on nmpjs.org
Gulp 2.x
In Gulp 2.x errLogToConsole may no longer be used. Fortunately, gulp-sass has a method for handling errors. Use on('error', sass.logError):
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
If you need more fine-grained control, feel free to provide a callback function:
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass()
.on('error', function (err) {
sass.logError(err);
this.emit('end');
})
)
.pipe(gulp.dest('./css'));
});
This is a good thread to read if you need more information on process-control: https://github.com/gulpjs/gulp/issues/259#issuecomment-55098512
A:
Actually above anwsers doesn't work for me (Im using gulp-sass 3.XX). What really worked:
gulp.task('sass', function () {
return gulp.src(config.scssPath + '/styles.scss')
.pipe(sourcemaps.init())
.pipe(sass({ outputStyle: 'compressed' })
.on('error', sass.logError)
)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.cssPath))
});
In gulp-sass 3.x.x when I was using "sass.logError(err);" I constantly recive error that "this.emit('end'); is not a function". Now when I'm using:
.pipe(sass({ outputStyle: 'compressed' })
.on('error', sass.logError)
)
everything is working like a charm
A:
In gulp "^2.0.0" the option errLogToConsole will no longer work. Instead gulp-sass has a built in error logging callback that uses gulp-util under the hood. Also, because gulp has some problems with killing the process on errors, if you are using with watch you will have to call this.emit('end')
https://github.com/gulpjs/gulp/issues/259#issuecomment-55098512
var sass = require('gulp-sass');
//dev
sass(config.sassDev)
.on('error', function(err) {
sass.logError(err);
this.emit('end'); //continue the process in dev
})
)
//prod
sass(config.sassProd).on('error', sass.logError)
| {
"pile_set_name": "StackExchange"
} |
Q:
Add new node to local XML file with JS or jQuery
I'd like to add new elements to a XML file from a user input.
I've tried a lot possible ways but none of them worked for me :(
How can I add a new node/element/item to a existing local XML file using JavaScript or jQuery?
This is my current state:
function addElement() {
var xml;
if (window.activexobject) {
xml = new activexobject("microsoft.xmlhttp");
} else {
xml = new xmlhttprequest();
}
xml.onreadystatechange = function () {
if (xml.readystate == 4 && xml.status == 200) {
var resp = xml.responsexml;
var user = xml.responsexml.createelement("User");
var name = xml.responsexml.createelement("name");
name.appendchild(xml.responsexml.createtextnode("sof_user"));
var admin = xml.responsexml.createelement("admin");
admin.appendchild(xml.responsexml.createtextnode("false"));
user.appendchild(name);
user.appendchild(admin);
xml.responsexml.documentelement.appendchild(user);
}
}
xml.open("get", "users.xml", true);
xml.send(null);
}
the XML should look like this:
<Users>
<User>
<name>testuser</name>
<admin>true</admin>
</User>
<User>
<name>sof_user</name>
<admin>false</admin>
</User>
....
</Users>
A:
You should be able to build up your XML something like this:
usersNode = document.createElement("Users");
userNode = document.createElement("User");
nameNode = document.createElement("name");
nameNode.innerText = "testuser";
adminNode = document.createElement("admin");
adminNode.innerText = "true";
userNode.appendChild(nameNode);
userNode.appendChild(adminNode);
usersNode.appendChild(userNode);
userNode = document.createElement("User");
nameNode = document.createElement("name");
nameNode.innerText = "sof_user";
adminNode = document.createElement("admin");
adminNode.innerText = "false";
userNode.appendChild(nameNode);
userNode.appendChild(adminNode);
usersNode.appendChild(userNode);
console.log(usersNode.innerHTML);
I think that should give you what you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
non-void function works fine even without executing return
I'm a computer science college student. Yesterday, I have a class about Binary Search Tree using C++. We are taught by lab assistants in that class.
They define the node in the tree as a struct like this :
struct Data{
char name[15];
int age;
Data *left,*right;
};
and they give us a code to search within the BST like this:
// temp is current node, name is the value of the node to be searched for.
Data* search(Data *temp,char name[]) {
if(strcmp(temp->name,name)>0)
search(temp->left,name);
else if(strcmp(temp->name,name)<0)
search(temp->right,name);
else
return temp;
}
I notice that code is wrong. If the function gets into the first or the second if block, it will not execute any return statement.
But when the lab assistant run the code, it works just fine.
I thought maybe this behaviour is compiler specific.
But when I tried that code on gcc, the function also work fine. (our university uses microsoft visual c++ compiler)
Can anyone explain what is happening? why is this code working?
PS: ignore other errors such as when the node is empty, the value is not found, etc.
A:
It's just undefined behavior.
It appears to work because there's one register that holds the return value. In the deepest paths of the recursion tree, the temp is moved into that register, and never cleared or changed afterwards, so that register will contain the correct node until the first call returns.
When the first call returns, the calling context checks that register for the return value, which happens to be correct. But you shouldn't rely on this. It's not safe to assume it will always work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is bind() necessary if I want to receive data from a server using UDP?
Is it necessary to have in the client bind, if I want to receive data from a server?
I've seen a schema (look at the image below), and it seems that it's not necessary. But from what I know, bind is necessary to give an address to a socket. If I don't "bind" the socket, how can I send data to it?
A:
As a client, the application needs to be aware of the server port to which it needs to connect, and as a server, the application needs to be aware of the server port to which it needs to listen. Therefore, the server needs to bind to an IP address and port so that the client can connect to it.
The client can simply create a socket and call connect(). Binding to an available IP address and ephemeral port shall implicitly happen. But, yes, nothing prevents you from having the client bind to a particular IP address and port.
In the case of UDP, despite there being no "connection" mechanism, servers still need to bind to IP addresses and ports to allow the clients to send data to them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prototype method attached to event getting undefined
I am new in OOP in Javascript, I wanted to have my Slider object with its own attributes and methods. It works fine until I add the Eventlistener with my method slideNextImage. Once this method is triggered every attribute inside the method is undefined. If I launch the method without attaching any event it works good.
function Slider(photos, currentPhoto){ //Constructor
this.photos = photos;
this.currentPhoto = currentPhoto;
}
Slider.prototype.slideNextImage = function () {
document.getElementById("slider").style.backgroundImage = "url(" + this.photos[this.currentPhoto] + ")";
console.log("La foto actual es la " + this.currentPhoto + " y en el almacen hay " + this.photos.length);
}
var photos = ["../imagenes/images/wallpaper_5.jpg", "../imagenes/images/wallpaper_4.jpg", "../imagenes/images/wallpaper_3.jpg", "../imagenes/images/wallpaper_2.jpg", "../imagenes/images/wallpaper_1.jpg"];
var slider = new Slider(photos, 0);
document.getElementById("next").addEventListener("click", slider.slideNextImage);
Thank you in advance.
A:
Thats because 'this' is not bound to the object you really want in this case. (in your case 'this' will be bound to the element on which the event had been triggered)
One way to solve it is by explicitly bind 'this' to the slider by changing the addEventListener line to:
document.getElementById("next").addEventListener("click", Slider.prototype.slideNextImage.bind(slider));
| {
"pile_set_name": "StackExchange"
} |
Q:
Changes in pfgplot barchart
I found many, many helpful things on tex.stackexchange for pgfplots - thanks for that!
But i can't figure out how to:
insert a new line after "without" or "with"
hide value 0 or the whole bar
change the x tick's so there's no decimal power ([10^..])
prevent nodes near coords of beein plottet outside the chart
the two charts:
and the sourcecode:
\documentclass[a4paper]{report}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{pgfplots}
\title{Tests}
\pgfplotsset{counter_barchart/.style={
width=0.85\textwidth,
height=5cm,
xbar,
xmin=0,
xmajorgrids = true,
tick align = outside, xtick pos = left,
x tick label style={ /pgf/number format/1000 sep=},
enlarge y limits=0.4,
symbolic y coords={Ass. Optimization,with Optimization,without Optimization},
ytick=data,
yticklabel style={text width=0.2\textwidth},
every node near coord/.append style={/pgf/number format/1000 sep=},
nodes near coords,
nodes near coords align={horizontal},
legend style={at={(0.5,-0.35)},anchor=north,legend columns=-1},
reverse legend
}}
\begin{document}
\begin{tikzpicture}
\begin{axis}[counter_barchart]
\addplot coordinates {(0,Ass. Optimization)(19243,with Optimization) (8898,without Optimization)};
\addplot coordinates {(7854,Ass. Optimization) (6652,with Optimization) (6548,without Optimization)};
\legend{Second,First}
\end{axis}
\end{tikzpicture}
\\
\begin{tikzpicture}
\begin{axis}[counter_barchart]
\addplot coordinates {(3985,without Optimization) (5456,with Optimization)};
\addplot coordinates {(5223,without Optimization) (11054,with Optimization)};
\legend{Second,First}
\end{axis}
\end{tikzpicture}
\end{document}
A:
To avoid the hyphenation in the yticklabel:
yticklabel style={text width=0.2\textwidth,align=flush left},
To hide value 0 as nodes near coords:
nodes near coords={%
\pgfmathtruncatemacro\NNC{\pgfkeysvalueof{/data point/x}}%
\ifnumequal{\NNC}{0}{}{\NNC}% needs package etoolbox
},
To avoid xtick scaling:
scaled x ticks=false,
To prevent nodes near coords of being plotted outside the chart:
enlarge x limits={0.15,upper},
Code:
\documentclass[a4paper]{report}
\usepackage{etoolbox}
\usepackage{pgfplots}
\pgfplotsset{
counter_barchart/.style={
width=0.85\textwidth,
height=5cm,
xbar,
xmin=0,
xmajorgrids = true,
tick align = outside, xtick pos = left,
x tick label style={/pgf/number format/1000 sep=},
scaled x ticks=false,
enlarge y limits=0.4,
enlarge x limits={0.15,upper},
symbolic y coords={Ass. Optimization,with Optimization,without Optimization},
ytick=data,
yticklabel style={text width=0.2\textwidth,align=flush left},
nodes near coords={%
\pgfmathtruncatemacro\NNC{\pgfkeysvalueof{/data point/x}}%
\ifnumequal{\NNC}{0}{}{\NNC}%
},
nodes near coords align={horizontal},
legend style={at={(0.5,-0.35)},anchor=north,legend columns=-1},
reverse legend
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[counter_barchart,xtick={0,4000,8000,12000,16000,20000}]
\addplot coordinates {(0,Ass. Optimization)(19243,with Optimization) (8898,without Optimization)};
\addplot coordinates {(7854,Ass. Optimization) (6652,with Optimization) (6548,without Optimization)};
\legend{Second,First}
\end{axis}
\end{tikzpicture}
\vspace{1cm}
\begin{tikzpicture}
\begin{axis}[counter_barchart]
\addplot coordinates {(3985,without Optimization) (5456,with Optimization)};
\addplot coordinates {(5223,without Optimization) (11054,with Optimization)};
\legend{Second,First}
\end{axis}
\end{tikzpicture}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving IVP with delta function
Solve the IVP. $y^{''}+2y^{'}+2y=\delta(t-\pi); \;\;y(0)=1\;\;y^{'}(0)=0$
Here is what I did: I took the Laplace transform of the IVP and obtained the following $$(s^2+2s+2)Y[S]-s-1=e^{-\pi s}$$ Solving for $Y[S]$ yields $$\dfrac{e^{-\pi s}+s+1}{s^2+2s+2}=\dfrac{e^{-\pi s}}{(s+1)^2+1}+\dfrac{s+1}{(s+1)^2+1}$$ The inverse LaPlace Transform of this function is simply $$u_{\pi}(t)e^{-(t-\pi)}\sin(t-\pi)+e^{-t}\cos(t)$$ according to the book I am missing a $+e^{-t}\sin (t)$ can anyone point out any errors I have made in my calculations?
A:
Your computation of the Laplace transform of the left hand side isn't quite correct; you should have
$$(s^2 Y(s) - s) + 2(s Y(s) - 1) + 2 Y(s) = Y(s) (s^2 + 2s + 2) - s - 2$$
Thus,
$$Y(s) = \frac{e^{-\pi s}}{(s + 1)^2 + 1} + \frac{s + 1}{(s + 1)^2 + 1} + \frac{1}{(s + 1)^2 + 1}$$
which gives exactly the $e^{-t} \sin t$ term you were looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using GetHttpConnection in MFC
I have a rest Server written in java and I am trying to call a GET method from an MFC client.
The server URL is http://localhost:8080/com.test.simpleServlet/api/customers and this returns me the proper value when I run through the crome postman plugin.
I have implemented Java Restful WebService as the Server, with com.test.simpleServlet as a servlet.
Now I am trying to implement a Client to call this URL using MFC. This is my sample code.
CString strServerName = L"http://localhost:8080/com.test.simpleServlet";
INTERNET_PORT nPort = 8080;
pServer = session.GetHttpConnection(strServerName, nPort);
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, L"/api/customers"); //strObject);
pFile->SendRequest();
pFile->QueryInfoStatusCode(dwRet);
I am not able to make this work and I get the error 12007(The server name could not be resolved) at
pFile->SendRequest();
I guess I am doing something very silly here, but unfortunately I am not able to figure it out. I am not sure if the ServerURL is passed correctly.
I had passed it as "http://localhost:8080/com.test.simpleServlet".
Request you to kindly guide.
Thanks
Sunil
A:
It was a very silly mistake.
The code should be
CString strServerName = L"http://localhost";
.............
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, L"/com.test.simpleServlet/api/customers");
| {
"pile_set_name": "StackExchange"
} |
Q:
A graph connectivity problem (restated)
Given an undirected connected graph, our goal is to remove some edges to make the graph disconnected. The constraint is that each node of the graph can not lose more than $m$ edges incident to it. I want to find the minimum $m$ for which the goal is achievable. Is there any efficient algorithm to compute this minimum $m$ (and/or which edges to remove)? Or is it NP-complete?
A:
It appears to be NP-complete even when m=1: see The Complexity of the Matching-Cut Problem, Maurizio Patrignani and Maurizio Pizzonia, WG 2001, http://dx.doi.org/10.1007/3-540-45477-2_26
| {
"pile_set_name": "StackExchange"
} |
Q:
Android custom view drawing twice
In my activity A, this view called twice, but in my activity B, there is no problem.
Activity A is very simple layout with a few linearLayout. I'm about to go crazy, what can be the problem?
Here is I have my AdBannerView:
public class AdBannerView extends LinearLayout {
public ImageView adIcon, adInstall;
public TextView_ adTitle, adDesc;
public ProgressBar adProgress;
RelativeLayout adWrapperLay;
private boolean impSent, adLoaded = false;
public AdBannerView(Context context) {
super(context);
}
public AdBannerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public AdBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View wrapper = inflater.inflate(R.layout.view_ad_banner, this, true);
adIcon = (ImageView) wrapper.findViewById(R.id.adIcon);
adInstall = (ImageView) wrapper.findViewById(R.id.adInstall);
adTitle = (TextView_) wrapper.findViewById(R.id.adTitle);
adDesc = (TextView_) wrapper.findViewById(R.id.adDesc);
adProgress = (ProgressBar) wrapper.findViewById(R.id.adProgress);
adWrapperLay = (RelativeLayout) wrapper.findViewById(R.id.adWrapperLay);
Log.d("AdBannerView", "before loadAd()");
if(NativeAdManager.getInstance().isAdEnabled)
loadAd();
}
public void loadAd(){
if(adLoaded)
return;
adLoaded = true;
Log.d("AdBannerView", "loadAd() request");
NativeAdManager.getInstance().getAd(getContext(), new NativeAdManager.AdListener() {
@Override
public void adLoaded(final NativeAdResponse.Ads[] ads) {
/* load img */
Picasso
.with(getContext())
.load(ads[0].adIc)
.into(adIcon);
/* load title */
adTitle.setText(""+ads[0].adTit);
adDesc.setText(""+ads[0].adDesc);
/* click listener */
adInstall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
App app = (App) getContext().getApplicationContext();
app.getUiController().loadUrlWithoutAdBlocker(ads[0].adClk);
}
});
/* show this layout */
showAd(ads[0].adBeacons);
Log.d("AdBannerView", "loaded with size = " + ads.length);
}
});
}
private void showAd(final NativeAdResponse.adBeacons[] adBeacons) {
adProgress.setVisibility(GONE);
adIcon.setVisibility(VISIBLE);
}
}
I'm including to layout like this:
<.... AdBannerView match_parent etc />
Logs that proves drawing twice:
10-29 20:28:19.219 6698-6698/pack D/AdBannerView﹕ before loadAd()
10-29 20:28:19.219 6698-6698/pack D/AdBannerView﹕ loadAd() request
10-29 20:28:19.295 6698-6698/pack D/AdBannerView﹕ before loadAd()
10-29 20:28:19.295 6698-6698/pack D/AdBannerView﹕ loadAd() request
10-29 20:28:19.636 6698-6698/pack D/AdBannerView﹕ loaded with size = 1
10-29 20:28:19.852 6698-6698/pack D/AdBannerView﹕ loaded with size = 1
Problematic activity A:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<package.AdManager.AdBannerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
/>
</RelativeLayout>
Activity A.java (I deleted everything in layout and class except of AdBannerView but still same):
package package.Activity;
public class NewsRead extends Base {
ToolBarView toolBarView;
RelativeLayout backgroundLayForMainBgColor;
ImageView imageView;
TextView_ titleText, contentText, sourceText;
LinearLayout wrapperLay /* for homeViewRowBg */, relatedNewsLay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
/*
this.toolBarView = (ToolBarView) findViewById(R.id.toolBarView);
this.backgroundLayForMainBgColor = (RelativeLayout) findViewById(R.id.backgroundLayForMainBgColor);
this.imageView = (ImageView) findViewById(R.id.imageView);
this.titleText = (TextView_) findViewById(R.id.titleText);
this.contentText = (TextView_) findViewById(R.id.contentText);
this.sourceText = (TextView_) findViewById(R.id.sourceText);
this.wrapperLay = (LinearLayout) findViewById(R.id.wrapperLay);
changeTheme();
toolBarView.hideDeleteButton().setToolBarClickListener(new ToolBarView.ToolBarClickListener() {
@Override
public void backButtonClick() {
finish();
}
@Override
public void deleteButtonClick() {
}
});
Intent intent = getIntent();
if(intent == null)
return;
loadNewsDetail(intent);
*/
}
private void loadNewsDetail(Intent intent) {
String neTi = intent.getStringExtra("neTi");
String neCo = intent.getStringExtra("neCo");
String neSi = intent.getStringExtra("neSi");
String neIm = intent.getStringExtra("neIm");
String neUr = intent.getStringExtra("neUr");
/**/
Picasso
.with(this)
.load(neIm)
//.placeholder(R.drawable.icon_placeholder)
.into(imageView);
titleText.setText(neTi);
contentText.setText(neCo);
sourceText.setText("Source: "+ Html.fromHtml("<u>"+neSi+"</u>"));
}
private void changeTheme() {
ThemeModel curTheme = ThemeController.getInstance().getCurrentTheme();
if(curTheme.hasBgImage()) {
backgroundLayForMainBgColor.setBackground(curTheme.mainBgDrawable);
} else {
backgroundLayForMainBgColor.setBackgroundColor(Color.parseColor(ThemeController.getInstance().getCurrentTheme().mainBgColor));
}
wrapperLay.setBackgroundColor(Color.parseColor(curTheme.homeViewRowBg));
}
protected int getLayoutResourceId() {
return R.layout.activity_news_read;
}
@Override
protected void onSoftInputShown() {
}
@Override
protected void onSoftInputHidden() {
}
@Override
protected String getActivityName() {
return "news_read";
}
@Override
public void onBackPressed(){
super.onBackPressed();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
Base:
public abstract class Base extends Activity {
private boolean isKeyboardOpened;
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(getLayoutResourceId());
keyBoardListener();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
TrackingController.onActivityOpen(getActivityName());
}
}, 50);
}
@Override
public void onDestroy() {
super.onDestroy();
}
protected abstract int getLayoutResourceId();
public void Toast(String str) {
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public void Log(String str) {
Log.d("act_name:"+getActivityName(), str);
}
private void keyBoardListener(){
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > 100 ) { // 99% of the time the height diff will be due to a keyboard.
if(isKeyboardOpened == false){
onSoftInputShown();
}
isKeyboardOpened = true;
}else if(isKeyboardOpened == true){
onSoftInputHidden();
isKeyboardOpened = false;
}
}
});
}
public String getString_(int resId){
return getResources().getString(resId);
}
protected abstract void onSoftInputShown();
protected abstract void onSoftInputHidden();
protected abstract String getActivityName();
}
A:
Here's your bug :) Hopefully
You have in your base a call to setContentView and then in your deriving class you have call to super create (which calls the setContentView [which creates the adElement]) but after that you call again setContentView(getLayoutResourceId()); (this time from your derived class which overrides the layout but even if it didn't it's calling actually the same content I imagine so that's why it looks normal :)
So the fix should be easy - remove the setContentView(getLayoutResourceId()) from your activity A because it's already called from the base activity
| {
"pile_set_name": "StackExchange"
} |
Q:
Go: time.Parse() issue
I have the following code:
timeLocal := "01/July/2015:18:12:25 +0900"
inFormat := "02/January/2006:15:04:05 -0700"
parsed, err := time.Parse(inFormat, timeLocal)
if err != nil {
log.Fatal("Time format was not recognized!")
}
Now, parsing works fine. But when I run:
fmt.Println(timeLocal)
fmt.Println(inFormat)
fmt.Println(parsed)
The output is:
01/July/2015:18:12:25 +0900
02/January/2006:15:04:05 -0700
2015-07-01 18:12:25 +0900 +0900
Should the second +0900 be there? What is the stupid thing that I'm doing? Sorry, it was really a long day, I don't see what I'm missing.
Oh, and the whole file is here:
package main
import (
"fmt"
"time"
"log"
)
func main() {
timeLocal := "01/July/2015:18:12:25 +0900"
inFormat := "02/January/2006:15:04:05 -0700"
parsed, err := time.Parse(inFormat, timeLocal)
if err != nil {
log.Fatal("Time format was not recognized!")
}
fmt.Println(timeLocal)
fmt.Println(inFormat)
fmt.Println(parsed)
}
A:
If you look at documentation of time.Time you will see what the default output format is:
String returns the time formatted using the format string:
"2006-01-02 15:04:05.999999999 -0700 MST"
Now you should see what the second +0900 is doing there – this is a location (time zone) name. Since your input format doesn't have a name it will simply repeat an offset.
You can provide name by altering your input format to parse location name. Alternatively you can provide an output format which doesn't print the name, if you don't need it.
Your modified example:
package main
import (
"fmt"
"time"
"log"
)
func main() {
timeLocal := "01/July/2015:18:12:25 +0900 XYZ"
inFormat := "02/January/2006:15:04:05 -0700 MST"
parsed, err := time.Parse(inFormat, timeLocal)
if err != nil {
log.Fatal("Time format was not recognized!")
}
fmt.Println(timeLocal)
fmt.Println(inFormat)
fmt.Println(parsed) // 2015-07-01 18:12:25 +0900 XYZ
fmt.Println(parsed.Format("02/January/2006:15:04:05 -0700"))
}
http://play.golang.org/p/xVGvlt-M5B
| {
"pile_set_name": "StackExchange"
} |
Q:
Definition question in algebraic topology.
Definition: The $p$th (de Rham) cohomology group is the quotient vector space $$H^p(U) = \frac{Ker(d:\Omega^{p}(U)\to \Omega^{p+1}(U)}{Im(d:\Omega^{p-1}(U)\to \Omega^{p}(U))}$$
where $U \in \tau_{\mathbb{R}^n}$, that is $U$ is an open set in $\mathbb{R}^n$.
I am wondering, because it says that $H^p(U) = 0$ for any $p <0$. So what happens if $p > n$ in the definition? For example, if $U \subset \mathbb{R}^2$ is an open set, then what is $H^1(U)$? Is it also zero?
My book also states the Mayer-Vietoris as an exact sequence of cohomology quotient vector spaces,
$$\dots\to H^p(U) \to H^{p}(U_1) \oplus H^{p}(U_2) \to H^{p}(U_1 \cap U_2) \to H^{p+1}(U) \to \dots$$ where $U = U_1 \cup U_2 \in \tau_{\mathbb{R}^n}$. Now does the "dot, dot, dot" imply it never ends in $0$?
A:
If $p>n$, then $H^p(U)=0$ since $\Omega^p(U)=0$ (for open $U\subseteq \mathbb{R}^n$).
If $U\subseteq \mathbb{R}^2$ is an open set, then $H^1(U)$ depends on $U$ (but it is always finite dimensional and its dimension counts the number of "holes" in $U$, roughly speaking).
The $\dots$ just signifies that the sequence extends over all integer $p$. However, this doesn't imply that it never ends in $0$ - in fact, all but finitely many terms in this sequence are $0$ by the above reasoning. Also, you could have a sequence consisting entirely of $0$'s too if you choose $U$ and $V$ appropriately!
Let me know if you need clarification on any of these points and I would be very happy to do so!
| {
"pile_set_name": "StackExchange"
} |
Q:
Heroku DB Query running thousands of times for 4 records
Not really sure what is going on. I have an application that worked fine until about a week ago. Now when I try to load a specific page that displays data it runs this query thousands of times and eventually times out. There are only 4 records that meet these criteria, and the query itself was working fine with as many as 4k + records (with some downtime but it is a personal app).
This is the output, over and over
...
2019-08-01T21:14:28.443577+00:00 app[web.1]: [9d861f61-b6eb-42a8-b3d2-a9132d974644] CACHE (0.0ms) SELECT COUNT(*) FROM "steps" WHERE (user_id = 1 AND status = 1)
...
The number in brackets changes but everything else just keeps running until it times out. I'm not sure if I have to dump a cache or something, never had this issue and I cannot figure out why it just keeps running this even though at the moment, if I run query on the db it returns 4 records.
This is the method generating the query, it hasn't changed
# Returns the user's grade to the profile view
def get_grade(user)
completed_steps = Step.where("user_id = ? AND status = ?", user, 1)
failed_steps = Step.where("user_id = ? AND status = ?", user, 2)
ongoing_steps = Step.where("user_id = ? AND status = ?", user, 0)
all_steps = completed_steps.count.to_f + failed_steps.count.to_f
if all_steps.to_f > 0
grade = completed_steps.count.to_f / all_steps * 100
return grade.to_i
else
grade = 0
return grade.to_i
end
end
A:
I realize this isn't your question, but I'm just wondering...
If you have a status enum in your Step model, couldn't you do:
# Returns the user's grade to the profile view
def get_grade(user)
completed_steps = user.steps.completed?.count
failed_steps = user.steps.failed?.count
all_steps = completed_steps + failed_steps
return ((completed_steps.to_f / all_steps) * 100).to_i if all_steps > 0
0
end
Apologies, it was just a random observation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to reload current page programmatically in react-native
My native app support multi-language functionality like 'English' and 'Danish'. For this I have created a drop down on top of the header with two menu options, for example if click on Danish language,it will set the 'Danish' language, but the effect is not displayed, for this I have to click on current menu, then the effect of the language is seen.
So my questions is how to reload current page in react native programmatically.
Thanks in advance.
A:
Try storing your locale in Redux and then update the UI from that state using container components.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get source maps working in Angular 4 and Laravel 5.6 (.map files are missing after build)
I inherited a Laravel and Angular app, and I am trying come up to speed.
I run a shell script which basically compiles everything into the project's ./public folder and nginx serves the app from there.
Here is the script that builds everything:
./compile-js.sh
rm -rf ./public/*.{js,css,svg,woff2,ttf,woff,eot,map,json,html,txt}* ./public/fonts ./public/images ./angular-app/dist/
cd ./angular-app/
yarn install
yarn run build:dev
rm -f ./dist/*.{txt,map} #{txt,map}
cd ../
cp -r ./angular-app/dist/* ./public/
cssTemplate=./resources/views/angular/angular-css.blade.php
jsTemplate=./resources/views/angular/angular-js.blade.php
beginJs='<script type="text/javascript" src="'
endJs='"></script>'
beginInlineJs='<script type="text/javascript">'
endInlineJs='</script>'
beginStyle='<link rel="stylesheet" href="'
endStyle='"/>'
truncate -s 0 "$jsTemplate"
truncate -s 0 "$cssTemplate"
src="$(cat ./public/inlin*.bundle.js)"
echo "$beginInlineJs$src$endInlineJs" >> "$jsTemplate"
src="$(find ./public/ -name 'script*.bundle.js' -type f -exec basename {} \;)"
echo "$beginJs$src$endJs" >> "$jsTemplate"
src="$(cat ./public/sw-registe*.bundle.js)"
echo "$beginInlineJs$src$endInlineJs" >> "$jsTemplate"
src="$(find ./public/ -name 'polyfill*.bundle.js' -type f -exec basename {} \;)"
echo "$beginJs$src$endJs" >> "$jsTemplate"
src="$(find ./public/ -name 'vendo*.bundle.js' -type f -exec basename {} \;)"
echo "$beginJs$src$endJs" >> "$jsTemplate"
src="$(find ./public/ -name 'mai*.bundle.js' -type f -exec basename {} \;)"
echo "$beginJs$src$endJs" >> "$jsTemplate"
src="$(find ./public/ -name 'style*.bundle.css' -type f -exec basename {} \;)"
echo "$beginStyle$src$endStyle" >> "$cssTemplate"
Here are the scripts:
./angular-app/package.json
"build": "ng build --env=prod --prod --aot --output-path ./dist",
"build:dev": "ng build --sourcemap=true --extract-css --env=dev --output-path ./dist",
I just changed the shell script today to yarn run build:dev (it was previously running in prod mode, making debugging very hard). Now after, Chrome Dev Tools is reporting that source maps are detected, but I am also seeing in the console:
DevTools failed to parse SourceMap: https://1.bundle.js.map
DevTools failed to parse SourceMap: https://2.bundle.js.map
DevTools failed to parse SourceMap: https://3.chunk.js.map
I see there are no .map files in the ./public folder, so this is probably why I am seeing this.
Where should I look to make Webpack create the map files?
my tsconfig.json file has "sourceMap": true,
there is no webpack:// area in the Dev Tools Sources Tab
A:
Found the answer. The reason is in the shown ./compile-js.sh file.
This is the culprit here:
rm -f ./dist/*.{txt,map} #{txt,map}
It was creating the map files and then deleting them before copying everything to ./public.
Changed it to this and it fixed it:
rm -f ./dist/*.{txt} #{txt}
I'm using this dev script now also:
"build:dev": "ng build --source-map --aot --extract-css --env=dev --output-path ./dist",
Rather than delete this question, I will keep it because searching Google for information about this stuff was pretty terrible. Maybe it will help someone one day.
| {
"pile_set_name": "StackExchange"
} |
Q:
filter to reverse anti-alias effects
I have bitmaps of lines and text that have anti-alias applied to them. I want to develop a filter that removes tha anti-alias affect. I'm looking for ideas on how to go about doing that, so to start I need to understand how anti-alias algorithms work. Are there any good links, or even code out there?
A:
I need to understand how anti-alias algorithms work
Anti-aliasing works by rendering the image at a higher resolution before it is down-sampled to the output resolution. In the down-sampling process the higher resolution pixels are averaged to create lower resolution pixels. This will create smoother color changes in the rendered image.
Consider this very simple example where a block outline is rendered on a white background.
It is then down-sampled to half the resolution in the process creating pixels having shades of gray:
Here is a more realistic demonstration of anti-aliasing used to render the letter S:
A:
I am not familiar at all with C# programming, but I do have experience with graphics. The closest thing to an anti-anti-alias filter would be a sharpening filter (at least in practice, using Photoshop), usually applied multiple times, depending on the desired effect. The sharpening filter work best when there is great contrast already between the anti-aliased elements and the background, and even better if the background is one flat color, rather than a complex graphic.
If you have access to any advanced graphics editor, you could try a few tests, and if you're happy with the results you could start looking into sharpening filters.
Also, if you are working with grayscale bitmaps, an even better solution is to convert it to a B/W image - that will remove any anti-aliasing on it.
Hope this helps at least a bit :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Почему не происходит подключения к MySql с помощью JDBC?
Всем доброго время суток. Скажите пожалуйста в чём может заключаться проблема при подключении к бд через JDBC? И возможно ли исправить? Пытался в интернете поискать решения (например), но интересного не чего нет.
Вот то что я сделал :
private static final String url = "jdbc:mysql://127.0.0.1:3306/mybd?autoReconnect=true&useSSL=false";
private static final String user = "root";
private static final String password = "welcome";
private static Connection con;
public static void connecttodb() {
// opening database connection to MySQL server
con = DriverManager.getConnection(url, user, password);
}
Собственно сама ошибка (вылазит секунд через 5 после вызова команды) :
Could not create connection to database server. Attempted reconnect 3
times. Giving up.
... чуть дальше ...
CLIENT_PLUGIN_AUTH is required
UPD (После первого решения) :
UPD :
UPD :
A:
private static final String url = "jdbc:mysql://127.0.0.1:3306/mybd?autoReconnect=true&useSSL=false";
private static final String user = "root";
private static final String password = "welcome";
private static Connection con;
public static void connecttodb() {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
con = DriverManager.getConnection(url, user, password);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to overcome missing values when importing date from excel to sas 9.4
I am trying to import an excel sheet into sas9.4. Interestingly, I can import most of the data without any problem. But for the date, there are lots of random missing values (there is no missing date in my excel file). Can anyone tell me how to improve my code please.
proc import out= sheet
datafile = 'D:\Date.xlsx'
dbms = excelcs replace;
sheet = "abc" ;
SCANTEXT=YES;
USEDATE=YES;
SCANTIME=NO;
run;
all date looks like this:21/06/2010, 22/06/2010.
A:
Change your DBMS to XLSX and USEDATE to No. Then you'll import the field as a text field.
You can then use an input() function to create a new date variable.
Not ideal, but easily accomplished.
| {
"pile_set_name": "StackExchange"
} |
Q:
Фоновое изображение во фрагменте
Как сделать фоновое изображение в фрагменте Android? Желательно, полупрозрачное.
Upd.
Сделал с android:alpha=".5" - стало всё прозрачное, вместе с другими элементами.
Так как сделать, таким же прозрачным только фон, не трогая другие элементы?
A:
За фон отвечает аттрибут android:background
Чтобы назначить фон только основному элементу разметки фрагмента надо именно так и сделать. Взять его разметку и присвоить ей фон используя аттрибут из п.1.
Чтобы фон был полупрорачный можно (в случае если фон - цвет) добавить 88 перед значением цвета. (т.е. #88424242 вместо #424242). Если фон - картинка, то надо получить корневой элемент разметки в onCreateView фрагмента, получить его фон методом getBackground() и присвоить ему прозрачность методом setAlpha(125)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.ИМЯ_ФАЙЛА_РАЗМЕТКИ, container, false);
v.getBackground().setAlpha(125);
...
return v;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading and storing unique values in an array (JAVA)
So i've got a problem in my java homework. The task is to write a program that reads in ten numbers and displays only distinct numbers along with the number of distinct values. what i've got so far is...
import java.util.Scanner;
import java.util.Collection;
public class Exercise06_05 {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] list = new int[10];//create my new 10 slot array
//i really want a variable length array but alas
for (int i = 0; i < 10; i++){//get and check the ten input variables
System.out.println("Enter an Integer");//ask for input
int integer = input.nextInt();//assign the input to a temp variable
if (isUnique(list, integer)){//check if the temp is unique to the array
list[i] = integer;//if so assign it
}
}
String output = "";
int j = 0;
for (j = 0; j < list.length; j++){
if(list[j] != 0){//this is where the error accours
output += (list[j] + " ");
}else
break;//this break ensures J doesn't get any higher
//so that i can plug that in for the number of distinct variables
}
System.out.println("The number of distinct numbers is " + j);
System.out.println(output);//print output, and the number of distinct values
}
public static boolean isUnique(int [] arry, int a){// my masterpiece of a method
for (int i = 0; i < (10);){
if (arry [i] == a){//check box
return false;//not unique
} else if (i == (arry.length - 1)){//we done yet?
return true;//if so, return that it's unique
}else//if we're not done increment the box
i++;//there that is
} return false;//now put this here just to safeguard
}
}
It works fine unless the user inputs two of the same ints in a row like 1 and then 1 again. What happens is the program doesn't store the second int, the array keeps a zero and then fails at the create output part. How do i get around this?
A:
Well, for one thing, if the number you get is unique you insert it into the array. If it is not unique, you don't insert it into the array, but you still advance the array index. Thus, you're going to leave it with the initialization default value of zero.
There's two problems with this.
There's no way to distinguish "duplicate value" from "zero". If zero is not a legal value, then okay fine. If zero is legal, this won't work.
More fundamental, when you loop through the array on output, you quit when you hit the first zero. So if the user entered, say, 1,2,4,2,3,4, you're goint to fill your array with 1,2,4,0,3,0. Then when you display the output you're going to write 1,2,4, see the zero and quit, and declare that there are 3 unique values. You'll never reach the 3.
I don't know how much they've taught you about the available data structures yet. A better solution would be to use an ArrayList rather than an array, and then only add to the ArrayList when an incoming value is unique. If you haven't learned about that yet, another idea would be to keep a counter of the number of unique values as you go along. Don't insert in the array when you get a duplicate value, and also don't increment the counter. That is, have one counter that's the position in the arrray, which is the same as the number of unique values. Have another counter which is the number of input values read. This will be greater than the position of the array once you see the first duplicate.
On, on one detail point, not directly related to your question: In your isUnique function, why do you loop up to a hard-coded ten, and then have a separate IF statement to test the array length and break when you reach the end? It would be a lot simpler and easier to read if you coded:
public static boolean isUnique(int [] arry, int a)
{
for (int i = 0; i < arry.length)
{
if (arry [i] == a)
{
return false; //not unique
}
}
return true; // we made it through without finding a dup, must be unique
}
Or if, as I suggest above, you have a separate variable to say how much of the array is actually filled:
public static boolean isUnique(int [] arry, int filled, int a)
{
// filled should always be <=arry.length, but we can check both just to be safe
for (int i = 0; i < arry.length && i<filled)
{
if (arry [i] == a)
{
return false; //not unique
}
}
return true; // we made it through without finding a dup, must be unique
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What can I do for this site?
I really like this site, and want to help it succeed. What can I do for Chemistry-Stack Exchange at this stage of the beta?
A:
This is what one can do, in order of preference (from "best thing to do" to "good thing to do")
First and foremost, vote for good posts. Voting rewards good posts and encourages users, besides sorting out the best post.
Advertise advertise advertise
Tell all who may be interested how awesome this site/network is.
Encourage colleagues/classmates/friends(who have a background in chem) to join.
Write an awesome blog post, like this one by a TW mod
Add/use suggestions here
Try to get more experts engaged.
Retweet the good questions posted by @StackChemistry
Ask questions
Try to ask good questions. Make them conceptual, thought-provoking, and specific. (more guidelines here)
Answer stuff
Write good answers to any question you may find. It doesn't matter if the question is already answered; if you have something already not in the other answers, feel free to add it as a separate answer!
You may use our unanswered questions as a good place to start.
Another thing one can do is write blog post-style Question-answer duets (use the "answer own question" button). Try not to do this too often, though--use it if you have something that will be interesting to the majority of the community and extremely informative.
| {
"pile_set_name": "StackExchange"
} |
Q:
unique_ptr: How to safely share raw pointer
I am making an class which is managed by a unique_ptr, but for various reasons I need to give implementations access to a raw pointer to the object. However I want to ensure that users don't inadvertently delete the underlying object. I have come up with the following example code:
(It is part of a tree structure, and I need to be able to look at members of tree nodes without actually detaching them. shared_ptr seems like overkill in this situation.)
#include <memory>
using namespace std;
class unOnly
{
~unOnly() {}
public:
unOnly() {}
friend class default_delete<unOnly>;
};
int main()
{
unique_ptr<unOnly> ptr(new unOnly());
}
This compiles for me in gcc 4.4.5. However, can I be sure that in all implementations default_delete is what actually deletes the object, as opposed to some private implementation class? Should I write my own deleter to be sure?
A:
Why not
class unOnly
{
unOnly() {}
~unOnly() {}
struct deleter { void operator()(unOnly* x) { delete x; }};
public:
typedef std::unique_ptr<unOnly, deleter> handle;
static handle create() { return handle(new unOnly); }
};
auto x = unOnly::create();
? Or even
class unOnly
{
~unOnly() {}
struct deleter { void operator()(unOnly* x) { delete x; }};
public:
unOnly() {}
typedef std::unique_ptr<unOnly, deleter> handle;
};
unOnly::handle x(new unOnly);
(I prefer the former, but the latter is perhaps more in the spirit of what you're asking for)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it a good practise to create a seperate java file for each class in Eclipse?
When I create a new class using the above menu ,a new java file is created for each class and as you can see this leads to a lot of .java files very quickly(Why does ellipse show a .class structure inside a .java file, ) , is this a good design practice considering the fact that sometimes I only want classes to be very small such as
class Name
{
String firstName;
String lastName;
}
I'm new to Eclipse and Java IDE's , can you also tell me a shortcut to create a new class .
A:
It is not only good practice, it is the way Java was intended to be written.
Why is each public class in a separate file?
Multiple classes in the same file is possible, with nested classes and anonymous classes and so on, but you should really have a good reason to do such a thing. There is nothing wrong with a small class, and it greatly improves readability when you are not searching through large files looking for internal classes.
| {
"pile_set_name": "StackExchange"
} |
Q:
What energy type has less chance for resistance
I am currently playing a level 7 Magus in a pathfinder group, almost level 8.
I was considering to buy an elemental metamagic rod, so that when I use spellstrike with shocking grasp, I can try to bypass electric resistance/immunity.
Given that you have to choose the element at the time of creation of the rod, and that I can pick between cold, fire or acid, which one of these would be the most effective, that is, which one has less monsters with resistance/immunity to that kind of damage AND to electric damage?
In other words, given the following energy combinations:
Electric + cold
Electric + fire
Electric + acid
with which one do I have the lowest chances to find a monster/enemy which is resistant/immune to both energy types?
A:
Fire > Cold > Electricity > Acid
To answer your first question, in general, your best bet would be to make your Elemental Metamagic Rod an Acid Rod. In my experience the fewest number of creatures in all the Bestiaries have resistance/immunity to Acid. However, take this with a grain of salt because your campaign setting may be completely different. My experience is with the default Pathfinder setting, Golarion.
The last post of this tread on the Paizo Messageboards (thanks @Lucas Leblanc for the link!) cites a table with statistics from d20pfsrd.com but does not link to it, so take it with a grain of salt. I could not find the original table on d20pfsrd.com. The numbers from the thread are:
319 creatures with resistance/immunity to fire
305 creatures with resistance/immunity to cold
268 creatures with resistance/immunity to electricity
258 creatures with resistance/immunity to acid
52 creatures with resistance/immunity to sonic (a significant contingient of which are agathions)
0 creatures with reistance/immunity to force
As @Lucas Leblanc points out, the differences between those numbers are really quite small (between the elemental types) so what will be most effective for you really depends on your campaign and setting. For example, if your campaign takes place in the north (like Irrisen or Whitethrone), you'll likely encounter more creatures that are resistant/immune to Cold than Fire even though technically more creatures are resistant/immune to Fire than Cold. Additionally, many outsiders (elementals, devils, demons, etc) are resistant to Fire and Cold and not many at all are resistant to Electricity or Acid (thanks @GreySage for reminding me of this!). Rise of the Runelords (RotRL) has quite a few outsider encounters in it, if I remember correctly. I've never played it, but I've read a few of the books and I did play Shattered Star which is kinda like RotRL 2.0 with a lot of Runelord emphasis.
I did find this Google spreadsheet which contains the stats from about 1200 monsters from the various Bestiaries (it may or may not contain all monsters, I don't know) and has a whole tab for resistance statistics. The table is broken out by CR, which is kinda cool. For example, of the CR 1 monsters:
Fire: 3.70% resistant, 1.23% immune
Cold: 2.47% resistant, 4.94% immune
Electricity: 2.47% resistant, 2.47% immune
Acid: 1.23% resistant, 2.47% immune
Sonic: 1.23% resistant, 0.00% immune
I also played a Magus who specialized in Electricity but could switch to Acid when necessary, and it was very effective. I never encountered a monster that was resistant to both Electricity and Acid but I would not go so far as to say that a monster like that does not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
checking if a number is divisible by 6 PHP
I want to check if a number is divisible by 6 and if not I need to increase it until it becomes divisible.
how can I do that ?
A:
if ($number % 6 != 0) {
$number += 6 - ($number % 6);
}
The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.
If decreasing is acceptable then this is even faster:
$number -= $number % 6;
A:
if ($variable % 6 == 0) {
echo 'This number is divisible by 6.';
}:
Make divisible by 6:
$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors
A:
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is "Xy" pronounced as "Ki Shi" in Xylitol「キシリトール」?
Why is "Xy" pronounced as "[Ki Shi]{キ シ}" in [Xylitol]{キシリトール}?
I believe "Xy" can pronounced as "Zai", which is probably a valid sound in Japanese.
I would like to know its etymology too, if there is any.
A:
It comes from the Greek word xylon, which means wood. The Greek word xylon is pronounced "ksilon", so the Japanese transcription is faithful to the original Greek pronunciation, rather than the English corruption of the word.
See the answer to this question for the reason why "x" is pronounced "z" at the beginning of English words.
As for the origin of the word, the Greek word xylon means wood. The -itol suffix is added to denote that it is a sugar alcohol. It is produced from xylose, which was first isolated from wood (such as birch).
A:
Xyl~ is the same as Xyl in Xylophone (coming from 'wood' in Greek). How it is pronounced varies between languages. You can see this by the explanation on the Japanese wiki article for Xylophone, which shows the different pronunciations in katakana:
Japanese: シロフォン
English: ザイロフォウン
German: クシュロフォーン
French: グジロフォヌ
Italian: クシロフォノ、シロフォノ
In German the IPA for Xylitol is ksyliˈtoːl, so キシリトール is likely to have come directly from German. Two groups, one French and one German, discovered Xylitol nearly simultaneously, so it makes sense for German to be the source language in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resource does not exist while calling `GetMemberGroupsAsync`
I am using Microsoft.Azure.ActiveDirectory.GraphClient;.
I am calling GetMemberGroupsAsync as follows:
IEnumerable<string> memberships = client.Groups.GetByObjectId(userObjectId).GetMemberGroupsAsync(true).GetAwaiter().GetResult();
I get the following exception:
System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"Request_ResourceNotFound","message":{"lang":"en","value":"Resource 'c92da223-a37f-4194-9bbf-74669885a0f0' does not exist or one of its queried reference-property objects are not present."}}}
at System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
Any idea on why does this exception occur and how to solve it?
A:
The error indicates the group you were requesting does not exist.
Based on the code, you were able to acquire the groups with userObjectId. Ensure that is a valid group id instead of user id.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does alpha blending gradient textures yield unexpected results in OpenGL ES 2.0?
I have a radial gradient texture (RGBA) that goes from a black fully opaque color in the center to fully transparent one at the edges:
I've set up an iOS project using the recent OpenGL template, which uses GLKit. I added texture capability and have the following code set in the setupGL method:
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
When I overlap two of these textures (each has a separate z) in an ortho projection on a white background, I expect something like this:
But instead I get this:
My question is simply: why? Can OpenGL ES 2.0's blending not achieve this effect? (I've gotten it to work before in OpenGL ES 1.1) Is there a common thing I'm missing? Is it maybe a premultiplied alpha problem with my texture? If so could it be something strange with my PNG or the way I'm loading it? I'm loading textures using GLKTextureLoader.
It's very possible I'm wrong, but I understand that it couldn't be a shader problem as alpha blending happens before it gets to the fragment shader. My shaders do little more than pass the information directly through. (Maybe that's a problem?)
Vertex Shader:
attribute vec4 position;
attribute vec2 texCoordIn;
varying vec2 texCoordOut;
uniform mat4 modelViewProjectionMatrix;
void main()
{
gl_Position = modelViewProjectionMatrix * position;
texCoordOut = texCoordIn;
}
Fragment Shader:
varying lowp vec2 texCoordOut;
uniform sampler2D texture;
void main()
{
gl_FragColor = texture2D(texture, texCoordOut);
}
I've also tried setting the glBendFunc as follows, but I get the same results:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
Any tips or common hangups are welcome. Thanks!
A:
Well, I'm an idiot. What's actually happening is a simple problem with my vertices. I was using a single glDrawArrays call to draw all the textures at once, but I forgot to add extra vertices between the rectangles to create the degenerate triangles. So basically a third ball was being drawn squashed in the center. But it LOOKED like an alpha blending problem!
Big dummy, right here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get value of input field after random function javascript
Hi I have a function that chooses a random list item and inside that list item has an input field. The goal is for the user to fill out the fields and then press a button to select a random list item and display the value of that input field inside that list item.
Right now I have the random function working, it selects a random list item but I am having trouble displaying the value on the input field. Seems like the browser cant recognize what the user has typed into the input field because all the console spits out is <li><input type='text'></li>
HTML:
<ul id="list">
<li><input type='text'></li>
<li><input type='text'></li>
<li><input type='text'></li>
</ul>
<button id="randomize">randomize</button>
<p id="result">hello</p>
jS:
var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");
randomize.addEventListener("click", randomizeIt);
function randomizeIt () {
var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
result.innerHTML = randomItem.value;
console.log(randomItem);
}
jsfiddle
thanks!
A:
You just need to grab the childNode (which is the input element).
result.innerHTML = randomItem.childNodes[0].value;
jsfiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongo: Quick way to find the last n inserts into a collection
I am running a query like the following:
db.sales.find({location: "LLLA",
created_at: {$gt: ISODate('2012-07-27T00:00:00Z')}}).
sort({created_at: -1}).limit(3)
This query is working as expected, but its not performing fast enough. I have an index on the location field, and a separate index on the created_at field. Please let me know if you see me missing something obvious here to make it faster.
Thanks for your time on this.
A:
Mongo won't use two indexes for a given query, if you want filter by location and sort by created_at you can add a compound index:
db.sales.ensureIndex({location: 1, created_at: -1})
You should run explain on your queries when you have issues like that. Sort in particular causes non-intuitive complications with indexing, and the explain command can occasionally make it obvious why.
It's also worth noting that you can usually sort by _id to approximate insert time (assuming auto generated ObjectId values), but that won't help you as much as a compound index will in this case since you're filtering on an additional field.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is EXTPROC in Oracle?
For security reasons I asked DB team to add EXTPROC_DLLS:ONLY; but they said this:
"Please be informed that the KEY = EXTPROC1526 doesn’t refer to any
external process at all. This is just a key used by any process needs
to call Oraxxx via IPC protocol. The key can be any value and the same
key value should be passed via the tnsnames.ora"
To me, it seems wrong. Could you please help me on this? What is the exact use of EXTPROC and what happens if we don't add EXTPROC_DLLS:ONLY?
A:
For any program to connect the oracle database you need Extproc agent.
PLS/SQL for example needs Extproc to work with oracle
You can find more information about the securit here
Ill past some of the link
Description
***********
The Oracle database server supports PL/SQL, a programming language. PL/SQ can execute external procedures via extproc. Over the past few years there has been a number of vulnerabilities in this area.
Extproc is intended only to accept requests from the Oracle database server but local users can still execute commands bypassing this restriction.
Details
*******
No authentication takes place when extproc is asked to load a library and execute a function. This allows local users to run commands as the Oracle user (Oracle on unix and system on Windows). If configured properly, under 10g, extproc runs as nobody on *nix systems so the risk posed here is minimal but still present.
and an example here
| {
"pile_set_name": "StackExchange"
} |
Q:
Trivial question about max number of distinct values in a B-tree index
I am trying to learn about indexing. I looked at the actual indexes used in the database at work.
I looked in to two random indexes:
SELECT
INDEX_NAME, INDEX_TYPE, LEAF_BLOCKS, DISTINCT_KEYS
FROM ALL_INDEXES
WHERE TABLE_NAME = 'TRANS'
AND INDEX_NAME IN ('TRANS_PK','TRANS_ORD_NO')
This gives:
INDEX_NAME | INDEX_TYPE | LEAF_BLOCKS | DISTINCT_KEYS |
TRANS_PK | NORMAL | 13981 | 3718619 |
TRANS_ORD_NO| NORMAL | 17052 | 43904 |
This is what makes no sense to me; shouldn't distinct(column_name) from the actual table yield the same number? It doesn't!
SELECT COUNT(DISTINCT ORD_NO) FROM trans
..gives 20273
TRANS_PK is an index for a column called NO.
SELECT COUNT(distinct NO) FROM trans
... gives 4 328 622
What am I not getting here? The select distinct should result in the same number as the "distinct keys" - column in the ALL_INDEXES- table?
A:
Dictionary views ( including ALL_INDEXES ) don't have real-time data, but the new statistics values are refreshed during the analyze time, and become stale as the time passes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Computational geometry, tetrahedron signed volume
Short version: I'm trying to compute the orientation of a triangle on a plane, formed by the intersection of 3 edges, without explicitly computing the intersection points.
Long version: I need to triangulate a PSLG on a triangle in 3D. The vertices of the PSLG are defined by the intersections of line segments with the plane through the triangle, and are guaranteed to lie within the triangle. Assuming I had the intersection points, I could project to 2D and use a point-line-side (or triangle signed area) test to determine the orientation of a triangle between any 3 intersection points.
The problem is I can't explicitly compute the intersection points because of the floating-point error that accumulates when I find the line-plane intersection. To figure out if the line segments strike the triangle in the first place, I'm using some freely available robust geometric predicates, which give the sign of the volume of a tetrahedron, or equivalently which side of a plane a point lies on. I can determine if the line segment endpoints are on opposite sides of the plane through the triangle, then form tetrahedra between the line segment and each edge of the triangle to determine whether the intersection point lies within the triangle.
Since I can't explicitly compute the intersection points, I'm wondering if there is a way to express the same 2D orient calculation in 3D using only the original points. If there are 3 edges striking the triangle that gives me 9 points in total to play with. Assuming what I'm asking is even possible (using only the 3D orient tests), then I'm guessing that I'll need to form some subset of all the possible tetrahedra between those 9 points. I'm having difficultly even visualizing this, let alone distilling it into a formula or code. I can't even google this because I don't know what the industry standard terminology might be for this type of problem.
One thing that occurs to me: Perhaps if I could fit non-overlapping tetrahedra between the 3 line segments, then the orientation of any one of those that crossed the plane would be the answer I'm looking for. Other than when the edges enclose a simple triangular prism, I'm not sure if this sub-problem is solvable either.
Any ideas how to proceed with this?
A:
I am answering this on both MO & SO, expanding the comments I made on MO.
My sense is that no computational trick with signed tetrahedra volumes will avoid the precision issues that are your main concern. This is because, if you have tightly twisted segments, the orientation of the triangle depends on the precise positioning of the cutting plane.
In the above example, the upper plane crosses the segments in the order (a,b,c) [ccw from above]: (red,blue,green), while the lower plane crosses in the reverse order (c,b,a): (green,blue,red). The height
of the cutting plane could be determined by your last bit of precision.
Consequently, I think it makes sense to just go ahead and compute the points of intersection in
the cutting plane, using enough precision to make the computation exact. If your segment endpoints coordinates and plane coefficients have $L$ bits of precision, then there is just a small constant-factor increase needed. Although I am not certain of precisely what that factor is, it is small--perhaps 4. You will not need e.g., $L^2$ bits, because the computation is solving linear equations.
So there will not be an explosion in the precision required to compute this exactly.
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Python import failed for PyQt4
I am trying to use the "imp" library to export all symbols of PyQt4. Use the built-in "import PyQt4.QtCore" is OK, but the python's code failed.
My Test is basing on Mac.
On Windows, it seems that if you put one "init.py" (empty file is OK) under the QtCore directory,
"import QtCore" will success.
But on Mac, for some unknown reason, it failed.
In the Cli:
bash-3.2# python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import PyQt4.QtCore as f
>>> print f.__file__
/Library/Python/2.7/site-packages/PyQt4/QtCore.so
However, this usage failed.
bash-3.2# cd /Library/Python/2.7/site-packages/PyQt4/
bash-3.2# python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import QtCore
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: dynamic module not initialized properly
Can someone explains it?
A:
QtCore cannot be directly imported into python. QtCore exists in the PyQt4 library. To access QtCore class you need do the following :
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from PyQt4 import QtCore
>>>
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resources for learning assembly on ti MSP430G2553
Im current in a class in my university that is teaching us assembly for the MSP430 launchpad. Im struggling a bit with learning it as it is very different from the other languages Im used to looking at, and the class isnt taught too well, at least for me. Its my understanding that Assembly is different for each piece of hardware, but is this at the family or group level, so would all MSP430's be the same or is the g2553 different than the other MSP430 boards in terms of Assembly language?
Do you have any recommendation for resources where I could learn the right Assembly language, good sample programs to test and look through to learn and get used to memory locations etc, and good projects to try to get better at it? Again the board we are using is the MSP430G2553.
Thank you for any and all help!
A:
All MSP430 use the same instruction set. The ones that exceed 64-KB of address space additionally support the MSP430X extension that lets you use memory up to 1MB.
https://www.ti.com/lit/ug/slau144j/slau144j.pdf is the guide for MSP430x2xx, which contains the instruction set. https://processors.wiki.ti.com/index.php/Category:MSP430 is the page that has links to the resources provided by TI. If you are blocked by the server, you can use the Internet Archive. https://web.archive.org/web/*/http://www.ti.com/lit/ug/slau144j/slau144j.pdf
Also see this Wikipedia page.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between and in Java
What is the difference between List<? super T> and List<? extends T> ?
I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super T> does.
A:
extends
The wildcard declaration of List<? extends Number> foo3 means that any of these are legal assignments:
List<? extends Number> foo3 = new ArrayList<Number>(); // Number "extends" Number (in this context)
List<? extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number
List<? extends Number> foo3 = new ArrayList<Double>(); // Double extends Number
Reading - Given the above possible assignments, what type of object are you guaranteed to read from List foo3:
You can read a Number because any of the lists that could be assigned to foo3 contain a Number or a subclass of Number.
You can't read an Integer because foo3 could be pointing at a List<Double>.
You can't read a Double because foo3 could be pointing at a List<Integer>.
Writing - Given the above possible assignments, what type of object could you add to List foo3 that would be legal for all the above possible ArrayList assignments:
You can't add an Integer because foo3 could be pointing at a List<Double>.
You can't add a Double because foo3 could be pointing at a List<Integer>.
You can't add a Number because foo3 could be pointing at a List<Integer>.
You can't add any object to List<? extends T> because you can't guarantee what kind of List it is really pointing to, so you can't guarantee that the object is allowed in that List. The only "guarantee" is that you can only read from it and you'll get a T or subclass of T.
super
Now consider List <? super T>.
The wildcard declaration of List<? super Integer> foo3 means that any of these are legal assignments:
List<? super Integer> foo3 = new ArrayList<Integer>(); // Integer is a "superclass" of Integer (in this context)
List<? super Integer> foo3 = new ArrayList<Number>(); // Number is a superclass of Integer
List<? super Integer> foo3 = new ArrayList<Object>(); // Object is a superclass of Integer
Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from List foo3:
You aren't guaranteed an Integer because foo3 could be pointing at a List<Number> or List<Object>.
You aren't guaranteed a Number because foo3 could be pointing at a List<Object>.
The only guarantee is that you will get an instance of an Object or subclass of Object (but you don't know what subclass).
Writing - Given the above possible assignments, what type of object could you add to List foo3 that would be legal for all the above possible ArrayList assignments:
You can add an Integer because an Integer is allowed in any of above lists.
You can add an instance of a subclass of Integer because an instance of a subclass of Integer is allowed in any of the above lists.
You can't add a Double because foo3 could be pointing at an ArrayList<Integer>.
You can't add a Number because foo3 could be pointing at an ArrayList<Integer>.
You can't add an Object because foo3 could be pointing at an ArrayList<Integer>.
PECS
Remember PECS: "Producer Extends, Consumer Super".
"Producer Extends" - If you need a List to produce T values (you want to read Ts from the list), you need to declare it with ? extends T, e.g. List<? extends Integer>. But you cannot add to this list.
"Consumer Super" - If you need a List to consume T values (you want to write Ts into the list), you need to declare it with ? super T, e.g. List<? super Integer>. But there are no guarantees what type of object you may read from this list.
If you need to both read from and write to a list, you need to declare it exactly with no wildcards, e.g. List<Integer>.
Example
Note this example from the Java Generics FAQ. Note how the source list src (the producing list) uses extends, and the destination list dest (the consuming list) uses super:
public class Collections {
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (int i = 0; i < src.size(); i++)
dest.set(i, src.get(i));
}
}
Also see
How can I add to List<? extends Number> data structures?
A:
Imagine having this hierarchy
1. Extends
By writing
List<? extends C2> list;
you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 subtypes of C2 (C2 included):
C2: new ArrayList<C2>();, (an object that can store C2 or subtypes) or
D1: new ArrayList<D1>();, (an object that can store D1 or subtypes) or
D2: new ArrayList<D2>();, (an object that can store D2 or subtypes) or...
and so on. Seven different cases:
1) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
2) new ArrayList<D1>(): can store D1 E1 E2
3) new ArrayList<D2>(): can store D2 E3 E4
4) new ArrayList<E1>(): can store E1
5) new ArrayList<E2>(): can store E2
6) new ArrayList<E3>(): can store E3
7) new ArrayList<E4>(): can store E4
We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented
As you can see, there is not a safe type that is common to every case:
you cannot list.add(new C2(){}); because it could be list = new ArrayList<D1>();
you cannot list.add(new D1(){}); because it could be list = new ArrayList<D2>();
and so on.
2. Super
By writing
List<? super C2> list;
you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 supertypes of C2 (C2 included):
A1: new ArrayList<A1>();, (an object that can store A1 or subtypes) or
A2: new ArrayList<A2>();, (an object that can store A2 or subtypes) or
A3: new ArrayList<A3>();, (an object that can store A3 or subtypes) or...
and so on. Seven different cases:
1) new ArrayList<A1>(): can store A1 B1 B2 C1 C2 D1 D2 E1 E2 E3 E4
2) new ArrayList<A2>(): can store A2 B2 C1 C2 D1 D2 E1 E2 E3 E4
3) new ArrayList<A3>(): can store A3 B3 C2 C3 D1 D2 E1 E2 E3 E4
4) new ArrayList<A4>(): can store A4 B3 B4 C2 C3 D1 D2 E1 E2 E3 E4
5) new ArrayList<B2>(): can store B2 C1 C2 D1 D2 E1 E2 E3 E4
6) new ArrayList<B3>(): can store B3 C2 C3 D1 D2 E1 E2 E3 E4
7) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented
As you can see, here we have seven safe types that are common to every case: C2, D1, D2, E1, E2, E3, E4.
you can list.add(new C2(){}); because, regardless of the kind of List we're referencing, C2 is allowed
you can list.add(new D1(){}); because, regardless of the kind of List we're referencing, D1 is allowed
and so on. You probably noticed that these types correspond to the hierarchy starting from type C2.
Notes
Here the complete hierarchy if you wish to make some tests
interface A1{}
interface A2{}
interface A3{}
interface A4{}
interface B1 extends A1{}
interface B2 extends A1,A2{}
interface B3 extends A3,A4{}
interface B4 extends A4{}
interface C1 extends B2{}
interface C2 extends B2,B3{}
interface C3 extends B3{}
interface D1 extends C1,C2{}
interface D2 extends C2{}
interface E1 extends D1{}
interface E2 extends D1{}
interface E3 extends D2{}
interface E4 extends D2{}
A:
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to access the texts from a text file present in hadoop cache
I have 2 files which needs to be accessed by the hadoop cluster. Those two files are good.txt and bad.txt respectively.
Firstly since both these files needs to be accessed from different nodes i place these two files in distributed cache in driver class as follows
Configuration conf = new Configuration();
DistributedCache.addCacheFile(new URI("/user/training/Rakshith/good.txt"),conf);
DistributedCache.addCacheFile(new URI("/user/training/Rakshith/bad.txt"),conf);
Job job = new Job(conf);
Now both good and bad files are placed in distributed cache. I access the distributed cache in mapper class as follows
public class LetterMapper extends Mapper<LongWritable,Text,LongWritable,Text> {
private Path[]files;
@Override
protected void setup(org.apache.hadoop.mapreduce.Mapper.Context context)
throws IOException, InterruptedException {
files=DistributedCache.getLocalCacheFiles(new Configuration(context.getConfiguration()));
}
I need to check if a word is present in a good.txt or bad.txt. So i use the something like this
File file=new File(files[0].toString()); //to access good.txt
BufferedReader br=new BufferedReader(new FileReader(file));
StringBuider sb=new StringBuilder();
String input=null;
while((input=br.readLine())!=null){
sb.append(input);
}
input=sb.toString();
iam supposed to get the content of good file in my input variable. But i dont get it. Have i missed anything??
A:
Does job finish successfully? The maptask may fail because you are using JobConf in this line
files=DistributedCache.getLocalCacheFiles(new JobConf(context.getConfiguration()));
If you change it like this it should work, I don't see any problem with remaining code you posted in question.
files=DistributedCache.getLocalCacheFiles(context.getConfiguration());
or
files=DistributedCache.getLocalCacheFiles(new Configuration(context.getConfiguration()));
| {
"pile_set_name": "StackExchange"
} |
Q:
IF Formula =IF(A6="a";1;0) strange behavior giving wrong result
A friend gave me a file with a strange result in it with the IF formula, it's an excel file with 2 sheet giving different result with the same formula.
I've also tried to compare those value with VBA but he give me the right answer, so A5 != "a",i couldn't go further with the explanation because it's really something stupid, it's happening just with this file so i need to post it here:
http://www.filedropper.com/ifanomalie
It's a file with 5 rows of data, someone could explain me what's happening there?
A:
There is an strange option set for your 1st sheet (foglio1). Generally, there is a surprising large amount of workbook and worksheet-specific settings in Excel.
Goto File->Options, choose Advanced and scroll down to the very end of the setting page. Under Lotus compability Settings for, choose foglio1 and remove the checkmark on Transition formula evaluation.
When you select the other sheet (foglio2), you see that this is already unchecked (and so it is probably for all other sheets you will see until the end of your Excel life.)
The help page suggest that empty cells are treated differently, don't ask me about details or reasons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where does my weight come from?
I weigh quite a lot and I am trying to lose weight.
I am currently 6 feet tall and my weight is 216 pounds, which is clearly too much.
I have been working out doing mainly clap pushups, pullups, and throwing a medicine ball and playing basketball
I have never lifted weights in my life.
The thing is, I am not really that fat, and I recently got my body fat measured from a doctor, with it coming out around 18%, which is ridiculous. It would give me an FFMI (Fat Free Mass Index) of 23.48, without ever lifting weights or anything like that.
Something has to be wrong.
A:
Your 'natural' body-mass percentages are hugely affected by genetics. Your hormone levels control how much muscle-mass you will have with any given level of activity.
It's entirely possible you're genetically gifted. If you start lifting weights more regularly, and get a solid plan for your diet, you could end-up being quite muscular.
The flip side is the body-fat % test might be waaayyyy off. Was it a body-caliper test? They can have major discrepancies, even when done by a doctor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if item exists in multiple arrays
I have a function which returns an array:
This is the fucntion:
{
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$product_names=array();
foreach($items as $item => $values) {
$_product = $values['data']->post;
$product_names[]=$_product->post_title;
}
$allproductname=print_r($product_names, true);
return $allproductname;
}
The output of this function:
Array(
[0] => Social media campagne
[1] => Marketingcampagne
)
I also have 2 arrays named group1 and group2.
$group1=array("Social media campagne","Marketingcampagne");
$group2=array("SEO","Facebook marketing");
Now what i want to check is if both of the values of the function output belong in $group1 then i want it to print "both values belong in group1"
And if 1 value belongs in group1 and one value in group 2 then echo "1 value belongs in group1 and one value belongs in group2"
--edit
I forgot to mention that this output can change its not always this:
Array(
[0] => Social media campagne
[1] => Marketingcampagne
)
it can also be 3 products for example
A:
It looks like what you want to do relates to set theory. You have a set of things (the return from the function) and you want to see if all the elements in that array are in another array (You want to check if the return array is a strict subset of the array you're checking against).
You can use array_intersect () to do this. This function takes at least 2 arrays as its arguments, and it returns an array of elements that exist in all the arrays passed to it.
If you have an array specifying all the values you want to check against and another array that may or may not be a subset of that array then you can use array_intersect to get a list of all the elements in both arrays. If the number of elements in the output match the number of elements in the array that you want to check then the array must be a strict subset of the array you're checking against.
The following code demonstrates the basic principle:
$set = [1, 2, 3, 4, 5, 6, 7, 8]; // Data you want to test against
$subset = [2, 4, 6, 8]; // Strict subset of $set
$notSubset = [2, 4, 6, 10]; // Not a strict subset of $set because it contains 10
var_dump (count ($subset) === count (array_intersect ($set, $subset))); // true
var_dump (count ($notSubset) === count (array_intersect ($set, $notSubset))); // false
NOTE: array_intersect is only really suitable when the contents of the arrays being compared are all primitive types, as PHP will cast them all to string while comparing them. If you're comparing arrays of arrays or arrays of object then you're better off using array_uintersect () and specifying how the elements are compared yourself with a callback function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quando é que se começou a chamar "meia" ao "6" no Brasil?
Eu já sabia que é comum no Brasil dizer meia no lugar de seis, como em números de telefone: meu número é nove-um-três-meia-quatro… Lembrei-me hoje disso ao ‘folhear’ o semanário lisboeta Sempre Fixe de 23 de dezembro de 1926, p. 6, que propõe nomes alternativos para os algarismos:
O 6, que para os brasileiros é o meia dúzia, será para nós o—pescadinha de rabo na bôca.
Quando é que isto começou? Também já se disse meia dúzia em números de telefone, meu número é o nove-um-três-meia dúzia-quatro… ?
A:
Quando nos referimos a dígitos, o uso de "meia" ao invés de "seis" em pt-BR falado, generalizou-se quando o telefone chegou ao Brasil no início do século XX. Antes disso, é de se supor que já fosse usado toda vez que alguém estivesse ditando números em alguma atividade séria, e que não admitisse erros como:
A "o número de série é 4687"
B "quatro, três, oito, sete?"
A "Não, quatro seis. Quatro meia", aqui já como uma redução de meia-dúzia.
Ao telefone, não visualizamos o movimento dos lábios e fica mais fácil confundir três e seis.
A fim de evitar que o número seis fosse confundido com o três em uma conversa, passamos a usar o "meia-dúzia", que logo foi reduzido a "meia".
Jà usávamos, há muitos anos, "meia" como redução de "meia hora" ao dizermos "às nove e meia da manhã" ou "à meia-noite e meia", como redução de "meia-calça", ou de "meia entrada".
Entretanto, nem sempre podemos usar "meia" ao invés de "seis". Veja por exemplo:
Meu filho tem seis anos.
Faço anos no dia seis de fevereiro.
Abram seus livros na página seis.
Isso porque "meia" refere-se ao dígito e não à quantidade.
ADDENDUM - Em situações onde o locutor quer ter a certeza de que todos entenderão o número corretamente, costuma-se dizer mesmo "meia-dúzia", como por exemplo durante um jogo de víspora, em que o número é cantado da seguinte forma: "sessenta e oito, meia-dúzia oito" de modo que fica praticamente impossível alguém confundir três com seis.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kmeans with an huge array
I'm trying to find 5000 center points of a huge data set. My input array is [5000000][512] meaning a lot of vectors with 512 dimension. C++ has a limit on array size and I can't seems to overcome this. I wanted to use opencv kmeans function.
Any idea???
A:
I ended up using mini batch kmeans which samples the data to batches. plus, the matrix was very sparse soo adding sparse matrix representation did the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
I/O performance - async vs TPL vs Dataflow vs RX
I have a piece of C# 5.0 code that generates a ton of network and disk I/O. I need to run multiple copies of this code in parallel. Which of the following technologies is likely to give me the best performance:
async methods with await
directly use Task from TPL
the TPL Dataflow nuget
Reactive Extensions
I'm not very good at this parallel stuff, but if using a lower lever, like say Thread, can give me a lot better performance I'd consider that too.
A:
This is like trying to optimize the length of your transatlantic flight by asking the quickest method to remove your seatbelt.
Ok, some real advice, since I was kind of a jerk
Let's give a helpful answer. Think of performance as in "Classes" of activities - each one is an order of magnitude slower (at least!):
Only accessing the CPU, very little memory usage (i.e. rendering very simple graphics to a very fast GPU, or calculating digits of Pi)
Only accessing CPU and in-memory things, nothing on disk (i.e. a well-written game)
Accessing the disk
Accessing the network.
If you do even one of activity #3, there's no point in doing optimizations typical to activities #1 and #2 like optimizing threading libraries - they're completely overshadowed by the disk hit. Same for CPU tricks - if you're constantly incurring L2/L3 cache misses, sparing a few CPU cycles by hand-writing assembly isn't worth it (which is why things like loop unrolling are usually a bad idea these days).
So, what can we derive from this? There are two ways to make your program faster, either move up from #3 to #2 (which isn't often possible, depending on what you're doing), or by doing less I/O. I/O and network speed is the rate-limiting factor in most modern applications, and that's what you should be trying to optimize.
A:
Any performance difference between these options would be inconsequential in the face of "a ton of network and disk I/O".
A better question to ask is "which option is easiest to learn and develop with?" Or "which option would be best to maintain this code with five years from now?" And for that I would suggest async first, or Dataflow or Rx if your logic is better represented as a stream.
A:
It's an older question, but for anyone reading this...
It depends. If you try to saturate 1Gbps link with 50B messages, you will be CPU bound even with simple non-blocking send over raw sockets. If, on the other hand, you are happy with 1Mbps throughput or your messages are larger than 10KB, any of these frameworks will do the job.
For low-bandwidth situations, I would recommend to prioritize by ease of use, i.e. async/await, Dataflow, Rx, TPL in this order. Note that high-bandwidth application should be prototyped as if it is low-bandwidth and optimized later.
For true high-bandwidth application, I can recommend Dataflow over Rx, because Rx is not designed for high concurrency. Raw TPL is the bottom layer, which guarantees the lowest overhead if you can handle the complexity. If you can make efficient use of dedicated threads, then that would be even faster. Async/await vs. Dataflow IMO doesn't make any performance difference. The overhead seems comparable, so choose one that's a better fit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does 12 V DC to +6 VDC and -6VDC with discrete components require conversion to AC?
I have a 12 volt battery and want to power a 741 Op Amp, but that requires + and - voltage supplies. Is there a more efficient way to give a + and - supply to the op amp from the battery without converting to AC first.
By converting to AC first I mean:
DC Battery->
AC Inverter->
Transformer:Primary Two Tap, Secondary Center Tap:Three Tap with center Tap Grounded->
DC Rectify Top and Bottom Tap
~ +6 V Top and ~ -6V Bottom
A:
It requires conversion to AC, but not necessarily a transformer. Maybe an inductor or capacitors will work fine, depending on the current requirements.
The easiest thing is to buy a DC-DC converter module with an isolated output or +/- output. You can also use a switchmode power supply chip as an inverting boost converter with only a single inductor. In keeping with your retro-space-age \$\mu A741\$ theme, you could use an MC34063. That could give you +/-12V
Alternatively, you could split the 12V into +6V/-6V. The easiest way to do that is to use a rail-splitter IC such as the TLE2426. The disadvantage of that is that you no longer have ground-referenced inputs and outputs relative to the +12V/0V supply. Whether that's an issue or not depends on your application. You could also have noise issues if the +12V supply is not clean (for example, if it's a vehicle +12V supply).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the following data discrete or continuous?
Here are the finishing times taken for a race in seconds.
$$10.1,10.6,11.2,12.1,10.9,11.3$$
Is this data discrete or continuous?
My understanding is that time is continuous data but these data are presented in a to-one-decimal-place form.
Are they now discrete?
A:
The concept of 'continuous data' is a theoretical convenience. In practice,
all data must be rounded to a certain number of decimal places.
Theoretically, running times are continuous. One can imagine infinitely
many values between 10.1 and 10.2, even if the measurement device is
not up to measuring them. Maybe the winner between 10.1 and 10.2 would
be determined by a photograph.
Whether you model these six observations as continuous or discrete may be
a matter of tradition or convenience.
How will you plot the data? Perhaps
a dotplot or stripchart, focusing attention on the six individual discrete values
observed.
Or perhaps you might use a histogram, speculating on the theoretical continuous
distribution that may have produced these data. Six observations are
not nearly enough for this to be successful, but below we show the "best-fitting" normal density (blue curve) and a kernel density estimator (green), just to
give an idea of what might be done with more observations. The tick
marks beneath the histogram show the six observations.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to auto boot a rooted android device on charging [code req]
How to auto boot a rooted android phone when it is dead and connected to the charger?
I know many people think its not possible as when the device is OFF and ADB isn't running. But it turns out that it is possible to write an application for rooted device.
There is an application for the same @playstore to do just that.
I just want to make similar app. Any ideas or pointers?
A:
You should google a bit
i guess your looking for something
similar to this?
https://android.stackexchange.com/q/39899
Mostly you will have to check the boot-sequence of multiple devices and code accordingly as each device will have different setups
for example the app you posted in your question works only for samsung devices
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't read data from Arduino Uno with serialport Node JS library
I'm using the [email protected] Node JS library, and have used it before (a prior version, 4.0.7) to communicate successfully with a GSM modem.
Now I'm using it with an Arduino Uno. However I can't seem to read data from it the way I used to with the GSM modem.
This is what I'm trying to do:
this.parser.on('data', (buffer) => {
console.log('in on data');
data += buffer.toString();
console.log("DATA: " + data);
var parts = data.split('\r\n');
console.log('PARTS:', parts);
data = parts.pop();
console.log(data)
console.log('POPPED DATA: ' + data);
})
I get nothing from it. I even tried using a parser, hence the this.parser.on. However I can't get it to work.
I can get data using this though:
this.parser.on('data', console.log);
But since I'm trying to process the data in the first place, it's useless.
Here are my serialport settings:
_.defaults(options, {
baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
autoOpen: false,
});
this.options = options;
this.serial = new SerialPort(this.port, this.options);
this.eventEmitter = new events.EventEmitter();
this.parser = new Readline({ delimiter: '\n' });
I'm invoking the serialport from a class. And yes, I get the port to open.
I can also write to the port.
A:
Resolved it, apparently the "buffer" variable in the on.data portion of my sample code already receives a string. Hence I can just print out the string as console.log(buffer).
The weird part is why the data += buffer.toString() portion behaves weirdly. I would expect that I would get at least something in the first console.log after that line. But it returns blank.
| {
"pile_set_name": "StackExchange"
} |
Q:
Determing if a SQL select returns an empty set asynchronously?
Is this possible easily? It seems the handleResult method is only executed if the result isn't the empty set.
A thought I had was to have handleResult and handleCompletion be member functions of an object and have handleResult update a member variable that handleCompletion can check. If the variable is set, not empty, if variable unset, empty and can act accordingly.
seems to be overly complicated and hoping there's a better solution?
A:
to sketch out a solution (the thought i had above) (edit2: per comment I made below)
function sql() {
this.results = false;
var me = this;
this.handleResult = function(aResultSet) {
for (var row = aResultSet.getNextRow(); row; row = aResultSet.getNextRow()) {
me.results = true;
var value = row.getResultByName("name");
}
};
this.handleError = function(aError) {
.... //deal with error
};
this.handleCompletion = function(aReason) {
if (me.results) {
....//results
} else {
....//no results
}
if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
....//handle these
};
};
s = new sql();
statement.executeAsync({
handleResult: s.handleResult,
handleError: s.handleError,
handleCompletion: s.handleCompletion
});
is this considered a good way to solve this problem?
edit1: this doesn't behave in the manner I'd expect (it works, but not 100% sure why). i.e. the this.results variable is undefined (not false), if handleResult never runs. So it appers as if handleResult and handleCompletion are operating on a different set of variables than I'd expect.
any help to understand what I'm doing wrong would be appreciated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Foreign characters showing from gcc compiler output
My locales are are set to generate en_US.ISO-8859-15 ISO-8859-15 and en_US.UTF-8 UTF-8. However the borders of raspi-config still have borders showing the accented âââ. And the gcc compiler output also show messages surround by this same character, for example:
test.c:9:22: error: âaddrâ undeclared
I am accessing my Pi remotely via SSH using Putty. How do I fix this?
A:
The problem is in Putty not the Pi. To fix the problem:
Load the stored profile for the Pi (I assume you have saved you connection details).
Open Putty Configuration.
From the left side menu click Translation from the Window section.
In the Remote character set dropdown select UTF-8.
Make sure that Use Unicode line drawing code points is selected.
Save the stored config and restart putty.
You should no longer see the accented characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does Amazon create the RDS for Postgres? Some kind of Docker?
I am really curious about the infrastructure of Amazon. When I create a new instance of RDS, it gives me a host, username, password.. Everything. Behind the curtains, how do they do this? It´s some infrastructure like Docker to run multiple instances of PostgreSQL? How do I replicate this?
My problem is: I have many users and I would like to let then manage their own tables. I thought that it could be done with schemas, but they still can see the other users tables, and I dont want that. Any sugestion?
A:
Amazon doesn't talk about this much and the servers are intentionally locked down, so it's hard to be completely sure.
They're EC2 instances that run a custom AMI and have automation tools - in-house, or something like Puppet/Chef/etc. These automation tools communicate with the AWS control panel over web service APIs, SSH push access, etc, and are responsible for managing the PostgreSQL configuration, starting/stopping/reloading the server, etc.
Each EC2 instance runs a single PostgreSQL database server, with its own users, roles, etc.
It's basically just a sealed AWS EC2 instance that you don't have much access to, you just get a locked down non-superuser PostgreSQL connection. Nothing magic.
This isn't the only way to do it. Heroku used to use OpenVZ on top of EC2 to partition EC2 instances into smaller containers, for example. I think these days they always have one EC2 instance per database though.
It sounds like what you want is multi-tenant hosting. You have many options for this:
One server per user with a single PostgreSQL instance on each server (EC2 or Heroku style)
one PostgreSQL instance per user on a single host server;
one database per user on a single PostgreSQL instance;
one schema per user in a single PostgreSQL database;
a single set of tables with your application limiting access to data within the tables based on enforced WHERE clauses or row-level security policies.
Which to choose depends on trade-offs involving isolation of users, performance, and cost.
There aren't currently any convenient canned recipes to do this that I know of, but searching for "multi-tenant postgresql" will help you find more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
GmailApp.sendEmail CC, CC not receiving
I am trying to send an CC email from a google form. The main person can receive the email notice but not the people on CC. Where is my mistake?
function submitForm(e){
var itemResponses = e.response.getItemResponses();
var message = '';
for (var i = 0; i < itemResponses.length; i++) {
var itemResponse = itemResponses[i];
var question = itemResponse.getItem().getTitle();
var answer = itemResponse.getResponse();
message += (i + 1).toString() + '. ' + question + ': ' + answer + '\n';
}
var address = "[email protected]"; // it is working untill here and can send email
var cc = address+["[email protected]","[email protected]"]; // this is not working
var title = '届出書が送信されました';
var content = '以下の内容で届出書が送信されました。\n\n' + message;
GmailApp.sendEmail(address, title, content);
}
A:
value for cc should be a comma-separated list of email addresses to CC, you need to extra options (see Advanced Parameters), like:
...
var address = "[email protected]";
var ccEmail = address + "," + "[email protected]","[email protected]";
var title = '届出書が送信されました';
var content = '以下の内容で届出書が送信されました。\n\n' + message;
GmailApp.sendEmail(address, title, content,{cc: ccEmail});
---
| {
"pile_set_name": "StackExchange"
} |
Q:
python module import conundrum (module from submodule)
I have the following project structure:
./app/__init__.py
./app/main/__init__.py
./app/main/views.py
./app/models.py
./app/resources/__init__.py
./app/resources/changesAPI.py
./config.py
./manage.py
The app/models.py file has the following line:
from app import db
db is defined in app/__init__.py
db = SQLAlchemy()
I'm importing classes from models.py from app/resources/__init__.py:
from app.models import User, Task, TaskChange, Revision
However, it fails when model tries to import db:
Traceback (most recent call last):
File "manage.py", line 5, in <module>
from app import create_app, db, api
File "/Users/nahuel/proj/ptcp/app/__init__.py", line 16, in <module>
from app.resources.changesAPI import ChangesAPI
File "/Users/nahuel/proj/ptcp/app/resources/__init__.py", line 5, in <module>
from app.models import User, Task, TaskChange, Revision
File "/Users/nahuel/proj/ptcp/app/models.py", line 1, in <module>
from app import db
ImportError: cannot import name db
What am I doing wrong?
A:
You have a circular import.
You are importing create_app, db and api from manage.py, which triggers an import of the app.resources.changesAPI module, which in turn then triggers import of the __init__.py package in app/resources which then tries to import your models, which fails because db was not yet defined in app/__init__.py.
You need to move importing ChangesAPI to after the line that defines db in your app/__init__.py file. Any name defined in app/__init__.py before the from app.resources.changesAPI import ChangesAPI is available to your sub-packages, names after are not.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python passing local variables for modification in function
and I'm trying to figure out how I would go about passing local variables to a function and then returning the modified values. I've written the code below:
def main():
change = 150
coins = 0
quarter = 25
while (change >= quarter):
change = change - quarter
coins += 1
print(coins)
if __name__ == "__main__":
main()
But I'd like to be able to extract the modification of the change and coins variables like so:
def main():
change = 150
coins = 0
quarter = 25
while (change >= quarter):
count (change, coins, quarter)
def count(change, count, n):
change = change - n
count += 1
return change, count
if __name__ == "__main__":
main()
However, I know this isn't the way to do it. From what I understand, there could be an issue with trying to return multiple variables from the function, but it also seems like there an issue when I try to even modify only the change variable within the count function.
I would really appreciate any advice.
A:
You're returning two values from count(), so you should capture those values when you call it:
while (change >= quarter):
change, coins = count(change, coins, quarter)
Modifying ch and co inside count() will not affect the outer values change and coins.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to give dynamic input for RGL::DirectedAdjacencyGraph?
I am new to RGL. I want to show a graph of all parent and children type relations.
I have written the following code.
My code is as:
require 'rgl/adjacency'
require 'rgl/dot'
input_arr = [1,2,2,3,2,4,4,5,6,4,1,6]
We need to give input as following to generate graph.
dg=RGL::DirectedAdjacencyGraph[1,2,2,3,2,4,4,5,6,4,1,6]
dg.write_to_graphic_file('jpg')
But I want to give the array dynamically, ie I want to pass input_arr. But it is not working.
can anybody explain how to go?
A:
Eventually I could solve my issue.
I have written like the folowing:
I have processed my main_arr variable something like this.
main_arr=[[1,2],[2,3],[2,4],[4,5],[6,4],[1,6]]
dg=RGL::DirectedAdjacencyGraph[]
main_arr.each do |ma|
dg.add_edge ma[0],ma[1]
end
Now it is working fine.
Now I can pass any dynamic values to generate graph.
| {
"pile_set_name": "StackExchange"
} |
Q:
How should I inspect a used piano prior to purchase?
I am considering finding a used grand (or baby grand) piano to purchase. This will be a standard acoustic piano, not an electronic version that "looks like" a grand piano. I am an experienced musician, though not an accomplished pianist.
I realize that the best way to determine:
the condition and value of the piano;
how much repair (in addition to tuning) the piano may need right away; and
how well the piano will survive being moved to my home, including the necessary disassembly and reassembly
would be to have an experienced professional inspect the instrument. However, before hiring such a person to make that inspection, I would like to judge whether the piano is worthy of consideration.
What can and should I look for on my own when first visiting the piano?
Note that I am not looking for how to maintain the piano after I have it, but rather how to determine whether to buy it. An answer similar to this answer regarding the cello may be a good starting point.
A:
Buying a used piano can be daunting task and large investment. You should make sure you know what you are buying before you buy it. I think that you are taking a very smart approach by inspecting it yourself and then having a professional look at it. When inspecting a piano I would search for the following things.
On first glance I would inspect the exterior:
The Pedals
If the pedals have just gone a bit limp it is usually because they have been detached from the surrounding parts (which is usually a very easy fix, depending on the accessibility of the piano). If the pedals don't move at all you might have a bigger problem at hand. A great way to look at pedal function is to make sure the hammers and dampers are in view when testing pedals (do dampers raise, action shift, etc.).
The Keys
Watch out for excessive damage on the keys because it can usually mean that not only is there damage on the outside, but something might be going on inside too. Strike every key and listen for buzzing, dead notes, notes that sounds like they strike twice, and sticky notes (the keys don't pop back up after you play them). Most of these issues can be remedied and fixed if you are willing to spend some money on your piano.
The Finish
Weather damage (such as humidity) is often a suspect in a piano's bad health. Cracks, scratches, discoloration (from sun damage), and warped wood can all be viewed from the outside, but it usually means the inside wood is not looking any better.
Next (if accessible) I would check out the interior:
The Soundboard
The soundboard is a wooden plate at the bottom of the case (in a grand piano). In an upright piano, it is at the back of the instrument. If any reinforcement ribs have come unglued, they will vibrate against the soundboard, causing for even slight buzzing when the keys are pressed. Also look at the bridge (where the strings touch the soundboard). If the bridge is cracked, uneven, or unglued from the soundboard, buzzing will occur, and further damage is likely to follow.
The Hammers
Look for deep grooves on the hammers caused by strings. Are they worn to the nub? If the felt on the hammer appears to worn all the way down play the note and listen for a harsh and blunt tone. The felt on the hammers cannot be re-glued due to the way they are originally applied.
The Pin block
If the pin block wood is damaged, the tuning pins can loosen, causing buzzing sounds and bad pitch (it can make one note sound like two due to one string going slightly out of tune). Keep an eye out for cracking in the wood block and loose pins. Also make sure that there is no rusting on the strings or tuning pins.
Here are some videos that could be helpful as well:
Inspecting a piano
Appraising a piano
Buying a used piano
Here are my sources:
http://www.ptg.org/Scripts/4Disapi.dll/4DCGI/cms/review.html?Action=CMS_Document&DocID=36&MenuKey=Menu2
http://www.allthingspiano.com/buyers-guide.htm
http://piano.about.com/od/buyinganinstrument/tp/used_3int.htm
http://www.pianoworld.com/forum/ubbthreads.php/topics/909668/How%20to%20test%20or%20inspect%20used%20pi.html
If it looks like this I would recommend not buying it. :)
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
How would I have someone input code, full with tabs and lines, and keep that figure
I have a textarea that someone can put code in. When someone clicks "Submit" it will create a txt file, and then re-display it somewhere else. But since it's code, I really need to keep the tabs and lines exactly the same. Using PHP, how would I go about that?
A:
My guess would be that you are dumping the code to a web page. You might want to wrap the code dump in <pre>...</pre> tags.
Observe:
<pre>
<?php echo $code ?>
</pre>
| {
"pile_set_name": "StackExchange"
} |
Q:
set value of input element with jquery
I am trying to change the value of the inputfields with JQuery and I have no idea why this doesn't work. It does not throw an error but it just doesn't change. I'm building with appgyver steroids but i don't think that matters.
javascript:
$(document.getElementById("url")).val('test');
html
<input type="text" id="url" class="topcoat-text-input"
style="margin-left:10%; margin-top:10px; width: 80%; text-align: center" autocapitalize="off"
autocorrect="off" required="true"
placeholder="something else"/>
A:
Make sure that your code is running after the DOM is loaded.
Also there is no need for jQuery in your example.
You can just do:
window.onload = function(){
document.getElementById("url").value = 'test';
};
Demo: http://jsfiddle.net/qwertynl/7uCfc/
And if you want to do full on jQuery:
$(function(){
$('#url').val('test');
});
Demo: http://jsfiddle.net/qwertynl/m5Ttn/
Or you could not wrap your code in an onload and just put the whole script at the end of the document after the page has loaded already.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem over-riding the Back button in iOS
I have a UITableViewController A that is pushing UITableViewController B onto the stack.
In A i have the code:
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Trending"
style:UIBarButtonItemStylePlain
target:self
action:@selector(backButtonClicked:)];
backButtonClicked: is also implemented.
B has the title Trending, but when I click it, it doesn't ever reach backButtonClicked:
Why is this?
A:
Try either setting the delegate:
[navigationController setDelegate:self];
Or using the left button. Sometimes the back button doesn't work with certain views and I have had to use the left button instead:
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Trending" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClicked:)];
Also, you can try setting B's button item instead of A:
viewControllerB.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Trending" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClicked:)];
| {
"pile_set_name": "StackExchange"
} |
Q:
Edit jar files with python
Do you know a python module with which i can add files to a JAR archive?
(what i wan't to do is add .class files to a jar archive)
and the program that has to do it has to be written in python
Thanks!
A:
.jar files are just .zip files with a different file extension and a manifest.
Try http://docs.python.org/library/zipfile.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Fresh Cordova build error
I just installed a fresh copy of Cordova on Windows 10 and am trying to build my first Android app (using this guide). It seems like the script couldn't download gradle-2.2.0.pom, I tried the URL and indeed the file isn't there. I am not sure where to go from here :/
c:\test\hello>cordova build android
ANDROID_HOME=C:\Users\Stuffe\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\java\jdk1.8.0_112
Subproject Path: CordovaLib
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':classpath'.
> Could not resolve com.android.tools.build:gradle:2.2.0.
Required by:
:android:unspecified
> Could not resolve com.android.tools.build:gradle:2.2.0.
> Could not get resource 'https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Could not GET 'https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Connect to repo1.maven.org:443 [repo1.maven.org/127.0.1.2] failed: Connection refused: connect
> Could not resolve com.android.tools.build:gradle:2.2.0.
> Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
>
BUILD FAILED
Total time: 3.134 secs
Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Connect to jcenter.bintray.com:443 [jcenter.bintray.com/127.0.1.3] failed: Connection refused: connect
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':classpath'.
> Could not resolve com.android.tools.build:gradle:2.2.0.
Required by:
:android:unspecified
> Could not resolve com.android.tools.build:gradle:2.2.0.
> Could not get resource 'https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Could not GET 'https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Connect to repo1.maven.org:443 [repo1.maven.org/127.0.1.2] failed: Connection refused: connect
> Could not resolve com.android.tools.build:gradle:2.2.0.
> Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/2.2.0/gradle-2.2.0.pom'.
> Connect to jcenter.bintray.com:443 [jcenter.bintray.com/127.0.1.3] failed: Connection refused: connect
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
A:
Remove the latest version of gradle and install gradle 2.1.4. Now try to build again. It worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle MERGE from external data source
I'm building a .NET application that talks to an Oracle 11g database. I am trying to take data from Excel files provided by a third party and upsert (UPDATE record if exists, INSERT if not), but am having some trouble with performance.
These Excel files are to replace tariff codes and descriptions, so there are a couple thousand records in each file.
| Tariff | Description |
|----------------------------------------|
| 1234567890 | 'Sample description here' |
I did some research on bulk inserting, and even wrote a function that opens a transaction in the application, executes a bunch of UPDATE or INSERT statements, then commits. Unfortunately, that takes a long time and prolongs the session between the application and the database.
public void UpsertMultipleRecords(string[] updates, string[] inserts) {
OleDbConnection conn = new OleDbConnection("connection string here");
conn.Open();
OleDbTransaction trans = conn.BeginTransaction();
try {
for (int i = 0; i < updates.Length; i++) {
OleDbCommand cmd = new OleDbCommand(updates[i], conn);
cmd.Transaction = trans;
int count = cmd.ExecuteNonQuery();
if (count < 1) {
cmd = new OleDbCommand(inserts[i], conn);
cmd.Transaction = trans;
}
}
trans.Commit();
} catch (OleDbException ex) {
trans.Rollback();
} finally {
conn.Close();
}
}
I found via Ask Tom that an efficient way of doing something like this is using an Oracle MERGE statement, implemented in 9i. From what I understand, this is only possible using two existing tables in Oracle. I've tried but don't understand temporary tables or if that's possible. If I create a new table that just holds my data when I MERGE, I still need a solid way of bulk inserting.
A:
The way I usually upload my files to merge, is by first inserting into a load table with sql*loader and then executing a merge statement from the load table into the target table.
A temporary table will only retain it's contents for the duration of the session. I expect sql*loader to end the session upon completion, so better use a normal table that you truncate after the merge.
merge into target_table t
using load_table l on (t.key = l.key) -- brackets are mandatory
when matched then update
set t.col = l.col
, t.col2 = l.col2
, t.col3 = l.col3
when not matched then insert
(t.key, t.col, t.col2, t.col3)
values
(l.key, l.col, l.col2, l.col3)
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing that a map defined using the dual is a bounded linear operator from X' into X'
I have trouble answering the second part of the following exercise. Any help would be appreciated!
Let $(X, \| \cdot \|)$ be a reflexive Banach space. Let $\{ T_n \}_{n = 1}^\infty$ be a sequence of bounded linear operators from $X$ into $X$ such that $\lim_{n \to \infty} f(T_n x)$ exists for all $f \in X'$ and all $x \in X$.
(a) Show that $\sup_{n} \|T_n' \| < + \infty$
(b) Show that the map $S$ defined by $(Sf)(x) := \lim_{n \to \infty} (T_n'f)(x)$ is a bounded linear operator from $X'$ into $X'$.
What I've done so far:
(a): I have done this using the Uniform Boundedness Principle twice after first showing that $\sup_n \| T_n' (f)(x) \| < + \infty$
(b): I think that $\displaystyle \sup_n\|T_n' \|$ would make a good bound since we have just seen that it is finite, but I have not succeeded in proving that so far...
Thank you very much for any hints you can offer me!
A:
After you have shown that $A := \sup\limits_n \lVert T_n'\rVert < \infty$, you have a known bound on $S(f)(x)$ for every $x\in X$ and $f\in X'$, namely
$$\lvert S(f)(x)\rvert = \lim_{n\to\infty} \lvert T_n'(f)(x)\rvert \leqslant \limsup_{n\to\infty} \lVert T_n'(f)\rVert\cdot \lVert x\rVert \leqslant \limsup_{n\to\infty} \lVert T_n'\rVert\cdot \lVert f\rVert\cdot \lVert x\rVert.$$
From $\lvert S(f)(x)\rvert \leqslant N\lVert f\rVert\cdot \lVert x\rVert$, we deduce by the definition of the norm on $X'$ that $\lVert S(f)\rVert \leqslant N\cdot \lVert f\rVert$, and this in turn shows that $S$ is a continuous (bounded) operator on $X'$ with $\lVert S\rVert \leqslant N$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this the right way of finding the Pearson coefficient?
I want to see the effect of discounts on sales. The discount is always 100 off and occurs in select months. I want to see what effect the 100 discount has on sales. I found the Pearson coefficient to be ~0.8 using the correl function in Excel.
My first array is the number of units sold every month. My comparison array is discount - everything on this column is 0 or 100.
Would this be the right approach? I'm not familiar with this type of work and the fact that the discount is constant is really throwing me off.
With a Pearson coefficient of ~0.8, does this mean that ~80% of purchases is made because of the discount?
Edit: 100 discount as in 100 dollars, didn't include the sign because it messed with formatting... sorry about that.
I know this entire set up seems a little illogical, but can someone point me on the right decision?
A:
A correlation coefficient is a measure of association between two variables. The Pearson correlation coefficient that Excel uses with correl looks at 2 continuous variables, and assumes they are normally distributed. You have one continuous and one dichotomous (or binary) variable - there was a discount or there wasn't. You could use a point-biserial correlation (not sure if Excel does that), which correlates a continuous variable and a binary variable, but you probably should do instead a simple t-test, which Excel does with t.test. That will compare the mean sales for times with the discount vs times without, and assess the statistical significance. This also assumes normality in your sales variable, so you should check that. If it isn't normal you can do some transformations - if it is skewed you could do a logarithmic transformation which often normalizes a skewed variable, and is easily interpretable as proportional increase in sales, rather than raw increase.
For your question on does r=.80 mean 80% of sales is associated with the discount, that's not r, but $r^2$ that you want. Simply take the correlation coefficient and square it, and that is how you interpret the percent of variability associated with the discount (we say "explained" but that's not correct if you think of explained to mean caused). But again, I don't think you want a correlation, but a test of means.
There's one other, really important point that Nick brought up that you need to recognize: your assumption about causality is not appropriate. You should not be talking about "how much sales is due to or caused by the discount." That takes experimental or near experimental conditions, or really strong time-series modeling. With just 2 variables, all you can talk about is association. It is up to you or the decision-maker to decide if you think that has causal implications, but the statistics clearly do not support that. If you come to the conclusion it is based on your beliefs about the situation - that is not a bad thing to do (in fact, most of us in our daily life do it all the time), but do not say that the numbers tell you that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Microsoft Office 2011 work in High Sierra?
Does anyone know if MS Office 2011 works in High Sierra? I'd like to upgrade, but I'm on a deadline and I can't spend a lot of time upgrading right now. Plus, I really detest "subscription" software which apparently is the way Microsoft is going.
A:
I have Microsoft Office 2011 installed on 2011 and 2013 iMacs. Both Macs have been upgraded to High Sierra (macOS 10.13.3). I have not noticed any problems. The update shown in the image below is available from Microsoft Office for Mac 2011 14.7.7 Update. The publish date for this update was 9/7/2017, making this is a fairly current update.
A:
"Deadline" and "upgrade" should be mutually exclusive concepts and not procrastinatory temptations.
MS Office 2011 does not work on macOS 10.13 High Sierra, officially. Microsoft has already ended all support for this package and wants you to switch.
Microsoft has announced in a support document that Office for Mac 2011 will not be supported under macOS 10.13 High Sierra. It doesn’t go as far as to say the software will not work, but hints at this.
Word, Excel, PowerPoint, Outlook and Lync have not been tested on macOS 10.13 High Sierra, and no formal support for this configuration will be provided.
However, there are options, first:
Does Office 2011 work on macOS 10.13 High Sierra? Yes
and of course friendlier alternatives like LibreOffice, complicated constructions including virtual machines and with Windows or macOS etc.
All fair game and nice to play with.
But then there is this dreadful word again: "deadline".
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set form field focus on page load in EWL?
I want to set focus to a particular form field on page load. This will be the same form field every time the page is loaded, even after posting-back a data modification. Is this possible?
A:
Yes. Override EwfPage.controlWithInitialFocus. This property is called after LoadData.
| {
"pile_set_name": "StackExchange"
} |
Q:
The RIGHT() function in PostgreSQL gives an error
I'm trying to use the RIGHT() function it so it will only display the last 4 digits of a credit card number pulled from the customer table. This is what I have so far:
create function get_customer(text) returns setof cusinfo as
$$
select upper(first_name)||' '||upper(last_name) as full_name, upper(address), upper(city)||', '||upper(state)||' '||zip as citystatezip, email, '************'||right(cc_number,4), cc_name
from customer
where customer_id = $1;
$$ language sql;
The error I am being given is:
psql:finalproject.sql:273: ERROR: function right(text, integer) does not exist
LINE 3: ...|' '||zip as citystatezip, email, '****'||right(cc_n...
Any ideas as to why this is happening? I tried only using RIGHT() by itself and putting in something like RIGHT('Help me', 2), but I get the same error.
A:
I'm assuming psql is PostgreSQL. If that's the case, you should read the PostgreSQL documentation describing the string functions that are available to you.
right is not one of them.
Try substring(cc_number from char_length(cc_number) - 3).
In future you may want to use Google to help answer questions like this. Google is a search engine; you can use search engines to find documentation; documentation tells you how to use a product.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.