text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Remove Bullet Symbols from List
I have to typeset a document which contains several dozen lists which are already numbered. For various reasons, I cannot use LaTex's enumerate automatic numbering feature for these lists--the numbers have to be entered manually. Nevertheless, the list format has to be maintained. I have used the mdwlist package to cut down on the extra spacing that LaTex adds to lists.
The lists then have both a bullet (added automatically) and a number (entered manually). What I would like to do is simply remove the bullet while keeping the other spacing aspects of the list.
Here is a MWE:
\documentclass[11pt,A4]{article}
\usepackage[utf8]{inputenc}
\usepackage{mdwlist}
\title{Brief Article}
\author{The Author}
\begin{document}
\maketitle
\begin{itemize*}
\item 1.\ \ Regular vacations and holidays according to the Law.
\item 2.\ \ Absence for performing examinations in accordance with what is stated in this Law.
\item 3.\ \ Leave without pay, which is not more than casual 20 days during the work year.
\end{itemize*}
\end{document}
Thank you. All of these answers were very helpful.
I agree that it's kind of an odd requirement--the problem is that I am typesetting legislative statutes and sometimes they are incomplete, contain errors in numbering and these errors have to be preserved. Also, for maintenance purposes it's useful to turn off automatic numbering. There is a German package--jura--designed for German legal typesetting and I have a feeling it has a way around these issues, but unfortunately the lengthy documentation is in German only.
A:
You can use enumerate* instead of itemize* for numbered lists. Also the numbers can be added manually:
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{mdwlist}
\title{Brief Article}
\author{The Author}
\begin{document}
\maketitle
\begin{enumerate*}
\item[2.] Regular vacations and holidays according to the Law.
\item[3.] Absence for performing examinations in accordance with what is
stated in this Law.
\item[5.] Leave without pay, which is not more than casual 20 days during
the work year.
\end{enumerate*}
\end{document}
A:
I don't know why have such a strange requirement, but you can simply redefine the itemize label (\labelitemi) to be empty.
\renewcommand{\labelitemi}{}
MWE
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{mdwlist}
\title{Brief Article}
\author{The Author}
\renewcommand{\labelitemi}{}
\begin{document}
\maketitle
\begin{itemize*}
\item 1.\ \ Regular vacations and holidays according to the Law.
\item 2.\ \ Absence for performing examinations in accordance with what is stated in this Law.
\item 3.\ \ Leave without pay, which is not more than casual 20 days during the work year.
\end{itemize*}
\end{document}
A:
How about having the freedom of adjusting the spacing by yourself? Use enumitem:
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
\title{Brief Article}
\author{The Author}
\begin{document}
\maketitle
\begin{enumerate}[itemsep=-1ex] %% change as you like
\item[2.] Regular vacations and holidays according to the Law.
\item[3.] Absence for performing examinations in accordance with what is
stated in this Law.
\item[5.] Leave without pay, which is not more than casual 20 days during
the work year.
\end{enumerate}
\end{document}
If you are tied to using itemize
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
\title{Brief Article}
\author{The Author}
\begin{document}
\maketitle
\begin{itemize}[itemsep=-1ex]
\item[2.] Regular vacations and holidays according to the Law.
\item[3.] Absence for performing examinations in accordance with what is
stated in this Law.
\item[5.] Leave without pay, which is not more than casual 20 days during
the work year.
\end{itemize}
\end{document}
Advantage of enumitem is you can adjust many other spaces neatly by yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET Core 2.0 Identity update user roles only after re-authorization
I`m using ASP.NET Core 2.0 with Identity authorization. When I change user roles through my data context, the changes take effect only when the user logout and login again. Can I somehow update them without re-authorization? Can there be a way to do this using managers?
A:
I asked MS about this, and it does not seem to be possible to update/refresh another user, only current. Se GitHub Issue here.
| {
"pile_set_name": "StackExchange"
} |
Q:
SwiftUI: Have button's right and left stick to parent's right and left
SwiftUI question here...
I am trying to layout my button so it has the full width of the screen minus some padding of 16. I don't want to use this UIScreen.main.bounds.width. I want it to be dynamic.
Do you guys have any idea how to do this?
Thank you!
Code sample
By using static value it works
struct TestButton : View {
var body: some View {
Button(action: {
}) {
Text("Tap me")
}
.modifier(PrimaryButton())
}
}
fileprivate struct PrimaryButton: ViewModifier {
func body(content: Content) -> some View {
content
.frame(width: 300, height: 28)
.padding()
.background(Color.yellow)
.foregroundColor(Color.white)
}
}
By using dfd's comment, does not change anything.
struct TestButton : View {
var body: some View {
Button(action: {
}) {
Text("Tap me")
}
.modifier(PrimaryButton())
}
}
fileprivate struct PrimaryButton: ViewModifier {
func body(content: Content) -> some View {
content
.relativeWidth(1.0)
.padding()
.background(Color.yellow)
.foregroundColor(Color.white)
}
}
A:
GeometryReader may help you
for example:
SomeButton: View {
var body: some View {
GeometryReader { geometry in
VStack() {
Button(action:{}) {
Text("\(geometry.size.width)")
}.padding()
.frame(minWidth: geometry.frame(in: .global).size.width,
minHeight: geometry.frame(in: .global).size.height
)
.background(Color.red)
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can buyer details be shown on paypal's order summary page?
Is it possible to submit other information to the paypal order summary page aside from just the product name and price? I have a form that submits to paypal and it contains the buyer's email address and their name which I would like it to appear on the summary page.
Can someone please post a small snippet of what the button code would look like for this?
A:
Once buyer login to their paypal account during checkout, the buyer will be able to see their email and shipping address as shown in the image for PayPal Payment Standard buttons such as buynow, addto cart.
If you are using Express checkout Integration, you can use GetExpressCheckoutDetails API to retrieve the buyer information and display in the order summary page on your website(not in paypal checkout page).
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between 2 dates in seconds
Possible Duplicates:
Number of seconds from now() to Sunday midnight
Calculates difference between two dates in PHP
Hello All,
In my project, I need to calculate the difference in seconds between two dates:
For Example :
$firstDay = "2011-05-12 18:20:20";
$secondDay = "2011-05-13 18:20:20";
Then I should get 86400 Seconds That is 24 hours.
Similarly For
$firstDay = "2011-05-13 11:59:20";
$secondDay = "2011-05-13 12:00:20";
It should return 60 Seconds.
I read lots of questions in the stackoverflow But they only deals with the difference between 2 minute fields like 11:50:01 and 12:10:57
A:
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add a tab Bar to a Default view and communicate with other views using navigation controller
It might be simple but not able to find exact solution for this.i am using xcode 4.2.
I want to use Tab bar in one of the view in my application. i went through many tutorials all tutorials are related to navigation based application and other view based application.Even i understood how to add a tab bar controller in story board which is main view.
What i need is i have class called Homepage.h and .m and .xib which is subclass of UIViewController class.Again my class is not main class its added later for one of the view.So i want to add a tab bar and communicate with navigationBar and other views so how can i do it plz give me some samples.
Problem is i want to add Tab bar to the default UIView and communicate with navigation controller and other views. i dont want to drag Tab bar controller from utilities.Incase if i drag how can i make it view on moving from one view to another as i already have a Default UIview.Please give me links or any tutorials where i can add tab bar and switch between views using navigation controller.
NOTE: i am using Single View based Application
A:
Take UINavigationController object and UITabBarController object in AppDelegate.h
In AppDelegate.h
First *first;
Second *second;
Third *third;
UINavigationController *navController;
UITabBarController *tabbar;
@property (nonatomic, retain) UITabBarController *tabbar;
@property (nonatomic, retain) UINavigationController *navController;
IN AppDelegate.m
@synthesize tabbar,navController;
in ApplicationdidFinishLaunching
tabbar=[[UITabBarController alloc]init];
first=[[First alloc]initWithNibName:@"First" bundle:nil];
second=[[Second alloc]initWithNibName:@"Second" bundle:nil];
third=[[Third alloc]initWithNibName:@"Third" bundle:nil];
navController=[[UINavigationController alloc]initWithRootViewController:first];
NSArray *viewControllerArray=[[[NSArray alloc] initWithObjects:navController1,second,third,nil] autorelease];
[self.window addSubview:tabbar.view];
[tabbar setViewControllers:viewControllerArray];
[first setTitle:@"First"];
[second setTitle:@"Second"];
[third setTitle:@"Third"];
Write this code and dont need to put Tabbar in XIB. Try thi code it will helps you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java-Maven: How to add manually a library to the maven repository?
I'm trying to generate a jasperReport, but I receive this:
net.sf.jasperreports.engine.util.JRFontNotFoundException: Font 'Times New Roman' is not available to the JVM. See the Javadoc for more details.
After searching on the net, I found that I need to add a jar to the classpath with the font. So, I create a jar file with the ttf files and now I want to add this as a dependency to my pom file.
So: I installed the file :
mvn install:install-file -Dfile=tf.jar -DgroupId=tf -DartifactId=tf -Dversion=1.0.0 -Dpackaging=jar
and in my pom, I added these lines:
<dependency>
<groupId>tf</groupId>
<artifactId>tf</artifactId>
<version>1.0.0</version>
</dependency>
but I receive this: Dependency 'tf:tf:1.0.0' not found less
I checked the repository folder and the jar file is there, in ... tf\tf\1.0.0\
What I'm doing wrong?
A:
The syntax of the command used to install your 3rd party jar looks identical to the reference (I would just also generate a pom by adding -DgeneratePom=true), the snippet to declare the dependency in your pom looks fine. What you're doing seems ok.
Could you provide the exact trace?
| {
"pile_set_name": "StackExchange"
} |
Q:
C# SendKey loop stuck
So, i've been trying to use SendKey.Send method with a for loop, and for some reason it gets stuck in an infinite loop only when i use it there. I've tried the code without it, and it worked for some reason.
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < trackBar2.Value; i++)
{
SendKeys.Send("{ENTER}");
System.Threading.Thread.Sleep(trackBar1.Value);
}
}
What seems to be the problem?
*EDIT: It can't be the "Enter" key because it does the same thing with other keys and strings, for example:
SendKey.Send("a");
A:
You press button1, at which time the code shown will be executed. This then sends Enter to button1 (because this still has focus), causing that code to run again, etc.
Thus, you have created a loop.
If you try with a different key sent, for instance a, then the program will hang for a bit, due to the Thread.Sleep, but after that should become responsive again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom field in Linked Products woocommerce
I found the following code to put the custom field in the linked products woocommerce function.
https://stackoverflow.com/a/45620800/9681621
Can someone please provide me the code to show the selected products in the cart page?
A:
you should look some woocommerce documentation. https://docs.woocommerce.com/documentation/plugins/woocommerce/woocommerce-codex/theming/
you can follow these steps.
the woocommerce>templates>cart>cart.php is the cart page.
you will find something like this.
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'],
$cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id',
$cart_item['product_id'], $cart_item, $cart_item_key );
loop display the products you added to the cart.Variable $product_id of the loop have the id of each product you added the the cart. now you can insert your custom field code here
echo get_post_meta( $product_id, 'my-field-slug', true );
it will look something like this.
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'],
$cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id',
$cart_item['product_id'], $cart_item, $cart_item_key );
// Display Custom Field Value
// my-field-slug should be change according to your slug
echo get_post_meta( $product_id, 'my-field-slug', true );
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create custom web security expression to use in JSP?
How is it possible to create your own web security expression, so that I'll be able to use it in JSP file like:
<sec:authorize access="isOwner()"> some content here </sec:authorize>
A:
Here is what you need.
Follow below to create custom SpEL expression:
1) Create custom subclass of WebSecurityExpressionRoot class. In this subclass create a new method which you will use in expression. For example:
public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {
public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
super(a, fi);
}
public boolean yourCustomMethod() {
boolean calculatedValue = ...;
return calculatedValue;
}
}
2) Create custom subclass of DefaultWebSecurityExpressionHandler class and override method createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) (not createEvaluationContext(...)) in it to return your CustomWebSecurityExpressionRoot instance. For example:
@Component(value="customExpressionHandler")
public class CustomWebSecurityExpressionHandler extends DefaultWebSecurityExpressionHandler {
@Override
protected SecurityExpressionRoot createSecurityExpressionRoot(
Authentication authentication, FilterInvocation fi) {
WebSecurityExpressionRoot expressionRoot = new CustomWebSecurityExpressionRoot(authentication, fi);
return expressionRoot;
}}
3) Define in your spring-security.xml the reference to your expression handler bean
<security:http access-denied-page="/error403.jsp" use-expressions="true" auto-config="false">
...
<security:expression-handler ref="customExpressionHandler"/>
</security:http>
After this, you can use your own custom expression instead of the standard one:
<security:authorize access="yourCustomMethod()">
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I sync a folder from one EBS volume to another for the same EC2?
I have an EC2 instance with EBS volumes A and B attached to it, and I want to copy/replicate/sync the data from a specific folder in EBS A to EBS B.
EBS A is the primary volume which hosts application installation data and user data, and I'm looking to effectively backup the user data (which is just a specific directory) to EBS B in the event that the application install gets corrupted or needs to be blown away. That way I can simply stand up a new EC2 with a new primary EBS, call it C, attach EBS B to it, and push the user data from EBS B into EBS C.
I am using Amazon Linux 2 and have already gone through the process of formatting and mounting the backup EBS. I can manually copy data from EBS A to EBS B but I was hoping someone could point me towards a best practices for keeping the directory data in sync between the two volumes?
I have found recommendations for rsync, a cron task, and gluster for similar use cases. Would is be considered good practice to use one these for my use case?
A:
While you can use rsync, a better alternative is Data Lifecycle Manager, which will make automated EBS snapshots.
The reason that it's better is that you can specify a fixed number of snapshots, at a fixed time interval, so you don't need to restore the latest (important if the "current" data is corrupted).
To use this most effectively, I would separate the boot volume from the application/data volume(s). So you could just restore the snapshot, spin up a new instance, and mount the restored volume to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use logger while setting SiftingAppender in logback.xml
I have this logback configuration:
<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator class="com.blackHole.programmingTrading.config.ThreadNameBasedDiscriminator"/>
<sift>
<appender name="FILE-${threadName}" class="ch.qos.logback.core.FileAppender">
<file>${LOG_HOME}/app-${threadName}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${UNION_LOG_PATTERN}</pattern>
</layout>
</appender>
</sift>
</appender>
and have this configuration class:
public class ThreadNameBasedDiscriminator implements Discriminator<ILoggingEvent> {
private static final String KEY = "threadName";
private boolean started;
@Override
public String getDiscriminatingValue(ILoggingEvent iLoggingEvent) {
return iLoggingEvent.getThreadName();
}
@Override
public String getKey() {
return KEY;
}
public void start() {
started = true;
}
public void stop() {
started = false;
}
public boolean isStarted() {
return started;
}
}
but when I get logger like this:
LoggerFactory.getLogger(Logger.class)
or this:
LoggerFactory.getLogger("SIFT")
the siftAppender don't work, and I have other appenders working together, so how to deal with it ?
A:
With identical settings, just using the logger like below works perfectly;
@Component
public class SomeService {
public void test() {
Logger logger = LoggerFactory.getLogger(SomeService.class);
logger.error("hey");
}
}
Then I can see the log in app-myThread.log in my local;
14:43:01.808 [myThread] ERROR com.example.demo.SomeService - hey
If you are trying to get a logger with its name specifically, you'd need to add below in your logback.xml;
<logger name="mylogger" level="error">
<appender-ref ref="SIFT"/>
</logger>
Because appender != logger, you can add your own configuration to this...
Then you can do;
LoggerFactory.getLogger("mylogger");
will result in a bit different log;
14:53:23.447 [myThread] ERROR mylogger - hey
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ticker List elements when they are Commands?
If I create a List based on an array of Commands, and the text of some Commands are not entirely shown in the List, although the List preferredWidth is set to the Form preferredWidth, how to ticker them ?
Thank you very much
A:
Try this code, it will show list in dialog box on clicking "Show list" command and will also enable ticker initially. Below is the code which shows how to use the above mentioned class to see ticker in list when list is contained in dialog.
Don't forget to make your list final so that it can be used in inner classes.
form.addCommand(new Command("Show list") { // add command in form and override its actionPerformed method
public void actionPerformed(ActionEvent evt) {
Dialog d = new Dialog() { // create an instance of dialog and make it an inner class so that you can override onShow() method and set focus on list when dialog gets initialized and also can set its index to ur preferred one (here it's 0)
protected void onShow() { // overriding of onShow() method
list.requestFocus(); // set focus on list
list.setSelectedIndex(0); // set selected index to 0
}
};
d.addComponent(list); // add list in dialog
d.show(); // show dialog
}
});
This code shows my list in dialog and starts ticker initially. If it doesn't help, post your code, i will try to see it.
| {
"pile_set_name": "StackExchange"
} |
Q:
The closure of an open subset in $\mathbb{R}^d$ is Ahlfors regular?
I have a question about Ahlfors regular space.
Let $U$ be a bounded open subset in $\mathbb{R}^d$. We denote by $m$ the Lebesgue measure on $U$. Then, can we show the following?
There exists a positive constant $C>0$ such that $$C^{-1}r^d \le m(U
\cap B(x,r)) \le Cr^d$$ for any $x \in U$ and $0<r<\text{diam}(U)$. Here $B(x,r)$ denotes the open ball centered at $x$ with radius $r>0$.
It is easy to prove $ m(U
\cap B(x,r)) \le Cr^d$. Can we show $ m(U
\cap B(x,r)) \ge C^{-1}r^d$?
A:
The answer is negative.
The idea is to find $U$ with a "local density" decreasing to zero.
Consider in $\mathbb R$
$$U = \bigcup_{n \in \mathbb N} (\frac{1}{n}, \frac{1}{n}+\frac{1}{n^3}).$$
Then for $n \ge 4$:$$m(U
\cap B\left(\frac{1}{n}+\frac{1}{2n^3},\frac{1}{2}\left(\frac{1}{n}-\frac{1}{n+1}\right)\right)) = \frac{1}{n^3}$$
And $$\lim\limits_{n \to \infty}\dfrac{ \frac{1}{n^3}}{\frac{1}{2}\left(\frac{1}{n}-\frac{1}{n+1}\right)}=0$$
in contradiction with $$\dfrac{m(U
\cap B(x,r))}{r} \ge C^{-1}>0$$ if such a $C$ would exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
swiftでrealmの導入
realmのデータベースを導入する為、半日cocoapodsでのrealmの導入法を調べたのですが、挫折してしまいました。。
サンプルのプロジェクトを作りXcodeを終了して、ターミナルでcocoapodsのインストールまではできたのですが、その先のpodfileを作って〜からがどのサイトを見ても理解できなく、導入ができません。
どなたか、導入法がわかる方がいましたら、どうかご教授お願いします。
よろしくお願いします。。
A:
質問する場合は環境のバージョンなどもあればいいかと思います。
また、実行出来るコードまで全て説明すると1つの記事が書けてしまうほど長くなるので
今、詰まっているであろうPodfileを導入するところまで回答します。
まず、cocoapodsのインストールまで出来たとのことですがpod setupまで終わりましたか?
とりあえず終わっている前提でお話しします。
ターミナルからプロジェクトのディレクトリに入り、pod initを実行します。
正常にcocoapodsのセットアップが終わっていればPodsとPodfileが作成されます。
もし既にPodfileがあるのであればエラーになるので削除してください。
上記のコマンドにより作成されたPodfileをvimコマンドなりテキストエディタなりで開き、
下記のように記述します。
target 'ProjectName' do
# Comment this line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for ProjectName(この下に必要なライブラリを記述する)
pod 'RealmSwift'
end
上記まで保存ができたらターミナルからプロジェクトディレクトリでpod installを実行します。
2回目以降の編集の場合などは各ライブラリを最新にする意味合いでpod updateでも良いです。
実行が終わりましたら普段開いているであろうProjectName.xcodeprojの他に
ProjectName.xcworkspaceが出来ているかと思いますので、そちらを開きます。
あとRealmとRealmSwiftをインポートしコードを記載してください。
上記、ターミナル操作に慣れている前提で記載しました。
不明点あれば追記しますのでコメントでおしらせください。
| {
"pile_set_name": "StackExchange"
} |
Q:
UIDocument with Autosave when is the file saved
I setting up UIDocument to save my files to the device. I mark a file needs to be saved with
[ myDoc updateChangeCount:UIDocumentChangeDone ]
Now it appears that the saving operation only kicks in when one is leaves the app. Now what would happen if I dereference the file when I have the file open, thinking that I have its content saved already, would the autosave kick in before the file is dereferenced.
Thanks
Reza
A:
If you're done with a UIDocument, you should close it using UIDocument closeWithCompletionHandler:
| {
"pile_set_name": "StackExchange"
} |
Q:
still have space after margin, padding, border all zero?
I have set margin, padding, and border to zero, yet there is still space around my canvases and divs in both Firefox and Chrome. Clearly, I do not understand how to snug up elements in HTML, and would be grateful for advice & pointers.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Spacing Question</title>
<style type="text/css">
*
{
border: 0px;
margin: 0px;
padding: 0px;
}
canvas
{
width: 150px;
height: 150px;
}
body
{
background-color: Purple;
color: Silver;
}
</style>
<script>
function draw() {
var canvas = document.getElementById('canvas1');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(200, 0, 0)";
ctx.fillRect(0, 0, 150, 150);
}
canvas = document.getElementById('canvas2');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(0, 200, 0)";
ctx.fillRect(0, 0, 150, 150);
}
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas1" width="150" height="150">
Fallback content 1.
</canvas>
<canvas id="canvas2" width="150" height="150">
Fallback content 2.
</canvas>
<div id="allYourControls">
</div>
</body>
</html>
A:
It's the whitespace (in this case, a line break) between your two <canvas>:
..
</canvas>
<canvas id="canvas2" ..
If you change it to this, the gap will be gone:
</canvas><canvas id="canvas2"
Alternatively, you can keep your whitespace, and add float: left to canvas in your CSS. If you choose to float them, you probably want to also add #allYourControls { clear: both } to clear your floats.
A:
The canvas element has a display of inline by default.
HTML collapses all multiple instances of whitespace into a single space.
These two properties combine in your case (and many others) to create a little gap between your elements. You have a line break between your canvases:
<canvas></canvas>
<canvas></canvas>
The browser thinks you're just trying to insert a bunch of spaces in between two inline elements. It thinks you're trying to do something like this:
<p>Best of all for man would be
to never exist, second best
would be to die soon.</p>
So it "collapses" those line breaks into a single space. It's the same reason that the above paragraph, for the most part, would be displayed as a single, normal line of text.
tl;dr Put your canvases on the same line.
As @thirtydot suggests, this is how to get rid of the gap:
<canvas>
...
</canvas><canvas>
...
</canvas>
| {
"pile_set_name": "StackExchange"
} |
Q:
Does God care about who we were?
I got the following line from the movie Cowboys vs Alien.
God doesn't care who you were. He only cares who you are.
Taking it with a pinch of salt, I'd like to ask the community if this statement can be asserted with biblical sources.
A:
Key Verses
If any one is in Christ, he is a new Creation. Behold, the old things have passed away, the new is come.
2 Cor 5:17
As far as the east is from the west,
so far has he removed our transgressions from us
- Psalm 103:12
Interpretation
So, the whole basis of the Gospel is grace - the unmerited favor of God towards sinners. Grace is the complete forgiveness of sin, and a core tenet of the Gospel is that God's grace is abundant. Put simply, there is no sin that God cannot forgive. (I know, somebody's going to link to the unforgivable sin of blaspheming the Holy Spirit, but that's not where I'm going.) In forgiving us, God's design is to make us a new creation.
Whether forgiveness means that the sin is forgotten or merely paid for is irrelevant to the original question - does God care about what we were? Not in the plainest sense, no. Its water under the bridge, so to speak.
If God's design then is that we are transformed into a new creation, it would seem silly to assume that God would spend much time caring about where we begin. Put another way, God is sufficiently focused on what he will make of us that it seems silly for him to focus on what we were when we came to him.
Now, here's where I'm going to shift from God's motivation to what I suspect is the real thrust of the quote - If God is more concerned about what he would make of us, then once we come to him, any time we spend focused on what we were is distraction. We feel guilt and shame, to be sure, but the awesome news that is the Good News is this - God has forgiven us.
I'm trying not to preach here, but the point is so basic I think it needs to be made: God has forgiven our sin. What we were is no longer relevant. (It may have consequences in the temporal - not arguing that, I'm just saying, God is making us new.) The theological import of the admonition is 100% right on - God doesn't care where we came from, because he wants to remake us into his new creation anyway.
One last avenue of argument - Temporal Omnipresence
Most Christians (Process Theologians excepted) would, I believe, argue that God is not constrained by time. Given temporal omnipresence, then, God would simultaneously see the sinner and the new creation. If God is outside of time, not part of the timestream if you will, then there is no past or present for God - all time happens at once. If that is the case, then it isn't possibly to for God to care where you came from or where you are going, because its all present tense to him. Being that God loves us, he must care for us as we are along.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability over a given $\sigma$-algebra
My question is very basic in a sens :
Given a set $\Omega$ and a $\sigma$-algebra $\mathscr T$ over $\Omega$, is it always possible to define a probability over $(\Omega, \mathscr T)$ ?
I assume my question is a little bit vague. Any piece of advise to precise it will be welcomed.
Thanks in advance !
A:
Assuming your set $\Omega$ is non-empty, you can always pick some $x\in\Omega$ and assign probability $1$ to those sets of $\mathscr T$ that contain $x$ and probability $0$ to those that don't. Maybe you did not mean this type of solution, but then you should be more specific about the conditions you want $\mathscr T$ to satisfy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Avoid Nested For Loop
I am new to python programming and I am getting my hands dirty by working on a pet project.
I have tried a lot to avoid these nested for loops, but no success.
Avoiding nested for loops
Returns values from a for loop in python
import requests
import json
r = requests.get('https://api.coinmarketcap.com/v1/ticker/')
j = r.json()
for item in j:
item['id']
n = item['id']
url = 'https://api.coinmarketcap.com/v1/ticker/%s' %n
req = requests.get(url)
js = req.json()
for cool in js:
print n
print cool['rank']
Please let me know if more information is needed.
A:
Your first request already gets you everything you need.
import requests
import json
response = requests.get('https://api.coinmarketcap.com/v1/ticker/')
coin_data = response.json()
for coin in coin_data:
print coin['id'] # "bitcoin", "ethereum", ...
print coin['rank'] # "1", "2", ...
print coin['price_usd'] # "2834.75", "276.495", ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Alternative for all_load in XCode's Other Linker Flags
I'm adding Rdio to my iOS app and I'm stuck on this part of the installation:
Add -all_load under Other Linker Flags in the project build info
If I add that flag, then another third party library breaks giving me the error message:
ld: duplicate symbol _vw_chartype_table_p in /Users/josh/
Projects/app/libs/libvt_universal.a(vw_ctype-3279EF26D0C25F3A.o) and /
Users/josh/Projects/app/libs/
libvt_universal.a(vw_ctype-34AB9EC0B46D954C.o) for architecture i386
Is there any way to use the Rdio library without using -all_load? For example, I've tried -force_load $(BUILT_PRODUCTS_DIR)/Rdio.framework but it seems to have no effect.
A:
force_load is exactly what you want - it allows you to load only that framework without messing with anything else. The problem is the exact syntax along with a few other unexpected tweaks to your settings.
-force_load syntax
Force load should be given the path to your object file, not the framework.
-force_load $(SOURCE_ROOT)/AppName/libs/Rdio.framework/Versions/Current/Rdio
Other Settings
Remove Rdio.framework from the 'Link Binary with Libraries' build phase.
Remove '/libs/Rdio.framework' from my LIBRARY_SEARCH_PATHS
| {
"pile_set_name": "StackExchange"
} |
Q:
Convenient ways to initialize nested fields with lenses
I have some data type which is very similar to ordinary trees, just some specialized form.
data NestedTree = NT
{ _dummy :: Int
, _tree :: HashMap String NestedTree
} deriving (Show)
makeLenses ''NestedTree
I want to initialize instances of my data type imperatively using lenses. Here is what I got now:
example :: NestedTree
example = flip execState (NT 0 mempty) $ do
dummy .= 3
tree.at "foo" ?= flip execState (NT 0 mempty) (dummy .= 10)
You can observe in this example that I can replace first (NT 0 mempty) with (NT 3 mempty) but this is not the point. What I want is too be able to initialize nested HashMaps using this nice imperative style. More precise, I want to be able to write something like this:
example :: NestedTree
example = flip execState (NT 0 mempty) $ do
dummy .= 3
tree.at "foo" ?= flip execState (NT 0 mempty) $ do
dummy .= 10
tree.at "foo nested" ?= NT 5 mempty
tree.at "bar" ?= flip execState (NT 0 mempty) $ do
dummy .= 15
tree.at "bar nested" ?= NT (-3) mempty
My real data structure is more complex and it very soon becomes really ugly to initialize it using just simple records. Thus I want to use some kind of DSL, and lenses fit quite good for my need. But you can notice that code above doesn't compile.
It's because ($) has lowest precedence and I can't just write tree.at "foo" ?= flip execState (NT 0 mempty) $ do. But I really don't want to add () around nested dos.
Is there any nice ways to mix arbitrary operators with $ and do in order to write such functions? I really don't want to introduce some helper like wordsAssign = (?=) and call functions like
wordsAssign (tree.at "foo") $ flip execState (NT 0 mempty) $ do
because I like ?= operator. Maybe I'm doing everything wrong and this kind of things I want to do can be done without lenses with some hand-written operators?
A:
zoom is tailor-made for handling nested state updates. In your case, unfortunately, the Maybe-ness makes using it slightly awkward:
example :: NestedTree
example = flip execState (NT 0 mempty) $ do
dummy .= 3
zoom (tree.at "foo") $ do
put (Just (NT 0 mempty))
_Just.dummy .= 10
_Just.tree.at "foo nested" ?= NT 5 mempty
-- Or, using zoom one more time:
zoom (tree.at "bar") $ do
put (Just (NT 0 mempty))
zoom _Just $ do
dummy .= 15
tree.at "bar nested" ?= NT (-3) mempty
For the sake of comparison, if you didn't need to insert new keys at the outer level, you would be able to use ix instead of at and drop all the Maybe-related boilerplate:
zoom (tree.ix "foo") $ do
dummy .= 10
tree.at "foo nested" ?= NT 5 mempty
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I directly send an email via the default mail app on a device
I have one of the questions of the type that would usually make me say "Why would you want to do that" and assume it will be used for malicious purposes, but here goes...
How can I send email without user interaction, without implementing my own email sender?
Before any of you suggest it - I'm aware of Javamail and I've used the approach before so will fall back to that if I need to. I'm also aware of how to trigger a chooser and how to open a compose screen directly. What I want is none of those.
I have a feedback form in my app. 3 text fields and a button. When the user hits the button I send the data in the fields to myself, but to save increasing my app's size further I want to send the mail through whatever mail app is currently installed/default, all without further user interaction.
Is this possible?
A:
You can use the SMS functionality of your phone:
SmsManager sms = SmsManager.getDefault();
String myPhoneNumber = "800 333-1212";
String toEmailAddress = "[email protected]";
String myEmailBody = "Here is my email message";
sms.sendTextMessage( toEmailAddress,"1"+myPhoneNumber, myEmailBody, null, null);
Granted, your email won't look pretty, but... Also don't forget the permission SEND_SMS in your manifest. Obviously, this will not work on some tablets that only have wifi and no telephony.
A:
What you want to achieve is not possible with your conditions, however there is plenty of choice you have to achieve the same thing in a cleaner manner.
1.Use libraries and services like ACRA, as @Oliver has mentioned.
2.Implement a simple restful API and use it to send your data, you can use services like Google app engine to make this more convenient.
Implement your own email sender which is not ideal at all.
Obviously your app need a backend.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX: ScatterPlots take too long to load
I have a JavaFX GUI application that has 6 ScatterPlot graphs. My application is reading & plotting data from a serial port. The TextAreas are displaying the raw data with no problem. My only issue is that when the application plots the points, the application freezes. Can someone explain to me what is causing this issue? Is there any way to fix it? Is there any way of plotting the streaming data without making the application freeze?
I'd upload my code, but it's too long & exceeds the StackOverflow's limit of 3000 characters.
PS: Most of my code is located in the start().
A:
I figured it out!
Turns out the reason why my graphs were freezing was because all incoming data was running on 1 thread. Using multiple threads improved the performance of the GUI & prevented the GUI from freezing
| {
"pile_set_name": "StackExchange"
} |
Q:
Menu and breadcrumbs
I need the menu bar and breadcrumbs to use different hierarchies. Specifically, I need the menu bar to have:
Home | Projects | About | Contact
but I need the breadcrumbs for a project page to be:
Home > Projects > Project title
In "Content > [Projects page] > Edit > Menu settings > Parent item", to get "Projects" to show up in the menu bar, I have to set the parent to "<Main menu>". But if I do that then the breadcrumbs on a project page become:
Projects > Project title
so I lose "Home" in the breadcrumbs.
So the question is, how do I get "Projects" to be in the menu, but allow it to be under "Home" in the breadcrumbs?
I see there are lots of contributed modules for managing menus and breadcrumbs, but I wonder if there's something readily available in core that I don't know about. If not, what is the right module to do this?
Thanks for your help.
A:
I think your best bet is defining custom breadcrumbs for your Project content type:
https://www.drupal.org/project/custom_breadcrumbs
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select where two columns are MAXIMUM
I've created a view in order to keep using it without having to write this part of code each time the view called "Data"
The first SQL statement will get me the max season for each series for specific user.
SELECT s_imdbID, MAX(ep_season) FROM Data
WHERE u_ID = 1
GROUP BY s_imdbID
The second SQL statement will get me the max episode of latest season for specific series for a specific user.
SELECT s_imdbID, ep_season, MAX(ep_episode) FROM Data
WHERE ep_season = (
SELECT MAX(ep_season)
FROM Data
WHERE u_ID = 1
AND s_imdbID = "tt4158110"
)
AND s_imdbID = "tt4158110"
AND u_ID = 1;
How can I integrate both of them into one SQL statement to get the following
seriesID | Max_Season | Max_Episode
-----------| ------------------| -----------
Value.... | Value............ | Value
this is the view code in the code you will be able to know the kind of data that will be retrieved from it
SELECT
-- episode data
e.title AS "ep_title",
e.year AS "ep_year",
e.rated AS "ep_rated",
e.released AS "ep_released",
e.season AS "ep_season",
e.episode AS "ep_episode",
e.runtime AS "ep_runtime",
e.genre AS "ep_genre",
e.director AS "ep_director",
e.writer AS "ep_writer",
e.actors AS "ep_actors",
e.plot AS "ep_plot",
e.language AS "ep_language",
e.country AS "ep_country",
e.awards AS "ep_awards",
e.poster AS "ep_poster",
e.metascore AS "ep_metascore",
e.imdbRating AS "ep_imdbRating",
e.imdbVotes AS "ep_imdbVotes",
e.imdbID AS "ep_imdbID",
-- series data
s.title AS "s_title",
s.year AS "s_year",
s.rated AS "s_rated",
s.released AS "s_released",
s.runtime AS "s_runtime",
s.genre AS "s_genre",
s.director AS "s_director",
s.writer AS "s_writer",
s.actors AS "s_actors",
s.plot AS "s_plot",
s.language AS "s_language",
s.country AS "s_country",
s.awards AS "s_awards",
s.poster AS "s_poster",
s.metascore AS "s_metascore",
s.imdbRating AS "s_imdbRating",
s.imdbVotes AS "s_imdbVotes",
s.imdbID AS "s_imdbID",
-- user data
u.ID AS "u_ID"/*, */
/*
u.username AS "u_username",
u.firstname AS "u_firstname",
u.lastname AS "u_lastname",
u.password AS "u_password",
u.email AS "u_email",
u.emailVerificationCode AS "u_emailVerificationCode",
u.location AS "u_location",
u.accesslevel AS "u_accesslevel",
u.disabled AS "u_disabled",
u.active AS "u_active"
*/
FROM test w
INNER JOIN users u
ON u.ID = w.userid
INNER JOIN episode e
ON w.epid = e.imdbID
INNER JOIN series s
ON e.seriesID = s.imdbID
WHERE e.seriesID IN (SELECT (imdbID) FROM series);
EDIT 1:
it's a series watchlist and the view Data are coming from a table in which I'm saving each user with it's watched episode
through that view I get the data of the episode, series, user
A:
You can try using NOT EXISTS() :
SELECT * FROM Data t
WHERE NOT EXISTS(SELECT 1 FROM Data s
WHERE t.s_imdbID = s.s_imdbID
AND s.ep_season > t.ep_season)
AND NOT EXISTS(SELECT 1 FROM Data p
WHERE p.s_imdbID = t.s_imdbID AND p.ep_season = t.ep_season
AND p.ep_episode > t.ep_episode )
First one makes sure that no newer season exists, second one that no newer episode exists .
| {
"pile_set_name": "StackExchange"
} |
Q:
How to program the tree view of directories
How to program the tree view of directories and files so that the user chooses one?
I have found nothing ralated on same.
A:
You can use this https://github.com/bmelnychuk/AndroidTreeView library for that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Ajax call with same JSON data key calling one php file
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
A:
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Outlook 2007 for two accounts but configuring one for sending by default.
I currently use outlook 2007 to manage two email accounts, but I want to set one address so all sent emails come from that address by default.
Currently all emails come in regardless of the account, but I want all responses to send from a specific email address. How do go about this?
All my emails come in from my current provider yahoo, but I'm not happy with them I and want everything to transition to go out from my new gmail account.
A:
This is easily done in the account settings inside the outlook account settings under tools.
Once both accounts are setup, select Tools from the Menu, and select Account Settings.
From Outlook 2007 Account Settings:
Highlight the desired account
Click Set as Default
Now click Close
You now have one account set as default, from now on, all e-mails (including replies) will be from the account set as default.
| {
"pile_set_name": "StackExchange"
} |
Q:
create sub-arrays from one main array
I am still getting my grip on Java. I need some help in looping through an array.
My array looks like this;
String [] allRecords = ["[BEGIN RECORD]", "[ID]1", "[cName]Agnes", "[Age]12", "[END RECORD]", "[BEGIN RECORD]", "[ID]2", "[cName]Hellen", "[Age]5", "[END RECORD]", "[BEGIN RECORD]", "[ID]3", "[cName]Jack", "[Age]34", "[END RECORD]" ];
//i use the below code to identify the beginning and end of a record in the array
String beginRecord = "[BEGIN RECORD]";
boolean foundBeginRecord = false;
int foundIndex = 0;
for (int i=0; i<allRecords.length; i++) {
if (beginRecord.equals(allRecords[i])) {
foundBeginRecord = true;
foundIndex = i+1; //added one
break;
}
}
String endRecord = "[END RECORD]";
boolean foundEndRecord = false;
int foundEnd = 0;
for (int i=0; i<allRecords.length; i++) {
if (endRecord.equals(allRecords[i])) {
foundEndRecord = true;
foundEnd = i; //one NOT added
break;
}
}
//i then use the below code to slice off part of the array
String [] partAllRecords = Arrays.copyOfRange(allRecords, foundIndex, foundEnd);
//this gives me a new sub-array like this: "[ID]1", "[cName]Agnes", "[Age]12"
The above code works OK. What I need now is to read/slice another portion from the allRecords array i.e.; "[ID]2", "[cName]Hellen", "[Age]5" and then slice the next block "[ID]3", "[cName]Jack", "[Age]34" till the end of the allRecords Array.
How can I do this?
Thank you!
A:
First, thank you Trenin and Jason for your guidance.
I struggled with the task and for the benefit of someone else one day, i will paste below the code that has worked for me;
String [] allRecords = {"[BEGIN RECORD]", "[ID]1", "[cName]Agnes", "[Age]12", "[END RECORD]", "[BEGIN RECORD]", "[ID]2", "[cName]Hellen", "[Age]5", "[END RECORD]", "[BEGIN RECORD]", "[ID]3", "[cName]Jack", "[Age]34", "[END RECORD]"};
String beginRecord = "[BEGIN RECORD]";
String endRecord = "[END RECORD]";
int foundIndex = 0;
int foundEnd = 0;
for (int i=0; i<allRecords.length; i++) {
if (endRecord.equals(allRecords[i])) {
foundEnd = i;
break;
}
}
//by saving the location of the end of the previous record, and picking up from there, your logic can now be repeatedly in a loop until all valid records are consumed from the input
foundEnd = foundEnd-1; //arrays are zero based
for (int i=0; i<allRecords.length; i++) {
if (beginRecord.equals(allRecords[i])) {
foundIndex = i+1; //arrays are zero based
String [] partAllRecords = Arrays.copyOfRange(allRecords, foundIndex, foundIndex+foundEnd);
System.out.println(Arrays.toString(partAllRecords));
//prints below arrays in logcat
//[[ID]1, [cName]Agnes, [Age]12]
//[[ID]2, [cName]Hellen, [Age]5]
//[[ID]3, [cName]Jack, [Age]34]
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to increment a month in a row based on the month in the previous row?
I have a dataframe which has a value column and "month year" column. In the first row Aug 2018 is written for the month year column. Is there a possibility that the following rows which hava a value in the value column are automatically filled with the next month respectively? So that row two is filled with Sep 2018 and row three with Oct 2018 and so on?
Actual result:
value month
645 Aug 2018
589 NA
465 NA
523 NA
632 NA
984 NA
Expected results:
value month
645 Aug 2018
589 Sep 2018
465 Okt 2018
523 Nov 2018
632 Dez 2018
984 Jan 2019
A:
In base R, you could do something like this to create a monthly sequence
df$month <- format(seq(as.Date(paste("01", df$month[1]), "%d %b %Y"),
length.out = nrow(df), by = "month"), "%b %Y")
df
# value month
#1 645 Aug 2018
#2 589 Sep 2018
#3 465 Oct 2018
#4 523 Nov 2018
#5 632 Dec 2018
#6 984 Jan 2019
Important assumption to note here is you have only one value of month which is present in the first row and you want to replace all other values of month by incrementing 1 month from the previous entry.
A:
We can do this with as.yearmon from zoo. Used package version 1.8.3
library(zoo)
df$month <- head(as.yearmon(df$month[1]) + c(0, seq_len(nrow(df)))/12, -1)
df
# value month
#1 645 Aug 2018
#2 589 Sep 2018
#3 465 Oct 2018
#4 523 Nov 2018
#5 632 Dec 2018
#6 984 Jan 2019
data
df <- structure(list(value = c(645L, 589L, 465L, 523L, 632L, 984L),
month = c("Aug 2018", NA, NA, NA, NA, NA)), class = "data.frame",
row.names = c(NA, -6L))
| {
"pile_set_name": "StackExchange"
} |
Q:
Install scipy for both python 2 and python 3
I used sudo apt-get install python-scipy to install scipy. This put all the files in /usr/lib/python2.7.dist-packages/scipy. My best guess is it chose that location because python 2.7 was the default version of python. I also want to use scipy with python 3 however. Does the package need to be rebuilt for python 3 or can I just point python 3 to the existing version?
I've tried using pip to install two parallel version, but I can't get the dependency libblas3 installed for my system.
What's the best way to do this?
I'm on Debian Jessie.
A:
To install scipy for python3.x the on a debian-based distribution:
sudo apt-get install python3-scipy
This corresponds to the python2.x equivalent:
sudo apt-get install python-scipy
On a more platform-independent note, pip is the more standard way of installing python packages:
pip install --user scipy #pip install using default python version
To make sure you are using the right pip version you can always be more explicit:
pip2 install --user scipy # install using python2
pip3 install --user scipy # install using python3
Also, I believe anaconda or the more lightweight miniconda were intended to make installation of python packages with complex dependencies more easy, plus it allows for using an environment, making it easier to have several configurations with non-compatible versions etc. This would create+use a python binary different from the one on your system though.
One would then install scipy using the command conda:
conda install scipy
If installing scipy for a specific version you would create an environment with that python version:
conda create -n my_environment_name python=3 scipy
One could also use pip inside a conda environment alongside conda python packages, but I would make sure that you are using pip installed using conda to avoid conflicts. An added benefit when installing conda for a user, is that you don't have to add the --user flag when installing with pip.
A:
If you can't find python3-scipy using apt-get you can use pip to install it for python3, you just have to make sure you use pip3 (if you don't have it apt install python3-pip
pip3 install --user scipy
| {
"pile_set_name": "StackExchange"
} |
Q:
Get character position in StringBuilder when using contains
Been looking high and low but couldn't find how to do it.
I'd like to do the following
I'm trying to get the second element from converted ToString returnCode
for example: A1235 is returnCode.
I'm trying to get the "1"
edit: Guys. It can contain two "1"s but not on the second position of the string. I need an if statement that does xyz IF the second character of returnCode is 1. Don't think "Char" is going to work.
StringBuilder matchCode = new StringBuilder();
//returnCode is a stringbuilder type variable.
if (returnCode.ToString().charAt(1).Contains("0"))
{
matchCode.AppendLine("Match Confidence Level: 0 (Low Confidence)");
}
A:
You don't need to cast your StringBuilder to string and then look for a char in it. You can use a code like this:
if (returnCode != null && returnCode.Length > 1 && returnCode[1] == '0') // no need to check for null if you are sure it's not null
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieve info in DLL assembly about calling assembly
I have created several DLL (.NET) libraries that are used in several projects. In these DLL libraries I want to know/retrieve which assembly (EXE) calls/uses the library, so if possible I want to know info like assembly name (EXE), strong name, version number, etc.
NB: Examples may be in C# or VB. I use both languages.
A:
You can use System.Reflection => Assembly.GetCallingAssembly() should do the job.
http://msdn.microsoft.com/en-en/library/system.reflection.assembly.getcallingassembly.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding the Document Approval template by Google AppMaker
Almost a month I tried to understand the template but found a dead end. Had tried posted here on the App Maker Users Forum to request on a tutorial video to explain on how's the template work .. yet still no reply from them.
Can anyone with the Google AppMaker expertise kindly explain to me how's this different layer of approval been done. In this example from Document Approval template, user need to manually key in their approver. But what I try to achieve is that, the system will automatically set the different layer of approval when user submit the request. Can anyone guide me on how to do that .. any help from the floor? Thanks ..
A:
Well I've been working on this template since last 5 months and you will need to do a lot of customization to use it in PROD like environment and I think that is okay because Google team has provided us a starting point by providing us templates. We need to customize it as per our need.
Here are the steps that template will do for you.
End user will see all the request he has already made on the home screen. If any. On the right hand side '+' button, user can start a new request.
Here an end user can choose any document from Google Drive/ Team Drive and provide the description for that file and click on 'ADD' button. On the next screen he can provide a list of approvers. Here this template supports both sequential and parallel approvals. i.e. More than one approver can take action at same time or you can have a workflow like approvals where Approver 1 approves first then only Approver 2 gets notified for the action.
Once all approvers are in place users can submit the request and Doc is sent for Approvals with the approvers.
Approvers can Approve/Reject the request with Comments. After all approvals are done workflow is closed.
Now your second question is somewhat unclear. I think you are referring to Auto Approver names should be added. Please refer this if your question is same, or else please provide exact use case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i get Tracking Number on Sales order grid
I need tracking number on sales order grid,
A:
You can do it with below.
Add below code in your app/code/local/Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Vendor_Module>
<version>0.1.0</version>
</Vendor_Module>
</modules>
<global>
<blocks>
<module>
<class>Vendor_Module_Block</class>
</module>
<adminhtml>
<rewrite>
<sales_order_grid>Vendor_Module_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>
Now create a file app\code\local\Vendor\Module\Block\Adminhtml\Sales\Order\Grid.php with below code.
<?php
class Vendor_Module_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->joinLeft(array("track_table"=>Mage::getSingleton('core/resource')->getTableName('sales/shipment_track')), "main_table.entity_id = track_table.order_id",array('track_number'))->group('main_table.entity_id');
$this->setCollection($collection);
return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
}
protected function _prepareColumns()
{
if ($this->_isExport) {
$this->addColumnAfter('track_number', array(
'header' => Mage::helper('sales')->__('Track Order'),
'index' => 'track_table.track_number',
'type' => 'text',
), 'status');
}
$this->addColumnAfter(
'track_number',
array(
'header' => Mage::helper('sales')->__('Track Order'),
'align' => 'left',
'type' => 'text',
'index' => 'track_number',
'filter_index' => 'track_table.track_number',
),
'status'
);
parent::_prepareColumns();
}
}
Create file app/etc/modules/Vendor_Module.xml
<?xml version="1.0"?>
<config>
<modules>
<Vendor_Module>
<active>true</active>
<codePool>local</codePool>
<version>0.1.0</version>
</Vendor_Module>
</modules>
</config>
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a cleaner way to handle compiler errors C1076 and C3859?
Today I've been adding some library headers to our precomp.h file. Then I tried to recompile in debug and got those two errors (spawned from a boost include):
error C3859: virtual memory range for PCH exceeded; please recompile with a command line option of '-Zm310' or greater
fatal error C1076: compiler limit : internal heap limit reached; use /Zm to specify a higher limit
So I fixed them by increasing the memory heap size. No problem there.
My question is more about if this problem hides another one? Will I eventually have to give it more memory if I keep on adding library headers to the precomp.h? Is this the way programmers handle it, or would there be a "cleaner" way to do it?
More info:
Visual Studio 2013
c++
A:
The /Zm parameter does not change anything about how the code is interpreted, so it does not hide a problem in the code, other than the fact that the code requires a lot of memory to compile.
The switch only informs the compiler about the memory costs it should plan for during compilation. In VS 2013, the default precompiled header buffer size is 75 MB, which is value that a complex project can reasonably exceed. In such situations, you can use /Zm to increase the limit. Alternately, you could invest significant work into reducing the complexity of your include files.
In most cases, it is a much better use of developers' time to increase /Zm.
| {
"pile_set_name": "StackExchange"
} |
Q:
Preventing browser redirects on Android (and iOS)
There seems to be an issue occurring with mobile browser apps on Android and iPhone being redirected to advertising sites. This is interrupting the browsing experience.
The problem:
A user visits a website on their phone in a current and up-to-date browser such as Chrome for Android or Firefox for Android, and a mobile ad is displayed
The ad causes a redirect from the currently displayed website to spaces.slimspots.com
The slimspots server seems to check if Javascript is active and then redirects to another ad, such as a competition webpage
Many users have reported this, both on the Chrome product forum and on the Apple forums, (links in the pastebin below) but nobody seems to understand what is actually occurring. People are doing unnecessary factory resets on their phones and complaining to various webmasters about the ads on their forums.
The behavior can be replicated in a desktop browser by changing the User-Agent to a Nexus 4 and reloading a forum thread on a website (eg. xda-developers) until an offending ad appears.
Since I can't create more than two links here without gaining more reputation, you can find some useful content in this pastebin.
Can anybody provide advice on how to suppress these redirects, without resorting to a non-stock browser?
A:
First of all: This kind of advertising should be reported!
Can anybody provide advice on how to suppress these redirects, without
resorting to a non-stock browser?
It looks like they use a bug in JavaScript. Maybe report to ad provider or app owner for blocking.
How to reproduce this issue:
If you use the preinstalled browser in Android, the ad site
opens "Google Play Store" and show you each time a different App.
How can I sandbox untrusted user-submitted JavaScript content?
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL query between three tables
This is a basic extract of the film rental platform I'm working on. To show you, I just need these three tables.
Film
Title | Genre |
-------------+---------------+
Why Me | Romantic |
The ET | Fantasy |
... | ... |
Planet | Documentary |
User
ID | Name |
-------------+---------------+
213 | Jonh D |
34267 | Smith E |
... | ... |
256 | Sally F |
Rent
User_ID | Film_Title | Date |
-------------+---------------+-------------+
34267 | The ET | 2015-11-01 |
256 | Planet | 2014-12-03 |
... | ... | ... |
256 | Why Me | 2016-03-04 |
That said, I need to do a SQL query that associates to each Film.Genre the User.Name that have rented the highest amount of films for that genre.
ID | Genre |
-------------+---------------+
Sally F | Romantic |
Smith E | Fantasy |
... | ... |
Sally F | Documentary |
I would have posted some of my attempts but honestly I didn't come out with anything which is barely sense making. I know that using JOIN statement would be easier that trying to build it with nested statements but I am stumped and this is so frustrating.
SELECT u.Name, f.Genre
FROM User AS u JOIN Rent AS r JOIN Film AS f
GROUP BY f.Genre
ORDER BY(COUNT(r.User_ID))
A:
You could use a subquery like this one:
SELECT sub.Name, sub.Genre, MAX(rent_number)
FROM (
SELECT User.Name, Film.Genre, Count(User.ID) as rent_number
FROM Film
INNER JOIN Rent ON Film.Title = Rent.Film_Title
INNER JOIN User ON Rent.User_ID = User.ID
GROUP BY User.Name, Film.Genre) sub
GROUP BY sub.Genre
| {
"pile_set_name": "StackExchange"
} |
Q:
Using malloc in C to make sure that user enter certain digits
So I want to write a program to check if user enter. Say requirement is 4 digits number, if user enters 5 then program keeps asking user to renter exactly 4 digit number.
I got the working code like this: basically use scanf to read in a string value, then use strlen to count number of digits. If user enters the correct digit, then I use atoi to convert that string into an int, which I will use for later.
Say requirement is 4 digit number:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int digit, mynumber;
int digit = 5;
char str[5];
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
I want to modify this a bit. Instead of doing char str[5] for 5 digit string. I want to try a dynamic array.
So in place of char str[5], I do this:
char *str;
str = malloc(sizeof(char) * digit);
Running this through the code gives seg fault. Can anyone help me with this?
This is the complete code with the issue
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int mynumber;
int digit = 5;
char *str;
str = malloc(sizeof(char) * digit);
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
A:
While you can use the formatted input function scanf to take your input as a string, scanf is full of a number of pitfalls that can leave stray characters in your input stream (stdin) depending on whether a matching-failure occurs. It also has the limitation using the "%s" conversion specifier of only reading up to the first whitespace. If your user slips and enters "123 45", you read "123", your tests fail, and "45" are left in stdin unread, just waiting to bite you on your next attempted read unless you manually empty stdin.
Further, if you are using "%s" without the field-width modifier -- you might as well be using gets() as scanf will happily read an unlimited number of characters into your 5 or 6 character array, writing beyond your array bounds invoking Undefined Behavior.
A more sound approach is the provide a character buffer large enough to handle whatever the user may enter. (don't Skimp on buffer size). The read an entire line at a time with fgets(), which with a sufficient sized buffer ensure the entire line is consumed eliminating the chance for characters to remain unread in stdin. The only caveat with fgets (and every line-oriented input function like POSIX getline) is the '\n' is also read and included in the buffer filled. You simply trim the '\n' from the end using strcspn() as a convenient method obtaining the number of characters entered at the same time.
(note: you can forego trimming the '\n' if you adjust your tests to include the '\n' in the length you validate against since the conversion to int will ignore the trailing '\n')
Your logic is lacking one other needed check. What if the user enters "123a5"? All 5 characters were entered, but they were not all digits. atoi() has no error reporting capability and will happily convert the string to 123 silently without providing any indication that additional characters remain. You have two-options, either use strtol for the conversion and validate no characters remain, or simply loop over the characters in your string checking each with isdigit() to ensure all digits were entered.
Putting that altogether, you could do something like the following:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NDIGITS 5 /* if you need a constant, #define one (or more) */
#define MAXC 1024
int main (void) {
int mynumber;
size_t digit = NDIGITS;
char buf[MAXC]; /* buffer to hold MAXC chars */
/* infinite loop until valid string entered, or manual EOF generated */
for (;;) {
size_t len;
printf("\nEnter a %zu digit number: ", digit); /* prompt */
if (!fgets (buf, sizeof buf, stdin)) { /* read entire line */
fputs ("(user canceled input)\n", stdout);
break;
}
buf[(len = strcspn(buf, "\n"))] = 0; /* trim \n, get len */
if (len != digit) { /* validate length */
fprintf(stderr, " error: %zu characters.\n", len);
continue;
}
for (size_t i = 0; i < len; i++) { /* validate all digits */
if (!isdigit(buf[i])) {
fprintf (stderr, " error: buf[%zu] is non-digit '%c'.\n",
i, buf[i]);
goto getnext;
}
}
if (sscanf (buf, "%d", &mynumber) == 1) { /* validate converstion */
printf ("you entered %zu digits, mynumber = %d\n", len, mynumber);
break; /* all criteria met, break loop */
}
getnext:;
}
return 0;
}
Example Use/Output
Whenever you write an input routine, go try and break it. Validate it does what you need it to do and catches the cases you want to protect against (and there will still be more validations you can add). Here, it covers most anticipated abuses:
$ ./bin/only5digits
Enter a 5 digit number: no
error: 2 characters.
Enter a 5 digit number: 123a5
error: buf[3] is non-digit 'a'.
Enter a 5 digit number: 123 45
error: 6 characters.
Enter a 5 digit number: ;alsdhif aij;ioj34 ;alfj a!%#$%$ ("cat steps on keyboard...")
error: 61 characters.
Enter a 5 digit number: 1234
error: 4 characters.
Enter a 5 digit number: 123456
error: 6 characters.
Enter a 5 digit number: 12345
you entered 5 digits, mynumber = 12345
User cancels input with ctrl+d on Linux (or ctrl+z on windows) generating a manual EOF:
$ ./bin/only5digits
Enter a 5 digit number: (user canceled input)
(note: you can add additional checks to see if 1024 or more characters were input -- that is left to you)
This is a slightly different approach to reading input, but from a general rule standpoint, when taking user input, if you ensure you consume an entire line of input, you avoid many of the pitfalls associated with using scanf for that purpose.
Look things over and let me know if you have further questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make a listview of objects in android and access the object fields by clicking listitems?
I have a listview of objects in my android application I have made it by using my custom ArrayAdapter and I want to get the fields of any object that now is a listItem by clicking the listItem but I haven't any idea to do this
my Content class is:
public class Content {
public String title;
public String text;
public int id;
public Date date;
}
and my ContentAdapter class:
public class ContentAdapter extends ArrayAdapter<Content> {
private ArrayList<Content> objects;
public ContentAdapter(Context context, int textViewResourceId,
ArrayList<Content> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.content_list_item, null);
}
Content i = objects.get(position);
if (i != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
if (tt != null) {
tt.setText("title");
}
if (ttd != null) {
ttd.setText(i.title);
}
if (mt != null) {
mt.setText("text:");
}
if (mtd != null) {
mtd.setText(i.text);
}
}
return v;
}
}
now I want to get date and id by clicking a list item but not show them in the list view
should I add id and date fields to my custom arrayAdapter class to do this?
A:
Assuming that your custom adapter holds a list of Content object, you will have to add an OnItemClickListener to your list view as below and obtain the object clicked and retrieve the attributes.
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
Content content = (Content ) adapterView
.getItemAtPosition(position);
//from the content object retrieve the attributes you require.
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How does PostgreSQL enforce the UNIQUE constraint / what type of index does it use?
I've been trying to sort out the relationship between unique and index in Postgres after reading the docs on index uniqueness being an implementation detail:
The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique
constraints could be considered an implementation detail that should
not be accessed directly. One should, however, be aware that there's
no need to manually create indexes on unique columns; doing so would
just duplicate the automatically-created index.
So taking the docs at their word I'm going to just declare things as unique and use the implicit index - or - create an index and not assume that the values are unique. Is this a mistake?
What kind of index will I be getting from unique? Given that only a btree will accept the unique constraint and unique implicitly creates an index is it true that UNIQUE creates a btree index? I don't want to be running ranges on a hash index inadvertently.
A:
or - create an index and not assume that the values are unique
It is safe to assume that values are unique, if you have a unique index defined. That's how unique constraints are implemented (at the time being, and probably in all future versions as well).
Defining a UNIQUE constraint does effectively the same (almost, see below) as creating a unique index without specifying the index type. And, I quote the manual:
Choices are btree, hash, gist, and gin. The default method is btree.
Adding a constraint is just the canonical way that would not break in future versions where it could be implemented differently. That's all.
And no, a unique constraint can only be implemented with a basic btree index in all versions up to and including PostgreSQL 9.4. I quote the "ADD table_constraint_using_index" paragraph in the manual here:
The index cannot have expression columns nor be a partial index. Also,
it must be a b-tree index with default sort ordering.
Other differences
Unique constraints can be deferred. That is not possible for unique indexes. Have a look at the SET CONSTRAINTS command and follow the links for more.
- A foreign key cannot reference columns with just a unique index. The manual:
A foreign key must reference columns that either are a primary key or
form a unique constraint.
The last bit seems to be outdated or a misunderstanding from the getgo. See:
NULL values for referential_constraints.unique_constraint_* columns in information schema
Related:
Is unique index better than unique constraint when I need an index with an operator class
| {
"pile_set_name": "StackExchange"
} |
Q:
Unknown number of fragments: FragmentPagerAdapter or FragmentStatePagerAdapter?
In activity I have ViewPager.
I don't know how many fragments will be added to viewPager.
The question is:
What I need to use in this case: FragmentPagerAdapter or FragmentStatePagerAdapter?
A:
Surely go with FragmentStatePagerAdapter.
FragmentPagerAdapter loads all fragments at once and will consume more memory. If you have a lot of fragments, loading all of them at once even may lead to out of memory error.
Even you have known number of fragments, FragmentStatePagerAdapter is recommended in most of the cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did my Visual Studio start acting this way? iisexpress cannot find or open the PDB file
When I first created my project and ran it, I didn't get these messages:
'iisexpress.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll'. Cannot find or open the PDB file.
So what did I do to my VS config, or maybe my project properties that caused this issue?
Before this started happening, running the application took a minute or two, now I'm waiting more like 5 mins. Which is nuts, there is something wrong with my config somewhere.
A:
The most likely reason you started getting the message
"'iisexpress.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll'. Cannot find or open the PDB file." is because that DLL is now being loaded during execution, and wasn't being loaded previously.
The missing PDB file however is not part of your problem. You can get rid of the warning message by obtaining this PDB file from Microsoft. But I suggest you focus on what you did to make it start appearing (ie when you started loading System.Web.dll). This might help explain why it takes longer to load.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert links to image banner slider in jQuery Plugin?
How to insert links to image slider in jQuery Plugin?
I got slider source from http://www.jqueryscript.net/slider/Responsive-jQuery-Full-Width-Image-Slider-Plugin-responsiveSlides.html
I try insert links like this :
<a href="www.google.coom"><img src="blablabla.jpg></a>
but, It does not work ... (T^T)
I recheck in Chrome (key F12)
<div class="tgtimg" style="position:absolute !important; height:600px !important; width:100% !important; background:#fff !important; z-index:1 !important; overflow:hidden !important"><img src="http://ikkorea.i.hhosting.kr/main/main_20150710_1.jpg" style="position: absolute; z-index: 1; top: 0px; left: -568.5px; height: 600px; display: block;" class="current"></div>
<a href="http://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&ie=utf8&query=%EC%9D%B5%EC%8A%A4%ED%8E%98%EB%94%94%EC%95%84+%EB%8F%84%EC%B0%A9"></a>
How can I?
this is my site:
http://www.istkunst.co.kr/preview/?dgnset_id=5834
A:
You can add an global class to all the images you want to be clicked, and add also the link for every image in data-link, like this :
HTML :
<div id="content">
<img class="img_link" data-link="www.google.com" src="1.jpg">
<img class="img_link" data-link="www.gmail.com" src="2.jpg">
<img class="img_link" data-link="www.yahoo.com" src="3.jpg">
</div>
Create fucntion to handle the click on images and redirect to the related link stored in data-link , just after the call of responsiveSlides().
JS :
$(function(){
var p=$('#content').responsiveSlides({
....
});
//Handling click event and redirecting to the related link
$('.img_link').click(function(){
window.location.replace($(this).data('link'));
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Year-Week format in ISO calendar format?
I am trying to get the current date in ISO Calendar format as follows alongwith the zero padding on the week?
2019/W06
I tried the following, but prefer something using strftime as it is much easier to read.
print(str(datetime.datetime.today().isocalendar()[0]) + '/W' + str(datetime.datetime.today().isocalendar()[1]))
2019/W6
A:
Use following code:
print(datetime.now().strftime('%Y/W%V'))
%Y Year with century as a decimal number.
%V - The ISO 8601 week number of the current year (01 to 53), where
week 1 is the first week that has at least 4 days in the current year,
and with Monday as the first day of the week.
https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior
| {
"pile_set_name": "StackExchange"
} |
Q:
Using page counter in \newtheorem
I would like to use the page counter as a the first part of the label for definitions. I tried
\newtheorem{definition}{Definition}[page]
but that wouldn't work if the definition is at the top of a new page, presumably because of this. Is there any way around it?
A:
You can use the perpage package:
\documentclass{article}
\usepackage{amsthm,perpage,etoolbox}
\theoremstyle{definition}
\newtheorem{definition}{Definition}
\MakePerPage{definition}
\renewcommand{\thedefinition}{\theperpage.\arabic{definition}}
% We encourage TeX to break before a definition so the numbering will be correct
\BeforeBeginEnvironment{definition}{\goodbreak}
\usepackage[paperheight=60pt]{geometry} % just for the example
\begin{document}
\begin{definition}
First on first page
\end{definition}
\begin{definition}
Second on first page
\end{definition}
\newpage
\begin{definition}
First on second page
\end{definition}
\end{document}
This will assign numbers 1.1, 1.2 and 2.1
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between a trap, an error, a failure and program abortion?
I see often the following terms in C++ interview questions :
program abort
error
failure
trap
I'm not sure to see clearly the differences between those terms. Can someone provide a clear concise explanation?
Edit : the context question was : "What happens when you delete a pointer twice?" but knowing the differences between those terms is more important for me than just the answer.
A:
These aren't really particular to C++.
Abort is when you terminate the program, or a particular operation, because of a problem. There is a C++ library function std::abort, inherited from the C library, which kills the program as if by an external signal, and does not run destructors or clean-up.
An error is when something goes wrong. In C++, many kinds of errors are not necessarily detected immediately. C++ instead specifies undefined behavior, which may involve quiet memory corruption that may cause mysterious misbehavior later.
A failure is when a program does the wrong thing. This is pretty generic engineering term. The pointy-haired boss is probably more familiar with this concept than the others, because it's the only one a customer is really aware of.
A trap is when the program detects an error condition and takes some action accordingly.
So if you detect that the network went down, and show a message to the user such as "Could not continue; your document has been automatically saved" before quitting, then you have trapped an error and aborted, but nevertheless there was a failure.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I debug a C program installed using guix?
I installed flatpak using guix, but it segfaulted on startup. I wanted to debug it, but guix installs a wrapper script for flatpak, so I get this error when trying to run it under gdb:
"/home/user/.guix-profile/bin/flatpak": not in executable format: file format not recognized
and I tried to edit the wrapper script to call gdb, but this wrapper script is not even editable by root, because it is owned by root and has read-only permissions.
A:
Simply copy the script to your current working directory:
cp /home/user/.guix-profile/bin/flatpak .
Mark it as writable:
chmod +w flatpak
Edit the script with your favourite text editor, to replace the string exec -a with exec gdb --args.
And finally, run it with any arguments you provided before, when it misbehaved:
./flatpak remote-add flathub https://flathub.org/repo/flathub.flatpakrepo
In this particular case, this wasn't immediately super-useful, because a debug symbol output hasn't been built for this package. But at least I could get a backtrace out of gdb.
| {
"pile_set_name": "StackExchange"
} |
Q:
MPI - scattering filepaths to processes
I have 4 filepaths in the global_filetable and I am trying to scatter 2 pilepaths to each process.
The process 0 have proper 2 paths, but there is something strange in the process 1 (null)...
EDIT:
Here's the full code:
#include <stdio.h>
#include <limits.h> // PATH_MAX
#include <mpi.h>
int main(int argc, char *argv[])
{
char** global_filetable = (char**)malloc(4 * PATH_MAX * sizeof(char));
for(int i = 0; i < 4; ++i) {
global_filetable[i] = (char*)malloc(PATH_MAX *sizeof(char));
strncpy (filetable[i], "/path/", PATH_MAX);
}
/*for(int i = 0; i < 4; ++i) {
printf("%s\n", global_filetable[i]);
}*/
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
char** local_filetable = (char**)malloc(2 * PATH_MAX * sizeof(char));
MPI_Scatter(global_filetable, 2*PATH_MAX, MPI_CHAR, local_filetable, 2*PATH_MAX , MPI_CHAR, 0, MPI_COMM_WORLD);
{
/* now all processors print their local data: */
for (int p = 0; p < size; ++p) {
if (rank == p) {
printf("Local process on rank %d is:\n", rank);
for (int i = 0; i < 2; i++) {
printf("path: %s\n", local_filetable[i]);
}
}
MPI_Barrier(MPI_COMM_WORLD);
}
}
MPI_Finalize();
return 0;
}
Output:
Local process on rank 0 is:
path: /path/
path: /path/
Local process on rank 1 is:
path: (null)
path: (null)
Do you have any idea why I am having those nulls?
A:
First, your allocation is inconsistent:
char** local_filetable = (char**)malloc(2 * PATH_MAX * sizeof(char));
The type char** indicates an array of char*, but you allocate a contiguous memory block, which would indicate a char*.
The easiest way would be to use the contiguous memory as char* for both global and local filetables. Depending on what get_filetable() actually does, you may have to convert. You can then index it like this:
char* entry = &filetable[i * PATH_MAX]
You can then simply scatter like this:
MPI_Scatter(global_filetable, 2 * PATH_MAX, MPI_CHAR,
local_filetable, 2 * PATH_MAX, MPI_CHAR, 0, MPI_COMM_WORLD);
Note that there is no more displacement, every rank just gets an equal sized chunk of the contiguous memory.
The next step would be to define a C and MPI struct encapsulating PATH_MAX characters so you can get rid of the constant usage of PATH_MAX and crude indexing.
I think this is much nicer (less complex, less memory management) than using actual char**. You would only need that if memory waste or redundant data transfer becomes an issue.
P.S. Make sure to never put in more than PATH_MAX - 1 characters in an filetable entry to keep space for the tailing \0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Expression has changed after it was checked. Angular 2 issue
Template:
<tbody>
<tr>
<td>{{getRand()}}</td>
<td>{{getRand()}}</td>
</tr>
</tbody>
Method:
getRand(){
return Math.floor(Math.random()*100);
}
Error:
Expression has changed after it was checked. Previous value: '90'. Current value: '32'.
Can anyone explain why this error occurs? Why can't I call this method multiple times?
A:
This is how Angular change detection works!
The change detection algorithm in Angular, goes through the component tree at specific times (some events), to determines what has changed.
It then update the UI based on the model changes and UI bindings.
In dev mode (look at https://angular.io/docs/ts/latest/api/core/index/enableProdMode-function.html and what exactly happens when `enableProdMode()` and What is difference between production and development mode in Angular2?) this component walk is performed twice just to make sure that model is stable after the changes. In your case the function you use for binding is not side-effect free, as each invocation of the function returns a different value.
As a rule of thumb, use side-effect free bindings.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP replace GET-value of a variable
I have a URL as a string in $url.
I want to replace a specific parameter (if it exists) in the URL.
For example
$url = "http://www.xxx.xxx?data=1234324&id=abc&user=walter";
I'd like check if id exists and if it does, I want to replace the value of that id to a specific value. But the value of the id isn't always the same and it's not always in the same place.
A:
You can extract your query with PHP's parse_url function:
$b = parse_url($url, PHP_URL_QUERY);
From here you can use parse_str to get an associative array:
parse_str($b, $arr);
Now you can access the parameters
$arr['data'];
$arr['id'];
$arr['user'];
If you want to check if the id parameter exists you can use
if (isset($arr['id'])) {
//Do something
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Connecting to a node.js server from C#
I'm trying to write a simple server that .NET clients can connect to to exchange messages. Any message from any client will go to all of the others. node.js + socket.io seems like a good way to go here, but I'm having trouble. I'm using sample code from the socket.io site, and when I connect to it from a browser, the console traces out all the connection and heartbeat events as it should, so I think I've at least got the environment setup correctly.
My client code (pasted below) is very similar to the example code for the Socket class, but it's behaving strangely. In the "ProcessConnect" handler, e.LastOperation == "Connect", and e.SocketError == "Success", but the connection event handler on the server side is not firing. Also weird is that when the code sends "Hello World", the receive handler also gets fired with "Hello World" coming back. I know this isn't coming from the server because there's no code on the server to do this. I thought maybe the socket was connecting to itself or something, but if I shut the server down, the connection fails.
Clearly there's something basic I'm missing about .NET sockets, but I'm not sure what it is.
Client:
public class NodeClient
{
Socket _Socket;
public NodeClient()
{
SocketAsyncEventArgs socketState = new SocketAsyncEventArgs();
socketState.Completed += SocketState_Completed;
socketState.RemoteEndPoint = new DnsEndPoint("localhost", 81);
_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_Socket.ConnectAsync(socketState);
}
private void SocketState_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
throw new SocketException((int)e.SocketError);
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
ProcessConnect(e);
break;
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new Exception("Invalid operation completed.");
}
}
// Called when a ConnectAsync operation completes
private void ProcessConnect(SocketAsyncEventArgs e)
{
byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
e.SetBuffer(buffer, 0, buffer.Length);
bool willRaiseEvent = _Socket.SendAsync(e);
if (!willRaiseEvent)
{
ProcessSend(e);
}
}
// Called when a ReceiveAsync operation completes
private void ProcessReceive(SocketAsyncEventArgs e)
{
string message = Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length);
}
// Called when a SendAsync operation completes
private void ProcessSend(SocketAsyncEventArgs e)
{
bool willRaiseEvent = _Socket.ReceiveAsync(e);
if (!willRaiseEvent)
{
ProcessReceive(e);
}
}
}
Server:
var io = require('socket.io').listen(81);
io.sockets.on('connection', function (socket) {
console.log('connected yo');
});
A:
You could try handle this using your own socket code.
I would recommend that you use a library like SocketIO4Net
to handle the integration with .Net
SocketIO4Net - http://socketio4net.codeplex.com
| {
"pile_set_name": "StackExchange"
} |
Q:
Safe to use a Switching Voltage Regulator to power a Microsoft Surface Pro 4?
Is it safe to use a switching voltage regulator to power a Microsoft Surface Pro 4? I'm specifically concerned with the ripple/noise that produced by this type of voltage converter.
Voltage Step Up Converter
A:
In general yes. The Surface Pro 99.999% probably uses a switching regulator to charge in the first place. What you really want to know is how sensitive it is, or if that specific regulator will work okay. Quality of regulation is important. It depends on the switching frequency used, the quality of parts used. If you are going from mains to 12V dc you have much more to filter out than you do if you are going from dc to dc, or batteries stepping up. And your source and regulator should be able to handle the current needed, both peak and nominal, as well as how fast it may pull.
As mentioned, the first step is figuring out the actual noise or ripple your converter will produce compared to the original one. Then take it from there.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the ultimate etymology of "false"?
The first two are based on wiktionary
false
From Middle English false, from Old English fals (“false, fraud, falsehood”), from Latin falsus (“counterfeit, false; falsehood”), perfect passive participle of fallō (“deceive”).
Uncommon before the 12 century, the word was reinforced in Middle English by Norman fals (compare Old French faus), eventually displacing native Middle English les, lese (“false”), from Old English lēas; See lease, leasing.
For spelling, the -e (on -lse) is so the end is pronounced /ls/, rather than /lz/ as in falls, and does not change the vowel (‘a’). Compare else, pulse, convulse.
fallo
From Proto-Indo-European *gʰwel- (“to lie, deceive”). Cognate with Ancient Greek φῆλος (phẽlos, “deceitful”), Sanskrit वृ (vṛ, “twist, crook”), Avestan (zurah, “injustice”), Lithuanian ẑulas (“rough”), Latvian zvel'u (“to turn aside”), Old Church Slavonic зълъ (zŭlŭ, “evil”)
But here is another etymology from myEtymology.com
false
the English word false
derived from the Latin word falsus (wrong, lying, fictitious)
derived from the Latin word fallere (deceive; slip by; disappoint)
derived from the Latin word facere (to make; act, take action, be active; compose, write; classify; do, make; create; make, build, construct; produce; produce by growth; bring forth)
derived from the Proto-Indo-European root *dhē-
The third etymology is from etymonline.
false
late 12c., from O.Fr. fals, faus (12c., Mod.Fr. faux) "false, fake, incorrect, mistaken, treacherous, deceitful," from L. falsus "deceived, erroneous, mistaken," pp. of fallere "deceive, disappoint," of uncertain origin (see fail). Adopted into other Germanic languages (cf. Ger. falsch, Du. valsch, Dan. falsk), though English is the only one in which the active sense of "deceitful" (a secondary sense in Latin) has predominated. False alarm recorded from 1570s. Related: Falsely; falseness.
fail
early 13c., from O.Fr. falir (11c., Mod.Fr. faillir) "be lacking, miss, not succeed," from V.L. *fallire, from L. fallere "to trip, cause to fall;" figuratively "to deceive, trick, dupe, cheat, elude; fail, be lacking or defective."
Related: Failed; failing. Replaced O.E. abreoðan. The noun (e.g. without fail) is from late 13c., from O.Fr. faile "deficiency," from falir. The Anglo-French form of the verb, failer, came to be used as a noun, hence failure.
I just don't know which PIE form of "false" is the right one.
A:
Here's the OED's etymology:
Etymology: late Old English fals adj. and n., < Latin fals-us false
(neuter fals-um , used subst. in sense fraud, falsehood), originally
past participle of fallĕre to deceive; compare Old Norse fals n. The
adj. is found in Old English only in one doubtful instance (see sense
A. 13); its frequent use begins in the 12th cent., and was probably
due to a fresh adoption through the Old French fals, faus (modern
French faux = Provencal fals, Spanish, Portuguese, Italian falso). The
continental Germanic languages adopted the word in an altered form:
Middle High German valsch, modern German falsch (compare Old High
German gifalscôn to falsify), Old Frisian falsch, Dutch valsch, late
Icelandic (15th cent.) falskr, Danish, Swedish falsk.
The etymological sense of Latin falsus is ‘deceived, mistaken’ (of
persons), ‘erroneous’ (of opinions, etc.). The transition to the
active sense ‘deceitful’ is shown in phrases like falsa fides ‘breach
of trust, faithlessness’, where the n. has a subjective and an
objective sense. In mod. English the sense ‘mendacious’ is so
prominent that the word must often be avoided as discourteous in
contexts where the etymological equivalent in other Germanic languages
or in Romanic would be quite unobjectionable. Some of the uses are
adopted < French, and represent senses that never became English.
A:
I asked you which IE languages you know - in order to critically evaluate these three hypotheses, a strong background in the history of Latin (at least) is necessary. There are three major textbooks on the history of Latin - Baldi 1999, Sihler 1995, and Weiss 2009.
The first hypothesis is best supported by evidence - and, in fact, pretty standard now (for example, de Vaan 2008).
The Anlaut (word-initial) PIE *gwh> Lat. f sound correspondence is well documented, cf. Latin formus 'warm' - MnE warm; Greek thermos; Rus. zhar 'heat', goret' 'burn' etc. We still don't really know how PIE *gwh turned into Latin f (via *χw?) but this correspondence is regular.
We may ignore the perfectum fefelli because it's a relatively new coinage (double ll), cf. pello-pepuli, fero-tetuli (Meiser 1998), although reduplicated perfectum is usually archaic/rare in Latin.
The second "hypothesis" does not stand to scrutiny - supposedly, Latin fallo is derived from Latin facio. The person who came up with that hypothesis doesn't know Latin morphology at all. I don't know of any rule of Latin word-formation that could explain such a connection.
The third hypothesis does not have any explanation - it stops at Latin fallo.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP return - beginner fault
I do not know what I'm doing wrong. Perhaps someone could advise me. I'm trying to define seasons and then use the result in index.
...
File with function:
function getCurrentTheme($for_area) {
// Definition of seasons
$spring='spring theme title';
$spring_season=array('03-21',......);
$summer='summer theme title';
$summer_season=array(......);
$autumn='autumn theme title';
$autumn_season=array(......);
$winter='winter theme title';
$winter_season=array(......);
// Today
$current_date=date('m-d');
// So what season is now?
if ($for_area==='some_area') {
if (in_array($current_date,$spring_season) {
$theme=$spring;
}
else if (in_array($current_date,$summer_season) {
$theme=$summer;
}
else if (in_array($current_date,$autumn_season) {
$theme=$autumn;
}
else if (in_array($current_date,$winter_season) {
$theme=$winter;
}
else {}
}
else if ($for_area==='other_area') {
// ...
}
else {}
return $theme;
}
...
Index:
$area='some_area';
getCurrentTheme($area);
// And here is the fault. Hope sometimes I will stop being retarded.
echo $theme;
// What should be printed?
summer theme title
Thanks in advance and please try understand my innocence.
A:
You need to store the value, so that you can then echo it:
$area='some_area';
$theme = getCurrentTheme($area);
echo $theme;
| {
"pile_set_name": "StackExchange"
} |
Q:
Alignment of numeric values in UILabel
I have a UITableView with custom UITableViewCells.
Each of these cells has six UILabels, in which numeric values are presented (please refer to the screenshot below).
Unfortunately the numeric values in the last row are not correctly aligned. Having them right-aligned would also not be helpful. The correct alignment would be along the "," comma.
How can I comma-align numeric values in iOS? Do you have any ideas?
A:
Use right alignment with a fixed width font like Courier.
| {
"pile_set_name": "StackExchange"
} |
Q:
Php replace string with regex
I want replace in my file all tags "<_tag_>" with "".
I've tried this solutions:
$_text = preg_replace('<\_\s*\w.*?\_>', '', $_text);
But I replace "<_tag_>" with "<>"
$_text = preg_replace('<\_(.*?)\_>', '', $_text);
But I replace "<_tag_>" with "<>"
How can I also select angle brackets?
A:
It could be
<_.+?_>
# <_, anything lazily afterwards, followed by _>
In PHP:
$string = preg_replace('~<_.+?_>~', '', $string);
As in
<?php
$string = "some <_tag_> here";
$string = preg_replace('~<_.+?_>~', '', $string);
echo $string;
# some here
?>
See a demo on ideone.com.
| {
"pile_set_name": "StackExchange"
} |
Q:
Excluding .git in an Ant task
I'm using Ant 1.7.1 to tar up the contents of a directory, that contains a .git subdirectory. My current task is
<tar
destfile="sali-src-${version}.tgz"
basedir="${basedir}"
compression="gzip"
excludes=".git, .gitignore, *.ipr, *.iws, *.iml">
</tar>
But the resultant tarball contains the .git subdirectory. Could anybody point out how I could prevent it being included?
A:
This works:
<?xml version="1.0"?>
<project name="test" default="tar">
<target name="tar">
<tar
destfile="sali-src-${version}.tgz"
basedir="${basedir}"
compression="gzip"
excludes=".git/**, .gitignore/**, **/*.ipr, **/*.iws, **/*.iml">
</tar>
</target>
</project>
Your patterns were wrong, for more information about patterns read here: http://ant.apache.org/manual/dirtasks.html#patterns
A:
Ant has pre-configured default excludes that prevent directory-based tasks from processing control files for CVS, Subversion and VSS. Unfortunately, these defaults don't cover any other version control systems. However, you can modify the defaults using the <defaultexcludes> task:
<defaultexcludes add="**/.git/**,**/.gitignore"/>
This will exclude your Git files from any subsequent processing (so every subsequent use of <tar>, <javac>, <jar> or similar will ignore the control files).
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the right context inside setInterval
I´m trying to create a JS/Jquery function to handle several image sliders on the same page.
Here´s my code:
var imageSlider = $('.imageSlider');
imageSlider.each(function(){
var imageBackground = $(this).find('.imageBackground');
var imageBackgroundFirst = $(this).find('.imageBackground:first');
var imageBackgroundLast = $(this).find('.imageBackground:last');
imageBackground.addClass('off');
imageBackgroundFirst.removeClass('off').addClass('on');
setInterval(function(){
var imageBackgroundOn = $(this).find('.imageBackground.on');
if (imageBackgroundLast.hasClass('on')){
imageBackgroundLast.removeClass('on').addClass('off');
imageBackgroundFirst.addClass('on').removeClass('off');
}
else{
imageBackgroundOn.removeClass('on').addClass('off');
imageBackgroundOn.next().addClass('on').removeClass('off');
}
}, 7500);
})
The problem is imageBackgroundOn variable inside set interval element returns undefined context...
I know that setInterval handles variables in its own context, so how can I link the setInterval lines to work independent for every imageSlider element?
I need that variable to be refreshed on every interval and in its own context.
Thanks in advance!
A:
I would use Function.prototype.bind method:
setInterval(function(){
var imageBackgroundOn = $(this).find('.imageBackground.on');
if (imageBackgroundLast.hasClass('on')){
imageBackgroundLast.removeClass('on').addClass('off');
imageBackgroundFirst.addClass('on').removeClass('off');
}
else{
imageBackgroundOn.removeClass('on').addClass('off');
imageBackgroundOn.next().addClass('on').removeClass('off');
}
}.bind(this), 7500);
IE8 doesn't support ES5 methods, so instead you can use $.proxy:
setInterval($.proxy(function() {
// ...
}, this), 7500);
Or simply use reference to correct context:
var self = this;
setInterval(function() {
var imageBackgroundOn = $(self).find('.imageBackground.on');
// ...
}, 7500);
| {
"pile_set_name": "StackExchange"
} |
Q:
Troubles with deploying Pivotal Cloud Foundry on AWS
I have been trying to install Pivotal Cloud Foundry on AWS and I have troubles with it.
In the section upload-cert mentioned that I need to create SSL Certificates for:
*.system.example.com
*.login.system.example.com
*.uaa.system.example.com
*.apps.example.com
So, I've created domain xxxxx.com on AWS Route53 and created a certificate on AWS ACM for domain and subdomains.
So, my questions are:
do I need to create subdomains (system, login, uaa, apps) in AWS Route53
do I need to bound my domain and subdomain somehow to PCF? Or the installation process had to do it for me?
for now, if I open http://login.xxxxx.com/ it responses with 503. what can be the reason?
what is the correct url to open the PCF UI?
I have such error in Ops Manager. What can be the reason of such error?
The same about logs. When I tried to download logs for failed services it failed too. What can be the reason?
Thank you for the help!
A:
do I need to create subdomains (system, login, uaa, apps) in AWS Route53
do I need to bound my domain and subdomain somehow to PCF? Or the installation process had to do it for me?
You can create a wildcard subdomain (*.xxxxx.com) and alias using the instructions here: https://docs.pivotal.io/pivotalcf/1-10/customizing/cloudform-er-config.html#cname
what is the correct url to open the PCF UI?
If you mean Ops Manager, it is whatever DNS entry you created and pointed to the Ops Manager public IP address in this step: https://docs.pivotal.io/pivotalcf/1-10/customizing/cloudform-om-deploy.html#create-dns
For the ERT UI, there is the Pivotal Apps Manager https://docs.pivotal.io/pivotalcf/1-10/console/index.html
which is usually apps.system.xxxx.com
You can see what system apps are deployed by connecting to Cloud Foundry using the CLI and seeing which apps are in the system org, and what their routes are.
for now, if I open http://login.xxxxx.com/ it responses with 503. what can be the reason?
If the DNS has not been set up, I'm surprised you're getting any response whatsoever. Usually you get 503s when the routers connected to the load balancers are failing for some reason (http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/ts-elb-error-message.html#ts-elb-errorcodes-http503)
I have such error in Ops Manager. What can be the reason of such error?
This would explain the 503s if the router is unhealthy. I would SSH into those machines and see what the logs say (in /var/vcap/sys/logs), which should tell you what is going wrong.
A:
The reason of the red instances on the Status page was that my AWS account had limit on number of instances and it failed to create VMs for this nodes.
To find more information open Changelog (https://ops_manager_host/change_log) and the open log of the FAILED setup.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write php returns json format according to the key?
I use XAMPP to create local networks and write php file to return the data in the database as json. This is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "landslide";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function myexample {
$mysqli = "SELECT id, temp, acc, moisture, battery, time FROM devices";
$result = $conn->query($mysqli);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$response["main"] =array();
$response["parameters"]= array();
$main = array();
$main["id"]=$row["id"];
array_push($response["main"],$main);
$parameter = array();
$parameter["temp"] = $row["temp"];
$parameter["acc"] = $row["acc"];
$parameter["moisture"] = $row["moisture"];
$parameter["battery"] = $row["battery"];
$parameter["time"] = $row["time"];
array_push($response["parameters"],$parameter);
}
// echoing JSON response
$result_response = echo json_encode($response);
return $result_response;
}
} // end of my example function
?>
now when you call this function you will get json_encode format
now parse it by using
$res = JSON.parse($result_response);
now
$moisture = $res['moisture'];
My local link: http://127.0.0.1/landslide/currentdata.php .
Now, I want to write one php file returns json format according to the "key"(here i want key is id). As of Openweather api address below, key is cities (example London). http://api.openweathermap.org/data/2.5/weather?q=London,uk
So, how to i return json format by php according to key? Please help me! (My expression was not good, sorry about that)
A:
when you are returning the json_encode($response);
You need to parse it to get in like an object and access it you can achieive it like in one variable.
$result = JSON.parse($response);
and access this $result array like if you want to access moisture
then $moisture = $result['moisture']; like so on...
| {
"pile_set_name": "StackExchange"
} |
Q:
Textarea maxlength issue with database column size constraint
I been searching online for support but I have not found anything useful.
I have a database table with a column that contains a size constraint of 1500 characters.
I am using hibernate as an ORM to a database.
My issue is with the newline character in HTML textarea.
In my HTML form, I have a textarea who's maxlength is set to 1500.
In the HTML textarea, a newline is perceived as ONE character only.
When I submit the form via servlet the newline character is perceived as TWO characters in java.
So assuming I have filled out the textarea with 1500 characters, which contains 2 newlines in it, java sees the data passed as 1502 characters.
Thus when I save the data to the database it exceeds the 1500 limit and therefor violates the database column constraints.
Sample Text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus in est eu augue facilisis viverra. Phasellus eu lectus a nisi feugiat aliquet quis ut velit. Nunc vehicula neque sit amet quam interdum viverra. Morbi aliquet consequat lorem non rhoncus. Sed mauris mi, scelerisque sit amet tempus molestie, dapibus vitae quam. Proin id massa velit, commodo facilisis velit. In blandit, nibh quis auctor convallis, lectus nibh venenatis orci, quis dignissim sapien arcu eget erat. In quis diam id mauris consectetur tempor sit amet sit amet justo. Donec egestas metus eu massa vestibulum ultrices. Quisque vitae scelerisque metus. Vestibulum vehicula mi id augue condimentum pellentesque.
Suspendisse tempus turpis lobortis turpis imperdiet vulputate. Fusce fringilla lorem et ligula feugiat id sodales nisi vehicula. Praesent egestas vestibulum ante, eget consequat magna molestie sit amet. Praesent egestas pharetra augue egestas imperdiet. Suspendisse ut elit augue, sit amet ornare nulla. Morbi cursus, diam at commodo gravida, elit lacus pulvinar lectus, vitae porttitor mauris sapien sed felis. Vestibulum non iaculis erat. Phasellus pharetra arcu sed dui porta tempus. Mauris lectus velit, cursus quis facilisis a, mattis rhoncus quam. Ut nisl nulla, malesuada imperdiet dictum id, sagittis quis orci. Duis bibendum pharetra quam eu pharetra. Fusce interdum nulla vel elit bibendum non pellentesque dui egestas. Praesent sed lacus sapien. Vesbulum id arcu neque, et faucibus lorem. Fusce metus.
The gap between the paragraphs contain 2 newlines
What I need to know is how can I go about the different interpretation of the newline character from HTML to Java?
Thank for your help.
A:
You can replace \r\n style line endings with \n line endings:
str = str.replaceAll("(\\r)", "");
This should leave just the \n line endings.
| {
"pile_set_name": "StackExchange"
} |
Q:
Production and sandbox profiles during deployment
I currently maintain two sandboxes. One is a mirror of the current production. The other is a Dev Sandbox which contains all of the new development which will be included in an upcoming release. My ultimate goal is to merge these two sandboxes into a third sandbox which would represent what Production will be upon the new release.
Right now not all of the production profiles are present in the Dev Sandbox. We have been developing with profiles which were simple, just used by developers. So, I'm guessing I essentially have to move all of the used Prod profiles over to the Dev sandbox and customize each one of them to include the access settings for all the fields which will be part of the new release in order for the new fields to have the proper settings in the third sandbox. Is that correct ?
I would go about with this sequence :
1) Deploy all the used Production profiles to the Dev Sandbox
2) Go into each and every one of them and make the settings for every single components (object,field etc)which is not included in the current Prod
3) Deploy all of those now-updated Profiles to the third sandbox along with the other components (objects, fields)
Would that be the proper procedure here ? Is there a short cut which I am missing ?
Any advice would be greatly appreciated.
Thank you.
A:
Seems correct to me.
However, you should deploy profils thanks to Eclipse and not Change Sets.
Indeed, change Sets only add permission for content included in the package and not migrate all the profil.
| {
"pile_set_name": "StackExchange"
} |
Q:
BrainTree PayPal configuration doesn't work with dropin integration
I am trying to customize the "PayPal" button within the BrainTree dropin, ideally simply to move it somewhere else.
If I use the dropin integration, nothing happens - the usual blue button is rendered above the fields. When I choose custom, it works. The BrainTree docs suggest that it should work in both setups.
Here's the relevant code:
<form id="paymentForm" action="/braintree.php" method="POST">
<div id="hostedFields"></div>
<input id="formSubmit" type="submit" value="Pay" />
<div id="paypalContainer"</div>
</form>
And the javascript:
braintree.setup("<?=$clientToken ?>",
"dropin",
{
container: "hostedFields",
onPaymentMethodReceived: onNonce,
onReady: onFormReady,
onError: onError,
paypal:
{
container: "paypalContainer",
singleUse: true,
amount: PRODUCT_PRICE,
currency: PRODUCT_CURRENCY,
}
});
What am I doing wrong?
A:
Well, I got a reply from Support; it looks like it really isn't possible to specify the location of the PayPal button with dropin setup.
| {
"pile_set_name": "StackExchange"
} |
Q:
reading both tcp and udp packets from same socket
I am trying to read packets in a router, like this in python:
# (skipping the exception handling code here)
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
while True:
p = s.recvfrom(2000)
pkt = p[0]
# process pkt here ...
Answers to a related question (36115971) say that parameters and methods for UDP vs TCP data are different (some say recv is for TCP and recvfrom is for UDP, and others say the opposite, similarly some say 1024 as buffer size for TCP and larger for UDP, and again some say the reverse). In my case of reading in a router, I do not have different sockets for TCP and UDP, so I need to read both from the same socket, so I am bit confused regarding how I should read the incoming packets.
(1) Should I use recv() or recvfrom(), if I want to read both TCP and UDP packets?
(2) Do the calls return data one packet at a time, or do they return after the buffer is filled up? eg, if I have a large buffer of 4096 bytes, and the incoming streaming 2 packets have 2400 bytes each, will the call return as soon as the 1st packet ends, or will it return after filling up the buffer from the 2nd packet also?
(2a) same question, but if I have a smaller buffer of 2000 bytes. It is clear that on the 1st call I will get the first 2000 bytes of the 1st packet. But on the next call, will I get the last 400 bytes of the 1st packet, or the first 2000 bytes of the 2nd packet?
(3) If I am delayed in making the next call, maybe because I was busy processing the 1st dataset, am I in danger of losing data, or will the OS keep its internal queue of the incoming packets to be given to me when I call the next time? If the OS keeps its internal queue, where can I find information about its size?
NOTE: Some of the given replies have been divergent, so let me put in some boundaries to my question. Hopefully these restrictions will help to give more specific answers.
(a) My objective is to sniff the incoming packets with python sockets only. So other solutions involving tcpdump or tshark etc are outside the scope.
(b) The objective is to only sniff for incoming packets. Additional details like packet reordering (for connection oriented protocols like TCP) are outside the scope, actually they are avoidable overhead.
A:
If you're reading packets from a raw socket (as shown in your source code), then you can easily read all packets from the same socket. Be sure this is what you intend to do. A raw socket is for doing packet inspection for troubleshooting, forensic, security or educational purposes. You cannot easily communicate with another system this way.
And likewise, the receive calls will not differ here by protocol because you are not actually using TCP or UDP, you're simply receiving the raw packets that those protocols build and decode.
(1) Should I use recv() or recvfrom(), if I want to read both TCP and UDP packets?
Either one will work. recv() will return to you only the actual packet data, while recvfrom will return to you the data along with metadata about the packet, including the interface from which the data was received (and other things defined in struct sockaddr_ll from the packet(7) man page).
(2) Do the calls return data one packet at a time, or do they return after the buffer is filled up? eg, if I have a large buffer of 4096 bytes, and the incoming streaming 2 packets have 2400 bytes each, will the call return as soon as the 1st packet ends, or will it return after filling up the buffer from the 2nd packet also?
When using a raw socket like this, you get exactly one packet at a time. You will never get more than one. If the buffer you give is not large enough, then the packet will be truncated (with the ending bytes discarded).
(2a) same question, but if I have a smaller buffer of 2000 bytes. It is clear that on the 1st call I will get the first 2000 bytes of the 1st packet. But on the next call, will I get the last 400 bytes of the 1st packet, or the first 2000 bytes of the 2nd packet?
Generally speaking, packets on most networks are limited to about 1514 bytes. This is because the traditional "MTU" (Maximum Transfer Unit) that is configured on the network interface is 1500 bytes and usually an Ethernet header containing two MAC addresses (6 bytes each) plus a two-byte Ethertype is prepended to that. In a switch or router, you may also see packets that have an additional 4-byte header containing a VLAN header (IEEE 802.1Q). (But, some networks internally use "jumbo" packets up to about 9K in size for specific purposes.)
You should also understand that, in writing an application, one can send UDP datagrams (or TCP buffers) larger than the maximum packet size. In that case, the OS breaks those up into smaller chunks for sending (and they are re-assembled on the destination side before being handed to an application). When you're receiving raw packets like this, you will see the packets in their low-level, possibly fragmented, state.
(3) If I am delayed in making the next call, maybe because I was busy processing the 1st dataset, am I in danger of losing data, or will the OS keep its internal queue of the incoming packets to be given to me when I call the next time? If the OS keeps its internal queue, where can I find information about its size?
The OS will keep a queue of packets for you. The size is of course limited since there is no way you would be able to keep up with, say, a 1Gb NIC at full line rate (let alone a 10Gb or higher NIC). The size is configured in a system-specific way. On linux -- and probably other Unix-based systems -- you can call getsockopt with SOL_SOCKET / SO_RCVBUF to get an idea of the queue space available.
On linux, at least, the size can be set with setsockopt up to a system-imposed maximum (which itself can be configured with various sysctl settings).
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails 3.1 Asset pipeline
I am fairly new to rails and Jquery and am looking for some guidance on which libraries I should keep and which one I don't need.
Anyway currently I have the following in my javascript library
admin.js.coffee
application.js
bootstrap-alert.js
calendar.js
documents.js.coffee
folders.js.coffee
fullcalendar.js
gcal.js
jquery-1.7.min.js
jquery-ui-1.8.9.custom.min.js
jquery-ui.js
jquery-ui.min.js
jquery.bookshelfslider.js
jquery.bookshelfslider.min.js
jquery.easing.1.3.js
jquery.js
jquery.rest.js
jquery.ticker.js
jquery_ujs.js
rails.js
site.js
stickybar.jquery.min.js
stickysidebar.jquery.js
turn.js
My application.js file looks like this
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
Is there anything anyone can see that would cause me any issues? if I am calling a library within application.js, do I need the library in my Javascript directory?
Any advice appreciated
A:
rails.js is the legacy name of jquery_ujs.js. You can remove the former.
Also, you don't need to store the following file in the javascripts directory
jquery-1.7.min.js
jquery-ui-1.8.9.custom.min.js
jquery-ui.js
jquery-ui.min.js
jquery.js
rails.js
Simply install jquery-rails gem.
For more information, here's the Rails 3.1 asset pipeline guide.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to assign a name to the a size() column?
I am using .size() on a groupby result in order to count how many items are in each group.
I would like the result to be saved to a new column name without manually editing the column names array, how can it be done?
Thanks
This is what I have tried:
grpd = df.groupby(['A','B'])
grpd['size'] = grpd.size()
grpd
and the error I got:
TypeError: 'DataFrameGroupBy' object does not support item assignment
(on the second line)
A:
The .size() built-in method of DataFrameGroupBy objects actually returns a Series object with the group sizes and not a DataFrame. If you want a DataFrame whose column is the group sizes, indexed by the groups, with a custom name, you can use the .to_frame() method and use the desired column name as its argument.
grpd = df.groupby(['A','B']).size().to_frame('size')
If you wanted the groups to be columns again you could add a .reset_index() at the end.
A:
The result of df.groupby(...) is not a DataFrame. To get a DataFrame back, you have to apply a function to each group, transform each element of a group, or filter the groups.
It seems like you want a DataFrame that contains (1) all your original data in df and (2) the count of how much data is in each group. These things have different lengths, so if they need to go into the same DataFrame, you'll need to list the size redundantly, i.e., for each row in each group.
df['size'] = df.groupby(['A','B']).transform(np.size)
(Aside: It's helpful if you can show succinct sample input and expected results.)
A:
You need transform size - len of df is same as before:
Notice:
Here it is necessary to add one column after groupby, else you get an error. Because GroupBy.size count NaNs too, what column is used is not important. All columns working same.
import pandas as pd
df = pd.DataFrame({'A': ['x', 'x', 'x','y','y']
, 'B': ['a', 'c', 'c','b','b']})
print (df)
A B
0 x a
1 x c
2 x c
3 y b
4 y b
df['size'] = df.groupby(['A', 'B'])['A'].transform('size')
print (df)
A B size
0 x a 1
1 x c 2
2 x c 2
3 y b 2
4 y b 2
If need set column name in aggregating df - len of df is obviously NOT same as before:
import pandas as pd
df = pd.DataFrame({'A': ['x', 'x', 'x','y','y']
, 'B': ['a', 'c', 'c','b','b']})
print (df)
A B
0 x a
1 x c
2 x c
3 y b
4 y b
df = df.groupby(['A', 'B']).size().reset_index(name='Size')
print (df)
A B Size
0 x a 1
1 x c 2
2 y b 2
| {
"pile_set_name": "StackExchange"
} |
Q:
minimum of a function predicted by 2nd-degree polynomial regression
I have a to fit curves to my data using a linear model with polynomial of 2nd degree, for example :
data <- data.frame(x=c(0,1,2,3,4,5), y=c(0, 2, 5, 10, 17, 26))
lm1 <- lm(y~x+I(x^2), data=data)
plot(y~x, data=data)
points(predict(lm1)~data$x, type="l", col="blue", lwd=1)
then I would like to find the minimum of the function predicted by the model. I can extract the coefficient to write the function
a<-summary(lm1)$coef[,1][1]
b<-summary(lm1)$coef[,1][2]
c<-summary(lm1)$coef[,1][3]
But after that I don't know how to do and didn't find an answer on Google. Isn't it a function in R that calculates that ? Or should I calculate the zero of the derivative ?
A:
Set up data and fit model:
dd <- data.frame(x=c(0,1,2,3,4,5),
y=c(0, 2, 5, 10, 17, 26))
lm1 <- lm(y~x+I(x^2), data=dd)
Get predictions:
pp <- data.frame(x=seq(-3,5,length=51))
pp$y <- predict(lm1,newdata=pp)
Function to return minimum x/y values:
getMin <- function(model) {
cc <- setNames(as.list(coef(model)),c("a","b","c"))
with(cc,
c(x=-b/(2*c),y=a-b^2/(4*c)))
}
mm <- getMin(lm1)
Plot the results:
plot(y~x,data=dd,xlim=c(-3,5))
with(pp,lines(x,y,col=4))
points(mm[1],mm[2],pch=16,col=2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why some Java functions requires bytes array length when byte arrays object was already provided in the argument?
While writing Java code, I really wonder why some functions require byte arrays length as an argument when the first argument was byte arrays object. Why they don't get the length from the object provided?
For example:
// E.g.: 1. Bitmap
byte[] bytes = task.getResult();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// E.g.: 2. Datagram
byte[] data = new byte[1024];
DatagramPacket request = new DatagramPacket(data, data.length);
If they want the length, why they don't use data.length?
A:
The byte array is a buffer to which data, the length of which is less than the length of the buffer, is read. The length parameter defines the amount of bytes in the buffer that are relevant. You're not supposed to pass the length of the buffer in the parameter, that would be redundant. You're supposed to pass the number of bytes in the buffer that contain actual data.
The API documentation of DatagramPacket, for example, reveals this.
length - the number of bytes to read
| {
"pile_set_name": "StackExchange"
} |
Q:
Using split to read specific string from a line in a file
Given the text file
sample.txt
2012-01-01 09:00 San Diego Men's Clothing 214.05 Amex
2012-01-01 09:00 San Diego Women's Clothing 153.57 Visa
2012-01-01 09:00 Omaha Music 66.08 Cash
I want to be able to read only the text for the third column. This code
for line in open("sample.txt"):
city=line.split()[2]
print(city)
can read the third column to a certain degree:
San
San
Omaha
but what I want is:
San Diego
San Diego
Omaha
How do I do this?
A:
It does look like your file is separated by tabs (or \t).
Have you tried splitting it by tabs ?
Instead of city=line.split()[2] try city=line.split('\t')[2].
Anyways, it looks like this file has been generated by an excel or similar, have you tried exporting it to a CSV (comma separated values) format, instead of pure txt ?
Then you can simply split by commas, like city=line.split(',')[2]
Hope it helps
| {
"pile_set_name": "StackExchange"
} |
Q:
SIGCHLD sended by another process to parent
Let's assume that our process creates a child and then calls wait().
When I try to send signal() or do
kill -SIGCHLD <PID>
nothing happens at all.
So the question is: How does the process in Linux determine that signal SIGCHLD hadn't been sent by the child? Or, maybe, there is some another mechanism?
A:
The kernel takes care of this.
wait() is not a signal handler listening for (any) SIGCHLD sent to a process, as it might be established via sigaction() or signal().
From wait()'s POSIX spec (emphasis by me):
The wait() and waitpid() functions shall obtain status information pertaining to one of the caller's child processes.
| {
"pile_set_name": "StackExchange"
} |
Q:
vxml: need help with in-line grammars
I am looking at some sample vxml scripts from vxml.org. When i call the script the prompts play, but it doesnt pick up any of my inputs at all. when i speak it responds "no input". could i be missing some tag that indicates input from the user. this is the example script from the website:
<?xml version="1.0" encoding="UTF-8"?>
<vxml version = "2.1">
<link next="#MainMenu">
<grammar type="text/gsl">[main back begin]</grammar>
</link>
<form id="MainMenu">
<block>
<prompt bargein="false">
This is the Hello World Main Menu.
</prompt>
</block>
<field name="MeatOrPlant">
<prompt>
Are you a "Carnivore" or "Vegetarian".
</prompt>
<grammar type="text/gsl">
<![CDATA[[
[vegetarian plant veggie] {<MeatOrPlant "plant">}
[meat carnivore flesh animal] {<MeatOrPlant "meat">}
]]]>
</grammar>
<noinput>
<prompt>
I did not hear anything. Please try again.
</prompt>
<reprompt/>
</noinput>
<nomatch>
<prompt>
I did not recognize that lifestyle choice. Please try again.
</prompt>
<reprompt/>
</nomatch>
</field>
<filled>
<if cond="MeatOrPlant == 'meat'">
<goto next="#Meat"/>
<elseif cond="MeatOrPlant == 'plant'"/>
<goto next="#Plant"/>
</if>
</filled>
</form>
<form id="Meat">
<field name="BackToMain">
<prompt>
PETA is coming for you, be afraid.
If you wish to try again, please say Main.
</prompt>
</field>
<filled>
<!-- no way this will get hit -->
</filled>
</form>
<form id="Plant">
<field name="BackToMain">
<prompt>
Protein is the spawn of the devil.
If you wish to try again, please say "Main".
</prompt>
</field>
<filled>
<!-- no way this will get hit -->
</filled>
</form>
</vxml>
Anyone have a clue? TIA
A:
You didn't mention the platform being used. Since you're using inline GSL, my first guess for platform would be TellMe or NVP, but I think there were others that supported inline GSL.
In any case, make sure you aren't getting a compilation error. I've seen a few platforms just ignore grammars that didn't compile. The snippets look correct, but given you aren't using the standard syntax (SRGS) I'm guessing this is an older implementation and the older the implementation, the more quirks and caveats you typically see.
Generally, I don't see anything wrong with the VoiceXML portion of your syntax to explain the behavior. While it's not associated with your symptoms, your destination forms may cause issues on some platforms given the lack of grammars and defined exits (your relying on default catch handlers). To just play information, the field sections should be blocks. And note, if the block just played audio and exited the link grammars may or may not be active (the specification would imply they are, but must platforms switch between processing and queuing audio and performing recognition. Recognition and the continuous switching in and out of active grammars is rare...
| {
"pile_set_name": "StackExchange"
} |
Q:
**kwargs in class defenition. Error : " __init__() takes exactly 1 argument (2 given)"
class Test_class(object):
def __init__(self,**kwargs):
for a in kwargs.values():
print a
dic = {"a_list":1}
Test_class(dic)
Hello Everybody,
I am trying to understand what's wrong with the code. I am getting the following error:
__init__() takes exactly 1 argument (2 given)
Can anybody explain, please?
Cheers
A:
Instead of keyword arguments you have passed a single positional argument. The method does not accept any positional arguments beyond the implicit instance argument. Expand the dictionary when passing.
Test_class(**dic)
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby on Rails design patterns and good practices
I have developed a code for an admin page with crud in ruby on rails. But I have a doubt. Can this code be improved in any way? In therms of design patterns, good practices and etc.
Also, I did separate the crud actions from the AdminController Class. Is this considered a good practice at all? Or is there any way I can improve it even further? Thank you.
# app/controllers/game_controller.rb
class GameController < ApplicationController
def create
Game.create(game_params)
end
def update
game = Game.find(params[:id])
if (game.update_attributes(game_params))
return true
end
return false
end
def read
game = Game.find(params[:id])
end
def delete
if (Game.find(params[:id]).destroy)
return true
else
return false
end
end
private
def game_params
params.require(:game).permit(:description,:name,:category,:status,:boxshot)
end
end
# app/controllers/admin_controller.rb
class AdminController < ApplicationController
before_action :require_logged_in_user
before_action :define_action
def index
@games = Game.all
@admin = get_admin_details()
end
def read
render :json => @action.read
end
def update
if ([email protected])
render :text => "false"
end
render :text => "true"
end
def delete
if([email protected])
render :text => "false"
end
render :text => "true"
end
def logout
reset_session
redirect_to(:controller => 'login', :action => 'view')
end
private
def define_action
@action = GameController.new()
@action.params = params
I18n.locale = cookies['language']
end
def get_admin_details
admin = User.find(require_logged_in_user())
end
def require_logged_in_user
if(session[:user_id])
return session[:user_id]
else
redirect_to(:controller => 'login', :action => 'view')
end
end
end
A:
To be honest, there's quite a bit that can be improved. Here's my take on GameController
class GameController < ApplicationController
before_action :find_game, only: [:update, :show, :delete]
def new
@game = Game.new
end
def create
@game = Game.new(game_params)
if @game.save
redirect_to game_path(@game)
else
render :new
end
end
def edit
end
def update
if @game.update(game_params)
redirect_to game_path(@game)
else
render :edit
end
end
def show
end
def delete
if @game.destroy
redirect_to games_path
else
render :show
end
end
private
def find_game
@game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:description, :name, :category, :status, :boxshot)
end
end
I would take some time to learn the basics of Rails a little more thoroughly. Check out Railscasts. It's older, but still good info. Any premium episodes can be found on Youtube.
You can also look at style guides an use the advice they provide.
Whatever you do, the most important thing is to stay consistent. Maintain the same indent amount, the same class structure, the same assignment and conditional structure, etc.
To answer your second question, you want a new controller for each new CRUD action. Don't try and shoehorn in a ton of functionality into one controller. Keep it simple, lines are cheap.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHPMyAdmin Setup Prompts for PHP 5.2+ after Install of PHP 5.3.8 on RHEL 5
I have a fresh RHEL 5 dedicated server that has just been updated with PHP 5.3.8. When I browse http://my.ip.addy/setup to start the PHPMyAdmin setup, I receive a message stating PHP 5.2+ is required. This is strange because the output of php -v show PHP 5.3.8. Do we need a server or Apache restart?
Thanks!!
A:
php -v shows correct cause the command line version is returning it.
You need to restart apache for the correct version of the php module to get loaded. Apache loads all the module on startup and to stay fast and quick.. isn't going to go off and look at the filesystem each request for module updates.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does this green/white icon in clan chat mean?
Does this mean the player is online?
A:
This is actually the icon representing the little menu that pops up when you tap a person's name. It's the same color and shape as the menu, just really tiny.
It doesn't show up next to your own messages (the ones marked "You") and if you try tapping the word "You" you will see that you don't get the pop-up menu.
I can safely say that it has nothing to do with their online state - I see this icon next to every name in my clan chat, and I know for a fact that several of them are offline currently.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trending algorithm
I'm working on a micro-forum of sorts, whereby a quick (close to tweet-size) topic message is posted by a special user, which subscribers can respond to with like-sized messages of their own. Straightforward, no 'digging' or voting of any sort, just a chronological flow of responses for each topic message. But with high traffic expected.
We would like to flag topic messages according to the response buzz they atract, using a scale of 0 to 10.
Been googling for trend algorithms and open source community application examples for a while, and so far have gleaned two interesting references, which I don't fully grok yet:
Understanding algorithms for measuring trends, a discussion on comparing wikipedia pageviews using the Baseline Trend Algorithm, here on SO.
The Britney Spears Problem, an in-depth article on how to rank search terms, while processing large streams of data.
From the first I understand the need to check the slope in activity, and to balance the weight between two items that differ greatly in scale of activity. But how do I compare many items, growing in number quickly across time? And then, how do I break the items within "buzz grades" from 0 to 10?
The second reference is fascinating, but over my head at this point. From a first pass I've understood the need to keep memory usage stable while keeping counters and storing references to items if necessary. But I haven't figured a fitting algorithm for my specific use case from it, yet.
It's worth noting that I come from a non-computer-science and definitely non-statistics background. Please bear with me :) Any help and code samples (specially in Ruby) would be greatly appreciated.
A:
Intuition says that a solution to this problem doesn't need a lot of statistics, by ranking the topics based on some simple measures may already provide you with an interesting selection of "trending topics."
One way is to order the topics by number comments generated in the last hour/day/week... and to select the top ones.
Another way is to count the number of comments for each of the topics and divide this by the "age" of the topic. New topics that immediately generate comments will be considered trending, while older topics with many comments will be less trending as they grow older.
These implementations can easily be created in Ruby/Rails and can even be done in an SQL query, provided that the tables contain publish dates and numbers of comments.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to query asp button text in gridview to see if any have a certain text value
I now have an asp button in a gridview which I can toggle the text from "Add" to "Remove". Now what I would like is either jquery or javascript to loop through all the rows (or inquire all rows) to determine if any buttons have been toggled (they would have text of "Remove" since the default is "Add"). I don't necessarily need to loop through and process anything, I just want to hide a div if no buttons have been toggled to text of "Remove". The user may have toggled the buttons to "Remove" and back to "Add". So I need to know if at least one button text is currently "Remove".
Here is my templated asp button definition:
<asp:TemplateField HeaderText="Prior <br /> Downld" HeaderStyle-ForeColor="White" >
<ItemTemplate >
<asp:Button id="btnBuy" runat="server" OnClientClick="btnBuyToggle(this); return false;" Text="Add" CssClass="buyButton" Visible='<%# Eval("SORD_ShowBuyButton") %>' />
</ItemTemplate>
<HeaderStyle Width="7%" />
<ItemStyle CssClass="sessionOrderDownloadItems" VerticalAlign="Middle" HorizontalAlign="Center" />
</asp:TemplateField>
Anyway, I am hoping for maybe a jquery selector looking for text = "Remove", but I am not sure how to construct it.
Note: Working result is this:
if ( $("input[value=Remove]").length == 0 ) {
$(".divDownloadHeaderClass").show();
$(".divPurchaseHeaderClass").hide();
}
}
A:
I think this would work:
if ( $("input[value=Remove][type=submit]").length > 0 ) {
$(".divDownload").hide();
}
Hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
removing value from array not working NEXT.JS
I have a filter options, which shows checkbox. So when click on each checkbox the value should be added to array if not exists and remove the value from array if already exists and the state should be updated. I have tried using below code and it is not working.
const [showFilter, setFilter] = useState([]);
useEffect(() => {
dispatch(fetchproducts(slug, sort, pageInitial+1, showFilter));
console.log(showFilter);
}, [showFilter]);
function filterClick (id, title) {
const index = showFilter.indexOf(id);
if (index > -1)
setFilter(showFilter.splice(index, 1));
else
setFilter(showFilter.concat(id));
}
return (
<ul style={{display: showMe.includes(index) ? "block" : "none"}}>
{item.items.map((single, index1) => (
<li key={index1}>
<label><input type="checkbox" name="checkbox" onClick={(e) => filterClick(e.target.value, item.title)} value={single.items_id}/> {single.items_value}</label>
</li>
))}
</ul>
)
In the above code, array insertion is working, but the splice is not working and the state is not updating.
How to alter my code to get the expected result.
A:
You use useEffect. The useEffect's callback will be triggered when one of dependency is changed.
splice function changes array in place (ie mutates the array). In this case your array variable (showFilter) is not changed, therefore useEffect's callback will not be triggered.
Try using filter function instead:
setFilter(showFilter.filter(el=> el !== id));
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I split a string with multiple separators in classic asp
How do I split a string as below, and add the record to the database? The order of the string is not the same user inputs.
string "Key3:352,Key1:353,Key2:380,Key4:381,Key5:181"
Result should be on records
fieldname key: 3 .. etc
fieldname ID: 352 .. etc
A:
If i understood the question, this should work:
var parser =function(toParse) {
var table = toParse.split(',');
for (var subString in table) {
var subString2 = subString.split(':');
var key = subString2[0].replace('Key', '');
var ID = subString2[1];
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Notice: Undefined offset
Please am trying to input points for 8 teams,with just one form. I want to compare and get the highest score after the form has been submitted. I have created the form, but am having a little problem. Am getting "Undefined offset: 8" error. but the scores and name of the team shows perfectly. Here is my html code
<div class="container">
<form method="post" action="../_libs/test.php">
<?php
foreach($teams as $arr)
{
?>
<div class="row team_result">
<div class="col-md-8">
<div class="row">
<div class="col-md-3"> <img class="img img-thumbnail" src="../_images/<?php echo $arr['Team_Logo']; ?>" width="50" height="50"> </div>
<div class="col-md-3"> <label> <?php echo $arr['Team_Name']; ?> </label> </div>
<div class="col-md-3">
<div class="input-group">
<input type="text" class="form-control" name="points[]" placeholder="points">
</div>
<input type="text" name="Name[]" id="" value="<?php echo $arr['Team_Name'] ?>"
style="display:none" >
</div>
</div>
</div>
</div>
<?php
}
?>
<div class="col-lg-6 col-lg-offset-4"> <input type="submit" class="btn btn-primary" name="submit" value="Post"> </div>
</form>
</div>
And the PHP code
<?php
//echo json_encode($_POST);
if(!empty($_POST['Name'])){
$team=$_POST['Name'];
$teams=count($team);
for($i=0; $i <= $teams; $i++)
{
echo $team[$i] .",". $_POST['points'][$i]."<br>";
// echo $teams;
}
}
?>
A:
In for loop you need to use just <, not <=
for ($i = 0; $i < $teams; $i++)
While you use <=, you have 8 teams, but 9 iterations in your loop (for $i equal to 0, 1, 2, 3, 4, 5, 6, 7 and 8). The last one is undefined.
| {
"pile_set_name": "StackExchange"
} |
Q:
ConfigMap mounted on Persistent Volume Claims
In my deployment, I would like to use a Persistent Volume Claim in combination with a config map mount. For example, I'd like the following:
volumeMounts:
- name: py-js-storage
mountPath: /home/python
- name: my-config
mountPath: /home/python/my-config.properties
subPath: my-config.properties
readOnly: true
...
volumes:
- name: py-storage
{{- if .Values.py.persistence.enabled }}
persistentVolumeClaim:
claimName: python-storage
{{- else }}
emptyDir: {}
{{- end }}
Is this a possible and viable way to go? Is there any better way to approach such situation?
A:
Since you didn't give your use case, my answer will be based on if it is possible or not. In fact: Yes, it is.
I'm supposing you wish mount file from a configMap in a mount point that already contains other files, and your approach to use subPath is correct!
When you need to mount different volumes on the same path, you need specify subPath or the content of the original dir will be hidden.
In other words, if you want to keep both files (from the mount point and from configMap) you must use subPath.
To illustrate this, I've tested with the deployment code below. There I mount the hostPath /mnt that contains a file called filesystem-file.txt in my pod and the file /mnt/configmap-file.txt from my configmap test-pd-plus-cfgmap:
Note: I'm using Kubernetes 1.18.1
Configmap:
apiVersion: v1
kind: ConfigMap
metadata:
name: test-pd-plus-cfgmap
data:
file-from-cfgmap: file data
Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-pv
spec:
replicas: 3
selector:
matchLabels:
app: test-pv
template:
metadata:
labels:
app: test-pv
spec:
containers:
- image: nginx
name: nginx
volumeMounts:
- mountPath: /mnt
name: task-pv-storage
- mountPath: /mnt/configmap-file.txt
subPath: configmap-file.txt
name: task-cm-file
volumes:
- name: task-pv-storage
persistentVolumeClaim:
claimName: task-pv-claim
- name: task-cm-file
configMap:
name: test-pd-plus-cfgmap
As a result of the deployment, you can see the follow content in /mnt of the pod:
$ kubectl exec test-pv-5bcb54bd46-q2xwm -- ls /mnt
configmap-file.txt
filesystem-file.txt
You could check this github issue with the same discussion.
Here you could read a little more about volumes subPath.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why $5 (\mod 7)$ is $5$?
$\frac 57$ is equal to $0.7$. Remaining is $1$.
by definition, the remainder when dividing $\frac mn$ is such a number $r$ such that
$0≤r<n$
There exists some $k$ such that $k\times n+r=m$
In this case: $1\times7+r=5$, so $r = -2$
And now? how do I get the $5$ as result?
A:
$\cfrac 57 \approx 0.713$
But modular arithmetic is integer division, unlike above.
$5 \mod 7\equiv 5$
$7$ goes into $5$ zero times
$k+(0*7)=5 \implies k=5$, and the remainder is $5$ after $7$ goes into $5$ zero times
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between pinax.apps.accounts, idios profiles, and django.auth.User
What's the difference between pinax.apps.accounts and the idios profiles app that were installed with the profiles base project?
As I understand it, the contrib.auth should be just for authentication purpose (i.e. username and password), and the existence of User.names and User.email in the auth model is historical and those fields shouldn't be used; but the distinction between accounts and profiles are lost to me. Why is there pinax.apps.account and idios?
A:
The Pinax account is just a wrapper for that holds the user, timezone and language. user is a foreign key relation to the standard django.auth User model.
class Account(models.Model):
user = models.ForeignKey(User, unique=True, verbose_name=_('user'))
timezone = TimeZoneField(_('timezone'))
language = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE)
def __unicode__(self):
return self.user.username
The idios Profile model basically does the same thing but has some custom methods:
class ProfileBase(models.Model):
# @@@ could be unique=True if subclasses don't inherit a concrete base class
# @@@ need to look at this more
user = models.ForeignKey(User, verbose_name=_("user"))
class Meta:
verbose_name = _("profile")
verbose_name_plural = _("profiles")
abstract = True
def __unicode__(self):
return self.user.username
def get_absolute_url(self):
if idios.settings.MULTIPLE_PROFILES:
# @@@ using PK here is kind of ugly. the alternative is to
# generate a unique slug for each profile, which is tricky
kwargs = {
"profile_slug": self.profile_slug,
"pk": self.pk
}
else:
if idios.settings.USE_USERNAME:
kwargs = {"username": self.user.username}
else:
kwargs = {"pk": self.pk}
return reverse("profile_detail", kwargs=kwargs)
@classmethod
def get_form(cls):
return get_profile_form(cls)
def _default_profile_slug(cls):
return cls._meta.module_name
profile_slug = ClassProperty(classmethod(_default_profile_slug))
Neither of them replicates the authentication functionality of django.auth.User if that is what you are asking. It doesn't look like either one has a dependency on the other either. So if you can't see a good use for both of them, just go with the one that makes sense.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML entities in CSS content (convert entities to escape-string at runtime)
I know that html-entities like or ö or ð can not be used inside a css like this:
div.test:before {
content:"text with html-entities like ` ` or `ö` or `ð`";
}
There is a good question with good answers dealing with this problem: Adding HTML entities using CSS content
But I am reading the strings that are put into the css-content from a server via AJAX. The JavaScript running at the users client receives text with embedded html-entities and creates style-content from it instead of putting it as a text-element into an html-element's content. This method helps against thieves who try to steal my content via copy&paste. Text that is not part of the html-document (but part of css-content) is really hard to copy. This method works fine. There is only this nasty problem with that html-entities.
So I need to convert html-entities into unicode escape-sequences at runtime. I can do this either on the server with a perl-script or on the client with JavaScript, But I don't want to write a subroutine that contains a complete list of all existing named entities. There are more than 2200 named entities in html5, as listed here: http://www.w3.org/TR/2011/WD-html5-20110113/named-character-references.html And I don't want to change my subroutine every time this list gets changed. (Numeric entities are no problem.)
Is there any trick to perfom this conversion with javascript? Maybe by adding, reading and removing content to the DOM? (I am using jQuery)
A:
I've found a solution:
var text = 'Text that contains html-entities';
var myDiv = document.createElement('div');
$(myDiv).html(text);
text = $(myDiv).text();
$('#id_of_a_style-element').html('#id_of_the_protected_div:before{content:"' + text + '"}');
Writing the Question was half way to get this answer. I hope this answer helps others too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a PeriodIndex to slice a pandas series
I have a few pandas series with PeriodIndex of varying frequency. I'd like to filter these based on another PeriodIndex of which the frequency is in principle unknown (specified directly in the example below as selectionA or selectionB, but in practice stripped from another series).
I've found 3 approaches, each with its own downside, shown in the example below. Is there a better way?
import numpy as np
import pandas as pd
y = pd.Series(np.random.random(4), index=pd.period_range('2018', '2021', freq='A'), name='speed')
q = pd.Series(np.random.random(16), index=pd.period_range('2018Q1', '2021Q4', freq='Q'), name='speed')
m = pd.Series(np.random.random(48), index=pd.period_range('2018-01', '2021-12', freq='M'), name='speed')
selectionA = pd.period_range('2018Q3', '2020Q2', freq='Q') #subset of y, q, and m
selectionB = pd.period_range('2014Q3', '2015Q2', freq='Q') #not subset of y, q, and m
#Comparing some options:
#1: filter method
#2: slicing
#3: selection based on boolean comparison
#1: problem when frequencies unequal: always returns empty series
yA_1 = y.filter(selectionA, axis=0) #Fail: empty series
qA_1 = q.filter(selectionA, axis=0)
mA_1 = m.filter(selectionA, axis=0) #Fail: empty series
yB_1 = y.filter(selectionB, axis=0)
qB_1 = q.filter(selectionB, axis=0)
mB_1 = m.filter(selectionB, axis=0)
#2: problem when frequencies unequal: wrong selection and error instead of empty result
yA_2 = y[selectionA[0]:selectionA[-1]]
qA_2 = q[selectionA[0]:selectionA[-1]]
mA_2 = m[selectionA[0]:selectionA[-1]] #Fail: selects 22 months instead of 24
yB_2 = y[selectionB[0]:selectionB[-1]] #Fail: error
qB_2 = q[selectionB[0]:selectionB[-1]]
mB_2 = m[selectionB[0]:selectionB[-1]] #Fail: error
#3: works, but very verbose
yA_3 =y[(y.index >= selectionA[0].start_time) & (y.index <= selectionA[-1].end_time)]
qA_3 =q[(q.index >= selectionA[0].start_time) & (q.index <= selectionA[-1].end_time)]
mA_3 =m[(m.index >= selectionA[0].start_time) & (m.index <= selectionA[-1].end_time)]
yB_3 =y[(y.index >= selectionB[0].start_time) & (y.index <= selectionB[-1].end_time)]
qB_3 =q[(q.index >= selectionB[0].start_time) & (q.index <= selectionB[-1].end_time)]
mB_3 =m[(m.index >= selectionB[0].start_time) & (m.index <= selectionB[-1].end_time)]
Many thanks
A:
I've solved it by adding start_time and end_time to the slice range:
yA_2fixed = y[selectionA[0].start_time: selectionA[-1].end_time]
qA_2fixed = q[selectionA[0].start_time: selectionA[-1].end_time]
mA_2fixed = m[selectionA[0].start_time: selectionA[-1].end_time] #now has 24 rows
yB_2fixed = y[selectionB[0].start_time: selectionB[-1].end_time] #doesn't fail; returns empty series
qB_2fixed = q[selectionB[0].start_time: selectionB[-1].end_time]
mB_2fixed = m[selectionB[0].start_time: selectionB[-1].end_time] #doesn't fail; returns empty series
But if there's a more concise way to write this, I'm still all ears. I especially would like to know if it's possible to do this filtering in a way that is more 'native' to the PeriodIndex, i.e., not converting it into datetime instances first with the start_time and end_time attributes.
| {
"pile_set_name": "StackExchange"
} |
Q:
The cost of creating an object
I am thinking of creating a complex data type myself, but just not sure of the cost of it.
Let's say , I have 3 lists, name,age,gender,
List<String> name = new ArrayList<String>;
List<Integer> age = new ArrayList<Integer>;
List<String> gender = new ArrayList<String>;
I would like to combine each element of these lists together, something like this:
public class Person {
private String name;
private int age;
private String gender;
public void Person(String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public void getName () {
return name;
}
public void getAge () {
return age;
}
public void getGender () {
return gender;
}
}
then I can create the object that contains these information:
Person person1 = new Person("John",22,"Male");
But the thing is the list of name is so big that may have 1,000,000 names(also the list of age and gender),meaning I would need to create 1,000,000 objects of Person. Is this a good idea to pass object containing name,age and gender to another class or I should just pass these name,age,gender separately?
How big would a object containing name,age and gender be, compared to the cost of String name, int age and String gender added together?
A:
Don't do premature optimizations. The most clear way will be to have one list of Person objects. If you actually experience performance problems with this part, then think about how to optimize it.
About the memory overhead of objects:
each object by itself has overhead of 8 bytes
String fields of the objects will occupy the same size as your current arrays
int field of the object will occupy less space comparing to the elements of List<Integer> 4 bytes vs 4 + 16 bytes
So, in summary, you will save 12 bytes on each record if you go with grouping Lists into single List of objects.
UPD the actual saving probably will be 8 bytes because of the alignment
| {
"pile_set_name": "StackExchange"
} |
Q:
"warning: section "__const_coal" is deprecated" error after updating Xcode to latest version on Mac OS
My g++ compiler for C++ program was working fine until I updated my Xcode to the latest version and accepted the license agreement. I also tried compiling with clang instead of g++ but got errors. Now I get a long stream of errors. Anyone has an idea what is wrong?
Ivans-MacBook-Pro:CS6771A3-GenericDirectedWeightedGraph ivanteong$ g++ -std=c++14 -Wall -Werror -O2 -o test6 tests/test6.cpp
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:1:11: warning: section "__textcoal_nt" is deprecated
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:1:11: note: change section name to "__text"
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:211:11: warning: section "__textcoal_nt" is deprecated
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:211:11: note: change section name to "__text"
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:604:11: warning: section "__textcoal_nt" is deprecated
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
/var/folders/3d/hqly97ld37b1kd6wx9gjn2tc0000gn/T//ccZfBPvE.s:604:11: note: change section name to "__text"
.section __TEXT,__textcoal_nt,coalesced,pure_instructions
^ ~~~~~~~~~~~~~
A:
I was getting the exact same warnings on updating to Xcode v8.0. However, you do not need to uninstall Xcode. Rather, you need to set the path of the active developer directory:
sudo xcode-select -s /Library/Developer/CommandLineTools
| {
"pile_set_name": "StackExchange"
} |
Q:
Using rawtherapee to create an image like a DSLR camera in bracketing mode
Can rawtherapee can be used to create an image like a DSLR camera in bracketing mode?
I noticed that rawtherapee has many controls under the exposure tab. I was told that just changing the exposure alone would not be the same as if I used a camera in braketing mode.
Thanks.
A:
It depends what you're trying to achieve from bracketing.
There's three basic variables that set your exposure - shutter speed, aperture and ISO.
Shutter speed and aprerture both have optical effects on the image that you'll know. Bracketing will usually change one of these, and you can't replicate that pos-capture.
ISO on a digital camera doesn't have optical effects. It acts like a volume control on an amplifier - you can amplify small signals, you just get more noise, and if you overamp a large signal it starts clipping. There's no reason you can't change that in bracketing if you're unsure of exposure levels or want a specific combination of ISO and shutter speed for any reason, and any raw converter will be able do a passable job at replicating that effect by changing the processing settings. It won't be as good as if you'd nailed it in-camera, but it won't be terrible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does bash sometime not flush output of a python program to a file
I have a crontab job calling a python script and outputting to a file:
python run.py &> current_date.log
now sometimes when I do
tail -f current_date.log
I see the file filling up with the output, but other times the log file exists, but stays empty for a long time. I am sure that the python script is printing stuff right after it starts running, and the log file is created. Any ideas why does it stay empty some of the time?
A:
Python buffers output when it detects that it is not writing to a tty, and so your log file may not receive any output right away. You can configure your script to flush output or you can invoke python with the -u argument to get unbuffered output.
$ python -h
...
-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
see man page for details on internal buffering relating to '-u'
...
A:
The problem is actually Python (not bash) and is by design. Python buffers output by default. Run python with -u to prevent buffering.
Another suggestion is to create a class (or special function) which calls flush() right after the write to the log file.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to config nginx to proxy to rails app? so that i dont have to say domain.com:port
Update: Currently i visit my app at domain.com:3000, but i would like to visit domain.com to see my app
I have setup nginx at 80 to proxy my rails app at 3000. below is the configuration
upstream railsapp {
server 127.0.0.1:3000;
}
server {
listen 80;
server_name APP;
# Tell Nginx and Passenger where your app's 'public' directory is
root /var/www/APP/current/public;
index index.html index.htm;
# Static assets are served from the mentioned root directory
location / {
root /var/www/APP/current;
index index.html index.htm;
proxy_pass http://railsapp/;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
# proxy_set_header X-Real-Port $server_port;
# proxy_set_header X-Real-Scheme $scheme;
proxy_set_header X-NginX-Proxy true;
}
# Turn on Passenger
passenger_enabled on;
passenger_ruby /usr/local/rvm/gems/ruby-2.1.3/wrappers/ruby;
}
i referred to :
https://stackoverflow.com/a/5015178/1124639
this is located at /etc/nginx/sites-enabled/APP.conf and is included in /etc/nginx/nginx.conf as below within http{...}
include /etc/nginx/sites-enabled/*;
but my APP.com still shows 'Welcome to nginx on Ubuntu!' and APP.com:3000 shows my app. What am i doing wrong?
What i am using:
Ubuntu 14.04 ec2 instance
nginx 1.8.0
unicorn server at 3000
A:
I was trying to run unicorn so i can fork my app to multiple instances. I guess the issue here was, i set passenger_enabled on and was actually running unicorn on 3000.
so instead i ran passenger
passenger start -a 127.0.0.1 -p 3000 -d -e production
and my nginx conf like this,
server {
listen 80;
server_name www.APPNAME.com;
# Tell Nginx and Passenger where your app's 'public' directory is
root /var/www/APPNAME/current/public;
index index.html index.htm;
# Static assets are served from the mentioned root directory
location / {
# root /var/www/APPNAME/current;
# index index.html index.htm;
proxy_pass http://127.0.0.1:3000;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
# proxy_set_header X-Real-Port $server_port;
# proxy_set_header X-Real-Scheme $scheme;
proxy_set_header X-NginX-Proxy true;
}
# Turn on Passenger
passenger_enabled on;
passenger_ruby /usr/local/rvm/gems/ruby-2.1.3/wrappers/ruby;
}
and everything works now!
| {
"pile_set_name": "StackExchange"
} |
Q:
Drupal: is the output of the dprint_r() only visible to administrators?
is the output of the dprint_r() function (introduced by devel module) visible only if I'm logged in drupal system (as administrator user) ?
thanks
A:
Looking at the function definition, you will find:
/**
* Pretty-print a variable to the browser (no krumo).
* Displays only for users with proper permissions. If
* you want a string returned instead of a print, use the 2nd param.
*/
function dprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r', $check= TRUE) {
if (user_access('access devel information')) {
// Snipped main function code ...
}
}
So it will only produce output for users with the access devel information permission. If you assigned this permission to no role, only user 1 will get to see the output.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - Loop and filter on List?
I have a List of data like this :
I need to get first and last records are same :
And my model is :
public class Modeltest {
private String lat;
private String lng;
private String date;
private String firstTime;
private String lasttime;
private String counts;
private String userCode;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
.......
.....
.....
}
I can getting first and last :
List<Unprocessed_DistanceTime_D> listCDM = QDB.DistanceSelect_D();
int count = 1;
boolean flag = true;
int index;
for (int i = 0; i < listCDM.size() - 1; i++) {
if (listCDM.get(count).getDate().equalsIgnoreCase(listCDM.get(i).getDate()) &&
listCDM.get(count).getLat().equalsIgnoreCase(listCDM.get(i).getLat()) &&
listCDM.get(count).getLng().equalsIgnoreCase(listCDM.get(i).getLng()) &&
listCDM.get(count).getCounts().equalsIgnoreCase(listCDM.get(i).getCounts())) {
if (flag){
index = i;
flag = false;
}
}else {
index = i;
flag = true;
}
count++;
}
}
But my problem is here. How I can add these in another list and add single records in it ?
I get the first and last record then add in another list (I wrote the model above) .
I should fill my list here :
if (flag){
index = i;
///HERE
flag = false;
}
}else {
index = i;
///HERE
flag = true;
}
A:
Here's a brute force method that first groups all the entries by a locally defined Identity and than merge those groups into a single Modeltest object.
There is probably a better way to do this though, since this disregards the fact that the input data is sorted.
List<Unprocessed_DistanceTime_D> list = ...;
class Identity {
private final String lat;
private final String lng;
private final String date;
private final String counts;
public Identity(Unprocessed_DistanceTime_D model) {
this.lat = model.getLat();
this.lng = model.getLng();
this.date = model.getDate();
this.counts = model.getCounts();
}
@Override
public int hashCode() {
int code = 0;
code ^= lat.hashCode();
code ^= lng.hashCode();
code ^= date.hashCode();
code ^= counts.hashCode();
return code;
}
@Override
public boolean equals(Object other) {
if(other == null)
return false;
if(!(other instanceof Identity))
return false;
Identity io = (Identity) other;
return lat.equalsIgnoreCase(io.lat)
&& lng.equalsIgnoreCase(io.lng)
&& date.equalsIgnoreCase(io.date)
&& counts.equalsIgnoreCase(io.counts);
}
}
List<Modeltest> models = list.stream()
.collect(Collectors.groupingBy(Identity::new))
.values().stream()
.map(group -> { // Convert groups into single Modeltest
if(group.size() == 1) { // Case for single entries
Unprocessed_DistanceTime_D e = group.get(0);
return new Modeltest(e.getLat(), e.getLng(), e.getDate(), e.getTime(),
e.getTime(), e.getCounts(), e.getUserCode());
}
// Case for more entries
group.sort(Comparator.comparing(Unprocessed_DistanceTime_D::getTime));
Unprocessed_DistanceTime_D first = group.get(0);
Unprocessed_DistanceTime_D last = group.get(group.size() - 1);
return new Modeltest(first.getLat(), first.getLng(), first.getDate(),
first.getTime(), last.getTime(), first.getCounts(), first.getUserCode());
})
.collect(Collectors.toList());
| {
"pile_set_name": "StackExchange"
} |
Q:
Using two wordlists to search a list of texts
I have a function that takes two separate wordlists and searches a third list, which is a text formatted as a list of wordlists.
The function finds the proximity between words in word_list1 and word_list2 by taking the difference between their indexes; (it takes one over the difference, so that larger numbers will indicate closer proximity).
I ultimately will write the output to a .csv file and create a network of the word proximities in gephi.
This function works for me, but it is very slow when used on a large number of texts. Do you have any suggestions for making it more efficient? (If this is unclear at all, let me know, and I will try to clarify.)
text = [
'This, Reader, is the entertainment of those who let loose their own thoughts, and follow them in writing, which thou oughtest not to envy them, since they afford thee an opportunity of the like diversion if thou wilt make use of thy own thoughts in reading.',
'For the understanding, like the eye, judging of objects only by its own sight, cannot but be pleased with what it discovers, having less regret for what has escaped it, because it is unknown.'
]
word_list1 = ['entertainment', 'follow', 'joke', 'understanding']
word_list2 = ['envy', 'use', 'nada']
text_split = []
for line in text:
text_split.append(line.split(' '))
def word_relations(list_a, list_b, text):
relations = []
for line in text:
for i, item in enumerate(line):
for w in list_a:
if w in item:
first_int = i
first_word = w
for t, item in enumerate(line):
for x in list_b:
if x in item:
second_int = t
second_word = x
if first_int:
if second_int != first_int:
dist = 1.0 / abs(second_int-first_int)
if dist in relations:
continue
else:
relations.append((first_word,
second_word, dist))
return(relations)
print(word_relations(word_list1, word_list2, text_split))
Here is the output:
[('entertainment', 'envy', 0.05263157894736842), ('entertainment', 'use', 0.02857142857142857), ('follow', 'envy', 0.1111111111111111), ('follow', 'use', 0.04), ('understanding', 'use', 0.03571428571428571)]
A:
Algorithm
You enumerate items within a loop also enumerating items. This means your algorithm is quadratic in the length of each sentence, which is bad. I think you can improve your algorithm to make only a single pass over items by creating a dict which stores unique words as keys, and lists of word indices as the values. Then you can lookup the appropriate indices of the items in your wordlists and perform the distance calculation. Since dict lookups are a constant-time operation, this reduces the complexity to linear in the length of each sentence. Do note that the algorithm is still quadratic in the length of your word lists, so there may be some improvement to be had if your word lists are long.
Correctness and Edge Cases
It's hard to tell exactly what this code is supposed to do, so I will be making a few assumptions. The handling of edge cases will vary depending on the requirements.
You likely have at least one bug in your code, which is reflected in your example output: you check if x in item, which will evaluate True for the string 'use' in the word 'because'. If this is not the desired behavior, you may want a stricter check like checking equality x == item, or something based on Levenshtein distance for a less strict evaluation.
Another possible bug is that you never include the first word of a sentence in your results. Your check if first_int: will be False for every word whose index is 0.
Code Style
Holy indentation, Batman! Deeply nested code is hard to read and understand, and usually indicates you can organize your code better. Usually the inner loops can be brought into their own function. You can sometimes reduce nesting by consolidating conditional statements. For example, an if statement immediately followed by another if with no else can be brought onto one line:
if first_int: if second_int != first_int:
can be written on one line as
if first_int and second_int != first_int:
Short variable names like w, t, and x aren't very descriptive, and make it hard for others to understand the code. Try to pick more descriptive names.
Make sure you don't include unnecessary logic. For example, your check if dist in relations will always be False, since you only insert tuples, and dist is a float. It can be removed, saving you a line of code and a level of indentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get EMU 1212m, EMU 1616m, or EMU 1010 to work with Ubuntu?
All of these models actually use the same exact PCIe card. I happen to have the 1212m model. It worked great in Windows, but unfortunately, Creative Labs E-MU only offers Windows drivers for this particular card. I have switched to using Ubuntu as my main desktop for a while now. How can I make it work in Ubuntu?
Furthermore, my chipset comes with integrated Intel HD Audio as well, and I'd like to be able to switch back and fourth between the E-MU sound card and the Intel one.
A:
Update Jul 3, 2014
As of Ubuntu 14.04, the ALSA driver is natively supported in the kernel, so the download-compile-install process for the driver should be skipped. The remaining of the instructions remains the same.
Instructions
In order to get this card to work, you need to set up ALSA (Advanced Linux Sound Architecture). Download the latest stable releases of alsa-driver, alsa-lib, alsa-utils, and alsa-firmware from their wiki page here and extract them.
0. Pre-reqs
To make sure you have all the pre-requisites for compiling code, run the following command:
sudo apt-get install build-essential linux-headers-$(uname -r)
1. Configure ALSA driver (skip this step if you are in Ubuntu 13.10+)
Now you need to configure which sound devices should be used with ALSA. I'll explain the instruction for having two sound devices, Intel HD Audio, and the E-MU 1212m. If you need ALSA to include another, you need to find the name of the ALSA driver that supports this device. In order to do that, check ALSA's sound card matrix here. If your sound card is supported, you should find a driver for it in the list of drivers. For Intel HD Audio, the driver is hda-intel, and for E-MU 1212m, the driver is emu10k1.
To configure the driver, go to the folder where you extracted alsa-driver in a terminal, and run the following command.
./configure --with-cards=hda-intel,emu10k1 --with-sequencer=yes --with-isapnp=no --with-oss=no --with-kernel=/lib/modules/$(uname -r)/build
--with-cards specifies a comma-separated list of the drivers that you need. As for the other options, I have the driver include a sequencer, specified the that the device is not plug and play, specified that OSS is not used, and specified the kernel. Although you shouldn't need to, but you can add additional configuration options for the ALSA driver as necessary. You can learn more about configuring ALSA driver by running the command ./configure --help.
Note: If you are not sure which card you have, try running lshw -c sound in the terminal. It will list all the sound hardware. If it is a PCI, it should also show up when you run lspci | grep audio.
2. Patch the emu10k1 driver (skip this step if you are in Ubuntu 13.10+)
Next we need to apply a small patch to one of the files.
In the same folder, open the file ./alsa-kernel/pci/emu10k1/emu10k1_main.c with a text editor of your choice. Find the line with
static struct snd_emu_chip_details emu_chip_details[] = {
Right below it, insert the following:
{.vendor = 0x1102, .device = 0x0008, .subsystem = 0x40071102,
.driver = "Audigy2", .name = "E-mu 1010 PCIe",
.id = "EMU1010",
.emu10k2_chip = 1,
.ca0108_chip = 1,
.spk71 = 1,
.emu_model = EMU_MODEL_EMU1010B},
Save this file, and close.
3. Compile and install
Go to each of the folders where you extracted driver* (skip if version of Ubuntu is 13.10+), firmware, lib, and utils, and for each of them run this command
./configure && make && sudo make install
Do the same for lib and utils.
4. Copy the firmware files to emu folder
Go to the folder where you extracted alsa-firmware in the terminal. Browse to the folder /emu/ there, and run the following command:
sudo cp *fw /lib/firmware/emu
Note:/lib/firmware/emu should exist, but if doesn't create it.
5. Configure the Linux sound base to use ALSA
Run this command:
sudo dpkg-reconfigure linux-sound-base
and choose ALSA.
6. Reboot!
This should be all. Once the system boots up, you should see SB0400 Audigy2 Value Analog Stereo in the sound settings of Ubuntu.
After you are done
This is enough for you to get started and get a sound output from your card. For more advanced ways to tweak the input/outputs of the cards see the following links:
emutrix : matrix-style mixer for this card. This will need to be compiled with Qt. It's relatively straightforward to build with qt4 and slightly more tricky with Qt5. The compilation command is simply qmake && make.
Here's how to compile this project with Qt5 (you can install Qt5 using sudo apt install qt5-default). Download and extract emutrix0.3.1 and open the file emutrix.pro with a text editor. After the line TEMPLATE = app, insert the following:
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets gui
Then save this file, and at the root of the project run the command
qmake
Next, open a text editor and open the file emutrix0.3.1/src/main.cc. At the top, delete the line #include <QtGui/QApplication> and replace it with #include <QtWidgets/QApplication>
Then open the file src/mainwindow.h and similarly delete the line #include <QtGui/QApplication> and this time replace it with
#include <QtWidgets/QMainWindow>
#include <QMainWindow>
And save these two files. Now we can compile the project by running
make
This might take a while. Note that you can run make -j 4 for example to use 4 threads if you have a machine with more available threads so that it compiles faster. If you do run into issues during the compilation, do a quick Google search of the compile error, usually the first one or two hits will resolve it.
Once everything is compiled, we are ready to launch it with ./emutrix. You can further create a .desktop file in /usr/share/applications so that you can launch emutrix from the start menu.
Additional Audio Tools
alsamixer: this is the main mixer that I often use to mute/adjust io levels. All you have to do to start it is to run in the terminal alsamixer.
gnome-alsa-mixer : or the gui version of it if you prefer (sudo apt-get install gnome-alsa-mixer)
qjackctl This is installed with sudo apt-get install jack qjackctl. Read more about jack on wiki. Some applications in Ubuntu may use this to have low latency and high resolution sound.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible for a css class to work with asp:Menu control in .net 2.0
I'm working on a migration of classic asp site to asp.net 2.0. There's a piece of CSS code associated with a div which I want to be used for an asp:Menu Control. I've tried various permutations but can't get figure it out.
The css is as follows:
.class{
color: black;
background-color: #A1A6AB;
border: thin solid black;
position: absolute;
top: 1;
width: 140;
text-align: center;
font: 9pt;
z-index: 2;
padding: 1;
cursor: pointer;
cursor: hand;
}
This needs to be associated with asp:Menu. Is it possible to do this?
A:
Here's some sample CSS for a Menu control, including fix to stop it jumping in Firefox:
http://codersbarn.com/post/2009/07/30/Fix-for-TreeView-Jumping-in-Firefox.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Database restore without deleting old database
I've done a copy of my database, using SQL Server 2008 R2 (DB -> Tasks -> Back Up).
Now I'm trying to restore it (DB -> Tasks -> Restore DataBase).
But SQL Studio give me an error and say, that I need to delete old DB to do it.
How to restore it without deleting?
A:
I'm assuming you want a second copy of your DB, but with another name... since you want to "restore it without deleting"? You can definitely do this.
Instead of selecting your current DB, right click on the "Database" item in the object explorer window
In the context popup window select "Restore Database...".
In the window that pops up, enter in a 'To Database' name for your copied DB, i.e. the new name for the DB copy. So if your original was TradeWind, call this one TradeWindCopy for example.
Make sure the 'From database' radio button is selected, and in the dropdown select the backup you just made (tick the required check box). You could also restore 'from device' if you wanted - in that case you need to select a ".bak" file to restore from.
Click the OK button and your DB backup is now restored as the new DB with the name you set in step 3.
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular expressions - turn it around
I'm having troubles with my regex. I managed to do the opposite of what i was looking for, but i need help to turn it around.
It supposed to do the following:
remove all words between all "bunny ears"
remove all words starting with -before the word (Not in-between the words)
The regex below somewhat does this, but the opposite! i need help to turn it around. I have looked through numerous tutorials and online guides but i cannot find any answer to this.
([\"].+?[\"])|([-][a-öA-Ö0-9]+)
Thank you!
Sorry all, i forgot to include what i expect.
if i test the regex on this text:
-item first search string -item2 -item3 "important"
I expect the Regex to match the following words only!
first
search
string
A:
This does the job:
$str = ' -item first search string -item2 -item3 "important"';
preg_match_all('/(?<!["-])\b\w+\b(?!")/', $str, $m);
print_r($m);
Output:
Array
(
[0] => Array
(
[0] => first
[1] => search
[2] => string
)
)
Explanation:
(?<!["-]) # negative lookbehind, make sure we haven't quote or dash before
\b\w+\b # 1 or more word characters, surrounded with word boundary
(?!") # negative lookahead, make sure we haven't quote after
| {
"pile_set_name": "StackExchange"
} |
Q:
How to see the actual memory and its properties (slot position, size, speed...)
I have 2 PCs. A Laptop dv600 and an Intel dp35dp. I want a command that shows me how many slots of memory I am using, the size, speed, etc.. For the moment the size of each would be good. Maybe see if there are slot free to use.
A:
lshw -short -C memory
or
dmidecode
A:
I find the following more more Human friendly and it gives the Speed, Size, Slot, Dimm Type, etc...
sudo dmidecode -t memory
If you only need to know the actual maximum memory and amount of slots in your motherboard then do the following:
sudo dmidecode -t 16
Changing 16 for 17 will give you an more detail look at each memory slot in your motherboard.
A:
sudo lshw -class memory worked for me.
Under
*-memory
You should see
*-bank:0
and
*-bank:1
If you have 2 slots. Only *-bank for 1 slot.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.