text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Multi-user,Multi-Touch and simultaneous input
it seems that it is not possible to control two seprate window in Windows 7 simultaneously.
any solution that each process capture it`s own touch input ?
A:
To my knowledge this is not currently possible on the Windows operating systems. I haven't heard of it being done in Windows but perhaps you could try to capture touch events and have another process emulate them into each window you want.
I don't know if this sort of hacking is possible in Windows but i've seen it done in Linux systems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"each day" → "daily"; "every other day" →?
Is there an adjective that means "every other day"? I found "bidaily" but it seems to mean "twice a day", not "every second day" (not even both as "biweekly" does).
I'd need this word to very concisely describe a questionnaire by its issuing frequency.
A:
There is no one word. The best you can do is "alternate day." An alternate day questionnaire is a questionnaire that appears every other day.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Negative magnitudes in the design of bandpass filter using Yulewalk in Matlab
I am trying to implement the filter attached in the picture but I cannot get the correct result (as seen in the other picture) as the Yulewalk function does not accept negative magnitudes. Can someone please help me?
This is what I get:
This is what I want to get:
A:
I think you're getting mixed up between magnitude (which is a positive number by definition) and dB magnitude (which is a log ratio, and can be positive or negative). yulewalk works with just plain magnitude, so you'll need to convert your dB values to absolute magnitude. Use 0 dB = 1.0, -20 dB = 0.1, etc:
magnitude = 10 ^ (magnitude_dB / 20)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MySQL Update Where Field is Different
I have a question about a MySQL query. I would (obviously) like to use as few queries as possible for this, and hopefully just one. What I'm trying to do is update a column in the database if the info is different.
For example, say I have the column "referer" and the column "date". If the user clicks the link and the referer is different but the date is the same, I would like to update only the referer column.
This is my current query:
mysql_query ("
UPDATE clicks
SET
clicks = clicks + 1
, referers = CONCAT(referers, ',$referer')
, dates = CONCAT(dates, ',$date')
WHERE shortURL = '$url'
AND referer != $referer
");
Is there any way to work this into one query?
A:
You should read something about database normalization.
first normalization rule is: fields have to be atomic. in your case: don't save multiple referers/dates into one field separated by commas.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get objectName of a pyqtgraph plotwidget during a mouse wheelEvent?
I am trying to identify the object name of a pyqtgraph plotwidget I am mouse wheeling on. However, I can only seem to get the object id "PyQt5.QtWidgets.QWidget object at 0x0000018ED2ED74C8". If I use the QApplication.widgetAt(event.globalPos()).objectName I get nothing, even though I have set the object name. Can you help me?
Sample code:
# Import packages
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout
import pyqtgraph as pg
import sys
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.graphLayout = QHBoxLayout()
self.graph = pg.PlotWidget(name="graph1")
self.graph.setObjectName("graph1")
self.graphLayout.addWidget(self.graph)
self.setLayout(self.graphLayout)
def wheelEvent(self, event):
hoveredWidget = QApplication.widgetAt(event.globalPos())
print(hoveredWidget.objectName())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
A:
A PlotWidget is actually a subclass of QAbstractScrollArea, which is a complex widget that has at least three children widgets: the scroll bars (even when they're hidden) and, most importantly, the viewport, which actually is the "content" of the scroll area.
This means that using widgetAt() you are not getting the plot widget (the scroll area), but its viewport. In fact, in your case you can get the plot widget by checking the parent:
def wheelEvent(self, event):
hoveredWidget = QApplication.widgetAt(event.globalPos())
if hoveredWidget and hoveredWidget.parent():
print(hoveredWidget.parent().objectName())
Be careful when intercepting events from a parent widget, especially for widget as complex as scroll areas: it's not guaranteed that you will receive them, as the children could accept them, preventing further propagation to their parent(s).
If you need more control over them, it's usually better to implement the respective methods in their subclasses or installing an event filter on the instances.
Note that, for the reason above, if you want to filter events on a scroll area you might prefer to install the filter on the viewport:
self.graph.viewport().installEventFilter(self)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ActiveRecord::RecordInvalid: Validation failed: User must exist
I'm working on a issue with Single Table Inheritance. I have two different types of Users. User model and Trainer model, Trainer user should inherit attributes from the User model. I created a User in the rails console and everything worked. As soon as I attempted to create a Trainer I get the following error.
Rails 5.0.4
ActiveRecord::RecordInvalid: Validation failed: User must exist
Am I setting up my model associations incorrectly?
Here is my User Model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
My Trainer Model
class Trainer < User
has_many :appointments
has_many :clients, through: :appointments
end
Schema for models
create_table "trainers", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "type"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
As you can see from my User model, I added the required :type column
Here is the schema for my client and appointment
create_table "appointments", force: :cascade do |t|
t.integer "client_id"
t.integer "trainer_id"
t.datetime "appointment_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "start_time"
t.datetime "end_time"
t.integer "status", default: 0
end
create_table "clients", force: :cascade do |t|
t.string "name"
t.string "phone_number"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
First I created a user in the console
User.create!(email:'[email protected]', password:'asdfasdf', password_confirmation:'asdfasdf')
Then I when on to create a Trainer
Trainer.create!(first_name:'Ryan', last_name:'Bent')
Trainers and Users should be associated. But I didn't think I needed add associations using Single Table Inheritance.
A:
With Single Table Inheritance, one table must have all the attributes that any of the subclasses need (more information). So for your situation, you'd need to add the Trainer columns (first_name, last_name) to the users table as well, and then Users would leave that empty on the table and Trainers would fill them in.
If you want to keep the separate tables, what you are doing is no longer single table and would require some sort of joining between the 2.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Planning Incident Response / Business Continuity
An IT company has already most of the standard procedures / precautions in place to do day-to-day business in a secure way e.g. policies for users what to do and what not to do, technical solutions like antivirus / spam protection / log management / .... There are also plans to restore systems and what service has which dependencies etc. for when something really goes south (either because of an attack or simple system errors) and plans how to deal with “normal” incidents like fire in the datacenter, virus infection of server / clients, total fail of service X. Now I want to prepare for a big fallout like the compromise of multiple systems and services with no clear understanding where the breach is and how the attacker could gain access and likely no clue what systems are compromised.
Question(s): How would somebody prepare for an incident that is not predictable? Are there templates someone could create to help guide through the (unknown) situation? How to take care of the (naturally) occurring panic that such an incident would cause? Should management get guidelines what to do or have a say in this situation at all (in my experience they don’t really understand what’s going on, are not helpful and are only concerned with identifying who to blame)? Is all hope lost in such a situation and should an external service provider be called to deal with the situation? The main problem here is that I can’t produce a step-by-step manual for a situation that is not predictable. Also a problem is that one team can’t check what systems are possibly compromised due to separation of power and restricted rights and I don't know which teams to call when nobody can tell which systems are affected.
Note: There is no incident response team or dedicated security analysis team in place. The only ones who really know the infrastructure and how their systems work are the people who do the standard workload e.g. windows team, linux team, vmware team, storage team, network team, … and for most of the teams there is 24/7 standby.
A:
This is a difficult question. To write proper incident response procedures you will probably want to consult with someone who does this as their full time job. They will be able to guide you through the creation of procedures for your business, by taking into account your level of tolerable risk, assets (company name, etc.), legal/regulatory exposure, and many other factors.
At the moment I wouldn't say that you should hire someone in case of a breach, rather hire someone before it happens to put together your plan. And yes, while it may be expensive, think of it like an insurance plan. This is what you're going to do when the company is in deep crisis.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Сформировать квадратную матрицу порядка N по заданному образцу
Даны числа а1, а2, … аn. Сформировать квадратную матрицу порядка n по заданному образцу:
Вот примерный код, что дальше делать не знаю.
int main() {
setlocale(LC_ALL, "Russian");
int n;
cout << "Введите порядок квадратной матрицы: ";
cin >> n;
int** arr = new int* [n];
for (int i = 0; i < n; i++)
arr[i] = new int[n];
cout << "Введите а1, а2, ... , a" << n << " : ";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> arr[i][j];
}
}
cout << "Введенный массив: " << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << setw(4) << arr[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
A:
Все очень просто. Если обозначить матрицу как b, то
b[i][j] = a[(i+j)%n+1]
Если, конечно, нумерация b - как принято в C/C++ - с нуля, а вот a - как в условии - с 1.
Если и a нумеровать с нуля - просто не нужно +1.
Все!
Код сами напишете?
Можно просто ввести все ai в первую строку матрицы, а остальные строки получить сдвигом влево.
Типа
for(int j = 0; j < n; ++j)
b[i][j] = b[i-1][(j+1)%n];
Вот, по просьбам трудящихся весь код ввода:
for (int i = 0; i < n; i++)
cin >> arr[0][i];
for (int i = 1; i < n; i++)
for(int j = 0; j < n; ++j)
arr[i][j] = arr[i-1][(j+1)%n];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I install PostgreSQL driver on Apache?
I need to be able to connect from my (Ubuntu + Apache) web server to a remote PostgreSQL database, but unfortunately, the version of PHP on my web server doesn't have the php_pgsql.dll library and throws an error if I try and uncomment this section of php.ini.
I've searched the internet and found lots of advice on how to install PostgreSQL on my server, but I don't need to run the database service on my web server, I just need to allow PHP to connect to the remote service.
Can anyone give me a step-by-step noob guide to installing the driver?
A:
Try this:
sudo apt-get install php5-pgsql
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make Ag-Grid cell text (not entire cell) have a click event
I'm trying to open a component whenever the user clicks on the text within a specific cell (in this case in the Name column). The problem I'm running into is that there isn't any method (as far as I can tell) in the Ag-Grid that allows for this. I believe there is a method for adding a click event for the specific cell, but I'm trying to only have it capture the events for when the cell text is clicked. Does anyone know how I can accomplish this?
I've tried many Ag-Grid methods, but none have cell text click event.
this.gridOptions.api.setColumnDefs([{
headerName: "Name",
field: "Name"
},
{
headerName: "Description",
field: "Description"
},
{
headerName: "Actions",
cellRendererFramework: ActionsRoleComponent,
autoHeight: false,
cellClass: 'actions-button-cell d-flex align-items-center justify-content-center',
width: 80,
pinned: 'right',
suppressResize: true,
suppressFilter: true,
suppressSorting: true,
suppressMovable: true,
cellEditorFramework: ActionsRoleComponent
}
]);
this.gridOptions.api.setRowData(receivedJson);
this.gridOptions.api.sizeColumnsToFit();
A:
When it comes to customising the cell renderers for ag-Grid, you will need to make use of the Cell Renderer Componenta.
First, on your component.html, include the input binding for frameworkComponents
<ag-grid-angular
#agGrid
style="width: 100%; height: 100%;"
id="myGrid"
class="ag-theme-balham"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents"
(gridReady)="onGridReady($event)"
.
.
></ag-grid-angular>
On your main component that is using and generating the ag-grid, you will need to import your custom cell component, define the property for frameworkComponents, followed by providing the value for cellRenderer for the particular column in your column definitions:
import { NameRenderer } from "./name-renderer.component";
this.columnDefs = [
{
headerName: "Name",
field: "name",
cellRenderer: "nameRenderer",
},
// other columns
]
this.frameworkComponents = {
nameRenderer: NameRenderer,
};
And on your custom cell renderer component, NameRenderer, you bind the click event. I am not sure which part of the cell you would require it to be clickable, but I assume you want the entire name to handle the click event
import {Component} from "@angular/core";
import {ICellRendererAngularComp} from "ag-grid-angular";
@Component({
selector: 'name-cell',
template: `<span (click)="onClick($event)">{{ params.value }}</span>`
})
export class NameRenderer implements ICellRendererAngularComp {
// other parts of the component
onClick(event) {
console.log(event);
// handle the rest
}
}
Do not forget to include the custom cell renderer components in your module.ts,
import { NameRenderer } from "./name-renderer.component";
@NgModule({
imports: [
AgGridModule.withComponents([NameRenderer])
// other imported stuff
],
declarations: [
NameRenderer,
// other components
],
bootstrap: [AppComponent]
})
I have forked and created a demo from the official ag-grid demo. You may refer to cube-renderer.component.ts for the handling of the click event.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cakephp get data from db
I'm new to cakephp how to write below sql query in cakephp
$sql = "SELECT * FROM `user` WHERE `email` = '" . $email . "' AND `password` = '" . $password . "'";
$result = mysql_query($sql, $connection);
while($fetchdata = mysql_fetch_assoc($result)){
echo $fetchdata['name'];
}
Please help me
Thanks
A:
For your query:
<?php
$this->loadmodel('User');
$result = $this->User->find('first',array('conditions' => array('email' => $email,
'password' => $password)));
foreach($result as $row)
{
//do whatever you want to do
}
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IOTA API command to request transaction details
I use Curl to familiarize myself with the IOTA API. By using findTransactions you can query the transaction hashes of addresses, bundles, tags and approvees.
But which command returns the details of a transaction (confirmation status, trunk transaction, branch transaction, message etc)? There doesn't seem to be a method in the official API reference.
A:
But which command returns the details of a transaction (confirmation status, trunk transaction, branch transaction, message etc)?
getTrytes is the endpoint for getting transaction details from the ledger. It returns raw trytes that can be converted to a transaction object.
You can check out implementation of asTransactionObject for trytes to plain transaction object conversion.
Confirmation statuses are not part of transaction trytes. They need to be fetched separately using getInclusionStates.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
php script sometimes receives post data sometimes not. It seems a cache problem
I am submitting post data from a HTML form (using javascript to validate the form) to a php script
Several hours ago I realized I was sending empty data so I fixed this problem and now I am still not receiving the post data in the server side even though I am sending it.
When I echo the post variables on the server side I can see the variables echoed when I remove the echo it keeps telling me "No login information". I tried to comment/uncomment the echo several times and it keeps showing the same problem. It seems some kind of cache.
I tried to disable cache using clearstatcache(); and
header("Content-Type: text/html");
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
It does not work. Maybe it is some kind of cache from the html form side, apparently it keeps sending the wrong (empty) data.
When I remove the "no login information" part, it tells me "user does not exist" as when the login info is really missing.
I need to add that this code has been working well for years. I did not change it , besides the first lines for preventing to cache (but this was after the problem appeared). The new code was the html form which is calling this php code.
Part of php code follows
<?php
clearstatcache();
header("Content-Type: text/html");
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
include("conexion/conexion.php");
//$form_password=$_GET['form_password'];
//$form_email=$_GET['form_email'];
$form_password=$_POST['form_password'];
$form_email=$_POST['form_email'];
//echo "form_password=$form_password";
//echo "form_email=$form_email";
function autentificar(){
global $form_email,$form_password;
echo "form_password=$form_password";
echo "form_email=$form_email";
//exit();
$mensaje=1;
if($form_email=='' || $form_password=='')
{
$mensaje="No login information";
//echo "form_password=$form_password";
//echo "form_email=$form_email";
}
else
{
$con=openDB();
if(!$con)
{
$mensaje="Database connection not opened";
//exit();
}
else
{
$query="SELECT USERCODE,NAME,AES_DECRYPT(UNHEX(PASSWORD),UNHEX(SHA2('xxxxx',512))) ,USERTYPE,BALANCE,ACTIVELESSONSTATUS,ACTIVELESSONCODEVAR FROM USERS WHERE EMAIL='$form_email'";
//echo "query=$query";
//exit();
//$query="SELECT * FROM usuario ";
$resultado=genesis_exec($con,$query);
//$resultado=mysql_query($query,$con);
if(!$resultado)
{
$mensaje="Error en la sentencia SQL";
echo "Sentencia: $query <br>";
echo "Error: ".mysql_error();
closeDB($con);
exit();
}
else
{
$fila=genesis_fetch_row($resultado);
if(!$fila)
{
$mensaje="User does not exist";
}
else
{
$user=genesis_result($resultado,1);
$name=genesis_result($resultado,2);
$p=genesis_result($resultado,3);
$type=genesis_result($resultado,4);
$balance=genesis_result($resultado,5);
$status=genesis_result($resultado,6);
$lesson=genesis_result($resultado,7);
if($p!=$form_password)
{
$mensaje="Incorrect password";
/*echo "user=$user";
echo "name=$name";
echo "p=$p";
echo "type=$type";
echo "$mensaje";
exit();*/
}
else
{
//AQUI ABRE LA SESION
//para abrir sesion y usar Header no se debe haber hecho ninguna salida
session_start(); //aqui se abre la sesion por primera vez
$SESION=session_id();
$query="UPDATE USERS SET SESSIONID='$SESION' WHERE USERCODE='$user'";
$resultado=genesis_exec($con,$query);
//Aqui registra las variables de sesion
$_SESSION['TIPO_USUARIO']=$type; //usar esto si register_globals=off
$_SESSION['COD_USUARIO']=$user; //usar esto si register_globals=off
$_SESSION['NOMBRE_USUARIO']=$name;
$_SESSION['BALANCE']=$balance;
$_SESSION['ACTIVE_LESSONSTATUS']=$status;
$_SESSION['LESSON_CODEVAR']=$lesson;
$mensaje=1; //solo devuelve 1 si el usuario se autentificó con éxito
if($pagina=="" && $type=="STUDENT") $pagina="lesson.htm"; //valor por defecto
if($pagina=="" && $type!="STUDENT") $pagina="opportunities.htm"; //valor por defecto
}
}
}
genesis_commit($con);
closeDB($con);
}
}
return $mensaje;
}//fin autentificar()
part of the client side code follows
<form id="sky-form" class="sky-form" method="post" onsubmit="return validate()" action="login.php">
<header>Login form</header>
<fieldset>
<section>
<div class="row">
<label class="label col col-4">E-mail</label>
<div class="col col-8">
<label class="input">
<i class="icon-append icon-user"></i>
<input type="email" name="form_email" id="form_email">
</label>
</div>
</div>
</section>
<section>
<div class="row">
<label class="label col col-4">Password</label>
<div class="col col-8">
<label class="input">
<i class="icon-append icon-lock"></i>
<input type="password" name="form_password" id="form_password">
</label>
<div class="note"><a href="#sky-form2" class="modal-opener">Forgot password?</a></div>
</div>
</div>
</section>
<!--
<section>
<div class="row">
<div class="col col-4"></div>
<div class="col col-8">
<label class="checkbox"><input type="checkbox" name="remember" checked><i></i>Keep me logged in</label>
</div>
</div>
</section>
-->
</fieldset>
<footer>
<div class="fright">
<a href="register.html" class="button button-secondary">Register</a>
<button type="submit" class="button">Log in</button>
</div>
</footer>
</form>
and the validation function is following
<script type="text/javascript">
function validate()
{
//alert('validate');
if(document.getElementById("form_email").value=='')
{
alert('Enter the email');
return false;
}
if(document.getElementById("form_password").value=='')
{
alert('Enter the password');
return false;
}
//alert(document.getElementById("form_email").value);
//alert(document.getElementById("form_password").value);
return true;
}
</script>
I need to say that all started when in fact I was not sending the data due to an issue with the form and javascript. But I am confident now I am sending the data Because when I echo the post data in the server side it shows the data when I do not echo the data it says "no login information"
IMPORTANT UPDATE: I deleted the file login.php from server and I am still getting the message "No login information" from server. What is going on ? Please help
A:
I had to merge both files in one single file and it works now
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a relationship between $e$ and the sum of $n$-simplexes volumes?
When I look at the Taylor series for $e^x$ and the volume formula for oriented simplexes, it makes $e^x$ look like it is, at least almost, the sum of simplexes volumes from $n$ to $\infty$. Does anyone know of a stronger relationship beyond, "they sort of look similar"?
Here are some links:
Volume formula
http://en.wikipedia.org/wiki/Simplex#Geometric_properties
Taylor Series
http://en.wikipedia.org/wiki/E_%28mathematical_constant%29#Complex_numbers
A:
The answer is, it's just a fact “cone over a simplex is a simplex” rewritten in terms of the generating function:
observe that because n-simplex is a cone over (n-1)-simplex $\frac{\partial}{\partial x}vol(\text{n-simplex w. edge x}) = vol(\text{(n-1)-simplex w. edge x})$; in other words $e(x):=\sum_n vol\text{(n-simplex w. edge x)}$ satisfies an equvation $e'(x)=e(x)$. So $e(x)=Ce^x$ -- and C=1 because e(0)=1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
org.apache.solr.common.SolrException: Document is missing mandatory uniqueKey field: id
I have run Apache solr 6.1.0 successfully. I have also created new core named "Testcore" and add all the required files solrconfig.xml, schema.xml in the solr\Testcore folder.
Now I have run following command in command prompt for indexing an csv file :
C:\>java -Durl=http://localhost:8983/solr/Testcore/update/csv -Dtype=text/csv -jar C:\solr-6.1.0\server\lib/post.jar C:\messages\TestInsert-08-16-2016-15-47-solr.csv
Now while indexing an csv file i am getting following error response code in command prompt :
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/solr/Testcore/update/csv usin
g content-type text/csv...
POSTing file TestInsert-08-16-2016-15-47-solr.csv to [base]
SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for url: http
://localhost:8983/solr/Testcore/update/csv
SimplePostTool: WARNING: Response: <?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">27</int
></lst><lst name="error"><lst name="metadata"><str name="error-class">org.apache
.solr.common.SolrException</str><str name="root-error-class">org.apache.solr.common.SolrException</str></lst><str name="msg">Document is missing mandatory uniqueKey field: id</str><int name="code">400</int></lst>
</response>
SimplePostTool: WARNING: IOException while reading response: java.io.IOException
: Server returned HTTP response code: 400 for URL: http://localhost:8983/solr/Testcore/update/csv
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/Testcore/update/csv
...
Time spent: 0:00:00.073
So In the response code it returns error msg as "Document is missing mandatory uniqueKey field: id". Also data is not getting indexed on solr site due to that error.
My schema.xml file :
<?xml version="1.0" encoding="UTF-8" ?>
<schema name="example" version="1.5">
<field name="_version_" type="long" indexed="true" stored="true"/>
<field name="_root_" type="string" indexed="true" stored="false"/>
<field name="id" type="string" indexed="true" stored="true" required="true" />
<field name="sku" type="text_en_splitting_tight" indexed="true" stored="true" omitNorms="true"/>
<field name="name" type="text_general" indexed="true" stored="true"/>
<field name="manu" type="text_general" indexed="true" stored="true" omitNorms="true"/>
<field name="cat" type="string" indexed="true" stored="true" multiValued="true"/>
<field name="features" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="includes" type="text_general" indexed="true" stored="true" termVectors="true" termPositions="true" termOffsets="true" />
<field name="weight" type="float" indexed="true" stored="true"/>
<field name="price" type="float" indexed="true" stored="true"/>
<field name="popularity" type="int" indexed="true" stored="true" />
<field name="inStock" type="boolean" indexed="true" stored="true" />
<field name="store" type="location" indexed="true" stored="true"/>
<field name="title" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="subject" type="text_general" indexed="true" stored="true"/>
<field name="description" type="text_general" indexed="true" stored="true"/>
<field name="comments" type="text_general" indexed="true" stored="true"/>
<field name="author" type="text_general" indexed="true" stored="true"/>
<field name="keywords" type="text_general" indexed="true" stored="true"/>
<field name="category" type="text_general" indexed="true" stored="true"/>
<field name="resourcename" type="text_general" indexed="true" stored="true"/>
<field name="url" type="text_general" indexed="true" stored="true"/>
<field name="content_type" type="string" indexed="true" stored="true" multiValued="true"/>
<field name="last_modified" type="date" indexed="true" stored="true"/>
<field name="links" type="string" indexed="true" stored="true" multiValued="true"/>
<!-- Testcore spcific fields -->
<field name="SRNO" type="int" indexed="true" stored="true"/>
<field name="IDENTIFIER" type="string" indexed="true" stored="true"/>
<field name="AGENTID" type="string" indexed="true" stored="true"/>
<field name="AGENTNAME" type="string" indexed="true" stored="true"/>
<field name="event_timestamp" type="date" indexed="true" stored="true" default="NOW" multiValued="false"/>
<field name="MONTH" type="string" indexed="true" stored="true"/>
<field name="DAY" type="string" indexed="true" stored="true"/>
<field name="TIMESTAMP" type="string" indexed="true" stored="true"/>
<field name="TYPE" type="string" indexed="true" stored="true"/>
<field name="TASKID" type="string" indexed="true" stored="true"/>
<!-- End of Testcore fields----->
<field name="content" type="text_general" indexed="false" stored="true" multiValued="true"/>
<field name="text" type="text_general" indexed="true" stored="false" multiValued="true"/>
<field name="text_rev" type="text_general_rev" indexed="true" stored="false" multiValued="true"/>
<field name="manu_exact" type="string" indexed="true" stored="false"/>
<field name="payloads" type="payloads" indexed="true" stored="true"/>
<dynamicField name="*_i" type="int" indexed="true" stored="true"/>
<dynamicField name="*_is" type="int" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_s" type="string" indexed="true" stored="true" />
<dynamicField name="*_ss" type="string" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_l" type="long" indexed="true" stored="true"/>
<dynamicField name="*_ls" type="long" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_t" type="text_general" indexed="true" stored="true"/>
<dynamicField name="*_txt" type="text_general" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_en" type="text_en" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_b" type="boolean" indexed="true" stored="true"/>
<dynamicField name="*_bs" type="boolean" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_f" type="float" indexed="true" stored="true"/>
<dynamicField name="*_fs" type="float" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_d" type="double" indexed="true" stored="true"/>
<dynamicField name="*_ds" type="double" indexed="true" stored="true" multiValued="true"/>
<!-- Type used to index the lat and lon components for the "location" FieldType -->
<dynamicField name="*_coordinate" type="tdouble" indexed="true" stored="false" />
<dynamicField name="*_dt" type="date" indexed="true" stored="true"/>
<dynamicField name="*_dts" type="date" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_p" type="location" indexed="true" stored="true"/>
<!-- some trie-coded dynamic fields for faster range queries -->
<dynamicField name="*_ti" type="tint" indexed="true" stored="true"/>
<dynamicField name="*_tl" type="tlong" indexed="true" stored="true"/>
<dynamicField name="*_tf" type="tfloat" indexed="true" stored="true"/>
<dynamicField name="*_td" type="tdouble" indexed="true" stored="true"/>
<dynamicField name="*_tdt" type="tdate" indexed="true" stored="true"/>
<dynamicField name="*_c" type="currency" indexed="true" stored="true"/>
<dynamicField name="ignored_*" type="ignored" multiValued="true"/>
<dynamicField name="attr_*" type="text_general" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="random_*" type="random" />
<!-- Field to use to determine and enforce document uniqueness.
Unless this field is marked with required="false", it will be a required field
-->
<uniqueKey>id</uniqueKey>
<copyField source="cat" dest="text"/>
<copyField source="name" dest="text"/>
<copyField source="manu" dest="text"/>
<copyField source="features" dest="text"/>
<copyField source="includes" dest="text"/>
<copyField source="manu" dest="manu_exact"/>
<!-- Copy the price into a currency enabled field (default USD) -->
<copyField source="price" dest="price_c"/>
<!-- Text fields from SolrCell to search by default in our catch-all field -->
<copyField source="title" dest="text"/>
<copyField source="author" dest="text"/>
<copyField source="description" dest="text"/>
<copyField source="keywords" dest="text"/>
<copyField source="content" dest="text"/>
<copyField source="content_type" dest="text"/>
<copyField source="resourcename" dest="text"/>
<copyField source="url" dest="text"/>
<!-- Create a string version of author for faceting -->
<copyField source="author" dest="author_s"/>
<fieldType name="string" class="solr.StrField" sortMissingLast="true" />
<fieldType name="uuid" class="solr.UUIDField" indexed="true" />
<!-- boolean type: "true" or "false" -->
<fieldType name="boolean" class="solr.BoolField" sortMissingLast="true"/>
<fieldType name="int" class="solr.TrieIntField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="float" class="solr.TrieFloatField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="tint" class="solr.TrieIntField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tlong" class="solr.TrieLongField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0"/>
<!-- A Trie based date field for faster date range queries and date faceting. -->
<fieldType name="tdate" class="solr.TrieDateField" precisionStep="6" positionIncrementGap="0"/>
<!--Binary data type. The data should be sent/retrieved in as Base64 encoded Strings -->
<fieldtype name="binary" class="solr.BinaryField"/>
<fieldType name="random" class="solr.RandomSortField" indexed="true" />
<fieldType name="text_ws" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
</analyzer>
</fieldType>
<fieldType name="managed_en" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.ManagedStopFilterFactory" managed="english" />
<filter class="solr.ManagedSynonymFilterFactory" managed="english" />
</analyzer>
</fieldType>
<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="lang/stopwords_en.txt"
/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EnglishPossessiveFilterFactory"/>
<filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
<filter class="solr.PorterStemFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="lang/stopwords_en.txt"
/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EnglishPossessiveFilterFactory"/>
<filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
<filter class="solr.PorterStemFilterFactory"/>
</analyzer>
</fieldType>
<fieldType name="text_en_splitting" class="solr.TextField" positionIncrementGap="100" autoGeneratePhraseQueries="true">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="lang/stopwords_en.txt"
/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
<filter class="solr.PorterStemFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="lang/stopwords_en.txt"
/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
<filter class="solr.PorterStemFilterFactory"/>
</analyzer>
</fieldType>
<fieldType name="text_en_splitting_tight" class="solr.TextField" positionIncrementGap="100" autoGeneratePhraseQueries="true">
<analyzer>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="0" generateNumberParts="0" catenateWords="1" catenateNumbers="1" catenateAll="0"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
<filter class="solr.EnglishMinimalStemFilterFactory"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
<fieldType name="text_general_rev" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.ReversedWildcardFilterFactory" withOriginal="true"
maxPosAsterisk="3" maxPosQuestion="2" maxFractionAsterisk="0.33"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<fieldType name="alphaOnlySort" class="solr.TextField" sortMissingLast="true" omitNorms="true">
<analyzer>
<!-- KeywordTokenizer does no actual tokenizing, so the entire
input string is preserved as a single token
-->
<tokenizer class="solr.KeywordTokenizerFactory"/>
<!-- The LowerCase TokenFilter does what you expect, which can be
when you want your sorting to be case insensitive
-->
<filter class="solr.LowerCaseFilterFactory" />
<!-- The TrimFilter removes any leading or trailing whitespace -->
<filter class="solr.TrimFilterFactory" />
<filter class="solr.PatternReplaceFilterFactory"
pattern="([^a-z])" replacement="" replace="all"
/>
</analyzer>
</fieldType>
<fieldtype name="phonetic" stored="false" indexed="true" class="solr.TextField" >
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.DoubleMetaphoneFilterFactory" inject="false"/>
</analyzer>
</fieldtype>
<fieldtype name="payloads" stored="false" indexed="true" class="solr.TextField" >
<analyzer>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.DelimitedPayloadTokenFilterFactory" encoder="float"/>
</analyzer>
</fieldtype>
<!-- lowercases the entire field value, keeping it as a single token. -->
<fieldType name="lowercase" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory" />
</analyzer>
</fieldType>
<fieldType name="descendent_path" class="solr.TextField">
<analyzer type="index">
<tokenizer class="solr.PathHierarchyTokenizerFactory" delimiter="/" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.KeywordTokenizerFactory" />
</analyzer>
</fieldType>
<fieldType name="ancestor_path" class="solr.TextField">
<analyzer type="index">
<tokenizer class="solr.KeywordTokenizerFactory" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.PathHierarchyTokenizerFactory" delimiter="/" />
</analyzer>
</fieldType>
<!-- since fields of this type are by default not stored or indexed,
any data added to them will be ignored outright. -->
<fieldtype name="ignored" stored="false" indexed="false" multiValued="true" class="solr.StrField" />
<fieldType name="point" class="solr.PointType" dimension="2" subFieldSuffix="_d"/>
<!-- A specialized field for geospatial search. If indexed, this fieldType must not be multivalued. -->
<fieldType name="location" class="solr.LatLonType" subFieldSuffix="_coordinate"/>
<fieldType name="location_rpt" class="solr.SpatialRecursivePrefixTreeFieldType"
geo="true" distErrPct="0.025" maxDistErr="0.000009" units="degrees" />
<fieldType name="bbox" class="solr.BBoxField"
geo="true" units="degrees" numberType="_bbox_coord" />
<fieldType name="_bbox_coord" class="solr.TrieDoubleField" precisionStep="8" docValues="true" stored="false"/>
<fieldType name="currency" class="solr.CurrencyField" precisionStep="8" defaultCurrency="USD" currencyConfig="currency.xml" />
</schema>
And in csv file there following fields : SRNO,IDENTIFIER,AGENTID,AGENTNAME,event_timestamp,MONTH,DAY,TIMESTAMP,TYPE,TASKID
These fields are added in schema.xml file with their data types.
Please do needful to help me out of this problem. Thanks in advance.
A:
You can just remove uniqueKey field that is declared as id on the top of schema.xml file . Also remove the required=true attribute from id field . Use any other field as your unique key , that your document has .
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pane.getChildren().addAll(); not working in a scene javafx
This code will not allow the line to draw in my window... All I have in the fxml file is a simple pane with the fx:id of hi to test things out. There is no error, the line simply doesn't appear. I've also tried this with a box and circle. I really need help, this is an important project.
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
public class PlotSceneController implements Initializable {
@FXML
Pane hi;
@Override
public void initialize(URL url, ResourceBundle rb) {
Line line = new Line(0,0,10,110);
line.setStroke(Color.BLACK);
line.setStrokeWidth(10);
hi.getChildren().addAll(line);
}
}
FXML File
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<Pane fx:id="hi" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-
Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
</children>
</Pane>
Main Class, leads to another page with a button that leads to the page I'm having trouble with.
public class Main extends Application {
Stage firstStage;
Scene loginButton;
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
firstStage = primaryStage;
loginButton = new Scene(root, 900, 700);
primaryStage.setTitle("Treatment Data");
primaryStage.setScene(loginButton);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) { //Main class
launch(args); //Launches application/window
}
}
A:
You are missed to set a controller class PlotSceneController.java. Set controller class in different two way like using main class setController() method or set controller class in left bottom side controller pane in scene Builder screen.
Using Main
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
loader.setController(new PlotSceneController());
Parent root = (Parent) loader.load();
Or Using FXML
Set Controller class with full package path like below way
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flip two coins, if at least one is heads, what is the probability of both being heads?
Quick basic question here to make sure I understand conditional probability properly.
You flip two coins, and at least one of them is heads. What is the probability that they are both heads?
Now, I think the answer to this is $\frac{1}{3}$, for the following explanation.
If $A$ is the event that the first coin lands heads, and $B$ is the result that the second coin lands heads, then what we're looking for is $P(A \cap B | A \cup B)$. The probability of both $A$ and $B$ is $\frac{1}{2}$, so $A \cup B$ is $\frac{3}{4}$. The probability of $A \cap B$ is $P(A|B)P(B)$, which is $\frac{1}{2}(\frac{1}{2}) = \frac{1}{4}$. Therefore, the probability is $\frac{\frac{1}{4}}{\frac{3}{4}} = \frac{1}{3}$.
Now, besides the obvious question of whether or not this is actually right, I'm wondering: why is it that $P(A|B) = P(A)$? Is it because these are independent events? If so, can I use this fact as proof that these are independent events?
Thanks for the help!
A:
Very easy solution to this not even requiring any formulas. There are only $4$ possible outcomes of $2$ fair coin flips: (HH, HT, TH, TT). If we know one of them is a H, then we can concentrate on just (HH, HT, and TH) since TT has no heads. Both HT and TH will result in the other coin being a tail and only the HH will result in the other coin being a head so it is $1$ good outcome out of $3$ possible and they are all equally likely so the correct answer is $1/3$ probability. Done!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
if string in pandas series contains a string from another pandas dataframe
Struggling newbie.
If I have two pandas dataframes something like :
import pandas as pd
data = {'col1': ['black sphynx bob','brown labrador','grey labrador mervin',
'brown siamese cat','white siamese']}
desc_df = pd.DataFrame(data=data)
catg = {'dog': ['labrador','rottweiler',
'beagle'],'cat':['siamese','sphynx','ragdoll']}
catg_df = pd.DataFrame(data=catg)
desc_df
col1
0 black spyhnx bob
1 brown labrador
2 grey labrador mervin
3 brown siamese cat
4 white Siamese
catg_df
cat dog
0 siamese labrador
1 sphynx rottweiler
2 ragdoll beagle
I'd like to end up with desc_df dataframe:
col1 col2
0 black spyhnx bob cat
1 brown Labrador dog
2 grey labrador Mervin dog
3 brown siamese cat cat
4 white Siamese cat
I thought I maybe could use the apply method with a function. I'm just not 100% confident if that is the best way to approach this and how exactly it could be done.
Many thanks
A:
You can using str.contains + np.where
desc_df['col2']=np.where(desc_df.col1.str.contains(catg_df.cat.str.cat(sep='|')),'cat','dog')
desc_df
Out[1538]:
col1 col2
0 black spyhnx bob dog
1 brown labrador dog
2 grey labrador mervin dog
3 brown siamese cat cat
4 white siamese cat
OK update for multiple condition
d=catg_df.apply('|'.join).to_dict()
desc_df.col1.apply(lambda x : ''.join([z if pd.Series(x).str.contains(y).values else '' for z,y in d.items()]))
Out[1568]:
0
1 dog
2 dog
3 cat
4 cat
Name: col1, dtype: object
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two kids sharing a sleeping bag
We are heading out on our first family camping. We tested out our sleeping bags in the living room.
The two kids ( ~2 & ~5 yo) wanted to share one adult sleeping bag. I'm expecting that it will end in a fight before long, but if it doesn't:
Is it a bad idea to let two small siblings share an adult sleeping bag?
(My quick googling about if one should have children sized bags or not brought up issues such as overheating and suffocation, neither one of had I ever worried about before! I thought maybe there is something else that I hadn't thought of... so anything less than obvious would be appreciated.)
A:
Not a bad idea.
I happen to have a 5 and 3 year old. I can think of reasons for not letting them sleep in the same sleeping bag, but none of them are because it wouldn't work in theory. If your two kids would actually sleep together in one bag, then I'd say it's a great idea. They'll stay warmer at night and that's one less bag for you to pack.
Your only concern with suffocation is if they go too deep inside the bag. I remember trying to spelunk all the way to the bottom of my adult sized sleeping bag when I was a kid; if you got stuck down there then you could get in trouble. The easy solution is to leave the bottom open. Most sleeping bags have a double zipper on them. The other thing you could do is fold the sleeping bag in half, folding the foot of the bag up underneath your kids. This will reduce the volume of the bag so they can't get swallowed by it, and it will add some extra warmth and comfort beneath them.
A:
I'd probably wonder about the quality of sleep they will get. This depends a lot on the sleeping bag itself, how warm it is, if it comes with a zip, what the outer temperature is, etc., but also, on the width (the inner circumference). Imagine they shared a bed: how wide would it need to be so they both get a good night's sleep? The bag circumference ought to be at least twice the width of the bed. They should be able to lie comfortably next to each other, with a little extra room.
Special bags for kids are shorter to economize on weight (if they need to carry the bag), but also in cold climates, it can be difficult for a child to warm up their leg area in an adult sleeping bag, because of the extra empty space. Other than that, I do not see a problem with a kid in an adult bag (though I'd be careful with the 2-year old). At the worst, the extra leg area can be tied up from outside with a string, so the kid cannot "sink" into it.
I might embrace the idea of kids sharing a bag but still pack another bag, just in case. Perhaps they change their mind quite early into the night.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ - Automatic Class Loading from DLL (Windows, Visual Studio)
I have a base class CDemonstration and multiple subclasses (each implementation runs a different coding Demonstration) and need to build a Main Menu (vector) containing one instance of each subclass. The goal is to maintain a Menu which lists each Demonstration with the least amount of effort.
Originally in the core application, I made a function which returns a vector containing one instance of each Demonstration, where each Demonstration required a push_back, and each new Demonstration required modification to the application by adding another push_back. To avoid altering the application's source code each time I need to add a new Demonstration to add to the list, I placed all of the Demonstrations into a separate DLL, and I created the same vector-returning function in the DLL so that it can be called from the core application. However, the work related to building/maintaining that list of Demonstrations has simply been pushed somewhere else.
I'd like to do one of the following:
Loop through each class in the DLL of type CDemonstration, use its default constructor to initialize it, and add it to the vector.
Add a static virtual const Factory function to the base class, implement it in each subclass, and then loop through each of these Factory functions to get the instances to add to the vector.
This sounds a lot like Reflection and may not even be appropriate in general C++, but it would be really nice to somehow add new Demonstrations to the list simply by virtue of them having implemented CDemonstration, vs. building an explicit list of each Demonstration.
Thanks !
A:
If you have each derived class in a separate DLL you could:
Use filesystem APIs to create a list of DLLs in a specific folder
Load each of them and call an API that returns a handle to the specific menu objects.
Add the objects by using the base class pointer type (just ensure any specific behavior is implemented as a virtual method)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CS0120 error under vs2010 beta 2 - object reference is required
the following code used to work fine under vs2008:
namespace N2.Engine.Globalization
{
public class DictionaryScope : Scope
{
object previousValue;
public DictionaryScope(IDictionary dictionary, object key, object value)
: base(delegate
{
if (dictionary.Contains(key))
previousValue = dictionary[key];
dictionary[key] = value;
}, delegate
{
if (previousValue == null)
dictionary.Remove(key);
else
dictionary[key] = previousValue;
})
{
}
}
}
but now it reports An object reference is required for the non-static field, method, or property 'N2.Engine.Globalization.DictionaryScope.previousValue'
It seems something changed in the compiler? Any workarounds?
update:
regarding the suggestion to use a virtual method. This probably wouldn work either, as the virtual method would get called from the base constructor, which I believe is also not possible?
Here is the implementation of the Scope (base class):
public class Scope: IDisposable
{
Action end;
public Scope(Action begin, Action end)
{
begin();
this.end = end;
}
public void End()
{
end();
}
#region IDisposable Members
void IDisposable.Dispose()
{
End();
}
#endregion
A:
Update:
§ 7.5.7 This access
A this-access consists of the reserved word this.
this-access:
this
A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.
This is none of these. The 4.0 compiler looks to be correct. Presumably it isn't happy because this in essence provides access to this at a point when the type isn't initialized. Maybe ;-p
Note that I expect that it isn't really the this.someField that causes this - more that the use of a field causes this to be captured, meaning it wants to hoist the this instance onto a compiler-generated class - as though you had written:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
The C# 3.0 compiler spots the above abuse of this.
Reproduced. Investigating. It looks like an issue resolving the implicit this in the constructor chaining.
The most likely workaround would be to use a virtual method instead of a delegate, and simply override it in the derived class.
One workaround would be to pas the instance in as an argument, so the delegate becomes "obj => obj.whatever...", and use theDelegate(this);.
Simpler repro:
public class MyBase {
public MyBase(Action a) { }
}
public class MySub : MyBase {
private string foo;
// with "this.", says invalid use of "this"
// without "this.", says instance required
public MySub() : base(delegate { this.foo = "abc"; }) { }
}
I would need to check the spec, but I'm not sure whether this is valid in this context... so the 4.0 compiler could be correct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
File and Text data submission using JQuery Ajax with PHP on the server side.
I have looked into many posts on this subject so please do not mark it as duplicate as there are no straight answers provided. But if you truly believe that I may have missed something, which provides cross-browser support (IE8+ too) do indicate which one and then mark it as duplicate.
I want to use JQuery AJAX to post files and some text data and access that info in PHP on the server side using $_FILES and $_POST. I am able to do so without AJAX. The problem is when I start using AJAX.
Here is a simple example:
HTML:
<form id="upload_form" method="POST" enctype="multipart/form-data">
<input type="text"/>
<input type="file"/>
<button type="submit">Submit</button>
</form>
JAVASCRIPT:
var ser_data = $('#upload_form').serialize();
...on submit... {
...
upload_promise = $.ajax({
url: 'upload1.php',
dataType: 'html',
type: 'POST',
data: ser_data,
});
...
}
Well, we all know that .serialize will serialize only the text fields input and file is not readable by JS, etc. I am not trying to do anything fancy here. I just need a mechanism to access $_FILES and $_POST in PHP on the server side with the file name and the text data entered on the client side. The actual form has more fields (more file and text types) but this is the crux of the problem.
A:
To send files and post data trough ajax, you should use a FormData object.
https://developer.mozilla.org/docs/XMLHttpRequest/FormData
var fd = new FormData();
var myFileInput = $(" ... "); //adapt to access your file input
var files = myFileInput[0].files ;
// The loop is there to handle file inputs with multiple files
for(var i = 0, c = files.length ; i<c ; i++){
var blob = new Blob(files[i]);
var fileAccessName = "myFiles_"+i ;
fd.append(fileAccessName, blob, files[i].name);
}
// You can also send simple data along your files
fd.append('otherData', $("...").val());
$.ajax({
url: ... , //the form's target
data: fd,
processData: false,
type: 'POST',
success: function(rep){
// ...
}
}
// since we are sending the form trough jQuery, you should also add a ev.preventDefault() to your .submit(function(ev){}) callback
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$\gcd(X^n - 1, nX^{n-1}) = 1$ in a field $K$ of characteristic $0$ or characteristic $p \nmid n$.
Why is $\gcd(X^n - 1, nX^{n-1}) = 1$ in a field $K$ of characteristic $0$ or characteristic $p \nmid n$.
Most book on abstract algebra don't prove explicitly this, but I wonder what technique I should use to prove this to be formal. Perhaps induction?
A:
Recall that the polynomial ring over a field is a principal ideal domain, hence it has unique factorization.
If $n=1$ the statement is trivial, so suppose $n>1$.
In a field of characteristic zero or $p\nmid n$ the polynomial $nX^{n-1}$ has degree $n-1$ and the only irreducible polynomial that divides $nX^{n-1}$ is $X$. Since $X$ doesn't divide $X^n-1$, we're done.
A different way is to observe that $n$ can be removed, because it's a nonzero constant. Since
$$
X^n-1=X\cdot X^{n-1}-1
$$
you're done using the Euclidean algorithm.
By the way, if the characteristic $p$ divides $n$, then $nX^{n-1}=0$ and the greatest common divisor is $X^{n-1}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error running Gulpfile from Visual Studio 2015 task runner
I am building a gulpfile to use in my aps.net winforms project. So far I have the following in the package.json
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"browserify": "^13.1.0",
"del": "2.2.0",
"gulp": "^3.9.1",
"gulp-sourcemaps": "^2.2.0",
"gulp-typescript": "^3.0.2",
"tsify": "^2.0.2",
"vinyl-source-stream": "^1.1.0"
}
}
and the gulp file has
/// <binding BeforeBuild='default' />
/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require('gulp');
var del = require('del');
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
var sourcemaps = require('gulp-sourcemaps');
gulp.task('default', function () {
// place code for your default task here
});
My node version is 6.9.1
If I run this from the command line ('gulp') it works fine. But in the Visual Studio task runner, it fails to load, and in the out put I see the following error. This error starts after I add the line var sourcemaps = require('gulp-sourcemaps');
Failed to run "H:\dev\myproj\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
H:\dev\myproj\node_modules\gulp-sourcemaps\node_modules\strip-bom\index.js:2
module.exports = x => {
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (H:\dev\myproj\node_modules\gulp-sourcemaps\src\init.js:10:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Also adding var tsify = require("tsify"); I get another error...
Failed to run "H:\dev\myproject\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
TypeError: Object #<Object> has no method 'debuglog'
at Object.<anonymous> (H:\dev\myproject\node_modules\tsify\index.js:4:32)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (H:\dev\myproject\gulpfile.js:17:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Anyone have any ideas why I am getting this?
Thanks in advance!
A:
My problem was I didn't realize Visual Studio has it's own (way out of date) version of the node tools (installed within the Visual Studio folders somewhere). How untidy!
To make it use the "global" node tools, I could go to the menu Tools | Options | Projects and Solutions | External Web Tools and move the $(PATH) to be before the $(DevEnvDir)\* locations. After I did this, my Gulp file would load.
The other option may have been to update the Visual Studio node tools via the Tools | Extensions and Updates, but (I think) I'd prefer to use the same external tools I will use outside of Visual Studio.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make line break inside bootstrap progress bar in case, if text is wider than a div?
By default progress bar shows text just inside the part which has some progress (if progress is 25%, the text can be shown just withing this 1/4 part). This can be fixed by white-space: nowrap;
How can be fixed the case without using js, when text is longer than div, ie how to apply something like height: auto in order to move some part of text to a new line?
.my-case {
width: 100px;
background-color: black !important;
}
.fix {
white-space: nowrap;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
By default
<div class="progress" style="width:100px">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">Some very very long text</div>
</div>
My case
<div class="progress my-case">
<div class="progress-bar fix" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">Some very very long text</div>
</div>
A:
The .progress-bar should be made position: absolute with height: 100%; inside a position:relative parent (our .progress) with auto height - in order to let the inner text/content dictate it's height.
The text should be than moved inside a separate element like i.e: .progress-label
.progress {
position:relative; /* add! */
width: 100px;
background-color: black !important;
height: auto !important; /* add! (let text dictate height! ) */
}
.progress-bar { /* Added styles */
position: absolute;
height: 100%;
}
.progress-label { /* added element and CSS */
position: relative;
color: #fff;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
<span class="progress-label">Some very very long text</span>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running multiple custom packages from Weka command line
I'm running WEKA from the unix command line. I want to encase an alternating decision tree (ADTree) within a Rotation Forest, two packages that are not part of the standard Weka 3.7 package.
Per http://weka.wikispaces.com/How+do+I+use+the+package+manager%3F, I understand that to call non-standard packages, (after first loading them using the package manager) I should envoke the weka.Run command. If I want to envoke ADTree, on the labor dataset that comes with Weka, I can do so with the following code:
java -cp weka/weka.jar weka.Run ADTree -t weka/data/labor.arff
Similarly, if I want to envoke a Rotation Forest, this code works:
java -cp weka/weka.jar weka.Run RotationForest -t weka/data/labor.arff
However, I'm not sure how to wrap the two algorithms together.
I can, say, wrap J48 in RotationForest:
java -cp weka/weka.jar weka.Run RotationForest -t weka/data/labor.arff -W weka.classifiers.trees.J48
But I'm not sure how to call ADTree after calling Rotation Forest. Neither of the following work:
java -cp weka/weka.jar weka.Run RotationForest -t weka/data/labor.arff weka.Run ADTree
java -cp weka/weka.jar weka.Run RotationForest -t weka/data/labor.arff -W weka.Run ADTree
java -cp weka/weka.jar weka.Run RotationForest -t weka/data/labor.arff -W weka.classifiers.trees.ADTree
Can someone please point out what I'm doing wrong?
A:
Sheepishly, I continued my Googling and found the solution here: http://forums.pentaho.com/showthread.php?152334-WEKA-RotationForest-by-comman-line-is-not-working!
Basically, I needed to start my syntax with:
java -cp wekafiles/packages/alternatingDecisionTrees/alternatingDecisionTrees.jar:wekafiles/packages/rotationForest/rotationForest.jar:weka/weka.jar
or
java -cp [path-to-package_1] : [path-to-package_2] : [path-to-weka.jar]
Then, I can envoke weka.classifiers.meta.rotationForest and weka.classifiers.trees.ADTree and go forward:
java -cp wekafiles/packages/alternatingDecisionTrees/alternatingDecisionTrees.jar:wekafiles/packages/rotationForest/rotationForest.jar:weka/weka.jar weka.classifiers.meta.rotationForest -t weka/data/labor.arff -W weka.classifiers.trees.ADTree
I'll leave this post open in case someone else might find it helpful.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use return value from function returning Future(Either[A, B]) in scala?
I have the below function.
def get(id: Int): Future[Either[String, Item]] = {
request(RequestBuilding.Get(s"/log/$id")).flatMap { response =>
response.status match {
case OK => Unmarshal(response.entity).to[Item].map(Right(_))
case BadRequest => Future.successful(Left(s"Bad Request"))
case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
val error = s"Request failed with status code ${response.status} and entity $entity"
Future.failed(new IOException(error))
}
}
}
}
I am trying to call this function but I am not sure how to know whether it is returning a String or Item. Below is my failed attempt.
Client.get(1).onComplete { result =>
result match {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
}
A:
onComplete takes a function of type Try so you would have to double match on Try and in case of success on Either
Client.get(1).onComplete {
case Success(either) => either match {
case Left(int) => int
case Right(string) => string
}
case Failure(f) => f
}
much easier though would be to map the future:
Client.get(1).map {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
and in case you want to handle the Failure part of onComplete use a recover or recoverWith after mapping on the future.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are big corporations the biggest beneficiaries from farming subsidies?
I've heard that big companies are the biggest beneficiaries of agricultural subsidies (in the US and other western countries). This would to me seem to be the opposite of the intention of those policies, and I'd like to know how true this statistic is.
A:
I'm unsure of where to find this for other countries, but I was able to find THIS report from the Government Accountability Office. The report may be a bit dated (2001, so 10 years old), but in looking through the first part alone, I see nothing but tables and charts showing that big farms receive more subsidy payments than medium or small farms.
Skimming aside, the report quite clearly states:
...the 7 percent of farms nationwide with gross agricultural sales of $250,000 or more— received about 45 percent of the payments.
As Lennart pointed out though, larger farms are, by definition, producing more crops. Subsidies (unsure of units, but say payed per volume or weight), therefore, would be paid in higher proportion to those producing more goods.
I did find the chart below, which suggests that small farms may actually be getting more payments per value of their establishments compared to large farms:
This bit preceded that table:
For example in 1999, large farms received 45 percent of the payments, while accounting for
46 percent of the planted acreage and 52 percent of the value of production of the eligible crops. Small farms received 14 percent of the payments and accounted for 10 percent of planted acreage and 8 percent of the value of production.
I was actually curious about this, wondering if large farms received a proportional payment per volume of crop compared to small farms. It seems that they actually receive less by value than small farms!
The report does give some explanations for the smaller payments to smaller farms, one being the obvious one already mentioned that larger farms produce more product. Another, however, was based on the type of goods typically produced by the farm sizes:
...beef is not one of the commodities for which farm payments are generally made. According to the Economic Research Service officials, beef is the primary commodity of about 40 percent of small farms, compared to 20 percent of medium farms and 10 percent of large ones.
So, small farms are substantially more targeted toward a non-subsidized product compared to their larger counterparts, and thus aren't receiving subsidies for those goods.
It would be great to see more current data on this topic, as the intro to the report states (addressed to the Chairman of the Committee on Agriculture at the time):
Dear Mr. Chairman,
...Concerned that farm payments are not being effectively targeted to aid the
survival of small farms and the entry of young people into agriculture, you
asked us to (1) determine the distribution of farm payments over the past
decade by farm size, operators’ age, state, and crop and (2) identify the
major barriers that make it difficult for young people to enter farming.
This leaves me wondering what the results were -- were the findings that the situation at the time was fair, or was action taken to rectify anything, have payment distributions changed much in 10 years, etc.? If I find answers to these questions, I'll update the answer to include them!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Serialized Data
I'm trying to add data to a serialized string -
I get the serialized string from my database - e.g. a:1:{i:0;s:2:"32";}
Unserialize it
add a value to it e.g. 128
serialize it and save it back
But I get
s:33:"a:2:{i:0;s:2:"64";i:1;s:3:"128";}";
Where did the s:33 come into it and surrounded the rest in quotes and ends with a semi colon?
function addItem($serializedArray, $item)
{
$a = unserialize($serializedArray);
$a[] = $item;
return serialize($a);
}
$lp = $wpdb->get_results( $wpdb->prepare("Select MemNo from YP_Members Limit 0, 10") );
foreach ($lp as $userid){
$user_id = $userid->MemNo;
$meta_value = $wpdb->get_var( $wpdb->prepare("Select meta_value from iropiusermeta Where meta_key = 'user_iro_area' AND user_id = $user_id") );
echo "User=".$user_id."<br />Value=".$meta_value."<br />";
if ($meta_value){
$user_iro_area = addItem($meta_value, "128");
update_user_meta($user_id, 'user_iro_area_new', $user_iro_area);
} else {
// Add meta_key user_iro_area
echo "<b>Add New Me</b><br />";
$iro_group_num[] = "128";
$user_iro_area = serialize($iro_group_num);
update_user_meta($user_id, 'user_iro_area_new', $user_iro_area);
}
} // End of Main While Loop
A:
your meta value is getting serialized twice, you should pass update_user_meta an array, not a serialized string. and while you're at it, get the user meta via get_user_meta and you won't have to think about serialization at all, WordPress handles all that behind the scenes if you stick to the API.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"has to be" or "is to be"
What is the difference between "has to be" and "is to be"?
This is the example sentence:
In case a diarization is desired, a proper XYZ algorithm is/has to be used.
I would like to point out, that my personal opinion is using the XYZ algorithm.
A:
"Is to be used" is grammatically acceptable but stylistically weak. Better to stick to one of these:
"has to do": it is required (Sometimes people use this hyperbolically: "I have to go to the movies, all my friends are."). In a technical setting like you allude to, this often means something that fundamental to the project blows up if you don't: CEO goes to jail, client withdraws funding, people get fired, etc. It is usually too strong to use it for an alternative implementation that is merely a mistake.
"should do": there are other valid alternatives, but it has been decided that this is the best one
"will do": this usually is reserved for a future certainty: "It will be February soon," "It will be night in 4 hours," "The sun will rise tomorrow," etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
awk file manipulation
I have the following words on my text file and I want extract as follow.
device1 te rfe3 -1 10.1.2.3 device1 te rfe3
device2 cdr thr 10.2.5.3 device2 cdr thr
device4 10.6.0.8 device4
device3 hrdnsrc dhe 10.8.3.6 device3 hrdnsrc dhe
my objective is to extract the device name and the ip adrress everything else to strip away.
the is no pattern after device name some of them has 2-3 word some of them does not have any thing. also I don't need the 3rd column. I am looking the result like this.
device1 10.1.2.3
device2 10.2.5.3
device3 10.8.3.6
device3 10.8.9.4
is this possible? Thanks in advance.
A:
In awk, this is something like
$ awk '{
for (f = 2; f <= NF; f++) {
if ($f ~ /^([0-9]+\.){3}[0-9]+$/) {
print $1, $f
break
}
}
}' file
Here's a transcript:
mress:10192 Z$ cat pffft.awk
{
for (f = 2; f <= NF; f++) {
if ($f ~ /^([0-9]+\.){3}[0-9]+$/) {
print $1, $f
break
}
}
}
mress:10193 Z$ cat pfft.in
device1 te rfe3 -1 10.1.2.3 device1 te rfe3
device2 cdr thr 10.2.5.3 device2 cdr thr
device4 10.6.0.8 device4
device3 hrdnsrc dhe 10.8.3.6 device3 hrdnsrc dhe
mress:10194 Z$ awk -f pffft.awk pfft.in
device1 10.1.2.3
device2 10.2.5.3
device4 10.6.0.8
device3 10.8.3.6
mress:10195 Z$ _
A:
in perl
perl -ne 'next if /^\s*$/ ; /^(\w+).*?(\d+(\.\d+){3})/; print "$1\t$2\n"' test_file
for sorted results you could probably pipe the output to sort command
perl -ne 'next if /^\s*$/ ; /^(\w+).*?(\d+(\.\d+){3})/; print "$1\t$2\n"' test_file | sort
Updated script like version
my $test_file = shift or die "no input file provided\n";
# open a filehandle to your test file
open my $fh, '<', $test_file or die "could not open $test_file: $!\n";
while (<$fh>) {
# ignore the blank lines
next if /^\s*$/;
# regex matching
/ # regex starts
^ # beginning of the string
(\w+) # store the first word in $1
\s+ # followed by a space
.*? # match anything but don't be greedy until...
(\d+(\.\d+){3}) # expands to (\d+\.\d+\.\d+\.\d+) and stored in $2
/x; # regex ends
# print first and second match
print "$1\t$2\n"
}
A:
sed -r 's/^([^ ]*) .* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1 \2/'
Proof of Concept
$ sed -r 's/^([^ ]*) .* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1 \2/' ./infile
device1 10.1.2.3
device2 10.2.5.3
device4 10.6.0.8
device3 10.8.3.6
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I prevent getting a routing error while trying to access a href
I have href rendered as "www.yahoo.com", but when the user clicks on it instead of re-directing to http://www.yahoo.com the page says Route not found error. How do I fix this?
A:
try this:
<%= link_to "Click Me", "http://www.yahoo.com" %>
it's need to put http:// before address.
Updated (according to your comment)
ok then just do this:
let,
@url = "www.yahoo.com"
now,
<%= link_to "Click Me", "http://#{@url}" %>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
For [single-word-requests], should we encourage "there is no such word" as an answer?
With single-word-requests, quite often the decisive, true, and most useful answer (most useful: for the OP, for 100,000 years of future googlers, etc) is simply that "hmm, there is in English no single-word for that concept".
{Note that single-word-requests come in two exceedingly distinct flavours: an English-learner who is trying to get at a word, and, an English-expert who has a word on the tip of their, uh, fingers and is needing The Gang to try to ah-hah the word. Interestingly, in both cases, the "does not exist" answer is extremely useful and clear and good.}
I guess, it's not worth some technological solution (so, in the case of single-word-requests flagged questions, there'd be a special button concept where you could set the answer as "no such word"...) ... I think I just mean basically, should The Community move socially towards "does not exist" as a typical (I'll say .. 25% of cases) Thing that you can and should post (where relevant) on single-word-requests QAs. (So, a social norm, exactly like "you should add references," say.)
Note too that once "does not exist" is on the table and accepted by all: it's then more possible / more clearcut to have a free-for-all of other sentence/etc suggestions in the comments.
It's slightly/very annoying that "does not exist" is rather — not so much avoided, but it's not embraced on single-word-requests --- proposal: embrace it.
A:
Sure.
Sometimes there really isn't the exact word for a given description. There have been thousands of years of language work, in stories and technology, where people have created the refined vocabulary of the world's languages. But just as the Cro-magnon (probably) didn't have words for 'vacation' or 'stirrup' (certainly they could understand and describe those concepts), we (all the world's languages) have quite a few similarly complicated concepts for which we have no single word.
However, as a student of a foreign language or someone rising through an academic career, one is getting acclimated to the more rarefied areas of concepts, where most people don't go often, but those who go there need to save space and time and thought by using abbreviations of descriptions that collapse into single words. Then there is the tendency to believe that there will always be a single word for a complex description, because every time they look beyond the horizon of what they know already, there is a new word for a new concept.
This is all to support your assumption that there truly are situations where there is no single word for a description.
Now to your point, 3) should we 2) encourage 1) giving 'no such word exists' as an answer?
We've justified that sometimes that 'no such word exists' is the case. But that is only sometimes. Other times it is a matter of tip-of-the-tongue or memory or lack of experience or rarity or obsolescence or lexical gaps (no one 'designs' a language systematically from scratch and so some slots just happen not to be filled, sometimes even when there is a need).
This meta question is encouragement enough. Asking the leading question "What is the single word for ...?" implies that there must be one, when there isn't. Suggesting in comments or editing the question to "Is there...?" is enough.
What you should always do is answer knowledgeably. A bald answer like "No, there is none." is a terrible answer. A positive answer of a single word is also terrible but there is some hope in being able to look it up in a dictionary. With "no", you have to explain that absence of word is, in this case, by much experience (which is not very justifiable by authority), evidence of the true lack of the word. (A systematic proof of the lack would have to be a laborious comprehensive listing of 'all' words and for each one justifying that they don't match the concept.)
So in the end, sure, for a single word, if you can justify with some knowledge that there is no such word (hopefully with a good thesaurus that gives the small neighborhood of related concepts where you can say "in this neighborhood there is no such word that matches exactly what is sought"), then yes, answer that way.
Even though such an answer may be correct, it will most likely not be a high scorer; no one like a negative answer even if correct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP file read not working
On a server I have the file some.php. I try to read the contents using file_get_content and fread. Both these don't read my content.
If I try some other URL like yahoo.com, these functions are reading the contents. Why does this happen?
$my_conetn = file_get_contents("http://example.com");
echo $my_conetn;
The above snippet is not working.
$handle = fopen($filename, "r");
$contents = fread($handle, 20);
echo $contents;
fclose($handle);
Also the above snippet is not working.
How to check my server? Is there any file read operation locked or not?
edit: I am not sure, but it is only my server file that can't be read. I can read the other server links. So I contact my hosting provider, then I get back to you guys/gals.
A:
When using file functions to access remote files (paths starting with http:// and similar protocols) it only works if the php.ini setting allow_url_fopen is enabled.
Additionally, you have no influence on the request sent. Using CURL is suggested when dealing with remote files.
If it's a local file, ensure that you have access to the file - you can check that with is_readable($filename) - and that it's within your open_basedir restriction if one is set (usually to your document root in shared hosting environments).
Additionally, enable errors when debugging problems:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WPF Binding with Notifyi does not update UI
My issue is that UI is not updated even when PropertyChanged is fired.
XAML:
<ListBox Name="BookShelf" Visibility="Hidden" SelectedItem="{Binding SelectedItem}" Panel.ZIndex="1" Height="Auto" Grid.Column="3" Margin="8,50,0,0" HorizontalAlignment="Center" ItemsSource="{Binding BookShelf}" Background="Transparent" Foreground="Transparent" BorderThickness="0" BorderBrush="#00000000">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center" Orientation="Vertical">
<TextBlock FontSize="14" Margin="0,10,0,0" FontWeight="Bold" Foreground="Black" HorizontalAlignment="Center" Text="{Binding Path=DbId}" />
<TextBlock FontSize="16" FontWeight="Bold" Width="170" TextWrapping="Wrap" Foreground="Black" Margin="5" HorizontalAlignment="Center" Text="{Binding Path=DisplayName}" />
<Image HorizontalAlignment="Center" Source="{Binding Path=bookImage}" Width="200" Height="200" Margin="0,0,0,10" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And:
<ComboBox Margin="8,15,0,0" Name="bookShelf_ComboBox" ItemsSource="{Binding BookShelf}" SelectedItem="{Binding SelectedItem}" VerticalAlignment="Center" HorizontalAlignment="Center" DisplayMemberPath="DisplayName" Height="22" Width="140" Visibility="Visible" SelectionChanged="bookShelf_ComboBox_SelectionChanged"/>
Viewmodel:
public class BookShelfViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event ShowContentInBrowser ShowDatabaseContent;
public BookShelfViewModel(ShowContentInBrowser showMethod)
{
ShowDatabaseContent += showMethod;
}
private ObservableCollection<DbInfo> _BookShelf = new ObservableCollection<DbInfo>();
public ObservableCollection<DbInfo> BookShelf
{
get
{
if (_BookShelf == null)
_BookShelf = new ObservableCollection<DbInfo>();
return _BookShelf;
}
set
{
if (value != _BookShelf)
_BookShelf = value;
}
}
private DbInfo _selectedItem { get; set; }
public DbInfo SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem != value)
{
_selectedItem = value;
RaisePropertyChanged(new PropertyChangedEventArgs("SelectedItem"));
if (_selectedItem == null)
return;
if (_selectedItem.RelatedId != null)
ShowDatabaseContent(_selectedItem, _selectedItem.RelatedId);
else
ShowDatabaseContent(_selectedItem, _selectedItem.RelatedId);
}
}
}
public void RaisePropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
}
This code I'm using is for setting DataContext and SelectedItem:
await System.Windows.Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(
() => this.BookShelf.SelectedItem = dbInfo
)
);
And DataContext:
await System.Windows.Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(
() => this.BookShelf.DataContext = bookShelfViewModel
)
);
I'm very new for this MVVM design and as far as I have can tell from articles I have read, I cant find what's wrong. I'm guessing that using Dispatcher is not necessary but I don't think it matters in this case...
ListBox does show my objects but updating SelectedItem is the issue here...
UPDATE:
Heres my code for DbInfo:
public class DbInfo
{
public int RelatedId { get; set; }
public string DbId { get; set; }
public TBase3.Article currentArticle { get; set; }
public string LinkId { get; set; }
public bool IsArticle { get; set; }
public string folder { get; set; }
public bool IsNamedArticle { get; set; }
public int currentBlockIndex { get; set; }
public int currentBlockCount { get; set; }
public string DisplayName { get; set; }
public int VScrollPos { get; set; }
public int THTextVersion { get; set; }
public bool isHtmlToc { get; set; }
public ImageSource bookImage { get; set; }
}
Reminder that when ever I set new value for ViewModel -> SelectedItem and It goes to PropertyChanged(this, e); line. It does not Selected that DbInfo as Selected in ListBox.
Update2:
I got right side of my window a list of books, like a Book Shelf many books in it.
It shows all book with scroll. Book which is selected its content is being shown in window.
But If for reason I want to change to another book from code-behind, it updates it content to webbrowser but not update ListBox that certain book as SelectedItem
ANSWER:
Okay I found the answer right now. Code which set BookShelf.SelectedItem = dbInfo should be bookShelfViewModel.SelectedItem = bookShelfViewModel.BookShelf.First(x => x.DbId == dbInfo.DbIf);
A:
Okay I found the answer right now. Code which set BookShelf.SelectedItem = dbInfo should be bookShelfViewModel.SelectedItem = bookShelfViewModel.BookShelf.First(x => x.DbId == dbInfo.DbIf);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
#1064 - You have an error in your SQL syntax;
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a','a','a','a','a','desc')' at line 1
my query is
mysql_query("insert into
room_booking(name,address,type,roomNo,arrival,arrivaldate,departure,
departuredate,identity,email,adult,children,contact,
extraroom,laundry,parking,spa,tennis,swimming,description)
values('$nm','$add','$typ','$roomno','$arrv','$arrivaldate',
'$departure','$dDate','$idt','$emailid','$adul','$child',
'$cont','$extra,'100','100','100','100','100','$desc')");
A:
you are missing "'" in '$extra, it is a simple error just see your syntax
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NSDate day of the year (swift)
How might the day number of the year be found with swift? Is there a simple way that I'm not seeing, or do I have to find the number of seconds from Jan 1 to the current date and divide by the number of seconds in a day?
A:
This is a translation of the answer to How do you calculate the day of the year for a specific date in Objective-C? to Swift.
Swift 2:
let date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
print(day)
Swift 3:
let date = Date() // now
let cal = Calendar.current
let day = cal.ordinality(of: .day, in: .year, for: date)
print(day)
This gives 1 for the first day in the year, and 56 = 31 + 25 for today (Feb 25).
... or do I have to find the number of seconds from Jan 1 to the current date
and divide by the number of seconds in a day
This would be a wrong approach, because a day does not have a fixed
number of seconds (transition from or to Daylight Saving Time).
A:
Swift 3
extension Date {
var dayOfYear: Int {
return Calendar.current.ordinality(of: .day, in: .year, for: self)!
}
}
use like
Date().dayOfYear
A:
Not at all !!! All you have to do is to use NSCalendar to help you do your calendar calculations as follow:
let firstDayOfTheYear = NSCalendar.currentCalendar().dateWithEra(1, year: NSCalendar.currentCalendar().component(.CalendarUnitYear, fromDate: NSDate()), month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)! // "Jan 1, 2015, 12:00 AM"
let daysFromJanFirst = NSCalendar.currentCalendar().components(.CalendarUnitDay, fromDate: firstDayOfTheYear, toDate: NSDate(), options: nil).day // 55
let secondsFromJanFirst = NSCalendar.currentCalendar().components(.CalendarUnitSecond, fromDate: firstDayOfTheYear, toDate: NSDate(), options: nil).second // 4,770,357
|
{
"pile_set_name": "StackExchange"
}
|
Q:
extjs: Changing the value of a node
I'm sure this is really simple, but i can't seem to find it anywhere!
All I am trying to do is change the displayed value of a tree node. I thought that tree.getNodeById(myNode).text='HHHHH'; or tree.getNodeById(myNode).value='HHHHH'; would do the trick, but i get nothing. What am i missing?
Thanks
Craig
A:
It's:
tree.getNodeById(myNode).setText('HHHHH');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Model already has an element" errors (TSD04105) when using Visual Studio 2008 Database Project GDR2
I am using Visual Studio 2008 Database Project GDR2 to manage multiple databases and I am getting a number of errors related to synonyms.
Project-A has a reference to Project-B because Project-A has a number of synonyms to tables in Project-B. The full error I'm getting is "TSD04105: The model already has an element that has the same name dbo.[OBJECT]". This always points at the synonym.
The issue seems to be that the synonym on Project-A has the same name as the table on Project-B. Obviously I could rename all my synonyms so that they have different names than the tables, but this introduces a LOT of work on my part (there's over 140 synonyms so far).
Removing the reference to Project-B will get rid of that error, but instead all of my stored procedures in Project-A generate errors because it can't reference the tables in Project-B any more.
Is there a way to fix this problem short of renaming all the synonyms? What is the appropriate way to handle this situation in the Database Project?
A:
I had this issue between a 2008 server project and a database project and I solved it by using a literal Database Variable Value.
Referencing project properties -> References Tab -> Database Variable Value
I would say that you could also use a Database Variable Name/Value pair as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Validating fields that aren't in the model/controller in Rails
I'm a relative newbie at Rails, so forgive me if my question's got an obvious answer.
I'm trying to include a field in a Rails form which isn't in the model/controller or the migration associated with the view.
The form is a simple public contact form, and I can validate against most of the fields easily enough. Eg name, email etc.
The model is form_submission.rb
However, I have a field in the contact form - captcha - which isn't mirrored in the form_submissions db table, etc.
There is a separate table, model etc for captcha which is captcha_answer.rb (etc)
The attributes for captcha_answer in the migration are: answer and is_correct.
The table simple contains a list of answers to a predefined question, some of which are true and some which are false.
Eg, the captcha question might be:
Which is these is an animal?
With the options of: cat, dog, tree, rabbit .. in a select.
What I want to be able to do is to validate that:
a) The captcha field exists in the POST (return message of "no captcha given" if not)
b) The answer given has a value in captcha_answers.is_correct of true (return message of "you gave a wrong answer" if not)
The capcha_answers.answer is always unique, so I want to do the equivalent of a SQL query which gets the first record where captcha_answers.answer = and returns the value of captcha_answers.is_correct
Like I say, if the attribute was in form_submissions then I'd be able to validate it no problem, but I can't figure out how I can validate a field against something in another model.
Any ideas?
A:
Define accessors for the extra field and use usual ActiveRecord validations:
class MyModel < ActiveRecord::Base
attr_accessor :extra_field
validates :extra_field, :presence => true
validate :custom_validation_method
def custom_validation_method
errors.add :extra_field, :invalid unless extra_field == "correct"
end
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading hyperlinks from pdf file
I'm trying to read a pdf file and get all hyperlinks from this file.
I'm using iTextSharp for C# .net.
PdfReader reader = new PdfReader("test.pdf");
List<PdfAnnotation.PdfImportedLink> list = reader.GetLinks(36);
This method "GetLinks" return a list with a lot of information about the links, but this method does not return the value that I want, the hyperlink string and I exactly know that there are hyperlinks in 36th page
A:
PdfReader.GetLinks() is only meant to be used with links internal to the document, not external hyperlinks. Why? I don't know.
The code below is based off of code I wrote earlier but I've limited it to links stored in the PDF as a PdfName.URI. Its possible to store the link as Javascript that ultimately does the same thing and there's probably other types but you'll need to detect for that. I don't believe there's anything in the spec that says that a link actually needs to be a URI, its just implied, so the code below returns a string that you can (probably) convert to a URI on your own.
private static List<string> GetPdfLinks(string file, int page)
{
//Open our reader
PdfReader R = new PdfReader(file);
//Get the current page
PdfDictionary PageDictionary = R.GetPageN(page);
//Get all of the annotations for the current page
PdfArray Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
//Make sure we have something
if ((Annots == null) || (Annots.Length == 0))
return null;
List<string> Ret = new List<string>();
//Loop through each annotation
foreach (PdfObject A in Annots.ArrayList)
{
//Convert the itext-specific object as a generic PDF object
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(A);
//Make sure this annotation has a link
if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK))
continue;
//Make sure this annotation has an ACTION
if (AnnotationDictionary.Get(PdfName.A) == null)
continue;
//Get the ACTION for the current annotation
PdfDictionary AnnotationAction = (PdfDictionary)AnnotationDictionary.Get(PdfName.A);
//Test if it is a URI action (There are tons of other types of actions, some of which might mimic URI, such as JavaScript, but those need to be handled seperately)
if (AnnotationAction.Get(PdfName.S).Equals(PdfName.URI))
{
PdfString Destination = AnnotationAction.GetAsString(PdfName.URI);
if (Destination != null)
Ret.Add(Destination.ToString());
}
}
return Ret;
}
And call it:
string myfile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
List<string> Links = GetPdfLinks(myfile, 1);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to have a optparse-applicative option with several parameters?
I just found out that my carefully crafted parser fails to parse any string I throw at it:
roi :: Parser (Maybe ROI)
roi = optional $ option (ROI <$> auto <*> auto <*> auto <*> auto)
$ long "roi" <> metavar "ROI" <> help "Only process selected region of interest"
where ROI = ROI Int Int Int Int
If that is important, it is nested in a higher parser
options :: Parser Opts
options = Opts <$> input <*> output <*> roi <*> startT <*> endT
where Opts is an appropriate ADT.
Now I assumed that the roi parser will parse expressions such as --roi 1 2 3 4 but it fails with Invalid argument '128' and giving me usage message.
--roi 1 instead parses but returns Just (ROI 1 1 1 1)
Is there a way to make this work?
A:
I don't think options are supposed to consume multiple arguments. At least I'm not sure how you'd go about implementing that. I'd suggest simply going away from that idea and putting your ROI options into a single argument, using syntax like --roi 1,2,3,4.
You'd simply have to implement a custom reader for that, here's an example of how you could do that:
module Main where
import Options.Applicative
data ROI = ROI Int Int Int Int
deriving Show
-- didn't remember what this function was called, don't use this
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn sep (x:xs) | sep==x = [] : splitOn sep xs
| otherwise = let (xs':xss) = splitOn sep xs in (x:xs'):xss
splitOn _ [] = [[]]
roiReader :: ReadM ROI
roiReader = do
o <- str
-- no error checking, don't actually do this
let [a,b,c,d] = map read $ splitOn ',' o
return $ ROI a b c d
roiParser :: Parser ROI
roiParser = option roiReader (long "roi")
main :: IO ()
main = execParser opts >>= print where
opts = info (helper <*> roiParser) fullDesc
A:
The type of option is:
option :: ReadM a -> Mod OptionFields a -> Parser a
ReadM, in turn, is "A newtype over 'ReaderT String Except', used by option readers". Since option is using ReaderT under the hood, when you use it with the Applicative instance of ReadM like you did here...
ROI <$> auto <*> auto <*> auto <*> auto
... the same, and whole, input string is supplied to each of the four auto parsers, because that's how the reader/function applicative instances work.
If you want values separated by spaces to be parsed into a single ROI, you need to write a custom parser. Here is a not particularly tidy attempt at that, built around eitherReader. Note that this will require the values to be within quotation marks (--roi "1 2 3 4"), so that they are taken in as a single string. Cubic's answer suggests an alternative approach, which uses comma-separated values instead (--roi 1,2,3,4).
import Text.Read (readEither)
-- etc.
roi :: Parser (Maybe ROI)
roi = optional
$ option (eitherReader $ \inp -> case traverse readEither (words inp) of
Right [x, y, z, w] -> Right (ROI x y z w)
Right _ -> Left "ROI requires exactly 4 values"
Left _ -> Left "ROI requires integer values")
$ long "roi" <> metavar "ROI" <> help "Only process selected region of interest"
Success and failure modes:
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 3 4"]
Success (Just (ROI 1 2 3 4))
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 3"]
Failure (ParserFailure (option --roi: ROI requires exactly 4 values
Usage: <program> [--roi ROI],ExitFailure 1,80))
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 foo 4"]
Failure (ParserFailure (option --roi: ROI requires integer values
Usage: <program> [--roi ROI],ExitFailure 1,80))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
closing a connection with twisted
Various connections - e.g. those created with twisted.web.client.getPage() seem to leak - they hang around indefinitely, since the OS time-out is measured in hours - if the server doesn't respond timely. And putting a time-out on the deferred you get back is deprecated.
How can you track the requests you have open, and close them forcefully in your twisted program?
(Forcefully closing connections that have timed-out in application logic is important to making a twisted server that scales; various reactors have different limits on the number of open file descriptors they allow - select being as low as 1024! So please help twisted users keep the open connections count nice and trimmed.)
A:
getPage accepts a timeout parameter. If you pass a value for it and the response is not fully received within that number of seconds, the connection will be closed and the Deferred returned by getPage will errback.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading config with .NET Core and Microsoft.Extensions.Configuration
In trying to read configuration in a .Net Core 2.0 project from multiple providers, I am not getting the desired result.
I added the following NuGet packages to a stock .Net Core C# project to read the config. Both installed version 2.0.2.
Install-Package Microsoft.Extensions.Configuration.Binder
Install-Package Microsoft.Extensions.Configuration.Json
This is the code to demonstrate the problem.
class Program
{
static void Main(string[] args)
{
var InMemoryValue = new Dictionary<string, string>()
{
["Configuration.Test1"] = "IndexerValue1",
["Configuration.Test2"] = "IndexerValue2",
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.AddInMemoryCollection(InMemoryValue)
.AddJsonFile("Config.json")
;
var configuration = configurationBuilder.Build();
Console.WriteLine("Indexer");
Console.WriteLine($" Test1:{configuration["Configuration.Test1"]}");
Console.WriteLine($" Test2:{configuration["Configuration.Test2"]}");
Console.WriteLine($" Test3:{configuration["Configuration.Test3"]}");
var getConfig = configuration.Get<Configuration>();
Console.WriteLine("Get");
Console.WriteLine($" Test1:{getConfig.Test1}");
Console.WriteLine($" Test2:{getConfig.Test2}");
Console.WriteLine($" Test3:{getConfig.Test3}");
var bindConfig = new Configuration();
configuration.GetSection("Configuration").Bind(bindConfig);
Console.WriteLine("Bind");
Console.WriteLine($" Test1:{bindConfig.Test1}");
Console.WriteLine($" Test2:{bindConfig.Test2}");
Console.WriteLine($" Test3:{bindConfig.Test3}");
Console.Write("Press [Enter] to end.");
Console.Read();
}
private class Configuration
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public string Test3 { get; set; }
}
}
Here is the contents of the Config.json file.
{
"Configuration": {
"Test1": "JsonValue1",
"Test3": "JsonValue3"
}
}
And lastly, here is the output.
Indexer
Test1:IndexerValue1
Test2:IndexerValue2
Test3:
Get
Test1:
Test2:
Test3:
Bind
Test1:JsonValue1
Test2:
Test3:JsonValue3
Press [Enter] to end.
As I understand it, I believe I should get JsonValue1, IndexerValue2, and JsonValue3 in every section.
Any clues would be appreciated.
A:
As noted in the comment... Change the references to colons, and omit the second case. That seems to be redundant. Here is the code that I came up with.
class Program
{
static void Main(string[] args)
{
var InMemoryValue = new Dictionary<string, string>()
{
["Configuration:Test1"] = "IndexerValue1",
["Configuration:Test2"] = "IndexerValue2",
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.AddInMemoryCollection(InMemoryValue)
.AddJsonFile("Config.json")
;
var configuration = configurationBuilder.Build();
Console.WriteLine("Indexer");
Console.WriteLine($" Test1:{configuration["Configuration:Test1"]}");
Console.WriteLine($" Test2:{configuration["Configuration:Test2"]}");
Console.WriteLine($" Test3:{configuration["Configuration:Test3"]}");
var bindConfig = new Configuration();
configuration.GetSection("Configuration").Bind(bindConfig);
Console.WriteLine("Bind");
Console.WriteLine($" Test1:{bindConfig.Test1}");
Console.WriteLine($" Test2:{bindConfig.Test2}");
Console.WriteLine($" Test3:{bindConfig.Test3}");
Console.Write("Press [Enter] to end.");
Console.Read();
}
public class Configuration
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public string Test3 { get; set; }
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Uploading ios build .dSYM files in Fabric takes long time
When I upload .dSYM files in Fabric it takes long time! Any Suggestions?
and why these files not included in the build?
A:
Hope this will help you permanently, after this you do not need to upload dSYM file separately.
Just go to Build Settings and then turn on these parameters:
Debug: DWARF with dSYM File
Release: DWARF with dSYM File
Enable Bitcode: No
This problem basically occurs if you have not implemented fabric in the proper way.
For reference: see this
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get path data for multiple nodes
I have a series of paths, how can I get the node data for all the paths. I can only seem to get the path information from the last path:
var paths = svg.selectAll('.path')
.data(data)
.enter()
.append('path')
.attr('stroke', 'black')
.attr('fill', 'none')
.attr('stroke-width', 1.5)
.attr('d', line)
console.log(paths.node())
A:
You can get the data for all paths by iterating over the elements in your selection, e.g.
var pathData = [];
paths.each(function() { pathData.push(this); });
or, if you want just the d attribute, something like
var pathData = [];
paths.each(function(d) { pathData.push(line(d)); });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I change the default size (width + height) of the XML layout preview in ADT plugin for Eclipse?
Every time that I want to do a Layout, I'm getting a black layout preview then I can drop stuff on it, that's ok, but how can I change the size of that blank surface (xml). The question came because I set a folder layout-large and then when I add a new layout.xml to that folder it came with the same size, as a layout-normal, so I’ve something like that
(folder)layout
layout.xml
(folder)layour-large
layout.xml
Both file has the same physical or visible size, how can I increase the large one?
A:
There is a toolbar above the preview where you can choose device (ADP1 by default).
You can change it to Nexus One (800x480) or create you own device with custom resolution and select it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I perform multiple actions on a visual-block selection in Vim?
I'm using GVIM on Windows, if it matters.
I often select a block, do something, and then need to do something else with the same block, but of course once I do anything with the block, I'm out of visual mode.
Is there a way to re-select or act on the previously selected visual block?
A:
I believe gv will reselect the previous block...
A:
gv as Joe pointed out does the trick (+1), but an extra tip as well is if you do a :s with a visual selection, it will automatically populate the marks '< and '> and those will persist until you make another visual selection. So, you can do :'<,'>s/foo/bar/ without having to go back into visual mode and it will still apply to the same range. Same thing with anything else that uses those marks.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Core javascript functions to make error, warning or notice messages appear?
Does anyone know what the core drupal javascript functions are to force an error message? More importantly, it must work with Message Effects (http://drupal.org/project/messagefx).
With JS Theming you can call these: (this is javascript code)
Drupal.messages.set("The Message!", 'error');
But, it doesn't hook into Message Effects, and after disabling JS theming, this function no longer works.
A:
It seems like you have asked the wrong question. The status, warning, error messages that you see, is not invoked by javascript. Instead they are generated by the drupal_set_message() function. It work, by saving the messages in the session table for that user, and then they get printed whenever that user (re)load a page. It ends up as $messages in the page.tpl.php. I believe that there are no javascript version of this functionality, but you could mimic it. It's no harder than to insert some html on the page, something like.
$("#message").append('<div class="message error">The error message</div>');
I'm not sure about the exact html structure, and it cal also vary from theme to theme, but you get the idea. If you do take this approach, you will also need to hook into the messagefx module's js, to add the effect, but this shouldn't be too hard.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Question on convergence of formula for Dirichlet eta function $\eta(s)$
The Dirichlet eta function $\eta(s)$ is related to the Riemann zeta function $\zeta(s)$ as illustrated in (1) below. References (1) and (2) claim formula (2) for $\zeta(s)$ is globally convergent (except where $s=1+\frac{2\,\pi\,i}{\log(2)}n$ and $n\in\mathbb{Z}$) which seems to imply formula (3) for $\eta(s)$ is globally convergent. This is consistent with an answer to one of my related questions posted at reference (3) which claims formula (3) is valid for all $s$.
(1) $\quad\eta(s)=\left(1-2^{1-s}\right)\zeta(s)$
(2) $\quad\zeta(s)=\frac{1}{1-2^{1-s}}\sum\limits_{n=0}^\infty\frac{1}{2^{n+1}}\sum\limits_{k=0}^n\binom{n}{k}\frac{(-1)^k}{(k+1)^{s}}$
(3) $\quad\eta(s)=\sum\limits_{n=0}^N\frac{1}{2^{n+1}}\sum\limits_{k=0}^n\binom{n}{k}\frac{(-1)^k}{(k+1)^s}\,,\quad N\to\infty$
Reference (1): Wikipedia Article: Riemann zeta function, Representations, Globally convergent series
Reference (2): Sondow, Jonathan and Weisstein, Eric W. "Riemann Zeta Function." From MathWorld--A Wolfram Web Resource.
Reference (3): Answer to Questions on two Formulas for $\zeta(s)$
Figure (1) below illustrates the error in formula (3) for $\eta(s)$ evaluated at $N=400$. Note formula (3) for $\eta(s)$ seems to diverge more and more as $s$ becomes increasingly negative.
Figure (1): Error in Formula (3) for $\eta(s)$ Evaluated at $N=400$
Figure (2) below illustrates a discrete plot of the error in formula (3) for $\eta(s)$ evaluated at integer values of $s$ and $N=1000$. Note formula (3) for $\eta(s)$ actually seems to converge better at negative integers than at positive integers.
Figure (2): Error in Formula (3) for $\eta(s)$ where $s\in \mathbb{Z}$ Evaluated at $N=1000$
Figures (3) to (6) below illustrate the error in formula (3) for $\eta(s)$ evaluated at $s=-9.5$ over several ranges of $N$. Note the divergence range of formula (3) for $\eta(s)$ evaluated at $s=-9.5$ seems to increase as the evaluation limit $N$ increases.
Figure (3): Error in formula (3) for $\eta(s)$ evaluated at $s=-9.5$ for $0\le N\le 100$.
Figure (4): Error in formula (3) for $\eta(s)$ evaluated at $s=-9.5$ for $0\le N\le 200$.
Figure (5): Error in formula (3) for $\eta(s)$ evaluated at $s=-9.5$ for $0\le N\le 400$.
Figure (6): Error in formula (3) for $\eta(s)$ evaluated at $s=-9.5$ for $0\le N\le 800$.
Question: What is the explanation for the apparent discrepancy between claimed and observational convergences of formula (3) for the Dirichlet eta function $\eta(s)$?
A:
You have to be careful with numerical computations. If you are summing positive and negative values, you may get massive loss of significance. Perhaps an example will show what can happen. I use PARI/GP for the calculations.
First, define the $\ \eta(s)\ $ function in terms of $\ \zeta(s)\ $ if $N=0$ and using the double sum in equation $(3)$ if $N>0$.
Eta(s, N=0) = {if( N<1, (1 - 2^(1-s)) * zeta(s), sum(n=0, N,
2^(-n-1) * sum(k=0, n, binomial(n, k) * (-1)^k/(k+1)^s, 0.)))};
Next, try it with low precision and see how the values differ.
? default(realprecision, 19)
? forstep(n=50, 600, 50, print(n, " ", Eta(-9.5) - Eta(-9.5,n)))
50 -9.642528737400027361E-6
100 0.04774435040966354144
150 2.599876523165513738
200 -2.964487980721362893
250 256.1738173836702262
300 35.26046969887404046
350 -4458.254870234773912
400 -9841.293439755364521
450 75026.15715491652695
500 208518.5008905734908
550 249654.0022175838606
600 -194943.3625446287684
Now, try it again but with double precision and see what happens.
? default(realprecision, 38)
? forstep(n=50, 600, 50, print(n, " ", Eta(-9.5) - Eta(-9.5,n)))
50 1.36634363860781380424739243811E-17
100 -9.168029132151541870E-22
150 1.0314039806014013156E-19
200 -1.2323365675288983452001952305E-18
250 -1.07380641622270909181919052693E-17
300 3.2225691859129092780110367112E-17
350 -6.2902053300577065279589792889E-16
400 -1.1634529955480626497925160353E-16
450 4.6382289819863037395153447751E-15
500 8.4040100485998106924892434233E-15
550 -6.8760525356739577517253084299E-15
600 1.24908747773726136990750433575E-14
Notice the huge errors in low precision are gone in double precision. However, the errors still increase with increasing $N$ for a fixed precision. So what you need to do is increase both the precision and the $N$ to get convergence.
P.S.
For proof of convergence see the answer to MSE question 3033238 "Questions on two formulas for $\zeta(s)$" in case you are rightfully wary relying on limited numerical evidence.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Display radio buttons depending on attributes present in dictionary
I need to dynamically display radio buttons depending on how many roi_ (e.g roi0 or roi1) each frame_number has.
For example if frame_number: 1, had only one roi_ (roi0) attribute then it would display one radio button. But in the below output.json form the first three frames have two roi_ (roi0, roi2) so therefore two radio buttons are displayed.
I've tried multiple ways but cant get it.Any sugestions?
Also in Buttons_footer, ive displayed two radio buttons temporary as this is what i want it to look like, but to change dynamically depending on the data.
[{"frame_number": 1, "roi0": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity0": 80.0, "roi1": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity1": 157.0},
{"frame_number": 2, "roi0": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity0": 80.0, "roi1": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity1": 158.0},
{"frame_number": 3, "roi0": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity0": 80.0, "roi1": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity1": 157.0},
import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import Radio_Button from "./components/Radio_Button.js";
import Buttons_Footer from "./components/Buttons_Footer.js";
import LeftPane from "./components/LeftPane.js";
//import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: [] };
}
// Comunicate with API
callAPI() {
fetch("http://localhost:9000/IntensityAPI") //React app talks to API at this url
.then(res => res.json())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}
render() {
return (
<div className="App">
<header className="App-header">
<p></p>
<div class="row fixed-bottom no-gutters">
<div class="col-3 fixed-top fixed-bottom">
<LeftPane></LeftPane>
</div>
<div class="offset-md-3" >
<Buttons_Footer readings = {this.state.apiResponse}/>
</div>
</div>
</header>
</div>
);
}
}
export default App;
import $ from "jquery";
import React, { Component } from 'react';
import { MDBFormInline } from 'mdbreact';
import { Container, Row, Col } from 'reactstrap';
import Radio_Button from "./Radio_Button.js";
// Footer Component with checkbox's used to select region/region's of interest
class Buttons_Footer extends Component {
// Enables the Functionality of the "Select Multiple Region's" switch using jquerys
componentDidMount() {
$(".region").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.region:checked').length > 1){ // Multiply regions unable to be selected
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){ // Multiply regions able to be selected
$(".region").prop('checked', false);
}); }
//<p>{this.props.region.roi0}</p>
render() {
return (
<Container class = "container offset-md-3" >
<div className='custom-control custom-switch' >
<input type='checkbox' className='custom-control-input' id='customSwitches' />
<label className='custom-control-label' htmlFor='customSwitches'>
Select Multiple Region's
</label>
{this.props.readings.map((region)=>{
return <Radio_Button region ={region} key ={region.frame_number}/>
})}
<MDBFormInline>
<input class="region" type="checkbox" name="region1" value="1" />
<label for="region1"> 1</label>
<input class="region" type="checkbox" name="region2" value="2" />
<label for="region2"> 2</label>
</MDBFormInline>
</div>
</Container>
);
}
}
export default Buttons_Footer;
import React, { Component } from 'react';
import { MDBFormInline } from 'mdbreact';
import { Container, Row, Col } from 'reactstrap';
class Radio_Button extends Component {
//
render() {
return (
<div>
//<p>{this.props.region.roi0}</p>
<input class="region" type="checkbox" name="region1" value="1" />
<label for="region1"> 1</label>
</div>
);
}
}
export default Radio_Button;
A:
Assuming that you don't know how many roi's will be in response:
Get keys of every frame object and insert that data into array. After that you should have arrays in array.
const keys = frames.map(frame => Object.keys(frame))
Filter keys with regex.
const filteredKeys = keys.map(frame => frame.filter(key => new RegExp(/^roi\d+$/).test(key)))
For each key that's left show button.
const showButtons = () => {
return filteredKeys.map(frame => frame.map(roi => <Button />))
}
That should work, but it won't be the fastest and cleanest solution.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prevent API user from setting properties of a property
I would like to prevent the user of one of my Objective-C objects from setting a property of a property of the object. Just like it is not possible to set the origin of a frame of UIView. I need this for the exact same reason: to be able to manage some side effects on the setter of the property.
Example:
@interface Time : NSObject
@property (nonatomic) NSInteger hours;
@property (nonatomic) NSInteger minutes;
@end
@interface Watch : NSObject
@property (nonatomic) Time *time;
@end
It now should not be possible to set the minutes directly by calling:
watch.time.minutes = 15;
…rather than:
Time *time = watch.time; // [watch.time copy]?
time.minutes = 15;
watch.time = time; // Here, in setTime:, I can implement some side effects
When trying to set a UIView frame's size, the compiler complains like so: "Expression is not assignable". How could Apple’s framework developers have done this? Can this only be done with structs? How can I achieve a similar thing?
A:
I see a few options:
Prohibit the change entirely by returning a copy of time from its getter. You'll have to document the fact that this happens, and it may violate the principle of least surprise.
Use KVO to allow Watch instances to react to the fact that their Time member has been modified. As long as the modification goes through the Time's setter (which it must for this situation), the Watch can do what it needs to do in observeValueForKeyPath:ofObject:change:context:
Finally, consider whether Time even needs to be mutable. Probably your code here is just an example, but Time seems to be a value type. In general in Cocoa, these are not mutable. Changing the properties of Time that you don't want modified to readonly would solve this neatly for both you and the API user.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular scope doesn't update when removing an item
I have a simple application where I can add users to a list and remove them.
The form to add a new user binds to $scope.newPerson. On submitting the form, I add the newPerson object to $scope.people which is an array containing person objects.
I loop over the people array with an ng-repeat directive, to print out the people who are currently added to the scope. These rows all have a remove button (Jade snippet):
div.row(data-person, ng-repeat="person in people", ng-model="person")
button(ng-click="removePerson(person)") Remove
When I click the Remove button, I execute this function:
$scope.removePerson = function(person) {
var index = $scope.people.indexOf(person);
if (index > -1) {
$scope.people.splice(index, 1);
person = null;
}
}
This removes the row from the table, and sets the person scope to null. Batarang shows { This scope has no models } afterwards.
However, I have noticed that my people array doesn't update. When I check it's scope in Batarang, the person I just deleted is still in that array. When I start typing to add a new person, it updates. If I submit the whole page to my server without doing this, the array still contains the removed people.
If i put $scope.$apply() after person = null;, I get the expected behaviour, however it throws an error that an apply is in progress. I also read calling $apply() yourself is considered bad practice. (?)
I'm new to Angular and I can't seem to find a lot of information about solving this problem. How would I make it update my array when I remove a person? Thanks.
A:
I did the following to fix this:
No more ng-model on the ng-repeat block:
div.row(data-person, ng-repeat="person in people")
Refactored the ng-click event for removePerson():
<button ng-click="removePerson($index)">
Remove
</button>
and changed the removePerson() code to this:
$scope.removePerson = function(index) {
$scope.people.splice(index, 1);
};
Not sure if this actually fixed anything compared to my previous code, because I noticed that this was also a Batarang issue. When I simply log {{ people }} to my HTML, or console.log($scope.people), I see the people array update. However, in Batarang, the array does not update.
Lesson learned: sometimes, logging stuff out yourself is better than relying on tools ;)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JS numbers counter only works once
so my counter works just the first time.
by clicking in the button again i need to continue counting, but the function don't works after run first time, anyone know how to do it?
My jsFiddle: http://jsfiddle.net/wtkd/xpqg0fa9/
My js if you don't want to see in jsFiddle:
window.Fighters = (function() {
var padNum;
function Fighters(options) {
var random;
this.greenFighter = $('.green-fighter');
this.blueFighter = $('.blue-fighter');
this.team = $('.green-team, .blue-team');
this.thumb = $('.thumb');
random = Math.ceil(Math.random() * 301232);
$('.punch1').on('click', (function(_this) {
return function(e) {
return _this.countUp(random, '.right-counter span', 2222);
};
})(this));
$('.punch2').on('click', (function(_this) {
return function(e) {
return _this.countUp(random, '.left-counter span', 2222);
};
})(this));
}
padNum = function(number) {
if (number < 10) {
return '0' + number;
}
return number;
};
Fighters.prototype.countUp = function(points, selector, duration) {
$({
countNumber: $(selector).text()
}).animate({
countNumber: points
}, {
duration: duration,
easing: 'linear',
step: function() {
$(selector).text(padNum(parseInt(this.countNumber)));
},
complete: function() {
$(selector).text(points);
}
});
};
return Fighters;
})();
new window.Fighters();
A:
The click function is running each time but with the same reference to random. Random is evaluated once on the first execute of your script this is then used within your closure not re-evaluated. (literally tons of articles relating to closures to that you can read up on if you need to - here is one - http://javascriptissexy.com/understand-javascript-closures-with-ease/)
Bring the random inside your closure to ensure it evaluated on each click like so:
$('.punch1').on('click', (function(_this) {
return function(e) {
random = Math.ceil(Math.random() * 301232);
return _this.countUp(random, '.right-counter span', 2222);
};
})(this));
http://jsfiddle.net/y6gwyv0x/1/
or make random a function which returns it's value
random = function(){return Math.ceil(Math.random() * 301232);};
$('.punch1').on('click', (function(_this) {
return function(e) {
return _this.countUp(random(), '.right-counter span', 2222);
};
})(this));
random still refers to the one outside the closure but because it is a function it will be run on each click returning a new number
http://jsfiddle.net/y6gwyv0x/3/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BIRT formatting - merge cells on specific rows
How do I merge cells for specific rows in BIRT? Something similar to using colspan when creating a table in HTML. The data is extracted from a database and returns a fixed number of rows.
Specifically I want to convert a BIRT report that looks like this:
to this:
Thank you for your assistance.
A:
I don't know if it is possible to do this within an onCreate event for the cells.
But depending on your use case, it may be sufficient to duplicate the detail row.
Keep the cells as is in the first detail row and merge them in the second row.
Determine a condition when to merge cells and when not.
Use this as an visibility expression for the first and second detail row like this:
First row: should_merge(...)
Second row: !should_merge(...)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the method super do in the ruby code?
I think I know super intends to override the same method inherited from the parent class. However, in this below message passing code example, I don't know what is the supersupposed to do there:
class WellBehavedFooCatcher
def respond_to?(method_name)
if method_name.to_s[0,3] == "foo"
true
else
super(method_name)
end
end
end
So what does superdo in the above code?
Thank you so much in advance!
A:
I think I know super intends to override the same method inherited from the parent class.
Actually, it is the opposite. When you override some method in a child class, super is used to refer to the behaviour of the same method in the parent class (i.e., the original behaviour).
In the given code, the indent is to make it dynamically respondable to any method that starts with foo without changing the respondability of other methods. The first part is done by:
if method_name.to_s[0,3] == "foo"
true
but if it were only that, all other undefined methods would simply return nil even if they are defined in some parent class. If some parent class were to respond to such method, then returning nil to respondability would incorrectly block such methods. The other part:
else
super(method_name)
is to return the correct value for such case. It means that in other cases, do what the parent class did.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Will a USB port be able to power a series of LEDs?
I'm planning on having a set of blue LEDs connected in series. I'm looking at having about 30-40 LEDs in series. The power supply will be from a USB 2.0 port mounted on my television. Reading up on the specs for USB 2.0 it has a pin for 5v and ground.
If I used this as my power supply, will my LEDs light up as much as they should or would they be really dim.
The specs for the LEDs are:
Material : Semiconductor; Light Color: Blue
Head Dia.: 5mm / 0.197"; Forward Voltage: 3.2-3.4V
Luminous Intensity: 2000-3000MCD; Wave Length: 460-463
Size: 24 x 3mm / 0.9" x 0.1"(L*W); Package Content: 50 x Light
Emitting Diode
And a link to amazon where I purchased is this
A:
They definitely won't work from USB if connected in series (even two LEDs in series won't work).
If you connect a ~100 ohm resistor in series with each LED, you may be able to run about five LED/resistor sets connected in parallel from a USB port. Without negotiation, a USB port is only guaranteed to supply up to 100 mA (although many USB ports have no current control, and may supply 500 mA or more).
According to the comments on Amazon, there is no recommended maximum current data for these LEDs, so I'm guessing 20 mA per LED would be acceptable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Autosave in MVC (ASP.NET)
I'm implementing a web system to manage some data from my company.
We are using MVC (more specically ASP.NET MVC 4), in which I'm completely new to.
The problem I'm having is that we planned to use autosave, just like GMail.
We were planning on using change events queuing and once in a while submit changes through ajax.
On a first thought I would use JavaScript, not sure though if that's the best way for MVC.
Another trouble that I'm having is that some of the information the user will enter is not inside forms, but in a table instead.
Also the layout of the page is a little sparse and I don't believe I can wrap all the inputs into a single form or even if I should do it.
My questions are:
What is the best way to implement autosave using MVC, should I use or not JavaScript?
Is there any library in JavaScript or a feature in ASP.NET MVC to implement the queuing or should I do it by hand?
Also, can I use form to wrap table rows?
Note: I've seen some suggestions to use localstorage or others client persistency, but what I need is server persistency, and we don't even have a save button on the page.
Thanks for the help in advance ;)
A:
You can add form="myformid" attribute to elements that are outside form to include it in form. I would add data-dirty="false" attribute to all elements at the beginning and attach change event that would change data-dirty attribute of changing element to true. Then you can save form each 30 seconds for example (get elements that have data-change=true and pass to server). After saving, every element's data-dirty becomes false again. Example of autosave with jQuery:
window.setInterval(function(){
var dirtyElements = $('#myformid').find('[data-dirty=true]').add('[form=myformid][data-dirty=true]');
if(dirtyElements.length > 0){
var data = dirtyElements.serialize();
$.post('saveurl', data, function(){
dirtyElements.attr('data-dirty', false);
alert('data saved successfully');
});
}
}, 30000); // 30 seconds
Attaching event to all elements of form:
$(function(){
var formElements = $('#myformid')
.find('input, select, textarea')
.add('[form=myformid]')
.not(':disabled')
.each(function(){
$(this).attr('data-dirty', false).change(function(){
$(this).attr('data-dirty', true);
});
});
});
A:
Answers...
Definitely use javascript and AJAX, you don't want the page to keep refreshing when the user makes a change
I don't know about any libraries, but I would be happy to do this by hand. Detect the changes using javascript and then post the data via AJAX
You can access any form field from your controller with the FormCollection parameter, or the classic Form["fieldname"] method. As long as your table cells have unique name values you will be able to fetch the data
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deleting a google calendar event with python - getting Event ID
I have recently followed the python quick start guide for python here:
https://developers.google.com/calendar/quickstart/python
And have successfully added some objects to my google calendar.
I am then trying to delete the events, using:
service.events().delete(calendarId='primary', eventId='eventId').execute()
While this would ideally work, I can't find a way to get the event ID of any of my events. How am I able to get/set my google calendar event Ids using python
A:
When you create an event using:
insert(calendarId=*, body=*, sendNotifications=None, supportsAttachments=None, sendUpdates=None, conferenceDataVersion=None, maxAttendees=None)
You get to specify your own event id in the body section. Here is what the documentation says:
"id": "A String", # Opaque identifier of the event. When creating new
single or recurring events, you can specify their IDs. Provided IDs
must follow these rules:
# - characters allowed in the ID are those used in base32hex encoding, i.e. lowercase letters a-v and digits 0-9, see section 3.1.2
in RFC2938
# - the length of the ID must be between 5 and 1024 characters
# - the ID must be unique per calendar Due to the globally distributed nature of the system, we cannot guarantee that ID
collisions will be detected at event creation time. To minimize the
risk of collisions we recommend using an established UUID algorithm
such as one described in RFC4122.
# If you do not specify an ID, it will be automatically generated by the server.
# Note that the icalUID and the id are not identical and only one of them should be supplied at event creation time. One difference
in their semantics is that in recurring events, all occurrences of one
event have different ids while they all share the same icalUIDs.
You can store this id and later use it to delete the event.
The body could be as follows:
{
"attachments": [
{
"mimeType": "...",
"title": "...",
"fileUrl": "...",
"iconLink": "...",
"fileId": "...",
},
],
"creator": {
"self": false,
"displayName": "...",
"email": "...",
"id": "...",
},
"organizer": {
"self": false,
"displayName": "...",
"email": "...",
"id": "...",
},
"summary": "...",
"id": "Your ID GOES HERE",
"hangoutLink":"..."
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Approach to Analytically Solving Nonlinear Differential
This first order nonlinear differential was posted on a science forum and I am very interested in it. I would like to know what are the most appropriate steps taken to test for the possibility of an analytical solution, as well as what might be the appropriate steps to solve it analytically.
$\dot{x} = - \alpha {x}^{1/2} \arctan{(kx)}$
for $x>0$ and $t \in [0,T]$, where $T < \infty$ and $k > 0$
I'm also kind of curious where it might have come from, which I hadn't asked the original poster and so I do not know! I'm not looking for a lesson, or a complete solution, just an outline if possible. The only book I have on differentials does not cover nonlinear and so I'm not even sure if this is a particular case of some subset of study.
A:
This is an equation in separeted variables. If $\dot x=dx/dt$, then
$$
\frac{dx}{\sqrt{x\,}\arctan(k\,x)}=-\alpha\,dt.
$$
Integrating
$$
\int\frac{dx}{\sqrt{x\,}\arctan(k\,x)}=-\alpha\,t+C.
$$
Unfortunately, I do not think the integral has a closed form in terms of elementary functions (Mathematica can't find it.)
Let $f(x)=-\alpha\,\sqrt{x\,}\arctan(k\,x)$; then $f$ is locally Lipschitz on $[0,\infty)$ (in fact it is differentiable with bounded derivative.) For any $x_0\ge0$, there is a unique solution such that $x(0)=x_0$ defined on a maximal interval $[0,T)$. If $x_0=0$, then $x\equiv0$. If $x_0>0$, it is easy to see that the solution $x$ is global (i.e. $T=\infty$), decreasing, convex, and $\lim_{t\to\infty}x(t)=0$.
For cuatitative results, numerical methods should be used.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Organizing files TO folders (Module programming)
I am creating a visual c++ project now, and I would like to make some way to arrange files. I tried to create folders but it seems it is pretty hard to make them into visual studio, because these folders are empty and after including to the solution only I am going work on them (like Java packages. You first add them and code in it, in the same IDE, same project).
It seems like this way is not working because I can not add anything to the include files. So I tried to create filters. It is not a physical divide of files but if this is the way c++ community code then I have no problem. Otherwise could be a probvlem because this is my university project.
So in case the best is "filters", how can I call from one filter to another? Look at the below example
FilterFolder1
people.h
people.cpp
FilterFolder2
vehicles.h
vehicles.cpp
Now, I have a problem in arranging the stuff in this way as well. Bceuase even I right click on FilterFolder1 and select Add -> C++ Class still that class is created in it's default location, header file in Header Files filter and cpp file in Source Files filter. I had to manually drag and drop those files to make the above architecture.
Now, how can I call from people class (people.h and people.cpp) to vehicle class (vehicles.h and vehicles.cpp) because they are in two folders which I FORCED them to see like above?
What I did is correct or wrong? If correct, what is thhe answer for the above? If wrong, what is the correct way of organizing files and using it?
A:
Folders and filters does not matter in your case. Simply call vehicle class from people class and go on. If you want to organize code logically, instead of physically, use namespaces.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python - Is there a way to wait os.unlink() or os.remove() to finish?
I have the following code:
os.remove('_Temp_Dir_\main' + str(i) + '.exe')
os.rmdir('_Temp_Dir_')
Which gives me:
OSError: [WinError 145] Directory is not empty: '_Temp_Dir_'
if i put the line
time.sleep(0.05)
before os.rmdir(), it works correctly. I think os.remove() isn't fast enough to remove the file. Any way to wait for it to finish its work?
A:
Use shutil.rmtree() to remove the directory and don't bother with removing the file:
import shutil
shutil.rmtree('_Temp_Dir_')
The os.remove() works just fine (it won't return until the file remove completes), there must be other files in that directory that the process left behind and are removed during your sleep() call.
A:
os.remove()` is a synchronous operation; when it returns, the file is definitely gone (unless it throws an error, of course).
The effect you see much be something else. I can imagine these effects:
Virus scanner
Desktop indexing
To find out what is going on, I suggest to use os.listdir() on the folder before you delete and print the result when os.rmdir() fails. The names in the list might give you an idea what is going on.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Facebook Ads API AdSet Creation Normalization Error
I'm getting an odd error from the Facebook ADs API. Sending the following payload:
{
"campaign_group_id": "54321",
"bid_type": "ABSOLUTE_OCPM",
"name": "Hello AdCampaign",
"bid_info": {
"ACTIONS": 1
},
"targeting": {
"behaviors": [
{
"name": "BEHAVIOR NAME",
"id": 12345
}
],
"geo_locations": {
"countries": [
"US"
]
},
"page_types": "feed"
},
"campaign_status": "ACTIVE",
"daily_budget": 100
}
Providing this payload to the ads api is returning the following error message:
You are requesting a transaction which requires the adgroups to be normalized, but normalize failed because Normalization expects a collection
Which has an associated error code of 1487079 which.. I cannot find documentation for.. ANYWHERE.
This will work, if I remove the behaviors attribute of targeting.. but of course that isn't desirable. So it's something to do with the behaviors.
A:
As per the docs, I believe page_types should be a list. Try this:
{
...
"page_types": ["feed"],
...
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grid points within polygon: previous solution does not work for me
For some reason I can't get the solution provided by @RichPauloo to work and do appreciate some help.
I have a SpatialPolygonsDataFrame called "spdf" (in the dropbox link below)
https://www.dropbox.com/s/ibhp5mqbgfmmntz/spdf.Rda?dl=0
I used the code from below post to get the grid data within the boundary.
Create Grid in R for kriging in gstat
library(sp)
grd <- makegrid(spdf, n = 10000)
colnames(grd) <- c('x','y');
outline <- spdf@polygons[[1]]@Polygons[[1]]@coords
library(splancs)
new_grd <- grd[inout(grd,outline), ]
Here is what I get:
Black dots are "grd" from makegrid
Blue dots are "outline" as boundary
Red dots are"new-grd" as the grid within the boundary
As you can see it does not capture all the data within the boundary? What am I doing wrong?
A:
Try this:
# packages
library(sp)
# make grid
grd <- makegrid(spdf, n = 100)
colnames(grd) <- c('x','y') # assign names to columns
# check the class
class(grd)
# transform into spatial points
grd_pts <- SpatialPoints(coords = grd,
proj4string=CRS(as.character(NA)))
# check the class again
class(grd_pts)
# show that points fall outside of polygon
plot(spdf)
points(grd_pts)
# subset for points within the polygon
grd_pts_in <- grd_pts[spdf, ]
# visualize
plot(spdf)
points(grd_pts_in)
# transform grd_pts_in back into a matrix and data frame
gm <- coordinates(grd_pts_in) # matrix
gdf <- as.data.frame(coordinates(grd_pts_in)) # data frame
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django-CKEditor with normal Django Forms and bootstrap
I'm new to Django and CKEditor and had been struggling with integration of Django-CKEditor in forms from past 1 week. It works perfectly fine in Django Admin forms but does not work in normal forms.
This is my forms.py
class ArticleForm(forms.ModelForm):
content = forms.CharField(widget = CKEditorWidget())
class Meta:
model = Article
fields = ['title','content','meta_description','meta_tags']
models.py
class Article(models.Model):
title = models.CharField(max_length=500)
url = models.CharField(max_length=500)
date = models.DateTimeField(auto_now_add=True, blank=True)
author = models.CharField(max_length=100)
content = models.TextField()
meta_description = models.TextField()
meta_tags = models.TextField()
is_published = models.BooleanField(default=False)
views
def new_post(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.url = form.data['title']
article.save()
return HttpResponse('/thanks/')
else:
form = ArticleForm()
return render(request, 'blog/new-post.html', {'form': form})
TO verify whether it works in admin, I had tested with Admin by adding it in admin form.
admin.py
class ArticleAdminForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Article
class ArticleAdmin(admin.ModelAdmin):
form = ArticleAdminForm
admin.site.register(Article, ArticleAdmin)
One more thing I'm using bootstrap3. and my template looks like
<form class="form-horizontal" action="/blog/new-post/" method="post" >{% csrf_token %}
<fieldset>
<legend>New Blog Post</legend>
{{ form.non_field_errors }}
<div class="fieldWrapper form-group">
{{ form.title.errors }}
<label class="col-lg-2 control-label" for="id_title">Title</label>
<div class="controls col-lg-10 ">
<input type="text" class="col-lg-10 form-control" name="title" id="id_title}}" placeholder="Title">
</div>
</div>
<div class="fieldWrapper form-group">
{{ form.content.errors }}
<label class="col-lg-2 control-label" for="id_content">Content</label>
<div class="controls col-lg-10 ">
<textarea class="col-lg-10 form-control" rows="17"name="content" id="id_content}}" placeholder="Content"></textarea>
</div>
</div>
<div class="fieldWrapper form-group">
{{ form.meta_description.errors }}
<label class="col-lg-2 control-label" for="id_meta_description">Description</label>
<div class="controls col-lg-10 ">
<textarea class="col-lg-10 form-control" rows="5"name="meta_description" id="id_meta_description}}" placeholder="Short description about this article."></textarea>
</div>
</div>
<div class="fieldWrapper form-group">
{{ form.meta_tags.errors }}
<label class="col-lg-2 control-label" for="id_meta_tags">Tags</label>
<div class="controls col-lg-10 ">
<input type="text" class="col-lg-10 form-control" name="meta_tags" id="id_meta_tags}}" placeholder="Comma separated tags eg. trekking, hiking ">
</div>
</div>
<input type="submit" value="Publish" class="btn btn-default btn-large pull-right">
</fieldset>
</form>
Any help would be great. Thanks in advance
A:
I think you missed the from ckeditor.fields import RichTextField line in models.py
Change content = models.TextField()
Into content = RichTextField(blank=True, null=True)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What mistake did I do in the code that gives me "False" as answer to all the cases?
I just started learning programming on my own. I am trying to solve the following practice problem on codingbat.com. Logic-2 > make_bricks
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
The following is my solution. It gives "False" as a result for every test case I tried! What mistake did I do?
def make_bricks(small, big, goal):
small_len = 1
big_len = 5
count_big = 0
count_small = 0
#Taking care of exceptional cases where no detailed calculations are required.
if (big_len == goal) or (small_len == goal):
return True
elif small_len > goal:
return False
elif big_len > goal:
for i in range(1,small+1):
if (small_len * i) < goal:
count_small += 1
if (small_len * count_small) == goal:
return True
else:
return False
# Taking care of all the other cases
else:
# Counting number of bigger bricks required
for i in range(1,big+1):
if (big_len * i) < goal:
count_big += 1
# Counting number of smaller bricks required
for i in range(1,small+1):
if ((big_len * count_big) + (small_len * i)) < goal:
count_small += 1
if ((big_len * count_big) + (small_len * count_small)) == goal:
return True
else:
return False
A:
You had some mismatch relational operators, you have used < operator instead of <= operator.
Due to this logical mismatch your code was not executing for last brick required.
I have edited your code at some points here:
def make_bricks(small, big, goal):
small_len = 1
big_len = 5
count_big = 0
count_small = 0
#Taking care of exceptional cases where no detailed calculations are required.
if (big_len == goal) or (small_len == goal):
return True
elif small_len > goal:
return False
elif big_len > goal:
for i in range(1,small+1):
if (small_len * i) <= goal:
count_small += 1
if (small_len * count_small) == goal:
return True
else:
return False
# Taking care of all the other cases
else:
print("else running")
# Counting number of bigger bricks required
for i in range(1,big+1):
if (big_len * i) <= goal:
count_big += 1
print("big brick used {}".format(count_big))
# Counting number of smaller bricks required
for i in range(1,small+1):
if ((big_len * count_big) + (small_len * i)) <= goal:
count_small += 1
print("small brick used {}".format(count_small))
if ((big_len * count_big) + (small_len * count_small)) == goal:
return True
else:
return False
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert Tuple into Foldable
Is there a way to derive Foldable from Tuple?
At least when the tuple is homogeneous?
For example let's say I have (1,2,3) and I want to reverse it or to transform it into [1,2,3] and similar things.
I've tried to do something like
over each (\x -> 4 -x) (1,2,3) -- lol
but I need a sort of equivalent of fold with lens...
and actually I see that I can do
foldr1Of each (\a x -> a+x) (1,2,3)
but I would need instead
foldr1Of each (\a x -> a:x) (1,2,3)
which doesn't compile
A:
but I would need instead
foldr1Of each (\a x -> a:x) (1,2,3)
which doesn't compile
The reason why this does not compile is because (:) :: a -> [a] -> [a] expects a list as second argument, but with foldr1Of, you provide it the last element of your fold, which is here a number.
You can solve it by using foldrOf :: Getting (Endo r) s a -> (a -> r -> r) -> r -> s -> r instead:
Prelude Control.Lens> foldrOf each (:) [] (1,2,3)
[1,2,3]
Here we thus pass [] as the "initial accumulator".
We can thus convert several several "containers" to lists with:
toList :: Each s s a a => s -> [a]
toList = foldrOf each (:) []
For example:
Prelude Control.Lens> toList (1,2)
[1,2]
Prelude Control.Lens> toList (1,2,3)
[1,2,3]
Prelude Control.Lens> toList (1,2,3,4)
[1,2,3,4]
Prelude Control.Lens> toList [1,2,3]
[1,2,3]
Prelude Control.Lens> toList Nothing
[]
Prelude Control.Lens> toList (Just 2)
[2]
A:
In addition to Willem's answer, it is worth noting that Control.Lens.Fold offers analogues for pretty much everything in Data.Foldable. That includes toList, which becomes toListOf:
GHCi> toListOf each (1,2,3)
[1,2,3]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Архивировать только «скрытые» файлы
tar -cvzf archive.tar.gz .*
Шаблон .* не работает
Как архивировать только файлы/каталоги, имена которых начинаются с точки?
A:
например так:
$ find -maxdepth 1 -regex './\..*' | tar -cvzf archive.tar.gz -T -
если не устраивает префикс ./ перед именами файлов/каталогов, то чуть длиннее:
$ find -maxdepth 1 -regex './\..*' -printf '%P\n' | tar -cvzf archive.tar.gz -T -
можно и без -regex:
$ find -maxdepth 1 -mindepth 1 -name .\* | tar -cvzf archive.tar.gz -T -
$ find -maxdepth 1 -mindepth 1 -name .\* -printf '%P\n' | tar -cvzf archive.tar.gz -T -
а можно и без find:
$ tar -cvzf archive.tar.gz .??*
но под маску не подпадут файлы/каталоги с именем, состоящим из двух символов. типа .1. тогда так:
$ tar -cvzf archive.tar.gz .[^.]*
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Close all files in notepad++
Is there a way to close all files from notepad++ less painfull than going over every single one of them at the time.
I always use it for quick editing files and now there are more 200 files open in the editor which is a bit annoying.
I have tried so far to close them by clicking on the close all button (in the menu toolbar) but still it's going over one single of them at the time .
And I have also tried to close notepad++ program through task Manager but It still keep the files there.
Here is the version of the notepad++ I'm using : Notepad++ v7.5.1
(64-bit)
Thanks in advance
A:
Via @Florent B.
Click Menu File. Click Close all.
Other Options:
Right-click on a tab then you have four options.
Close <- close current tab.
Close all but this.
Close all to the left.
Close all to the right.
Your best bet is Close all but this. That will leave you at two total clicks to close all files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to give the carousel image the full screen width?
I am learning about carousel in flutter. I want to give the carousel image the full screen width. But the width is automatically taken by the carousel itself. Is there any way to give the image the full screen width inside carousel?
Here I have used both carousel_pro and carousel_slider, neither works as I expected. Please help.
List _images = [
Image.network(
"https://stimg.cardekho.com/images/carexteriorimages/630x420/Lamborghini/Lamborghini-Huracan-EVO/6731/1546932239757/front-left-side-47.jpg?tr=w-456,e-sharpen"),
Image.network(
"https://auto.ndtvimg.com/car-images/big/lamborghini/aventador/lamborghini-aventador.jpg?v=5"),
Image.network(
"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/gateway-family/few-off/sian/car_sian.png"),
Image.network(
"https://www.topgear.com/sites/default/files/styles/16x9_1280w/public/images/news-article/2018/01/38eba6282581b285055465bd651a2a32/2bc8e460427441.5a4cdc300deb9.jpg?itok=emRGRkaa"),
Image.network(
"https://blog.dupontregistry.com/wp-content/uploads/2013/05/lamborghini-egoista.jpg"),
];
List _images2 = [
"https://stimg.cardekho.com/images/carexteriorimages/630x420/Lamborghini/Lamborghini-Huracan-EVO/6731/1546932239757/front-left-side-47.jpg?tr=w-456,e-sharpen",
"https://auto.ndtvimg.com/car-images/big/lamborghini/aventador/lamborghini-aventador.jpg?v=5",
"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/gateway-family/few-off/sian/car_sian.png",
"https://www.topgear.com/sites/default/files/styles/16x9_1280w/public/images/news-article/2018/01/38eba6282581b285055465bd651a2a32/2bc8e460427441.5a4cdc300deb9.jpg?itok=emRGRkaa",
"https://blog.dupontregistry.com/wp-content/uploads/2013/05/lamborghini-egoista.jpg",
];
Carousel(
images: _images,
autoplay: true,
boxFit: BoxFit.fitWidth,
dotBgColor: Colors.transparent,
dotSize: 3,
dotColor: Colors.red,
dotIncreasedColor: Colors.red,
autoplayDuration: Duration(seconds: 3),
animationCurve: Curves.fastOutSlowIn,
),
),
SizedBox(height: 20),
CarouselSlider(
items: _images2
.map(
(x) => Container(
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(x, scale: 1),
),
),
),
)
.toList(),
autoPlay: true,
height: 200.0,
),
A:
This is example, hope it works for you
List<String> imgList;
CarouselSlider(
items: map<Widget>(
imgList,
(index, i) {
return Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Stack(children: <Widget>[
InkResponse(
child: Image.network(i,
fit: BoxFit.cover, width: 1000.0),
onTap: //....
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the grouped product link from one of it's childs in woocommerce 3
With woocommerce 2.3 there was post_parent for single products what was the part of grouped product. So it was possible to link them by:
function parent_permalink_button() {
global $post;
if( $post->post_parent != 0 ){
$permalink = get_permalink($post->post_parent);
echo '<a class="button" href="'.$permalink.'">Link to Parent</a>';
}
}
with woocommerce 3.0.0 update situation changed. Actually it is opposite now. Grouped product has its _children.
How can I create the link from single product to its grouped? It can be a part of more grouped product so there can be multiple links (but it is not the case of my shop)
Thanks Michal
A:
It's possible to build that function for WooCommerce 3+ this way:
(with an optional $post_id argument)
/**
* Get a button linked to the parent grouped product.
*
* @param string (optional): The children product ID (of a grouped product)
* @output button html
*/
function parent_permalink_button( $post_id = 0 ){
global $post, $wpdb;
if( $post_id == 0 )
$post_id = $post->ID;
$parent_grouped_id = 0;
// The SQL query
$results = $wpdb->get_results( "
SELECT pm.meta_value as child_ids, pm.post_id
FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
INNER JOIN {$wpdb->prefix}term_relationships as tr ON pm.post_id = tr.object_id
INNER JOIN {$wpdb->prefix}terms as t ON tr.term_taxonomy_id = t.term_id
WHERE p.post_type LIKE 'product'
AND p.post_status LIKE 'publish'
AND t.slug LIKE 'grouped'
AND pm.meta_key LIKE '_children'
ORDER BY p.ID
" );
// Retreiving the parent grouped product ID
foreach( $results as $result ){
foreach( maybe_unserialize( $result->child_ids ) as $child_id )
if( $child_id == $post_id ){
$parent_grouped_id = $result->post_id;
break;
}
if( $parent_grouped_id != 0 ) break;
}
if( $parent_grouped_id != 0 ){
echo '<a class="button" href="'.get_permalink( $parent_grouped_id ).'">Link to Parent</a>';
}
// Optional empty button link when no grouped parent is found
else {
echo '<a class="button" style="color:grey">No Parent found</a>';
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works in WooCommerce 3+
USAGE: (2 cases)
1) Without using the optional argument $post_id for example directly in the product templates:
parent_permalink_button();
2) Using the function everywhere, defining the it's argument $post_id:
$product_id = 37; // the product ID is defined here or dynamically…
parent_permalink_button( $product_id );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rendering lilypond score into html page
What would be the best way of rendering specific parts of a lilypond score,
into an HTML page? I did that using lilypond-book by previously embedding
<lilypondfile> tag into my html file, and it works, however that way I am
embedding the whole melody.
I know also there is a possibility to render small pieces of melody using
<lilypond> tag, but I would like to import parts of already written stuff.
Do I have possibility to render only part of melody from files, without doing manual copy paste of that specific part, into another file, just for that purpose?
A:
While it isn't Lilypond,the similarly-text-based ABC notation format has an open source javascript renderer named abcjs, that you might find interesting.
A:
I've had some success using lilypond from within Emacs Org-Mode files; but I have not done what I'm proposing (mostly I've used it as a replacement for lilypond-book).
Org-Mode is an extension to the Emacs editor (which runs cross-platform) that allows one to write plain text files and export them into HTML (or pdf).
In addition to supporting outlining, it also supports "literate programming" where you embed code blocks in the text document, and have commands so that the resulting code blocks can be exported (tangled in the parlance) into files that can be compiled and/or run.
I mention all this background because I would believe that the following would be possible:
1) You edit a .org file, embedding various portions of your score in lilypond code blocks within that file;
2) You export this file (using the Org-Mode export functionality) into the desired HTML file,
3) You tangle the file (using the Org-Mode literate programming functionality) to produce the .ly file that you can then compile.
The other way that I can imagine trying to do this is by doing some scheme programming within lilypond itself: you have full access to the entire(?) guile programming environment, so it should be possible to scheme write functions that produce the HTML that you seek, and pull in the portions of your score that you want. This seems like it would be a highly non-trivial programming problem (even the OrgMode approach will probably be non-trivial). If you consider going this route, I'd strongly recommend checking with the lilypond user (or maybe even developer) mailing lists to see what help you can get from them.
A:
For those that might be interested, here is what I did to make this work for
me in VIM, using a little of shell scripting:-
Requirements for this script to work are:
hxpipe which is part of html-xml-utils package. Please find a version
for your particular distribution.
awk which should be present on your machine, if it's not install that
too.
And of course, our main buddy lilypond-book.
#!/bin/bash
fromvim="$1"
PID=$$
lilypond-book -f html -o output "$fromvim" 2>/dev/null
hxpipe output/stdin.html | awk '/src/||/href/ {$3="output/"$3;}{ print }' | hxunpipe > result$PID
cat result$PID
exit 0
Save this as ly2vim, make it executable with chmod +x ly2vim and place it into some directory, in your path.
Now the VIM part:
Add the following to your .vimrc configuration file:-
#note the dash symbol, it is important, as it will send current line from `VIM` as standard input to `lilypond-book` command.
nnoremap <leader>ly :.!ly2vim -<CR>
That's it. Now when you are in a middle of editing your html file, you just
place line like this:-
<lilypondfile>yourmusic.ly</lilypondfile>
While cursor anywhere on that line, do your <leader>ly key combination while
in normal mode, and voila!, png file will be generated, and code snippet
inserted at that place for you. Preview in your browser, and enjoy! :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ruby object.hash
What's the meaning of an object's hash value? And in which case does two object has the same hash value?? Also it is said that Array|Hash can't be Hash keys, this has something to do with object's hash value, why?
A:
For objects to be stored in hashmaps or hashsets the following must hold true:
If two objects are considered equal, their hash value must also be equal.
If two objects are not considered equal, their hash value should be likely to be different (the more often two different objects have the same hash value, the worse the performance of operations on the hashmap/set).
So if two objects have the same hash value there is a good chance (but no guarantee) that they are equal.
What exactly "equal" means in the above is up to the implementor of the hash method. However you should always implement eql? to use the same definition of equality as hash.
For classes that don't override hash (i.e. classes using Object's hash implementation) hash equality is defined in terms of object identity. I.e. two objects are considered equal if and only if the reside at the same location in memory.
In ruby up to 1.8.6 Array and Hash did not override hash. So if you used arrays (or hashes) as hash keys, you could only retrieve the value for a key, if you used the exact same array as a key for retrieval (not an array with the same contents).
In ruby 1.8.7+ Array#hash and Hash#hash (as well as their eql? methods) are defined so that they are equal when their elements are equal.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does health link work, exactly?
I'm kind of confused by this mod on elite enemies. Is it supposed to make it harder to kill each one individually? If so, how does it work?
A:
The Health-Link description taken from here says:
This trait is for champion monsters only and it activates only if more
than one champion is present. Health Link reduces the amount of damage
taken by the champion with that trait by linking his HP to that of all
other Health Link champions in the area.
This trait can occur only for
monsters equal to or greater than level 51
In short, any damage one monster takes is divided between all monsters in the link, so providing X monsters with health link stay near each other, it takes X times as long to single-target dps a monster with Health Link than one without.
It should be noted that if monsters are far enough apart, their "link" isn't active, so you can dps them one at a time if you can separate the group
A:
Health Link means that the elite enemies pass some damage off to each other, i.e. if you focus one elite, the damage will be reduced because it is shared with nearby pals.
If they have no nearby pals, the damage doesn't seem to be shared. If you separate them it is possible to nuke one, and in practice because they spend some time separated so they will not die at exactly the same time.
So yes, it is harder to kill each one individually. However, if you use area-of-effect abilities you won't notice the difference.
For example, think about an ability that hits all three elites, and say anyone hit takes 33% damage while 66% is passed off to the other two elites (combined). So elite A takes 33% damage while B and C take 33% each. However, if you also hit elite B the same applies - he takes 33% while A and C take 33% each. Same goes for elite C, so added together each elite takes 33% directly, plus 33% x 2 from the other two elites passing damage off. Overall you still dealt 33% + 33% x 2 = ~100% damage to your main target.
This doesn't mean that area-of-effect abilities are better at dealing with them - it only means that you won't notice the effects of Health Link.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use existing variable in JavaScript?
var list = [{name: 'foo'}, {name: 'bar'}];
var x = list[0];
x.name = 'baz'; // Changes name in list[0]
x = {name: 'baz'} // Doesn't change name in list[0] - PROBLEM
Looks like line #4 is creating a new variable. How to tell JavaScript to use existing variable x that was created in line #2?
A:
The variable x holds a reference to an object.
x.name = ... changes a property on the particular object that x refers to.
x = { ... } changes which object x refers to.
Here's the setup:
x ==> { old object } <== list[0]
When you do x = { .. }, here's what happens:
x ==> { brand new object }
{ old object } <== list[0]
But you want it to do this (note: this never happens):
x ==> { brand new object } <== list[0]
{ old object } // referred to by no one! (will be garbage collected on the next sweep)
It seems you would like the statement x = { ... } to completely replace the object that x formerly referred to with a new object. You can't; JavaScript doesn't have any mechanism to allow this kind of replacement. Objects can't "be replaced" like my second example. You need to manually change each reference.
Instead, if you want to change the first element of list, you need to do the replacement directly on the array. Namely, you must do list[0] = { ... }, or list[0] = x after you've already changed x.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Query Dynamic PIVOT
Possible Duplicate:
SQL Server dynamic PIVOT query?
I have temporary table with following structure:
MONTH ID CNT
----- ----------- ---
4 TOTAL_COUNT 214
5 TOTAL_COUNT 23
6 TOTAL_COUNT 23
4 FUNC_COUNT 47
5 FUNC_COUNT 5
6 FUNC_COUNT 5
4 INDIL_COUNT 167
5 INDIL_COUNT 18
6 INDIL_COUNT 18
How i can get the Pivot over month in this table like:
ID APRIL MAY JUNE
----------- ----- --- ----
TOTAL_COUNT 214 23 23
FUNC_COUNT 47 5 5
INDIL_COUNT 167 18 18
Please consider this table format. I am little messy in posting this format.
A:
While you can use a Static Pivot - one that you hard-code the months. In the comments, you stated that the number of months maybe be unknown, if that is the case then you will want to use a Dynamic Pivot to generate the list of months. Using a Dynamic Pivot gives you the flexibility of not knowing the columns you need until you run it.
create table t
(
[month] int,
[id] nvarchar(20),
[cnt] int
)
insert t values (4,'TOTAL_COUNT',214)
insert t values (5,'TOTAL_COUNT',23)
insert t values (6,'TOTAL_COUNT',23)
insert t values (4,'FUNC_COUNT',47)
insert t values (5,'FUNC_COUNT',5)
insert t values (6,'FUNC_COUNT',5)
insert t values (4,'INDIL_COUNT',167)
insert t values (5,'INDIL_COUNT',18)
insert t values (6,'INDIL_COUNT',18)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month)
FROM t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT id, ' + @cols + ' from
(
select month, id, cnt
from t
) x
pivot
(
sum(cnt)
for month in (' + @cols + ')
) p '
execute(@query)
drop table t
The results would be:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What "God's law" is Matthew Henry referring to?
Part of Matthew Henry's commentary on Exodus 22 says:
A man's house is his castle, and God's law, as well as man's, sets a guard upon it; he that assaults it does so at his peril.
What is he referring to as "God's law" in reference to setting a guard upon it?
A:
Considering that this is a commentary on Exodus 22, which is dealing with issues relating to theft, this is likely on the specific "thou shalt not steal" commandment.
The idea of property rights is found throughout Scripture, and taking someone's property is, in it's most basic form, theft.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I write a companion book/blog?
As a spinoff to this question: Incorporating research and background: How much is too much?
I'm writing a middle-grade fantasy novel with a historical fiction component based in Ancient Egypt. I'm doing enormous amounts of research on both the history and the religious aspects (it's based on the Exodus). A lot of people seem to think my research would be of interest to people and have suggested I consider a companion book and/or a blog.
Obviously I don't want to take away writing time for my novel. I have to finish it first. But the longer I wait with research notes, the more I forget the details. Writing everything down takes a while.
Has anyone done this or seen this done (especially not by hugely popular books/authors...I mean, let's not count A Song of Ice and Fire)? Is it just another time sink to slow down finishing my novel? Or is it worthwhile?
A:
I think, done correctly, a blog could be a tremendous support to your book. Among other things, it could be a selling point for getting the book actually published (publishers like authors to have "platforms" these days). However, as you pointed out, a blog can be a big time-suck, and it needs to be updated at least once a week, or no one will ever read it.
My recommendation would be to go ahead and get a blog account --I strongly recommend wordpress (you can get a free basic account on wordpress.com if you don't have your own hosting). You don't necessarily have to publish any of the entries --you can use it as a useful note-organizing system, with the advantage of categories, tags and dated entries. But if you do get an entry that just needs a little tweak to be publishable, keep a note of it. Then, during the long horrible waiting periods while you're waiting for the book to find an agent or publisher or to come out, you can go back through and convert your notes to publishable entries. You could spend some concentrated time polishing several up at once, and schedule them in advance.
I've had blogs for a long time, and I've used them both as places to workshop new material that might be a book someday, and as an alternate place to publish material that was intended as a book but never sold. I haven't ever seen any huge popularity from any of my blogging, but it does raise your online profile, and it looks good in a query letter. I've even occasionally had people reach out to me because of it, and I once even had someone refer to a bit of my blogged writing in a major venue (the "generic parody" referenced in the opening paragraph).
As far as a companion book, that's really just a way to get double benefit out of your research after your novel is done. As I mentioned, you'll probably have a lot of downtime between finishing the book and seeing it in print.
A:
A companion book - it's way too early to think of that. There's no sense in writing a companion book when you haven't written the main book yet. A companion to what would it be? Once you've published your story, if it sells well, there might be a market for a companion book with additional information. Of course, by then you might be tired of Exodus, and eager to do something new instead.
A companion blog - you could do that now. It might even help generate interest in your upcoming book. I see one serious problem though: you have X hours a day for writing. If you spend Y hours writing your blog, you've only got (X - Y) left to write your novel. And the novel is what you want to write, right?
If writing the blog helps you write your novel in some way - helps you arrange your thoughts, get over a writing block, gives you some sort of encouragement - then go ahead and do it. Otherwise, your goal is the novel. Don't let yourself get so distracted from it that you don't actually finish the novel.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Pythonic" equivalent for handling switch and multiple string compares
Alright, so my title sucked. An example works better:
input = 'check yahoo.com'
I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it:
if len(input) > 0:
a = input.split(' ')
if a[0] == 'check':
if len(a) > 1:
do_check(a[1])
elif a[0] == 'search':
if len(a) > 1:
do_search(a[1])
I like Python because it makes normally complicated things into rather simple things. I'm not too experienced with it, and I am fairly sure there's a much better way to do these things... some way more pythonic. I've seen some examples of people replacing switch statements with dicts and lambda functions, while other people simply recommended if..else nests.
A:
dispatch = {
'check': do_check,
'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
dispatch[cmd](arg)
else:
do_default(cmd, arg)
A:
I am fairly sure there's a much better way to do these things... some way more pythonic.
Not really. You code is simple, clear, obvious and English-like.
I've seen some examples of people replacing switch statements with dicts and lambda functions,
Yes, you've seen them and they're not clear, obvious or English-like. They exist because some people like to wring their hands over the switch statement.
while other people simply recommended if..else nests.
Correct. They work. They're simple, clear, ...
Your code is good. Leave it alone. Move on.
A:
This lets you avoid giving each command name twice; function names are used almost directly as command names.
class CommandFunctions:
def c_check(self, arg):
print "checking", arg
def c_search(self, arg):
print "searching for", arg
def c_compare(self, arg1, arg2):
print "comparing", arg1, "with", arg2
def execute(self, line):
words = line.split(' ')
fn = getattr(self, 'c_' + words[0], None)
if fn is None:
import sys
sys.stderr.write('error: no such command "%s"\n' % words[0])
return
fn(*words[1:])
cf = CommandFunctions()
import sys
for line in sys.stdin:
cf.execute(line.strip())
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proper way to create an untextured, colored cube in XNA?
I'm currently trying to convert this code to C# XNA, however I'm having an issue with converting the CreateCube method - the resources on creating vertex lists in XNA seem to be outdated, dead, or just don't work.
Can anyone give me some help? I just want to create a colored, untextured cube by manually setting the vertexes of each face, then adding the (Those) cubes, or portions of cubes, to a VertexList to render.
A:
Check out this article on how to Construct, Draw and Texture a cube. You can leave out the Texturing part as you don't require that, but the article is a good start and follows a similar approach to your article.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Images in iPhone app appear in Simulator, but not when compiled to device
I am learning iPhone development, and have built a simple app that has an image that changes to another image when you tap it.
If i build it to the simulator, it works fine, but if i build it to the device the images dont appear. i feel like they aren't being copied across. I have checked they have been named correctly and i have made sure i imported them to 'resources'
I dont think it is a problem with the code because i added a thing to also make text appear when the image is tapped, and this works, so a button is still there doing something, it just doesn't have an image on it.
-(IBAction)changeImage:(id)sender {
[fortuneCookieButton setImage:[UIImage imageNamed:@"Image2.jpg"] forState:UIControlStateNormal];
label.hidden = NO;
}
-(IBAction)restoreImage:(id)sender {
[fortuneCookieButton setImage:[UIImage imageNamed:@"Image1.jpg"] forState:UIControlStateNormal];
label.hidden = YES;
}
A:
Does the case (upper/lower) of all your file names match exactly for all letters? Source code & project & Mac?
A:
just to share with you, I had this same problem and I found out the solution: I was using lower case in the file name and upper case in code. The thing is on Simulator there was no problem because Mac file system is case-insensitive but in the iPad it didn't work because iOS file system is case sensitive. ;-)
A:
I had this problem. Bizarrely the image had been working in the past, then just stopped appearing on the device one day.
It was a PNG.
I opened it in GIMP and saved it again. Then it went back to working again. No idea why.
Crazy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Periodic Binary Strings
Is there any efficient algorithms to check whether a binary string is periodic or not?
Let S be a binary string and H be the set of sub strings of S. Then S is said to be periodic if it can be obtained by concatenating one or more times, at least one h in H, also h != S .
A:
Initial string S with length Len. Double the string (really we need S + half of S). Search for occurrence of initial string S in doubled string SS, beginning from 2nd position, ending at Len/2 + 1. If such occurence exists with position P, then S is periodic with period P - 1.
S = abbaabbaabba Len = 12
SS = abbaabbaabbaabbaabbaabba
Searching from 2nd to 7th position, S found at P=5, period = 4
S = abaabaabaabb
SS = abaabaabaabbabaabaabaabb
S doesn't occur in SS (except for 1 and L+1), no period exists
P.S. Note due to useful Venkatesh comment:
We need to add minimal possible periodic unit, it's length is L/2 for even-size strings, and maximum divisor of L for odd-size strings (if length is prime number, string cannot be periodic). Simple factorization methods have O(N^1/2) complexity, more complex - O(N^1/4), so sometimes it is worth to factorize length to avoid unnecessary comparison of long strings.
A:
I'm pretty sure it is possible to improve on this, but I would have started by breaking the length of S (I'll call that L) to prime factors, and checking for a period of length of S/f for each prime factor f (len(h) must divide len(S) and I'm since not looking for the shortest possible h, prime L/len(h) is enough).
As to improvements, random check order would help in some circumstances (to prevent constructing input for worse case scenarios, etc.).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why would we multiply something by 10 if it's zero
I don't understand why we multiply i by 10 if it's already a zero.
so i would appreciate if some could explain why did we use this type of expressions to solve this problem.
#include <stdio.h>
main(void)
{
int n, num = 0;
printf("Enter any number to print individuellement : ");
scanf("%d", &n);
while(n != 0) // Instructions à répéter
{
> ***num = (num * 10) + (n % 10);***
`n = n / 10;`
}
while(num != 0) // Instructions à répéter
{
switch(num % 10)
.
.
.
.
.
.
.
.
.
.
num = num / 10;
}
}
A:
num is initialised to be zero only in the beginning.
After each iteration, its value changes as per the condition defined.
As a simplified example, you can see in the for loop, a variable is initialised to zero and then condition is provided and instructed to increment or decrement (usually) until the condition satisfies.
Initialising a variable to zero is to assign the value 0 to it if not, it will take the value of meromy block.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CodeIgniter unexpectedly redirects to 404 page
I am trying to make search engine but when I click on search button it goes to 404 page. Here is my view:
<aside class="widget">
<h5>SEARCH BLOG</h5>
<form class="form-inline search" role="search" action="<?php echo site_url('blog/search/');?>" method = "post">
<div class="form-group">
<div class="input-group">
<input name="search" type="text" class="form-control" id="search" placeholder="Search">
<div class="input-group-addon">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
</aside>
Here is my model:
function blog_search($keyword) {
$this->db->select('*');
$this->db->from('news');
$this->db->like('title_rus',$keyword);
$this->db->like('body_rus',$keyword);
$query = $this->db->get();
return $query->result();
}
Here is my controller:
function search() {
$keyword = $this->input->post('search');
$data['random_courses'] = $this->courses_model->get_random_course();
$data['category'] = $this->news_model->get_category_for_sidebar ();
$data['blog'] = $this->news_model->blog_search($keyword);
echo '<pre>';
print_r($data['blog']);
echo '</pre>'; die();
$this->load->view('templates/header');
$this->load->view('blog/blog', $data);
$this->load->view('templates/footer');
}
A:
Change $route["blog/search/(:any)"] = 'blog/search/$1' to $route["blog/search"] = 'blog/search' and try again. I don't think query param will count as (:any) in your routes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to identify which textfield is currently first responder
If you have several text fields on the screen, and the keyboard pops up for each one when they are tapped, what if you want to programmatically hide the keyboard, or resign first responder, but you don't know which textfield to send the resignFirstResponder message to? Is there a way to identify which object/textField should get this message?
A:
check all of your textfield call
[textfield isFirstResponder]
A:
You could keep track of which text field is the first responder by either setting your view controller to be the delegate object of all text fields and then when your subclassed text fields gets the "becomeFirstResponder" method call, tell your view controller which text field is the current one.
Or, there's a more blunt force approach which is a category extension to "UIView":
@implementation UIView (FindAndResignFirstResponder)
- (BOOL)findAndResignFirstResponder
{
if (self.isFirstResponder) {
[self resignFirstResponder];
return YES;
}
for (UIView *subView in self.subviews) {
if ([subView findAndResignFirstResponder])
return YES;
}
return NO;
}
@end
which I got from this potentially very related question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Incorrect syntax near the keyword 'if' SQL
I am trying to get result5 = 1 in case average of operating cashflow is <=0 or average of top 3 operating cashflow is <=0. The Error message says incorrect syntax near the keyword 'if'.
begin
declare @OperatingCashflow5 int
declare @OperatingCashflow3 int
declare @result5 int
select @OperatingCashflow5 = AVG(hpd.TotalCashFromOperations)
from HistoricalFinPerformanceDataStagingGlobal hpd
where hpd.companyid = @companyid
select @OperatingCashflow3 = AVG(hpd.TotalCashFromOperations)
from (
select top (3) hpd.TotalCashFromOperations
from HistoricalFinPerformanceDataStagingGlobal hpd
where hpd.companyid = @companyid
)
if @OperatingCashflow5 <= 0 OR @OperatingCashflow3 <= 0
begin
select @result5 = 1
end
else
begin
select @result5 = 0
end
end
A:
It's MUCH easier to see the problem when you take a moment to format the code.
In this case, you have a nested SELECT statement, and a nested select must have an alias. All you have to do is add a single letter (any letter) after the closing parentheses:
begin
declare @OperatingCashflow5 int
declare @OperatingCashflow3 int
declare @result5 int
select @OperatingCashflow5 = AVG(hpd.TotalCashFromOperations)
from HistoricalFinPerformanceDataStagingGlobal hpd
where hpd.companyid = @companyid
select @OperatingCashflow3 = AVG(hpd.TotalCashFromOperations)
from (
select top (3) hpd.TotalCashFromOperations
from HistoricalFinPerformanceDataStagingGlobal hpd
where hpd.companyid = @companyid
) hpd -- <<<< Need a name here
if @OperatingCashflow5 <= 0 OR @OperatingCashflow3 <= 0
begin
select @result5 = 1
end
else
begin
select @result5 = 0
end
end
I suspect there are other problems with that specific select query, as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UICollectionView interactive transition throwing exception
I'm trying to implement pinch-to-expand on a UICollectionView and am running into some trouble. Unlike all the sample code I can find, I'm not doing this as part of an interactive UINavigationController transition - I just need to expand an item in-place.
Here's my pinch gesture recognizer:
- (void)pinchGestureDidPinch:(UIPinchGestureRecognizer *)recognizer
{
CGFloat targetScale = 3.0;
CGFloat scale = recognizer.scale;
if (recognizer.state == UIGestureRecognizerStateBegan) {
CGPoint point = [recognizer locationInView:self.collectionView];
NSIndexPath *rowUnder = [self.collectionView indexPathForItemAtPoint:point];
self.pinchingRow = [NSIndexPath indexPathForItem:0 inSection:rowUnder.section];
self.currentState = HACStreamViewControllerTransitioning;
self.expandedLayout.expandedSection = self.pinchingRow.section;
self.transitionLayout = [self.collectionView startInteractiveTransitionToCollectionViewLayout:self.expandedLayout completion:nil];
} else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {
if (scale >= targetScale) {
[self.collectionView finishInteractiveTransition];
self.currentState = HACStreamViewControllerExpanded;
} else {
[self.collectionView cancelInteractiveTransition];
self.currentState = HACStreamViewControllerCollapsed;
}
} else {
// change
CGFloat progress = MIN(targetScale / scale, 1.0);
progress = MAX(0.0, progress);
self.transitionLayout.transitionProgress = progress;
[self.transitionLayout invalidateLayout];
}
}
Calling startInteractiveTransitionToCollectionViewLayout: causes an exception though:
0 ??? 0x0fcf577f 0x0 + 265246591,
1 UIKit 0x01e1f582 -[UICollectionViewTransitionLayout setTransitionProgress:] + 643,
2 UIKit 0x01d13053 -[UICollectionView _setCollectionViewLayout:animated:isInteractive:completion:] + 658,
3 UIKit 0x01d12be8 -[UICollectionView setCollectionViewLayout:] + 225,
4 UIKit 0x01d15e0a -[UICollectionView startInteractiveTransitionToCollectionViewLayout:completion:] + 821,
5 HAW Couples 0x0001beae -[HACStreamViewController pinchGestureDidPinch:] + 782,
6 UIKit 0x01a74f8c _UIGestureRecognizerSendActions + 230,
7 UIKit 0x01a73c00 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 383,
8 UIKit 0x01a7566d -[UIGestureRecognizer _delayedUpdateGesture] + 60,
9 UIKit 0x01a78bcd ___UIGestureRecognizerUpdate_block_invoke + 57,
10 UIKit 0x01a78b4e _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 317,
11 UIKit 0x01a6f248 _UIGestureRecognizerUpdate + 199,
12 UIKit 0x0173bd4a -[UIWindow _sendGesturesForEvent:] + 1291,
13 UIKit 0x0173cc6a -[UIWindow sendEvent:] + 1030,
14 UIKit 0x01710a36 -[UIApplication sendEvent:] + 242,
15 UIKit 0x016fad9f _UIApplicationHandleEventQueue + 11421,
16 CoreFoundation 0x033988af __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15,
17 CoreFoundation 0x0339823b __CFRunLoopDoSources0 + 235,
18 CoreFoundation 0x033b530e __CFRunLoopRun + 910,
19 CoreFoundation 0x033b4b33 CFRunLoopRunSpecific + 467,
20 CoreFoundation 0x033b494b CFRunLoopRunInMode + 123,
21 GraphicsServices 0x042619d7 GSEventRunModal + 192,
22 GraphicsServices 0x042617fe GSEventRun + 104,
23 UIKit 0x016fd94b UIApplicationMain + 1225,
24 HAW Couples 0x0000eefd main + 141,
25 libdyld.dylib 0x03bd5725 start + 0
The message on the exception:
*** setObjectForKey: object cannot be nil (key: actualAttribute)
I've verified that my "destination" UICollectionViewLayout is good. The following alternative (triggered by a tap) works fine, and animates as expected:
[self.collectionView setCollectionViewLayout:self.expandedLayout animated:YES completion:^(BOOL finished) {
}];
A:
I have exactly same problem, and in my case, this crash occurs when one of the layout is custom layout and the other one is UICollectionViewFlowLayout. I am still looking into this issue, but I was wondering if you have the same settings.
Edit 1)
In my custom layout, I had a decoration view and I returned UICollectionViewLayoutAttributes for the decoration view in [UICollectionViewLayout layoutAttributesForElementsInRect:] operation. I tested after removing layout attributes for decoration view and now it works perfectly. Decoration View in one layout that does not exist in the other layout seems to be an issue, and I will update my answer when I figure out more info.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect to url within another url using .htaccess
I have a problem, I need to redirect users to a URL within a url.
For example:
When the user visits the URL: api.example.com/redirect/www.google.com
I want the user to be redirected to: www.google.com
I've been trying for a while now, but no sucess.
A:
You are probably looking for something like that:
Variant for the main http server configuration:
RewriteEngine on
RewriteRule ^/redirect/(.+)$ http://$1 [L,R=301]
Variant for a .htaccess style file:
RewriteEngine on
RewriteRule ^redirect/(.+)$ http://$1 [L,R=301]
It obviously requires the rewrite module being available inside your local http server.
In general you should prefer putting such rules into the main server configuration, if you have access to that. A .htaccess style file should only be used if you have no other alternative. The reason is that such files are notoriously error prone, hard to debug and really slow the http server down.
A more robust approach would be to take the captured part of the url and hand it over to a script on the server side as a parameter. The script can validate the part, whether it is a valid "url" (to keep things simple here...). And maybe make a head request to check of the target exists and is usable. Only then it redirects. Otherwise it returns a meaningful error message.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the league structure in Starcraft II?
I've only played one placement match so far and I won it because my opponents were less than stellar. I'm afraid that if I get similar placement matches in the future and end up winning them all I might get put into a league beyond my skill.
How many different leagues are there?
Once placed in a league, is there any way to move to a different one? How?
A:
Currently (2013-04-01) the list of Leagues is:
Bronze League: 8% of all players
Silver League: 20% of all players
Gold League: 32% of all players
Platinum League: 20% of all players
Diamond League: 18% of all players.
Master League: The best 2% of all players. It is impossible to qualify directly into this League.
Grand Master: The top 200 players in a region. Is created only after 2 weeks into a new season. Players that are not active for a certain time get demoted to Master.
Before you are placed in a League, you must play 5 Placement Matches against random opponents. After that, the game tracks your skill by assigning you a matchmaking rating (MMR), which is not exactly your League points, but similar. Different Leagues correspond to different MMR ranges, and it is possible to be promoted or demoted, if your MMR stabilizes within another League's range.
After a Season ends, all Leagues are wiped, but MMR does not. To be placed in a new Season, you have to play one Placement Match, which does not actually mean more than any other match - it is just there to filter inactive players from League rankings. Skipping several Seasons does reset your MMR.
Since some patch there is also a button to Leave League - if you feel that your MMR is well in another League (like if you are constantly encountering equal opponents from there), but a promotion just doesn't come, you can try to force it. Note that this doesn't reset your MMR, of course.
There is also a special, Practice League. When you start playing on a new account, you are placed here, and can play fifty games here before your placement matches into "real" Leagues (you can leave whenever you want though). Practive League matches are played on a special, more "noob-friendly" maps, that have destructible obstacles completely blocking bases off, eliminating early pressure. After you leave Practice League, there is no way back ever.
Further reading: Starcraft Wikia
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replacement of sentence symbols by $0$-place connectives
Suppose we add $0$-place connectives $\top, \bot$ to our language. For each well-formed formula wff $, \phi$ and sentence symbol, $A,$ let $\phi^{A}_{\top}$ be the wff obtained from $\phi$ by replacing $A$ with $\top.$ Similarly for $\phi^{A}_{\bot}.$ Let $\phi^{A}_{*}= (\phi^{A}_{\top} \lor \phi^{A}_{\bot}).$
(i) Suppose $\phi \models\psi$ and $A$ does not appear in $\psi,$ could anyone advise me on how to show $\phi^{A}_{*} \models \psi$ and (ii )how to show $\phi$ is satisfiable iff $\phi^{A}_{*}$ is satisfiable?
Hints will suffice. Thank you.
A:
You must start with the definition of tautological implication (we may use this because we are considering only sentence letters) :
$\phi \models\psi$ iff, for every valuation $v$ such that $|\phi|_v = t$, also $|\psi|_v = t$.
Now assume that $\phi$ is built from $n$ sentence letters : $A, A_1, ... A_{n-1}$.
Consider now the truth-table (with $2^n$ rows) for $\phi$ : in these table, half of the rows have $A$ evaluated at t and half evaluated at f.
When we build the formula $\phi^{A}_{\top}$, this formula is equivalent to all the rows of the t-t for $\phi$ where $A$ is evaluated to t; the same with $\phi^{A}_{\bot}$, that is equivalent to the rows with $A$ evaluated to f.
So the formula $\phi^{A}_{*} = (\phi^{A}_{\top} \lor \phi^{A}_{\bot})$ may replace all the truth-table for $\phi$.
Now, go back to the tautological impliction :
$\phi \models\psi$ iff for every valuation $v$ such that $|\phi|_v = t$, also $|\psi|_v = t$,
i.e. for every row in the t-t for $\phi$ that evaluates to t, also $\psi$ is evaluated to f.
But the rows of the t-t for $\phi$ which evaluate to t may have $A=t$ or $A=f$; both cases are covered by the disjunction $\phi^{A}_{\top} \lor \phi^{A}_{\bot}$ (if the row has $A=t$, this row is "covered" by $\phi^{A}_{\top}$ and if the row has $A=f$, it is covered by$\phi^{A}_{\bot}$.
So the taut implication still hold : of course, $A$ must not be in $\psi$, because substituting $A$ with $\top$ or $\bot$, we have lost "the link" between the two original formuals when we use the valuation $v$.
Now I think that you can easily use this argument to show satisfiability...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to set two relative position div align top
See the full code here:
http://jsfiddle.net/jx2jc0xv/
.one {
position: relative;
display:inline-block;
width:70px;
background-color: #ddd;
}
.two {
position: relative;
display:inline-block;
width:80%;
background-color: #ddd;
}
I want to set .one and .two divs align top where .two div will be responsive width and height.
Here I used in .two div width: 80%; which is not full width also.
A:
If I understand you correctly, this should work:
.one {
position: relative;
top: 0;
float: left;
width:70px;
background-color: #ddd;
}
.two {
position: relative;
top: 0;
float: left;
width:80%;
background-color: #ddd;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does MVC3 web.config allow authentication over individual Controllers?
I have seen such as
<location path="~/SomeController">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
I placed this section after the section where it has the with authentication. This doesn't seem to work. It still asks for log in.
Am I missing something? I'm really new to this so I apologize if this is very rudimentary stuff.
A:
You really shouldn't be using the web.config to control the authentication of your application.
Use the Authorize attribute on the controllers you want to secure, and leave it off the ones you don't.
See this blog post for more details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Force mounting an external disk that is not recognized
I recently bought a 4 TB naked (no enclosure) external hard drive that I mount via a Newer Tech dock (the ones where you insert the naked drive like bread in a toaster) and is connected to my MacBook pro via FireWire 800.
About a month later I wanted to use the drive and it would not mount.
Disk Utility reports that it is "Not Mounted".
When I connect the drive I get this:
The disk you inserted was not readable by this computer.
So I tried terminal commands like:
diskutil list
which yelds this:
I also tried:
mount force /dev/disk3
and got:
mount: You must specify a filesystem type with -t.
and then:
mount force -t Apple_HFS /dev/disk3
which outputs:
usage: mount [-dfruvw] [-o options] [-t external_type] special node
mount [-adfruvw] [-t external_type]
mount [-dfruvw] special | node
I also tried:
diskutil repairVolume /dev/disk3
which gives back:
Error starting file system repair for disk3: Unrecognized file system (-69846)
and finally:
sudo gpt -r show /dev/disk3
which returns:
I am at a loss, can anyone give me some advice on how to mount this drive?
A:
Just when I was about to give up, format the drive and lose my data, somehow I was able to fix the drive so I am posting what exactly I did in terminal for the benefit of other people who might come across this post and have the same problem. I hope this will be helpful to somebody:
Admins-MacBook-Pro:~ admin$ diskutil mount /dev/disk3
Volume on disk3 failed to mount; if it has a partitioning scheme, use "diskutil mountDisk"
If the volume is damaged, try the "readOnly" option
If the volume is an APFS Volume, try the "diskutil apfs unlockVolume" verb
Admins-MacBook-Pro:~ admin$ mount force /dev/disk3
mount: You must specify a filesystem type with -t.
Admins-MacBook-Pro:~ admin$ mount -t /dev/disk3
Admins-MacBook-Pro:~ admin$ mount force -t /dev/disk3
usage: mount [-dfruvw] [-o options] [-t external_type] special node
mount [-adfruvw] [-t external_type]
mount [-dfruvw] special | node
Admins-MacBook-Pro:~ admin$ mount -t force /dev/disk3
usage: mount [-dfruvw] [-o options] [-t external_type] special node
mount [-adfruvw] [-t external_type]
mount [-dfruvw] special | node
Admins-MacBook-Pro:~ admin$ diskutil verifyDisk /dev/disk3
Nonexistent, unknown, or damaged partition map scheme
If you are sure this disk contains a (damaged) APM, MBR, or GPT partition
scheme, you might be able to repair it with "diskutil repairDisk /dev/disk3"
Admins-MacBook-Pro:~ admin$ diskutil repairDisk /dev/disk3
Nonexistent, unknown, or damaged partition map scheme
If you are sure this disk contains a (damaged) APM, MBR, or GPT partition map,
you can hereby try to repair it enough to be recognized as a map; another
"diskutil repairDisk /dev/disk3" might then be necessary for further repairs
Proceed? (y/N) y
Partition map repair complete; you might now want to repeat the
verifyDisk or repairDisk verbs to perform further checks and repairs
Admins-MacBook-Pro:~ admin$ diskutil repairDisk /dev/disk3
Repairing the partition map might erase disk3s1, proceed? (y/N) y
Started partition map repair on disk3
Checking prerequisites
Checking the partition list
Adjusting partition map to fit whole disk as required
Checking for an EFI system partition
Checking the EFI system partition's size
Checking the EFI system partition's file system
Checking the EFI system partition's folder content
Checking all HFS data partition loader spaces
Checking booter partitions
Reviewing boot support loaders
Checking Core Storage Physical Volume partitions
Updating Windows boot.ini files as required
The partition map appears to be OK
Finished partition map repair on disk3
Admins-MacBook-Pro:~ admin$
Since I've tried pretty much every terminal line under the sun, I think the key was the sequence in which this worked, which was:
mount -t /dev/disk3
mount force -t /dev/disk3
diskutil verifyDisk /dev/disk3
diskutil repairDisk /dev/disk3
diskutil repairDisk /dev/disk3
When I heard tried to verifyDisk and repairDisk a few days ago it had not worked but somehow with this sequence it was able to repair the partition map
Thank you to all of you guys who have tried to help me with this.
I am glad to have my data back ;)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to output mtr command in human-readable form to standard output?
When I run sudo mtr 4.2.2.1, it runs in the Terminal in a loop.
I'd like to keep the same format as below:
Host
1. 192.168.15.1
2. ???
3. 10.254.254.x
4. 10.254.254.x
5. core1.lon2.he.net
6. 10gigabitethernet2-1.core1.lon2.he.net
7. a.resolvers.level3.net
but printed once to the standard output.
In manual I can see only options to print it in XML, JSON, CSV or RAW formats, but not in the human-readable format as above printed once. Basically I'm interested in similar format when using traceroute command, but for mtr. Is it possible?
I've tried to run as sudo mtr -c1 4.2.2.1 | head -n20, but it breaks the terminal, so I've to reset it after each use. Any workaround to that?
A:
If you want to process mtr's output, or keep it displayed after mtr quits, you need to run it in report mode, or better, wide report mode:
mtr -r -c1 4.2.2.1
or
mtr -w -c1 4.2.2.1
(the difference is that in wide report mode, it won't truncate hostnames).
mtr -w -c1 4.2.2.1 | awk 'NR>1 {print $1, $2}'
would give something close to what you're after.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Animate Wordpress site navigation menu
I have this site: http://bit.ly/1p1Dr9W
This navigation looks kind of blank. I'd love to add css animation to it. I tried using opacity, but it does not work as intended. What am I doing wrong?
I added hover animation over each navigation elements and it works fine, but I'd like to add animation to whole navigation menu, so the whole list of sub menu elements would open with some animation (for example slow opacity to 1).
This is what i got:
#menu-menyy li ul {
background-color: transparent; }
#menu-menyy li ul:hover {
background-color: #00a3fc !important;
-o-transition:.8s;
-ms-transition:.8s;
-moz-transition:.8s;
-webkit-transition:.8s;
transition:.8s;}
But whole navigation menu still just pops open, and as i move my mouse over the actual menu, i see the transition in the background. Can this be done in CSS afterall or it is made with jquery?
A:
Change css to
#menu-menyy li ul {
opacity: 0; }
#menu-menyy li:hover ul {
background-color: #00a3fc !important;
opacity: 1.0;
-o-transition: opacity .8s;
-ms-transition: opacity .8s;
-moz-transition: opacity .8s;
-webkit-transition: opacity .8s;
transition: opacity .8s;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pip install not functioning on windows 7 Cygwin install
I'm having a terrible time of getting pip up and running on Cygwin which I just recently installed on my Windows 7 Computer. I am writing in the hope that anyone out there can tell me what I am doing incorrectly in terms of getting these packages installed correctly.
To start, I followed the instructions on this site:
http://www.pip-installer.org/en/latest/installing.html
with setuptools installed prior to pip installation. I followed the steps, ran this command:
Ryan@Albert ~
$ python get-pip.py
got this output:
Downloading/unpacking pip
Downloading pip-1.5.tar.gz (898kB): 898kB downloaded
Running setup.py egg_info for package pip
warning: no files found matching 'pip/cacert.pem'
warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.rst' found under direct
no previously-included directories found matching 'docs/_build/_sources'
Installing collected packages: pip
Running setup.py install for pip
warning: no files found matching 'pip/cacert.pem'
warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.rst' found under direct
no previously-included directories found matching 'docs/_build/_sources'
Installing pip script to /usr/bin
Installing pip2.7 script to /usr/bin
Installing pip2 script to /usr/bin
Successfully installed pip
Cleaning up...
and lo and behold, ran pip with this command:
Ryan@Albert ~
$ pip install --upgrade setuptools
which led to absolutely no output. A blank line appeared underneath for 3-4 seconds and then the input prompt came up again without pip actually doing anything. I did a bunch more testing to confirm that there was something called pip on my machine but anytime it ran, it essentially did nothing. It did not download or install any programs.
I went about trying to install pip another way after uninstalling the first version. This time I tried:
$ easy_install pip
And got the following output:
Searching for pip
Best match: pip 1.5
Adding pip 1.5 to easy-install.pth file
Installing pip script to /usr/bin
Installing pip2.7 script to /usr/bin
Installing pip2 script to /usr/bin
Using /usr/lib/python2.7/site-packages
Processing dependencies for pip
Finished processing dependencies for pip
Again, tried using pip to install virtualenv using this command:
$ pip install virtualenv
and it paused for 3-4 seconds, then made the command prompt available again. Exactly like the previous time. When I checked to see whether virtualenv was installed, it was not.
Essentially I have tried and tried to get pip up and running on my windows 7 Cygwin install but to no avail. I am aware of the fact that I can use other packages to install plugins and so forth but I would really appreciate it if someone had any knowledge on why this was happening so it doesn't plague me when I try to install stuff further on down the line.
Any help would be greatly appreciated!
A:
There's a bug(?) in 64-bit Cygwin which causes ctypes.util to segfault when trying to find libuuid (/usr/bin/cyguuid-1.dll). The fix is to install libuuid-devel from Cygwin setup. I found this from an issue filed against requests.py, but it's noted (and worked around in different ways) in a few other places, too.
A:
Came across the same problem. Installation of binutils cygwin package solved it for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vscode on Centos 7.7 does not recognize Intel AVX functions, errors about __mm256i
I want to use some avx2 functions by including <immintrin.h> library in my project; however, Vscode does not seem to recognize these functions, as it is showing that my project contains various identifier "__m256i" is undefined errors as the attached pictures. I can compile and run smoothly, but the errors are really disturbing. I tried adding the declarations of these types into the Vscode path, but it does not help.
I am using the latest Vscode version in Centos 7.7.
Vscode show errors
Try added the include path, but does not help
A:
__mm256i is a typo for __m256i.
The type names have 2 underscores and one m like __m128i
The intrinsic function names have one underscore and 2 ems like like _mm_add_epi32
I can compile and run smoothly, but the errors are really disturbing.
That's highly implausible, are you sure you're not running an old version of your executable from before you introduced this bug in your source? This is an error, not a warning; gcc won't produce a .o from a source file with this bug. Hard errors are the opposite of compiling "smoothly".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Will there be consequences or issues if I install XQuartz?
I need to install XQuartz to install Inkscape, a vector graphics application.
May I know if issues would come when I install XQuartz? I'm new to OS X and I find the need to install an application to install another application unusual.
A:
It's absolutely fine, it's essentially a standalone application that you can uninstall again anytime. Except when you're running Inkscape, you'll never know it's there.
In fact, XQuartz used to come on the OS X install DVD (though it wasn't installed by default), but like Java and Flash, Apple just prefer not to package and ship those things with the OS any more, and require you to install it separately direct from the developer.
If you're still not sure, there is a native port of Inkscape in progress that doesn't require XQuartz, but it was a little buggy last time I tried.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to explan this SAS macro?
I'm a new SAS learner. Here is a SAS statement.
%if %sysfunc(prxmatch(/^(E0349646)$/i, &SYSUSERID.)) ne 0 %then %do;
I only know the "E0348535" is a user ID, but can't understand this whole statement. Please explan this SAS macro. Many thanks!
A:
First a little on terminology. The SAS macro processor is a tool that can manipulate text and pass the result onto the actual SAS system to interpret. That one line of code is using macro processor statement, but it is not a full macro definition. In fact starting with SAS 9.4 (I think perhaps maintenance release 9.4m4?) you could use that %if/%then/%do type of statement in a normal SAS program, without ever having to define an actual macro at all.
So what you have is a macro %if statement. General form is:
%if condition %then statement ;
Since the statement after the %then part is a %do macro statement then your program will need a %end; statement to mark the end of the block to execute when the condition is true.
Let's look at the condition being tested in your %if statement.
%sysfunc(prxmatch(/^(E0349646)$/i, &SYSUSERID.)) ne 0
So that is using macro function %sysfunc() to let you call the SAS function prxmatch() in macro code. That is part of the group of functions that implement Perl Regular Expressions. You are also referencing a macro variable named SYSUSERID. That particular macro variable is one that SAS creates automatically to contain the userid of the user that is running the SAS program. The regular expression being used in the prxmatch() function call is testing if the value is equal to E0349646, ignoring case. The result will be position of the first found location in the string being searched. If it is not found then it will return 0. (SAS, like humans, uses indexes starting from one and not zero.).
Note that including the ^ and $ in the regular expression means that it needs to match the full string. So you are testing if E0349646 is running the program.
It would be much easier to test that directly without the need for a regular expression or the need to use non-macro function calls.
%if %upcase(&sysuserid)=E0349646 %then %do;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extracting data using BeautifulSoup and a loop
The data I need is enclosed between two HTML comments. The first is "Data starts here" and the second is "Data ends here"
I've figured out how to get the next line after the comment, but I need the one after, and the one after that, until it hits the "Data ends here" comment.
Here's my attempt at writing a loop for it. However, that just enters an infinite loop of printing the first line after the comment.
I don't know how many lines will be between the two comments, so it needs to be a while loop. Any tips? I think I'm close. I'm just not knowledgable with BeautifulSoup 4 yet.
import requests
from bs4 import BeautifulSoup, Comment
response = requests.get(url)
soup = BeautifulSoup(response.content, "lxml")
for comment in soup.findAll(text=lambda text:isinstance(text, Comment)):
if comment.strip() == 'Data starts here':
while comment.next_element.strip() != 'Data ends here':
print(comment.next_element.strip())
EDIT:
</div>
<p clear="both">
<b>Data at: 0734 UTC 27 Jan 2017</b></p>
<!-- Data starts here --> KJXN 270656Z AUTO 30012KT 10SM SCT026 OVC033 00/M04 A2980 RMK AO2 SNE0558 SLP100 P0000 T00001044<br/><hr width="65%"/> KTEW 270724Z AUTO 27008KT 10SM OVC040 00/M04 A2979 RMK AO2 T00001042<br/><hr width="65%"/>
<!-- Data ends here -->
<br clear="both" style="clear:both;"/>
</div> <!-- awc_main_content -->
</div> <!-- awc_main -->
WEBSITE LINK: https://www.aviationweather.gov/metar/data?ids=KJXN%20KDTW%20KLAN&format=raw&hours=0&taf=off&layout=on&date=0
A:
import requests, bs4
r = requests.get('https://www.aviationweather.gov/metar/data?ids=KJXN%20KDTW%20KLAN&format=raw&hours=0&taf=off&layout=on&date=0')
soup = bs4.BeautifulSoup(r.text, 'lxml')
text_list = soup.find(id="awc_main_content").find_all(text=True)
start_index = text_list.index(' Data starts here ') + 1
end_index = text_list.index(' Data ends here ')
text_list[start_index:end_index]
out:
['\nKJXN 270656Z AUTO 30012KT 10SM SCT026 OVC033 00/M04 A2980 RMK AO2 SNE0558 SLP100\n P0000 T00001044',
'\nKDTW 270653Z 28012KT 9SM -SN BKN020 BKN035 OVC065 02/M04 A2980 RMK AO2 SNB08\n SLP095 P0000 T00171039',
'\nKLAN 270653Z 27012KT 10SM OVC042 00/M05 A2979 RMK AO2 SLP096 T00001050',
'\n']
text_list will return all the text in the div tag, we can use index to get the start and end index of info we need then slice the list.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.