INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Running Hadoop tests on remote Hadoop cluster
I have extracted hadoop source code from <
Currently, hadoop tests spins up a mini single node cluster on the same jvm and executes the tests. However, my goal is to run the Junit tests on already installed remote hadoop cluster. I want to keep the unit tests as client which runs outside cluster. Not able to figure out if the hadoop tests supports the same.
|
The tests are designed to run it against localhost and not a real cluster. Bigtop Apache is the ongoing one for that. Refer <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "unit testing, hadoop, junit, hdfs, hadoop2"
}
|
Probability in a deck of cards to have two jacks in a row
In a deck of $36$ cards ($9$ cards per color, $4$ colors) what is the probability to have $2$ jacks (or more) that follow each other?
|
There are $36\choose 4$ ways to position the jacks. There are $33\choose 4$ ways to position the jacks without adjacencies (imagine to first lay aside three neutral cards and later insert them after the first three jacks). Therefore the answer is $$1-\frac{33\choose 4}{36\choose 4}=1-\frac{33\cdot 32\cdot 31\cdot 30}{36\cdot 35\cdot 34\cdot 33}=\frac{109}{357}. $$
|
stackexchange-math
|
{
"answer_score": 8,
"question_score": 4,
"tags": "probability, combinatorics, card games"
}
|
One MsgBox To show all passes and fails
I am trying to make one message box to include passes and fails of samples.

Dim x As Long
For x = 2 To 8
If Sheet2.Range("B" & x).Value < 0.24 Then
y = Sheet2.Range("A" & x).Value
MsgBox "Pass: " & y
Else
MsgBox "Fail: " & y
End If
Next
End Sub
|
You could accumulate the results in two string variables as shown below, and display the results after the loop has completed. Also, `y` is set only if the value is smaller than `0.24`. You need to set `y` before the `If`.
Sub MsgB()
Dim x As Long
Dim pass as String
pass = ""
Dim fail as String
fail = ""
For x = 2 To 8
y = Sheet2.Range("A" & x).Value
If Sheet2.Range("B" & x).Value < 0.24 Then
pass = pass & ", " & y
Else
fail = fail & ", " & y
End If
Next
' Print pass and fail, removing the leading ", ".
pass = Right(pass, Len(pass) - 2)
fail = Right(fail, Len(fail) - 2)
MsgBox "Pass: " & pass & vbCrLf & "Fail: " & fail
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 1,
"tags": "excel, vba, msgbox"
}
|
Cannot install Core, unlikely download issues reported
I'm trying to install Janestreet's Core for OCaml using opam on Mac OsX to get started with the "Real world OCaml" book.
I get the following error:
===== ERROR while installing herelib.109.35.02 =====
Could not get the source for herelib.109.35.02:
# opam-version 1.1.1
# os darwin
Cannot download
please check your connection settings.
All other libraries after `herelib` fail as well.
I don't have connection problems, though, as the libraries up to `herelib` do download (last successful is `type_conv` as far as I can tell). Also, pasting the reported URL in Chrome starts a file download immediately, so it doesn't seem to be a server problem at the source.
Homebrew reports my Opam and Ocaml as up to date.
Any ideas?
|
Your version numbers for both `herelib` and `opam` looks quite outdated. The following may help:
1. Update your repository with `opam update`
2. Try to use more recent `opam`, it is available under macports and brew.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ocaml"
}
|
Reference custom table in WiX fragment file
I want to create a fragment file that will only contain a CustomTable in the file. This is easy enough, but I do not know how to link/include it back into the main product.wxs file.
The fragment file is in the same project as the product file, and I have also tried adding an include tag for the file without success, and even putting the custom table into a WiX include file.
Is there a way to do this? Or is it going to have to live in the product file?
|
The WiX toolset compiles and links in a similar manner to the C/C++ compiler. The linker starts at the "main" entry point (Product element, in your case) then follows the references from there, which in turn follows references from there until all are resolved.
Part of your question is missing but based on the title I'm going to guess that you want a `CustomTable` element. Typically that `CustomTable` is processed by a `CustomAction`. There are a couple good ways to reference a `CustomAction`.
I would _not_ use an include file.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "visual studio 2010, wix, wix3.5"
}
|
ANR (Force close/Wait) while generating a big enough list
I am creating a kind of file explorer, in which if any application files are copied to phone/SD card I am showing it on an activity with dialog theme to user. For every new "app.apk" copied I am appending the name of the app and location to the dialog and the list is scrollable. My problem is, if I copy some 200+ apps onto the storage at once the list population gives Force close/wait dialog (ANR). How can I prevent my app from getting this kind of ANR?
|
If some large calculation and UI tries to run at the same time and it takes enough time to launch (approximately over 5 sec) then the system concerns user to close the application.
To solve this, an option is to distribute your operations into different child thread and then run UI on an asynchronous thread (runOnUiThread) for scheduling application task.
new Thread() {
@Override
public void run() {
try {
// code runs in a thread
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// code runs in a UI(main) thread
}
});
} catch (final Exception ex) {
}
}
}.start();
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "android, android anr dialog"
}
|
Paste clipboard data as plain text Service?
Is there a Mac OS X service that takes clipboard data and pastes it as plain text? Or an easy way to create one?
|
A couple options, gleefully swiped from Mac OS X Hints:
Applescript, converting pasteboard contents to plain text and pasting:
tell application "Finder" to set frontApp to (name of 1st process whose frontmost = true)
tell application frontApp
activate
set clip to «class ktxt» of ((the clipboard as text) as record)
tell application "System Events" to keystroke "v" using {command down}
end tell
Shell script, save it in your Scripts folder and chmod 755
#!/bin/sh
pbpaste | pbcopy
osascript -e 'tell application "System Events" to keystroke "v" using {command down}'
|
stackexchange-apple
|
{
"answer_score": 4,
"question_score": 3,
"tags": "services, copy paste"
}
|
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ')' while creating the table in sql
Whenever I try to create table in my selected database I get
> Msg 102, Level 15, State 1, Line 1
> Incorrect syntax near ')'
Can anybody tell me whats the error and how to overcome.
What's the error in it ?
CREATE TABLE first_name
(
)
|
The error is that every table needs to have at least a single column.
CREATE TABLE users
(
id int,
firstname varchar(255),
lastname varchar(255)
)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server"
}
|
How to link Question node to current page?
I would like users to be able to ask questions related to current page without going to another page as it works now in the Relevant Answers module. There is a related issue: <
I can create a custom block with form in it, and create new `Question` node on submit.
How can I link that new node to current page?
|
In your custom block return your form like this.
global $user;
// You may need to get your path a different way here?
$original_path = implode('/', args());
// Just set the GET path to the path ^ from there. The form_alter()
// will pick it up automatically for you on line 86 in relevant_answers.module.
$_GET['path'] = relevant_answers_compress_string($original_path);
$node = (object) array('type' => 'question', 'uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'language' => LANGUAGE_NONE);
$form = render(drupal_get_form('question_node_form', $node));
// Return your rendered form.
// You may need to do some stuff with redirecting if its not going to the right page after you submit.
return $form;
This is completely untested but should get you down the right path to solving your issue.
|
stackexchange-drupal
|
{
"answer_score": 4,
"question_score": 5,
"tags": "7"
}
|
Notebook CPU that supports 16GB of memory?
I am planning to buy a new notebook, and among the requirements I thought that I want 8GB of memory now, and the possibility to upgrade to 16 later.
I have done some searching and I have learned that Intel's Core i3/i5/i7 branding is a complete mess, and that the mobile versions of Core i3/i5/i7 (Arrandale or Clarksfield) have no or little corresponding matching with the desktop versions (Lynnfield, Clarkdale, Bloomfield, ...).
Apparently the desktop Core i7 cpus can support 24GB of memory, but that does not help me since it appears that none of the mobile CPU supports more than 8GB (not even the core i7 extreme edition).
I gave up on finding information on AMD's web site; I could not find any mentioning about memory limitations at all.
Is really only 8GB of memory the maximum amount of memory possible for a notebook today???
|
No. You can get laptops from both Dell and HP that support 16 GB of memory or more. Look for laptops described as "mobile workstations". For Dell that is their Precision line and HP has the Elitebook.
|
stackexchange-superuser
|
{
"answer_score": 6,
"question_score": 4,
"tags": "memory, cpu, hardware rec"
}
|
SVN stops realizing a directory has a new file, so add on parent folder does not find files
I used to be able to use the tortoiseSVN add on the parent folder o my project and it would find all files new that needed to be added them, give me a list and I could click okay. Now if I do this it says no new files, and yet I know there are and have to manually goto the file and add it. Was it a setting change I am unaware of, I am not even sure what the parent down method of adding is called (subdirectories? but the add doesnt give that option) . This is a WAG I am taking posting here grasping at straws...my project is getting large and remembering all the files I added to the Unity project is getting tedious, not sure what stopped it from working the other way...
|
1. With TortoiseSVN, you can do not add explicitly new files in WC before commit - TSVN will discover new files for you automatically
2. SVN (TortoiseSVN) will skip files, if they match ignore-pattern (global or local): `svn status`|`svn status --no-ignore` inside folder in question may help you detect such ignored files
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "svn, tortoisesvn"
}
|
Where could be inline-css in Wordpress
I am working on this webpage:< which runs on Wordpress with this theme If you check source code you can see a lot of inline-css and I want to know in which files are actually defined. Only thing what I know about it they are called by function wp_head() in header.php. I have local copy of all files on this web and I can't find any mention about some of that css rules through unix grep. Anyone suspect where these css rules could be located?
check site and let me know.
|
Run a search in the source code for
style-inline
As this appears to be the 'handle' designated as the first variable in the function **wp_add_inline_style**. The "-css" is added automatically. You'll see this on line 79 of the page source.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, wordpress"
}
|
Not able to connect to external sites on Cisco Anyconnect using Ubuntu 20.04
I am using Cisco AnyConnect Mobility Client 4.5.02033 on Ubuntu 20.04.
When I try to connect to the company's network it is working fine but as soon as I open any external website, (example: www.google.com) it doesn't open them.
Can someone please help me figure out the issue?
|
So I finally contacted the network admins and they informed me that I need to put "Wpad" as network proxy and that solved my problem.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "networking, internet, 20.04, vpn, cisco"
}
|
updating options on signature pad plugin
I am trying to update the options on Signature Pad but it does not seem to be working.
The option that I am trying to update is the pen colour, i have created a button that once clicked on should update the object and change the pen colour.
var options = {
drawOnly: true,
defaultAction: 'drawIt',
validateFields: false,
lineWidth: 0,
output: null,
sigNav: null,
name: null,
typed: null,
clear: 'input[type=reset]',
typeIt: null,
drawIt: null,
typeItDesc: null,
drawItDesc: null,
penColour: '#000',
};
var api = $('form').signaturePad(options);
$('.green').click(function(){
api.clearCanvas();
$.fn.signaturePad.penColour = '#00FF00';
});
any ideas?
|
You can supply new options when you regenerate the signature.
Documentation: <
Using the API:
$('.green').click(function() {
// Store the signature JSON object so you can regenerate
var sig = api.getSignatureString();
api.clearCanvas();
// Regenerate the signature with the updated option
api.updateOptions({ penColour: '#00FF00' }).regenerate(sig);
});
Or, you can just recreate the whole thing, without the API:
$('.green').click(function(){
// This is a JSON formatted signature
var sig = api.getSignatureString();
api.clearCanvas();
var options = {
penColour: '#00FF00'
/* other options */
}
$('form').signaturePad(options).regenerate(sig);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery"
}
|
How to collect docs in order in collect() method of a custom aggregator?
I am developing a custom aggregator using ES 1.3.4. It extends from `NumericMetricsAggregator.MultiValue` class. Its code structure closely resembles that of the `Stats` aggregator. For my requirements, I need the doc Ids to be received in ascending order in the overridden `collect()` method. For most queries, I do get the doc Ids in ascending order. Interestingly for `bool` `should` queries having multiple clauses, I get doc Ids in descending order! How can I fix this? Is this a bug?
|
I asked the same question on github and got the answer which worked for me. Here's the solution:
> You can call aggregationContext.ensureScoreDocsInOrder(); to make sure that docs are going to come in order, have a look for instance at ReverseNestedAggregator which uses this method.
>
> Queries are indeed allowed to emit documents out-of-order if allowed to do so and if it makes things faster. I believe the only case when it happens today is when you get Lucene's BooleanScorer which is used for top-level disjunctions, so your observation makes sense.
Link to the issue: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "elasticsearch, aggregation"
}
|
Copy files from specific directory using PowerShell
I want to copy files witch part of they folder name is same e.g ../example/test_n, n is from 1 to 15. I saw a resolution when using bash, we just need to write one line and it would be cp ../example/test* ..example/dest. And my question is, is there a equal operation in PowerShell?
|
Equivalent of your bash sample with a wildcard could be
Copy-Item C:\example\test* C:\example\dest\ -recurse
Assuming you don't need to have a control to limit the 1-15 range.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "powershell, shell"
}
|
Remove trailing commas in ruby string
I am getting the following value in my params: "45,284"
How can I remove the the leading and trailing double quotes from my string?
The output that I should get is: 45,284
|
You can do this to your `params[:userValues]` to make it suitable for `IN` clause in your query
"45,284".split(",").map(&:to_i) #=> [45, 248]
So for `params[:userValues]` it will be
user_values = params[:userValues].split(",").map(&:to_i)
Now the query will look like this
@user = User.where('is_active = ? and is_support_user = ? and id IN (?)', true, false, user_values).order(:user_name)
This will work, try it out
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -4,
"tags": "ruby on rails, ruby"
}
|
How to create prepared statements for mariadb, node.js and websockets
I'm trying to create a db query using a prepared statement.
I have:
connection.query('
INSERT INTO myTable (column_1, column_2, column_3)
VALUES (?`, [col_1_val]`, ?`, [col_2_val]`, ?`, [col_3_val]`)`)
Obviously this is pretty wrong. In the above example, all variables are numbers. But in production some will be strings.
I've also tried lots of other things, such as:
connection.query('
INSERT INTO myTable (column_1, column_2, column_3)
VALUES (?, ?, ?`, [col_1_val, col_2_val, col_3_val])
|
Prepared statements in node.js can be written as:
connection.query("
INSERT INTO myTable (column_1, column_2, column_3)
VALUES (?, ?, ?)", [col_1_val, col_2_val, col_3_val])
For those variables you wish to convert to strings:
connection.query("
INSERT INTO myTable (column_1, column_2, column_3)
VALUES (?, ?, ?)", [col_1_val.toString(), col_2_val.toString(),
col_3_val.toString()])
The MariaDB getting started page provides an example of prepared statements: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql, node.js, websocket, mariadb, prepared statement"
}
|
Is the graph of $y=\frac{k}{x}$ a hyperbola?
Is the graph of the following inverse relation a hyperbola?$$y=\frac kx$$
If yes, is it the only kind of hyperbola whose equation is an explicit function?
|
Yes, $$y=\frac kx$$ is a hyperbola. In fact, it is a type of _rectangular hyperbola_ which you can read more about here.
This means that a function $y(x)$ that takes the form $$y-k=\frac {k}{x-h}$$ is also hyperbola.
~~I suppose that is the only type of hyperbolas that is a function since any rotation of this type of hyperbolas will immediately cause the plot to fail the vertical line test.~~
Thanks to @Blue:
> Any (non-degenerate) hyperbola with a vertical asymptote is the graph of a function. Rectangularity is not a requirement.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 1,
"tags": "conic sections"
}
|
How to move ownership across unique_ptrs
I have two smart-pointers:
Foo *p1 = new Foo;
Foo *p2 = new Foo;
std::unique_ptr<Foo> u1(p1);
std::unique_ptr<Foo> u2(p2);
Now I want `u1` to own `p2`. And I want `u2` to own nothing (or `nullptr`). Of cource, at the same time `p1` must be deleted gracefully.
What C++ code should I write to accomplish it?
|
Use `std::move` to cast `u2` to an rvalue then use move assignment to "move" `u2` into `u1`:
u1 = std::move(u2);
After the move, `u2` will be `nullptr` although that is special case for `unique_ptr`, don't expect moved from objects to be in any particular state generally. And of course `p1` will be deleted gracefully.
I recommend you don't create `p1` or `p2` at all and never have any owning raw pointers:
std::unique_ptr<Foo> u1(new Foo);
Or better yet, in C++14:
auto u1 = std::make_unique<Foo>();
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "c++, c++11"
}
|
Python Pandas imputation of Null values
I am attempting to impute Null values with an offset that corresponds to the average of the row df[row,'avg'] and average of the column ('impute[col]'). Is there a way to do this that would make the method parallelize with .map? Or is there a better way to iterate through the indexes containing Null values?
test = pd.DataFrame({'a':[None,2,3,1], 'b':[2,np.nan,4,2],
'c':[3,4,np.nan,3], 'avg':[2.5,3,3.5,2]});
df = df[['a', 'b', 'c', 'avg']];
impute = dict({'a':2, 'b':3.33, 'c':6 } )
def smarterImpute(df, impute):
df2 = df
for col in df.columns[:-1]:
for row in test.index:
if pd.isnull(df.loc[row,col]):
df2.loc[row, col] = impute[col]
+ (df.loc[:,'avg'].mean() - df.loc[row,'avg'] )
return print(df2)
smarterImpute(test, impute)
|
Notice that in your 'filling' expression:
impute[col] + (df.loc[:,'avg'].mean() - df.loc[row,'avg']`
The first term only depends on the column and the third only on the row; the second is just a constant. So we can create an imputation dataframe to look up whenever there's a value that needs to be filled:
impute_df = pd.DataFrame(impute, index = test.index).add(test.avg.mean() - test.avg, axis = 0)
Then, there's a method in called `.combine_first()` that allows you fill the NAs in one dataframe with the values of another, which is exactly what we need. We use this, and we're done:
test.combine_first(impute_df)
With pandas, you generally want to avoid using loops, and seek to make use of vectorization.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, pandas, imputation"
}
|
How to use events of SwipeView in qml?
I have created an new project of qt quick controls 2 .It have an `SwipeView` as default.
Now I want to use `onIndexChanged` event of `SwipeView` but I got an error
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
SwipeView {
id: swipeView
anchors.fill: parent
currentIndex: tabBar.currentIndex
Page1 {
}
Page {
Label {
text: qsTr("Second page")
anchors.centerIn: parent
}
}
onIndexChanged: { //error is in this line
console.log(index)
}
}
**Error**
> qrc:/main.qml:25 Cannot assign to non-existent property "onIndexChanged"
|
`SwipeView` does not have such property as `index`. You probably meant `currentIndex`.
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
SwipeView {
// ...
onCurrentIndexChanged: {
console.log(currentIndex)
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "qt, events, qml, swipeview"
}
|
Let $f:\mathbb R^2\rightarrow \mathbb R$ s.t. $f(x,0)=x^2, f(0,y)=y^2$ then $f$ is differentiable
> Let $f:\mathbb R^2\rightarrow \mathbb R$ s.t. $f(x,0)=x^2, f(0,y)=y^2$
>
> Prove or disprove: $f$ is differentiable at $(0,0)$
I think that this is a simple disprove question, but couldn't find a counterexample.
|
It is indeed false. You can take, say$$f(x_1,\ldots,x_n)=x_1^{\,2}+x_2^{\,2}+\cdots+x_n^{\,2}+\begin{cases}1&\text{ if }x_1=x_2=\cdots=x_n\ne0\\\0&\text{ otherwise.}\end{cases}$$It is discontinuous at $(0,0,\ldots,0)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus, multivariable calculus, derivatives, examples counterexamples"
}
|
smart guide is not happening
Is smart guide in illustrator limited to some certain capacity?
I wonder why i don't see any smart guide line (magenta one) in circled portion. I think i should see one. (pic 2)
When two circles' circumference overlap each other (pic 1) smart guide says 'intersect' but why is that not happening when two edges of separate triangles are intersecting? (pic 2)
When i see smart guide i am sure that the overlapping has taken place so that i dnt have to check it in outline mode and manually drag to make tht happen. But sometimes checking is tedious when you have so much to do...
Does smart guide have no jurisdiction over triangles? Or i need to change some preference? 
You can edit the **Construction Guides**. They have some presets you can choose from, or you can define custom angles, with up to 6 entries.
 and move the path by the point, instead of the entire path.
You use the _Selection Tool_ (`V`) to select the entire path easily, then hit `A` to switch and only drag from a single anchor point.
|
stackexchange-graphicdesign
|
{
"answer_score": 2,
"question_score": 1,
"tags": "adobe illustrator, smart guides"
}
|
expand zoo timeline in R
Hi I have a time series dataset contains a few data points in Aug and Sep.
How can I fill in the missing days with a default value easily, say 0 in this case:
What I am thinking right now to `merge` the dataset with a sequential time series for the timeline I like, then do `na.fill` to replace NAs with the default value I want.
This is what I have done:
# This is my data z1
z1 <- zoo(c(1,2,3,4,5), as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))
# This is the timeline I want
z2 <- zoo(0, seq(from=as.Date('2013-08-01'), to=as.Date('2013-09-30'), by="day"))
# This is my result
na.fill(merge(z1, z2)[,1], 0)
But I am wondering is there a function already existing to do what I want. Something like:
result <- foo_fill(z1, 0, start, end)
|
If you want to replace NAs with fixed specified values, I think `merge` is the way to go. You can make some simplifications though: you don't need the 'zero-column' in z2, and you can fill with zeros in the `merge` step:
# input as per question
z1 <- zoo(c(1,2,3,4,5),
as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))
start <- as.Date('2013-08-01')
end <- as.Date('2013-09-30')
tt <- seq(start, end, by = "day")
merge(z1, zoo(, tt), fill = 0)
On the other hand, if you want to replace NAs by the last previous non-NA (`na.locf`), then the `xout` argument may be a way to specify which date range to use for extra- and interpolation, and you don't need `merge`. For example:
na.locf(z1, xout = tt)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "r, time series, zoo"
}
|
Why do some fighter jets have double wheels in the front gear whereas some other aircraft have a single wheel?
The Typhoon has a single wheel in the front gear, but the Rafale or Gripen have double wheels in the front gear. What is the reason for this difference?
|
Ther are a lot of reasons for doing one over the other, from design trade offs to steering mechanisms to weight savings vs Service life, runway loading requirements, etc. In the case of the Rafale-N, the nose landing gear is designed to interface with the catapult shuttle on the ship, so a single nosewheel would not be an option here.
|
stackexchange-aviation
|
{
"answer_score": 1,
"question_score": 0,
"tags": "fighter, landing gear"
}
|
Using dojo/touch with event delegation
Is it possible to delegate dojo/touch events using dojo/query and selectors?
Given I've included `dojo/query` and `dojo/touch` as `touch`, the following pseudocode represents what I want.
on(target, '.myClass:touch.press', 'myPressHandler');
This obviously does not work because touch.press is a function, not an event.
Another way, which I'm trying to avoid would be:
on(target, '.myClass:mousedown', 'myPressHandler');
on(target, '.myClass:touchstart', 'myPressHandler');
Yeah, it only saves a line, but hey still saves typing a line, and over a bunch of files or targets or types of events lines add up!
EDIT This question would also apply to Dojox/gesture/tap, since it behaves similarly. Given `dojox/gesture/tap` as `tap`,
on(target, '.myClass:tap', 'myPressHandler');
|
Dojox gesture tap. Should do what you need. <
define(["dojo/on", "dojox/gesture/tap"], function(on, tap){
on(target, on.selector(".myClass", tap), ''myPressHandler);
}
or for dojo/touch
define(["dojo/on", "dojox/touch"], function(on, touch){
on(target, on.selector(".myClass", touch.press), ''myPressHandler);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, dojo"
}
|
Importing project-specific rc files in Neovim
Vim probably did this by default, whenever I invoke files from a project that has its own `.vimrc`s it's auto-sourced. Neovim, however, doesn't import `vimrc`s. How can I make Neovim scan and use project-specific configuration files?
|
Vim doesn't do that by default, you probably had `set exrc` in your `.vimrc`, see `:h 'exrc'`.
As the doc says if you add `set exrc` to your vimrc you also probably want to add `set secure` (`:h 'secure'`).
Both of these options are also available in neovim.
You may also want to have a look at this Luc Hermitte's plugin which also allows to enable local configurations files with more options.
|
stackexchange-vi
|
{
"answer_score": 3,
"question_score": 2,
"tags": "vimrc, neovim"
}
|
UITextView displaying spaces after newline/wordwrap
I am using a UITextView to display arbitrary NSStrings, with various font sizes (depending on the length of the string, and the screen resolution of the device). My problem is that the UITextView seems to display these little "underscore like" characters, instead of spaces, if the space character is the first character on a newline (after the text has been wrapped). Anyone know a way to turn this off?
|
OK, I think this was a problem with the font I was using. Also possibly the text size of the font was important. Perhaps the fact that I was displaying in italic was the thing. Anyhow, now that I have a different font, different size, not italic, I haven't noticed this problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, user interface, uitextview"
}
|
SML or if boolean
I am new to SML and don't know how to use the "or" operator in an if statement. I would be really grateful if someone explains it to me, since I have checked multiple sources and nothing seems to work. Thank you !
|
In SML, logical or is called `orelse` and logical and is called `andalso`.
As an example
if x = 2 orelse x = 3 orelse x = 5
then print "x is a prime"
else print "x is not a prime (also, I don't believe in primes > 5; please respect my beliefs)"
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "boolean, sml"
}
|
MySQL Show value based on dates between START and END dates
I'm trying to make simple house reservation system and my DB is like:
TABLE HOUSES
id | name
============
1 | house_1
2 | house_2
TABLE RESERVATIONS
id | id_house | date_start | date_end
=====================================
1 | 2 | 2015-11-02 | 2015-11-10
2 | 1 | 2015-10-02 | 2015-10-15
And I have no idea how to show reserved houses based on new reservation eg.
> id_house **2** **2015-11-05** to **2015-11-20**
System should output: House num. **2** is reserved on this days
|
**Input:** a date range for a new reservation (2015-11-05 to 2015-11-20)
**Output:** a list of houses that are already reserved for those dates
**Query:**
SELECT HOUSES.name, HOUSES.id, RESERVATIONS.date_start, RESERVATIONS.date_end
FROM RESERVATIONS
LEFT JOIN HOUSES ON HOUSES.id=RESERVATIONS.id_house
WHERE
RESERVATIONS.date_start < '2015-11-20'
AND
RESERVATIONS.date_end > '2015-11-20'
Something like that, but it depends on your logic (which I did not fully understand).
Hope that helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "mysql"
}
|
Databricks table metadata through JDBC driver
The Spark JDBC driver (SparkJDBC42.jar) is unable to capture certain information from the below table structure:
1. table level comment
2. The TBLPROPERTIES key-value pair information
3. PARTITION BY information
However, it captures the column level comment (eg. the comment against employee_number column), all columns of employee table, their technical data types.
Please advise if I need to configure any additional properties to be ale to read/extract the information that the driver could not extract at the moment.
create table default.employee(
employee_number INT COMMENT ‘Unique identifier for an employee’,
employee_name VARCHAR(50),
employee_age INT)
PARTITIONED BY (employee_age)
COMMENT ‘this is a table level comment’
TBLPROPERTIES (‘created.by.user’ = ‘Noor’, ‘created.date’ = ‘10-08-2021’);
|
You should be able to execute:
describe table extended default.employee
via JDBC interface as well. In first case it will return a table with 3 columns, that you can parse into column level & table level properties - it shouldn't be very complex, as there are explicit delimiters between row-level & table level data:
 = 0 (where v is a vector of finitely many integers) for some polynomial p, is there a Turing machine which prints out all values of x?
|
Given a polynomial $p(\bar{x},\bar{v})$ with integer coefficients, there is indeed a Turing machine that enumerates all tuples of integers $\bar{x}$ for which there exists a tuple of integers $\bar{v}$ with $p(\bar{x},\bar{v}) = 0$. In other words, the set of such tuples $\bar{x}$ is recursively enumerable.
One way to do the enumeration is to start by making a machine that enumerates _all_ pairs of integer tuples $(\bar{x}, \bar{v})$ (where each tuple has the appropriate length). Then feed the output of this machine into a machine that checks whether $p(\bar{x},\bar{v}) = 0$.
On the other hand, there is no Turing machine that takes a polynomial $p$ as input, and a tuple $\bar{x}$ as a second input, and decides whether there is a tuple $\bar{v}$ of integers with $p(\bar{x},\bar{v}) = 0$. This is the MRDP theorem, which solved Hilbert's 10th problem.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 4,
"tags": "diophantine equations, computability"
}
|
How to call a button click event from another method
How can I call `SubGraphButton_Click(object sender, RoutedEventArgs args)` from another method?
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
// call SubGraphButton-Click().
}
|
You can call the button_click event by simply passing the arguments to it:
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 81,
"question_score": 41,
"tags": "c#"
}
|
Remove element in strings arraylist java
Hi am new in using Java and I just placed a list of strings in an array list of which I would like to remove certain elements in each of the strings below
ArrayList<String> data = new ArrayList<String>();
data.add( "ksh10,000");
data.add( "ksh20,000");
data.add( "ksh30,000");
data.add( "ksh40,000");
data.add( "ksh50,000');
so I would like to remove the "ksh" and the comma in between the strings so as to get an out put like
10000,20000,30000,40000,50000
what i tried
for (int i = 0; i < data.lenght(); i++ ) {
data.set(i, data.get(i).replace("ksh", ""));
data.set(i, data.get(i).replace(",",""));
}
.Thanks in advance for your help.
|
If all you want to do is change the values put into data, loop through each element and use the `replace` method:
for (int i = 0; i < data.size(); i++ ) {
data.set(i, data.get(i).replace("ksh", ""));
data.set(i, data.get(i).replace(",",""));
}
This replaces "ksh" strings and commas with an empty string. as Snoob said, `replace()` only returns the new String, because Strings are immutable.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -5,
"tags": "java, android"
}
|
Can I get my grandad to write a review for university?
You always see the general "you can't list family members" when it comes to references, but what if you're working at a company where your granddad is also your boss? He has a different last name to me so it wouldn't be obvious. Would they ask if they are related or does it not really matter?
|
**Assumption:** This answer assumes that the "no family members as reference" is only a common practice for references, and that there is no hard rule specified for the university you're applying to. If there is indeed a hard rule, please disregard this answer.
This said, yes you can.
The only way for them to notice your family relationship is that your grandad mentions it. As long as you make sure that this does not happen you're fine.
And even if they were to notice it, he was your boss, not your grandad, when you were working for him. Just ensure that the review is strictly professional, as any review from any "normal" boss would be.
|
stackexchange-workplace
|
{
"answer_score": -2,
"question_score": 1,
"tags": "references, education"
}
|
Will there be a Win64 API?
If I'm correct, Win32 is adapting or has been adapted to cope with 64 bit windows, for example, GetWindowLongPtr on 64 bit as opposed to GetWindowLong on 32 bit. Will there be a Win64 Api, and if so, is there any indication on when the transition will happen?
I'm not very knowledgeable on this subject so I apologize if I have anything obvious wrong. Thanks in advance, ell.
|
This transition happened around the turn of the century. 64 bit versions of Windows using the 64 bit version of Win32 have been in use for a long time now.
However, the 64 bit version of Win32 is still known as Win32 since it is essentially an identical interface with the only major difference being different sized pointers.
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 20,
"tags": "windows, winapi, 64 bit, 32bit 64bit"
}
|
how to get the first and the last character of a string using a Regex and Javascript
I need to get the first and the last letter of a string, using a regex in Javascript and I have no Idea how to achieve this. Anyone has an Idea?
|
As the comments indicate, it would be very simple to do it without regexp:
var str = "This is my string";
var first = str[0];
var last = str[str.length-1];
If you really need to use a regexp, you could do it like this:
var matches = str.match(/^.|.$/g); // ["T", "g"]
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "javascript, regex"
}
|
Add padding if screen is wider than 900px
I am trying to make my website appear differently on different screens.
I am using a media query in my CSS to change certain elements. However, I seem to be doing something wrong, since the browser is doing exactly opposite of what I want it to.
I want to add padding to my content element (a single div with class `content`) only if the screen is wide enough to fit it. In my case, I want the padding to be added only if the screen is wider than 1000px.
This is what I have now:
.content {
margin: auto;
width: 990px;
overflow: hidden;
padding:0 5px 0 5px;
}
@media (max-width:1000px) {
.content{
padding:0;
}
}
Can anyone help here? I know this is probably something really simple, but I haven't used these media queries a lot before, so I don't know all the syntax.
|
It seems that code you provided is working, at least for me. But the problem might be that 5px is to small to notice.
Try increasing it to 20px or 50px to see if its working.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css, width, media queries, padding"
}
|
C language - how to create PostScript file
How can I create a PS (PostScript) file in C language?
For example, I want create file myfile.ps and _draw_ to PostScript this code:
%!
newpath
0 0 moveto
120 120 lineto
144 120 lineto
200 122 lineto
0 0 lineto
stroke
showpage
|
Normally postscript is just ascii text, so the standard text-output facilities will work just fine.
#include <stdio.h>
int main(void) {
FILE *outfile;
outfile = fopen("myfile.ps", "w");
fprintf(outfile,
"%%!\n"
"%d %d moveto\n"
"%d %d lineto\n"
"%d %d lineto\n"
"%d %d lineto\n"
"%d %d lineto\n"
"stroke\n"
"showpage\n",
0, 0,
120, 120,
144, 120,
200, 122,
0, 0
);
return 0;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c, postscript"
}
|
Iniciando na linguagem C#
Galera, estou começando em C# agora e gostaria de saber o que eu preciso fazer para deixar meus sistemas Desktop com a msm aparencia do Windows 8?
Por exemplo a referencia: using Windows.UI
Espero uma ajuda de vcs.. Abraço!
|
* Use o Blend for Visual Studio para modelar sua aplicação;
* Use o Visual Studio Community 2013 para desenvolver o Back End;
* Para fazer perguntas aqui sobre este tipo de desenvolvimento, utilize as tags wpf e xaml;
* Veja também os Wikis dessas tags. É lá que colocamos informações sobre tutoriais, dicas e links de informações úteis;
* A "aparência" de uma aplicação Windows 8 nós chamamos de XAML. A aplicação deve ser criada como XAML para que você tenha acesso aos recursos visuais tanto do Windows 8 quanto do Surface e do Windows Phone;
* A aparência de uma aplicação do Windows 7 nós chamamos de WPF.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 4,
"question_score": -3,
"tags": "c#"
}
|
How can I change the x-axis index date format in matplotlib?
My code below outputs the following image:
from datetime import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import os
start = dt(2017, 1, 1)
end = dt.now()
df = web.get_data_yahoo('AAPL', start, end, interval = 'd')
df['30_sma'] = df['Adj Close'].rolling(window=30,
min_periods=None).mean()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(df.index, df['Adj Close'])
ax.plot(df.index, df['30_sma'])
plt.show()

ax = fig.add_subplot(1, 1, 1)
df[['Adj Close', '30_sma']].plot(ax=ax)
plt.show()
 et un complément circonstanciel de mesure (2 euros).
|
stackexchange-french
|
{
"answer_score": 6,
"question_score": 0,
"tags": "vocabulaire"
}
|
Complex numbers: find all $z$ such that $e^{z-2}=-ie^2$
Ok, so I think I'm getting the hang of this. Is this more or less on the right track?
$$e^{z-2}=-ie^2$$ $$e^ze^{-2}=-ie^2$$ $$e^z=-ie^4$$ $$\ln(e^z)=\ln(-ie^4)$$ $$z=\ln|-i|+iarg(-i)+2\pi ik+4$$ $$z=\frac{i\pi}{2}-\frac{i\pi}{2}+4+2\pi ik$$ $$z=4+2\pi ik$$
|
Note that $e^{z-2}=-ie^2=e^{2-\frac{i \pi}{2}+2\pi ki}$, so $$z-2=2-\frac{i \pi}{2}+2\pi ki$$ $$z=4+i(2\pi k-\frac{ \pi}{2}).$$ In your solution the last two rows are seems to be wrong, since $arg(-i)=-\pi/2$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex numbers, logarithms"
}
|
Convert integer value to fractional value (decimal)
Looking for a way to convert a positive number (integer) from e.g. 123 to 0.123 without using strings. Can be any size integer. Not concerned about negative values.
Dim value As Integer = 123
Dim num As Decimal = "." & value.ToString
It seems simple but I'm not sure how to do it using math. How can I convert without using strings?
|
You can get the number of digits using `Log10`. I think the best way is thusly:
Dim value = 123 'Or whatever other value
Dim digitCount = Math.Floor(Math.Log10(Math.Abs(value))) + 1
Dim result = value * CDec(10 ^ (-digitCount))
You need to use `Floor` rather than `Ceiling` in order to get the right result for 0, 10, 100, etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "vb.net, math"
}
|
how to add a column from one table to another
in have two oracle tables, as below. they have the same index column. (in my actual application, my master table has 30M rows and ~100 columns). what's the easiest way to add the "feat4" column of the feature 4 table to the master table? is there way to do this in sqldeveloper (other than writing sql)? thanks!
; --Should be whatever datatype is in the feature_4_table
MERGE INTO master_table m
USING (SELECT id, feat4 FROM feature_4_table) f
ON (m.id = f.id)
WHEN MATCHED
THEN
UPDATE SET m.feat4 = f.feat4;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "oracle, oracle sqldeveloper"
}
|
Oracle installation script execution privileges: "oracle is not in the sudoers file"
I'm currently installing Oracle 11g on Ubuntu 10.10
It had been asked to execute some scripts as "root" while installation.
I'm doing:
oracle@sergio:/u01/app/oraInventory$ sudo sh orainstRoot.sh
And got:
[sudo] password for oracle:
oracle is not in the sudoers file. This incident will be reported.
How could I actually run these scripts if I logged under `oracle` user with "root" privileges?
thank you for help.
|
Although I do not have experience in Oracle installation, the error message makes me think, this might work:
sudo adduser oracle admin
This will add the user 'oracle' to the admin group, and the 'admin' group is in the sudoers file by default.
Edit: you need to run this command as the very first user of your system (the one you had to name during install), or as a root (in this case you do not need the sudo part).
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 3,
"tags": "installation, root, scripts, oracle"
}
|
I want to write DXF attributes to a DXF file from VB
So I wrote a massive plugin for Rhino5. I now need it to somehow talk to sigmanest. The best way I can do that is string tags.
Meaning, I DXF a part with the correct part information in text boxes next to the part. But my job does not want that (I have no idea why)
The next thing I can do is embed attributes into the DXF. My plan is to export the part, then write to the DXF file new attributes.
Has anyone done such a thing? I've done some pretty heavy googling, but couldn't find any topics on just writing new attributes to a DXF.
A quick and dirty sample code would be great if you have done this, or link to the information.
Thanks for reading!
|
I am only answering for googles sake...
netDXF is a C# library that reads and writes dxf files and is freely available.
To insert a custom attribute, do the following
Dim aTT= New AttributeDefinition(AttributeNameString)
aTT.Flags = AttributeFlags.Hidden
block.AttributeDefinitions.Add(aTT)
block.AttributeDefinitions(AttributeNameString).Value = VaribleorString
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "vb.net, dxf"
}
|
Preinstalled python on mac a cpython?
As the title says,I want to know if the python which comes pre installed on mac is cpython. I mean logic says it probably is,but I couldn't find it being written anywhere officially so wanted to confirm.
I want to download a few things and for compatibility they require the installed python to be cpython/iron python.
|
With command `Python --version` you get the information like that:
> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
It is almost affirmative that it is `cpython` with `gcc` as compiler.
An alternative(which is more **official** ) is to check with python code:
import platform
platform.python_implementation()
The function python_implementation:
> Returns a string identifying the Python implementation. Possible return values are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, macos, cpython"
}
|
enabling jumbo frames on an iSCSI network after the fact
We're using iSCSI storage and have two dedicated VLANs for iSCSi. We didn't implement jumbo frames initially. I'd like to turn it on now. I understand I need to turn it on for the NICs that connect to the iSCSI VLANs and on the switch ports they connect to and then do the same for the SAN itself. My question is about the timing of all of this. I've got 4 iSCSI boxes and 30 servers connecting to them. Can I make the change at different times without causing big trouble? For instance, if I go through and set all the NICs to jumbo frames first and then do the switches and then the storage, will I have issues if iSCSI traffic is moving at the same time? For obvious reasons, I'd prefer not to shut down all iSCSi traffic first. I think I can reasonably coordinate this work with the network guys to do it all in one evening and plan to enable flow control on the switch ports at the same time. Advice?
|
I would go this way:
1) switches 2) storage 3) clients
I've had several times in my practice that using iSCSI with 9k jumbos thru a switch with disabled jumbo could cause a slow as hell throughput. So, obviously, switches always go first, you actually don't change anything with this, you just ALLOW clients to use frames more than 1.5k but they of course can continue using a standard size frames w/o any restrictions.
The second one will be a storage because (I'm not sure here) when the client initiates a tcp connection, it asks a storage to use a standard frame from start, if this client isn't switched yet to jumbo. So the storage can deal simultaneously with a clients using a jumbo frames aswell as with clients which're still on the standard frames.
|
stackexchange-serverfault
|
{
"answer_score": 5,
"question_score": 4,
"tags": "iscsi, jumboframes"
}
|
Android RelativeLayout class cast exception
Hi guys I have a class that `extends RelativeLayout` and I want to inflate an xml file with `RelativeLayout` as the parent viewgroup and then assign it to the variable.
public class MyLayout extends RelativeLayout {
....
}
Within activity `onCreate()` method:
MyLayout layout;
layout = (MyLayout) inflater.inflate(R.layout.layout_page_one, null);
This is causing a class cast exception. Perhaps someone can shed some light.
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to com.example.test.MyLayout
|
We can typecast sub Class to Super class but not Super class to sub calss so In your `R.layout.layout_page_one.xml` Xml file Instead of definig `RelativeLayout` define MyLayout thyen it will work..
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android relativelayout, classcastexception"
}
|
How can I add a computer to a domain programmatically (using .NET)?
I need to write a program or script that does a few things with (or to) a server after a Windows install. Among those is adding the server to a domain.
Is there a way to do this programmatically or using a script command?
|
If you want to do it from the Domain Controller:
Source: `net computer \\computername /add`
If you want to do it from the workstation:
Source: `NETDOM JOIN /DOMAIN:[DOMAINNAME] /USERD:[USERNAME] /PASSWORDD:[PASSWORD]`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": ".net, windows, dns"
}
|
Using the vala programming language, can you detect when other applications are full screen or maximized, and suspend their own programs?
Using the vala programming language, can you detect when other applications are full screen or maximized, and suspend their own programs? Is there a similar Demo?
|
This is something that can only be done by asking the window manager/compositor, since that is the component that actually deals with this kind of thing. And depending on the session type, this will or will not work.
* In Wayland, it is impossible to query info/events about other windows for security reasons.
* In X, this might be possible using things like `xwininfo` (see for more info < You can either directly call it and parse the result, or see which parts of the X protocol it uses by looking at its source code.
Since you mentioned [gnome] as a tag, you _might_ be able to do this by writing your own GNOME Shell extension, since this has direct access GNOME Shell's internals.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "gtk, gnome, vala"
}
|
django==1.4 support for html5
I have a small blog app I have built using Django 1.4 and recently, I have been learning "bits and pieces" of html5 and css3. I am about the start transitioning my site to html5/css3 and I was wondering if Django widgets support html5(?)
My blog is nothing special - a few forms, a few tables etc.. For example when I do,
{{form_as_p}}
I was wondering if django would generate the required html5 markup(?) I read the docs, and it says the admin pages support html5, but I could not find any docs for regular apps.
If html5 is not supported by Django, what is the best way going about achieving this?
Thanks for your time.
|
Django's form output is XHTML. Django does not snip with support for the new HTML5 input types such as number, email, url, etc but it is not difficult to add them. See < or < That being said I don't know any place where Django generates markup that is invalid for HTML5.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 9,
"tags": "django, django templates"
}
|
How to set a variable (using set tag) in django template?
I want something like this inside django template. I want to use these variables in javascript file or another template file.
{% set titles = {
'table': form._meta.model._meta.verbose_name_plural.title(),
'form': form._meta.model._meta.verbose_name.title()
}
%}
{% set dtable = "dt_" + page %}
How can I create "set tag" in django template? Your answer would be helpful for me.
|
Although I think this is generally to be avoided (mixing template & logic is generally advised against in django), it appears this is possible through the use of the `with` tag.
{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
In javascript, it would probably look like this
$(document).ready(function(){
{% with greeting="hello" %}
var text = '{{ greeting }}'
{% endwith %}
});
There are some constraints, I don't believe you can set tuples or dictionaries this way. That said, if you're trying to set more complex types using {% with ... %} that logic should probably be handled in the view.
Referenced from this SO question.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, python, django, django templates"
}
|
How to do a bezier interpolation mode animation along a path?
When I parent an object to follow a path and animate it, I only get a linear mode animation and changing that in Grapth Editor to bezier doesn't work! How to do that?
|
When you parent an object to a curve with _Follow Path_ to control its motion,
 to a new domain
www.example.com
I have tried to redirect the old `index.html` to the new `index.html` using 301 redirect and the standard methods found online using the `.htaccess` file, but it doesn't seem to work.
|
_If_ your university webserver uses Apache httpd, the most robust method is to place a `.htaccess` file within the document root:
Redirect 301 /
This will also redirect subpaths correctly.
* * *
Failing that, the second-best way is to use a scripting language (if you have access to one) to send a redierct header. This can be a PHP script, or a CGI script (placed in cgi-bin).
* * *
If all else fails, you can place a meta refresh within your HTML file. This is the worst method, as it requires the browser to load the HTML page and then load the page it redirects to, while the redirect headers don't require loading the body. A meta refresh cannot be used to send a 301 redirect (which is necessarily an HTTP header).
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apache http server, webserver, redirection"
}
|
Select yes if bigger no if smaller
Simple query: I want to include a column/field which says `Yes` when `SUM` field is larger than `yield` field and `No` when the other way around.
Mysql says I have an error in the query near (my whole query) and doesn't specify:
select *, IF(CONVERT(float,SUM) > CONVERT(float,yield),'Yes','No') from active_samples_w_seq where id > 100 and id < 200
|
As @DanFromGermany said, the order is CONVERT(expr,type), but for float values you should use DECIMAL instead of FLOAT:
select *, IF(CONVERT(SUM,decimal) > CONVERT(yield,decimal),'Yes','No')
from active_samples_w_seq
where id > 100 and id < 200
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
}
|
"How did you make it this far?" vs "how have you made it this far?"
Example:
> You said you couldn't run. **How did you make it this far then?**
>
> You said you couldn't run. **How have you made it this far then?**
Is there any difference between the two? Or they mean the same thing?
|
Their meaning is near identical. There is a slight shade of emphasis because of the verb tense, though. "How did you make it this far" puts the emphasis on what might have happened to get you here—it asks you to explain your past. "How have you made it this far" puts the emphasis on your current situation—it asks you to explain your present.
|
stackexchange-ell
|
{
"answer_score": 3,
"question_score": 2,
"tags": "phrase meaning, phrase usage, phrase choice"
}
|
Boolean check inside a for loop in a Django template
In a Django template I have the following for loop
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
Through this loop I am showing the user all the uploaded files of my app.
Now say that I want to show the user only the files he/she has uploaded.
I have the current user in the variable `{{ request.user }}` and also I have the user who did the i-th upload in `{{ document.who_upload }}`
My question is how can I compare these two variables inside the loop to show only the uploads that have a `who_upload` field that of the current user?
For example I tried the syntax
{% if {{ request.user }} == {{ document.who_upload }} %}
{% endif %}
but it does not seem to work.
What is the proper syntax for this check?
Thank you !
|
This should get the job done:
{% if request.user.username == document.who_upload.username %}
{% endif %}
But you should consider performing this logic in your view. This is assuming you're not looping over the entire queryset anywhere else.
views.py
========
from django.shortcuts import render
from .models import Document
def documents(request):
queryset = Document.objects.filter(who_upload=request.user)
return render(request, 'document_list.html', {
'documents': queryset
})
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "django, django models, django forms, django templates, django views"
}
|
Querying in SFMC
I am trying to write a Query in Exact Target to pull some report. I understand that what we call Tables in SQL is termed as 'Data Views' here. So where can we see those Data View definitions, I mean column names, primary key details and relationship to other tables? I am beginner for Marketing Cloud and couldn't find straight cut answers in SF Communities and please correct me if I have referred something wrongly.
|
**Data Extensions** in SFMC are equivalent to database tables. Those can include any columns that suit your requirements.
The **Data Views** ( **System Data Views** ), are read-only tables of Subscriber and Subscriber activity data.
The schemas for those are found on the **Query Activity** page.
Query Activities can only do SQL Select statements and add/update/append another Data Extension.
If you're looking for some syntax help, SFMC Query Activities follow **Microsoft Transact-SQL**.aspx) (T-SQL) conventions (with a few exceptions).
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 1,
"tags": "marketing cloud, query"
}
|
Microsoft Chart Control labels
I've been searching for a while and browsing through the samples but could not find a solution to my problem.
In Microsoft Chart Control I have created a line series that plots real-time data. As new data points are added, the chart margins will sometimes jump on the form. I have tried disabling the grid lines and have determined that the margins change when the x-axis label overlaps with the y-axis label. I have tried auto-fitting the labels but that does not seem to work probably because it treat x-axis and y-axis separately. Is there any way to prevent the overlap, or keep the labels and corresponding grid lines stationery and just change their value when the data scrolls?
Thank you for your help.
|
I set IsEndLabelVisible = false to solve this problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, .net, microsoft chart controls"
}
|
What Sign Language developed among orphans/homeless children using the environment as a base for the signs?
I remember in one of my linguistics classes, a rather complex sign language (perhaps in Brazil, if I recall correctly) exists among, I believe, deaf children homeless children/orphans on the street. I believe that researchers, for quite a while, had much trouble figuring it out, but a breakthrough was made when they figured out that the signs we're patterned after the shape of streets on signs such as subway or bus maps.
Unfortunately, that is all that I can remember about the subject, and I don't even know how accurate my information is. And so I ask: where is this type of sign language used and what is it's story / what is unique about it?
|
Perhaps you mean Nicaraguan Sign Language? I don't know about sign patterns, but that's a language of particular interest because of its spontaneous development, unlike many others.
|
stackexchange-linguistics
|
{
"answer_score": 5,
"question_score": 5,
"tags": "sign languages"
}
|
Type error for initial empty object with useState (union type)
How can I set the types correctly for an initial empty object + an interface?
interface IInputs {
prop1: string
prop2: string
prop3: string
}
const [inputs, setInputs] = useState<IInputs | {}>({})
Gives the following error in the value attribute of the input:
Property 'prop1' does not exist on type '{} | IInputs'.
Property 'prop1' does not exist on type '{}'.ts(2339)
|
Use `Partial` to make all properties optional.
const [inputs, setInputs] = useState<Partial<IInput>>({})
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "typescript, use state"
}
|
How to unlock my device after blocking with "Find my device"?
I lost my phone in a taxi and blocked it using Find My Device. I managed to get it back but now it has a button to call my home and a lock icon, but won't unlock.
|
You must restart your phone. Turn it off. When you turn it on again you'll be able to enter your password.
**Update** : after doing this, it will lock again. You must really login again using your account in "Find my Device". The option is somewhat hidden in the suspension points button. See:  simple examples where this time and input analysis would not hold good is if you have certain `if` statements in your code that cause something to execute that the inputs you have provided do not take into consideration.
You could refer to this answer:
> How to find time complexity of an algorithm
Another answer that is helpful is:
> Big O, how do you calculate/approximate it?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "algorithm, time complexity"
}
|
How can I Git Push without triggering a build?
We currently have git setup so that whenever we push to the repository on our build server a bash script on the server is executed that starts a build.
Occasionally we make changes that **shouldn't** trigger a build. Is there any extra parameter we could give to git push so that it doesn't execute the receive hooks, or passes the parameter into the receive hooks? Any other solutions to prevent a build being kicked off also welcome.
|
If the "special keyword in the commit message" suggested by tauran isn't a good solution enough, don't forget about **`git notes`**. (See Notes to self).
You can attach any kind of text metadata to a commit (without having to change its SHA1).
You can then parse not for a commit message content, but for the existence of a special note on the pushed commits.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "git"
}
|
How to draw nodes with "stubs" in Latex?
I'm trying to draw this in latex. Anyone know how? at (0,0) {A};
\draw let \p1=(A) in (A) -- (\x1+40,\y1+10);
\end{tikzpicture}
\end{document}
Using the `let`-statement it allows you to specify a reference point (or even more) to use it's coordinates for further calculation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "latex"
}
|
android sound gets disabled after sometime
i want to check how the service feature set in android works. to check it, i have a controller class that will start the service. in the service i have a handler that executes a function every minute.the function plays the sound. everything works well when the screen is on but after the screen goes dark(off), the sound is heard about 2-3 times (2-3 minutes) and then it stops... any idea why? and how can i make it (execute the sound function)work every minute?
|
When the phone goes into sleep mode, so does the cpu. Some recievers may wake the phone up causing your sounds to be heard. Take a look into PowerManager and try to wake your phone(and cpu) up when you want to hear the sound.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, service, audio, handler, android service"
}
|
$x^3-3x^2+4x-2$ cannot be factored over $\mathbb R$
I'm new to the site, and I need a bit of help from you.
How can I prove that the polynomial: $f(x)=x^3-3x^2+4x-2$ cannot be factored as a product of polynomials of degree 1 with real coefficients?
Thanks.
|
Observe that$$\begin{align*} f(x)=x^3-3x^2+4x-2&=(x^3-3x^2+3x-1)+(x-1)\\\\\\\ &=(x-1)^3+(x-1)\\\\\\\ &=(x-1)((x-1)^2+1)\\\\\\\ &=(x-1)(x^2-2x+2) \end{align*}$$ By the quadratic formula, the roots of $x^2-2x+2$ are complex, so $f$ cannot be factored any further into polynomials with real coefficients.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "polynomials"
}
|
filtering measures based on two columns in power bi dax
I want to use a measure and filter the result based on the columns:
My measure is :
TotalProductionCon =
SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[SGWCP8] )
+ SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[retard] )
and I want it to summarize only when column année = column year.
I tried `CALCULATE` and `FILTER`;
TotalProductionCon =
CALCULATE (
SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[SGWCP8] )
+ SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[retard] );
FILTER (
ALL ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[Année] );
_BI_SOVAC_PROD_KIT_LIFE_CYCLE[Année] = _BI_SOVAC_PROD_KIT_LIFE_CYCLE[year]
)
)
but it generates an error that the columns contain much value and I need to use aggregation.
Can you help me?
|
The problem with your formula is that you limited ALL function to only one column (Annee), and as a result FILTER does not "see" the other column it needs.
To fix that, change your formula as follows:
TotalProductionCon =
CALCULATE (
SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[SGWCP8] )
+ SUM ( _BI_SOVAC_PROD_KIT_LIFE_CYCLE[retard] );
FILTER (
ALL (
_BI_SOVAC_PROD_KIT_LIFE_CYCLE[Année];
_BI_SOVAC_PROD_KIT_LIFE_CYCLE[year]
);
_BI_SOVAC_PROD_KIT_LIFE_CYCLE[Année] = _BI_SOVAC_PROD_KIT_LIFE_CYCLE[year]
)
)
I am assuming here that your choice of ALL function is appropriate; otherwise you might need to use a different technique such as SUMMARIZE function.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "powerbi, dax, powerbi desktop"
}
|
VB - Access a control created with code
So if I create a `PictureBox` with the code...
Dim the_pic As New PictureBox
With the_pic
.Name = "pic"
.Size = New Size(30, 100)
.Location = New Point(0, SCREEN_HEIGHT / 2 - 50)
.SizeMode = PictureBoxSizeMode.StretchImage
.BackColor = Color.White
End With
Me.Controls.Add(the_pic)
...How do I access the methods and properties of the created `PictureBox`? Because it is created in code, I can't program directly to it. If I do `pic.*` it doesn't know that pic even exists, because its created at runtime. How do I account for this? All help is greatly appreciated.
|
> it doesn't know that pic even exists, because its created at runtime
That's not quite correct.
Actually, it doesn't know that `the_pic` exists because it's a **local variable**.
The variable is not visible outside the function it's defined in.
If you make it a field in the class, it will be visible everywhere in the class.
If you want to have more than one of them, you should use a `List(Of PictureBox)`.
Note that the `Name` property is not relevant.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vb.net"
}
|
Laravel 4: Confused about how to use App::make()
I am trying to follow the repository pattern outlined in this article < And I am trying to instantiate a class in Laravel using App::make() (Which I am guessing is Laravel's factory pattern?) and I am trying to parse arguments to my class but I can't work out how to do it.
**Code:**
namespace My;
class NewClass {
function __construct($id, $title)
{
$this->id = $id;
$this->title = $title;
}
}
$classArgs = [
'id' => 1,
'title' => 'test',
]
$newClass = App::make('My\NewClass', $classArgs);
Can anyone point to an example of how to use App::make() or have I gone in the completely wrong direction and shouldn't be using App::make()?
|
The good people in the Laravel forum answered this one for me <
Pretty much if you can bind custom instantiation code with App::bind(); like so
App::bind('My\NewClass', function() use ($classArgs) {
return new My\NewClass($classArgs['id'], $classArgs['title']);
});
// get the binding
$newClass = App::make('My\NewClass');
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 10,
"tags": "php, laravel, laravel 4, factory pattern"
}
|
When a shell executes an external command/program - does that program have file descriptors?
There are alot of documents and discussion around the file descriptors of shells and how those file descriptors can be manipulated for redirection etc.
My question is, when a shell command is an external program, like `rsync`, `cat`, `curl` etc, do those commands have file descriptors in the same way the shell does?
To give a concrete example, if I run this command at a terminal prompt
% cat << EOF | php
<?php
echo "hello". PHP_EOL;
echo "another line" . PHP_EOL;
EOF
I'm assuming the contents of this heredoc are being fed to STDIN, but of which process? the shell, or does `cat` have a file descriptor `0` and the contents of the heredoc are being fed to `cat`'s `fd0` directly?
|
Lets begin by saying that all I/O whether file based, interactive or any other way require unique file descriptors for each.
The standardization of interactive file descriptors is what allows redirection and piping.
The shell is an expert at standard I/O manipulations.
In your example, `cat` is called with its STDIN set to the shell's output representing your HEREDOC script (sent through a `popen()`), and with its STDOUT piped (with popen()) to `php`'s STDIN. `php`'s output not being redirected, point to the shell's initial STDOUT.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "shell"
}
|
Laravel 4 validation says column not found
This is my first time using Laravel 4. I am sending some input. There is an email in the input. I am trying to check whether that already exists or not. If it does than it should send some error. But it is saying there is no such column in my table.
Here is my code:
$rules = array(
'email' => array('required', 'email', 'unique:users, user_email'),
'password' => array('required', 'min:7', 'unique:users, user_password')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
$messages = $validation->messages();
dd($messages);
}
My table name is users and column name is user_email and user_password. The name of the input field is email.
|
Reading through the documentation for validation rules, I do not see any spacing between column names, and the column info. It may be that spaces are not stripped from the data, and this would probably be the cause of your error. Remove the spacing issues, and it should work: `unique:users,user_email,etc`.
(Note, this is an expanded answer based off of my comment, which solved the user's problem).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, database, validation, laravel 4"
}
|
Write elevate.xml file from MVC application
I use Apache Solr with Dot Net MVC application. Now I want to right query tag in elevate.xml file of Solr from my application.
Structure of elevate.xml file is like:
<elevate>
<query text="foo bar">
<doc id="1" />
<doc id="2" />
<doc id="3" />
</query>
<query text="ipod">
<doc id="MA147LL/A" /> <!-- put the actual ipod at the top -->
<doc id="IW-02" exclude="true" /> <!-- exclude this cable -->
</query>
</elevate>
same way I want to add other query tag. How can I do it? Is there any API available to write it?
|
Try This one
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFilename);
XmlElement elmRoot = xmlDoc.DocumentElement;
XmlElement elmNew = xmlDoc.CreateElement("Query");
XmlAttribute attribute = xmlDoc.CreateAttribute("text"); //attribute of query tag
attribute.Value = "foo bar";
elmNew.Attributes.Append(attribute);
elmRoot.AppendChild(elmNew);
xmlDoc.Save(strFilename);
strFilename --> Your File name including the path and extension (.xml)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "xml, asp.net mvc, solr"
}
|
sparc assembly - add instruction with i=0 or i=1
From the Sparc architecture manual, page 110 for `Add` instruction:
> "If i = 0, ADD and ADDcc compute “R[rs1] + R[rs2]”. If i = 1, they compute “R[rs1] + sign_ext(simm13)”. In either case, the sum is written to R[rd]."
When reading the assembly, how can I know whether i=0 or i=1 ? It doesn't look like there is any change in the mnemonic/opcode as it appears in the disassembled code.
|
The "i" indicates an "immediate" value in the instruction. An immediate is a constant. So you'll see something like this:
add %g1, 59, %g1
That means "add the constant 59 to g1 and put the result in g1".
When i=0, it means that the parameter is not an immediate. So it's a register! You will see this in the assembly or disassembly:
add %g1, %o3, %g1
And that means add registers g1 and o3 and put the result in o3.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "assembly, add, sparc"
}
|
How to check all elements in an array in pascal
How would I code this so that if an element equals a certain value it would display a message, but if ALL elements inside that array aren't equal to that value, then it would output 'None'?
I've tried
for i := 0 to high(array) do
begin
if (array[i].arrayElement = value) then
begin
WriteLn('A message');
end;
end;
That bit works, but I don't know how to do the check all bit. I had this:
if (array[i].arrayElement to array[high(array)].arrayElement <> value) then
begin
WriteLn('None');
end;
But it didn't allow me to use "to"
|
It's clearest to write a helper function for this:
function ArrayContains(const arr: array of Integer; const value: Integer): Boolean;
var
i: Integer;
begin
for i := Low(arr) to High(arr) do
if arr[i] = value then
begin
Result := True;
Exit;
end;
Result := False;
end;
Or using `for/in`:
function ArrayContains(const arr: array of Integer; const value: Integer): Boolean;
var
item: Integer;
begin
for item in arr do
if item = value then
begin
Result := True;
Exit;
end;
Result := False;
end;
Then you call it like this:
if not ArrayContains(myArray, myValue) then
Writeln('value not found');
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "arrays, pascal, freepascal"
}
|
Pass a parameter to a parameterized query?
I need to get a query from a database table that contains a parameter. Then use that query to update another table but I need to be able to pass another parameter to that update statement.
declare @locnum int
set @locnum = 032
declare @tempPersonID int
set @tempPersonID = 10008
declare @passwordQuery varchar(max)
set @passwordQuery = (select passwordQuery from location where locationNum = @locnum)
select @passwordQuery
update tempPerson
set [password] = @passwordQuery
where tempPersonID = @tempPersonID
select *
from tempPerson
`select @passwordQuery` returns `(select left(firstname,1) + left(lastname,1) + custom as [password] from tempPerson where tempPersonID = @tempPersonID)`. I need to able to use the `@tempPersomID` parameter in this query and the where statement.
|
Firstly, as you are updating the record that you are selecting the information from you only need the following as your `@passwordQuery`:
left(firstname,1) + left(lastname,1) + [custom]
Then the following code takes your code and adapts it for dynamic SQL:
declare @locnum int = 032, @tempPersonID int = 10008, @passwordQuery varchar(max), @sql nvarchar(max), @params nvarchar(max);
select @passwordQuery = passwordQuery from [location] where locationNum = @locnum;
-- select @passwordQuery
set @sql = 'update tempPerson set [password] = ' + @passwordQuery
+ ' where tempPersonID = @tempPersonID';
set @params = '@tempPersonID int';
execute sp_executesql @sql, @params, @tempPersonID = @tempPersonID;
select *
from tempPerson
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql, sql server"
}
|
Default Garbage collector for a jvm
> **Possible Duplicate:**
> find which type of garbage collector is running
Is there a way to tell what garbage collector is being used in a jvm by default?
|
This will print out a list of all of the Garbage Collectors currently loaded in your JVM.
import java.lang.management.*;
import java.util.List;
public class x {
public static void main(String args[]) {
List<GarbageCollectorMXBean> l = ManagementFactory.getGarbageCollectorMXBeans();
for(GarbageCollectorMXBean b : l) {
System.out.println(b.getName());
}
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 9,
"tags": "java"
}
|
what rect size for retina display?
I just wanted to know if my image has x*y dimensions.
When retina display devices show that image created with a `CGRectMake(0,0,x,y)`, would that be a pixelated image?
Should the correct size have been `CGRectMake(0,0,x/2,y/2)`?
How can I tell the rect size that an image should have?
Do I need to use the `contentScaleFactor = [UIScreen mainScreen].scale;`?
or maybe divide by it as in: `CGRectMake(0,0,x/contentScaleFactor,y/contentScaleFactor)`?
|
Dimensions are measured in _points_ instead of pixels. Both retina and non-retina display devices have the same points. On a non-retina display device, one point equals one pixel, but on a retina display device, one point equals two pixels. So, you will use `CGRectMake(0,0,x,y)` for both.
To avoid a pixelated image, make sure to provide a double-resolution image with the `@2x` suffix. For example, if your regular image was named `foo.png`, then the retina version should be named `[email protected]`.
When coding, refer to `foo.png` at all times. When your app is running on a retina display device the double-resolution image (`[email protected]`) will be used automatically.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "objective c, ios, xcode, retina display"
}
|
Install pngquant on apache server and use it in command shell
First, I am trying to compress png images using < but I didn't know how to download it on Apache server (Windows). The browser hits an error that pngquant is not installed on server (xampp). How do I do that?
Second, do I have to do this:
$command = "find . -name '*.png' -exec pngquant --ext .png --force 256 {} \;";
shell_exec($command);
after this code here < ?
I've never used command line in PHP. Thanks.
|
as i checked out "< where it is telling that pngquant library is available in linux so not sure about window so let me put the list of procedures how will it work
1) try to find out the dll library(which supports in window) for pngquant if available then put this library in extension folder which is located inside php folder (not exactly sure about the path please figure it out) then it will work perfectly
explanation : pngquant is php extension which must be available inside extension folder as a dll library then it will work perfectly in windows
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, apache, pngquant"
}
|
Which vendors/companies have Multi-threaded Video codec solutions?
If its not relevant here, pls. move to correct place.
I want to find out which all vendors/companies have developed multi-threaded video codecs(decoders , encoders) as commercial products? Not opensource solutions like libavcodec/x264/ffdshow etc... but commercial solutions for which one can obtain licenses/performance numbers of those solutions.
thanks,
-AD.
|
MainConcept has some excellent codec options. They offer support for multi-threading as well as support for hardware accelerated encoding:
MainConcept Codec SDK
In my opinion they offer the best performance and quality (no I do not work for MainConcept).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "multithreading, video, encoding, decoding, codec"
}
|
Why put void in params?
What's the reason for putting void inside of the params?
Why not just leave it blank?
void createLevel(void);
void createLevel();
|
The `void` in the parenthesis are from C. In C a function with empty parentheses could have any number of parameters. In C++ it doesn't make any difference.
|
stackexchange-stackoverflow
|
{
"answer_score": 47,
"question_score": 36,
"tags": "c++"
}
|
typeError: isinstance() arg 2 must be a type or tuple of types >>>
>>> names=['jill','jack']
>>> isinstance(names,list)
Traceback (most recent call last):
File "<pyshell#291>", line 1, in <module>
isinstance(names,list)
TypeError: isinstance() arg 2 must be a type or tuple of types
>>>
Am I missing something here?
|
You've stomped on `list` by assigning to a local variable of the same name. Don't do that.
|
stackexchange-stackoverflow
|
{
"answer_score": 64,
"question_score": 37,
"tags": "python"
}
|
Use mysqldump to export all databases into a file using DAYOFMONTH()
I would like to run a task in my cron to export all databases into a single file. I would like to create 1 file for every day of the week (e.g. `all_[1-7].sql`). And I'd like it to replace the previous file if it exists. Is it possible to use MySQL's date and time functions e.g.:
mysqldump -u user -ppass –all-databases | gzip > /backups/mysql/all_`DAYOFMONTH(CURDATE())`.sql.gz
|
No. What comes after the pipe character runs a shell command, not MySQL. Therefore you need to generate the date "the shell way". E.g.
... | gzip > /backups/mysql/all_`date +%u`.sql.gz
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
}
|
Parse Compound Queries in Swift 1.2
I have this query
var postsExploreQuery = Post.query()
postsExploreQuery!.whereKey("isPrivate", equalTo: false)
var query = PFQuery.orQueryWithSubqueries([postsExploreQuery])
query.whereKey("isPublished", equalTo: true)
return query
and Xcode shows me error
> Cannot invoke 'orQueryWithSubqueries' with an argument list of type '([PFQuery?])'
what I'am doing wrong :(
|
You really should get out of the habit of putting `!` after all your optionals. This removes all the safety that optionals are intended to give you. Unless it has been poorly designed, there's a reason the API you are using will return an optional. Unwrap your optional safely using `if let`. This removes the chance that your program will randomly crash in the future and also gives you the chance to handle the error with an else if it makes sense for your program.
var postsExploreQuery = Post.query()
if let postsExploreQuery = postsExploreQuery {
postsExploreQuery.whereKey("isPrivate", equalTo: false)
var query = PFQuery.orQueryWithSubqueries([postsExploreQuery])
query.whereKey("isPublished", equalTo: true)
return query
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, xcode, swift, parse platform"
}
|
Css positioning without background image
I am facing a problem in positioning a text at the top of the image. The image is not in background.It's just with image tag.
The thing is I can't change the html code. Is it possible to achieve what I want but without changing the html code.
<div class="home_box">
<img src=" class="holding">
<h4>hot off the server</h4>
</div>
Jsfiddle : <
I have updated the fiddle. Now when you resize the window the image is moving but the text is staying there.Is there any way to make it **responsive**
|
Try this: **FIDDLE**
CSS:
.home_box {
position:relative;
text-align:center;
}
img.holding {
position:relative;
margin-top:40px;
}
.home_box h4 {
color: #000;
font-family:'arial';
font-size: 15px;
left: 140px;
line-height: 33px;
position: absolute;
text-align: center;
text-transform: uppercase;
width: 200px;
height:40px;
left:50%;
top:0;
margin-left:-100px;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "html, css"
}
|
Custom Formula Data Validation
Can we set the following data validation rule across a range to prevent duplicate entries?
=COUNTIF(B$6:B,B6)<2
The above custom formula in Data Validation stops duplicate entries in column B from row 6 downwards, so the rule on the 15th column would be:
=COUNTIF(B$6:B,B15)<2
Can we do this programmatically in GAS?
|
## Solution:
The Data Validation Builder can define a data validation rule across a range:
**Sample Code:**
function myFunction() {
var cell = SpreadsheetApp.getActive().getRange("B6:B");
var rule = SpreadsheetApp.newDataValidation().requireFormulaSatisfied("=COUNTIF(B$6:B,B6)<2").build();
cell.setDataValidation(rule);
}
**Sample Sheet:**
` to the rule definition.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "validation, google apps script, google sheets, formula"
}
|
how to write the current system time to a csv file using python
I have a list of people and want to track their attendance each time a person is recognized. I have written the name to a csv file how to write their corresponding time also .
code:
for i in face_names:
if "Unknown" in i:
pass
else:
temp_mul_list.append(i)
print(str(temp_mul_list))
with open("res.csv", "w", newline='') as f:
writer = csv.writer(f)
for i in temp_mul_list:
writer.writerow([i])
where **temp_mul_list** contains the names of the persons identified
|
This is what your code could look like
import datetime
for i in face_names:
if "Unknown" in i:
pass
else:
temp_mul_list.append([i, str(datetime.datetime.now())])
print(str(temp_mul_list))
with open("res.csv", "w", newline='') as f:
writer = csv.writer(f)
for i in temp_mul_list:
writer.writerow(i)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python 3.x, csv"
}
|
Catalog price rule not excluding specific categories
I have set up a catalog price rule for a specific customer group. I want to exclude some different categories with this rule.
See setting in screen: !enter image description here
For some reason this is not excluding products OR categories.
This is in Magento 1.9.1.0
I have tested exact same settings in 1.7.0.2 where this works perfectly.
What am I missing here?
|
Settings in my screenshot are correct for excluding multiple categories and SKU's from some catalog price rule.
After banging my head against the wall for several day i tried changing away from flat category structure, which seemed to solve my problem. Category indexes must be currupt or something, but i did not investigate further.
Anyone else have this problem, try and do what i did and see if it works. Did in my case.
|
stackexchange-magento
|
{
"answer_score": 1,
"question_score": 2,
"tags": "magento 1.9, magento 1.7, ce 1.7.0.2, catalog price rules, ce 1.9.1.0"
}
|
Imitating Rabbanim
Is it Lashon Hara (or any other aveirah) to imitate a rav. It’s a common thing in yeshivos (at least the ones I’ve been involved in) that some bachrim imitate the rebbes mannerisms and way of speaking in a joking manner. For the most part the bachrim who do this have a lot of respect and yirah of the rabbi but enjoy getting a kick out of the way he talks/gives shiur.
Is this type of imitation considered Lashon Hara or is there any way to defend such behavior? _please bring source if possible of course_
|
R Avrohom Ehrman, writing in his book The laws of interpersonal relationships, explicitly addresses your case and calls it _leitzanut_ (mockery). Based on Rabbeinu Yonah in Shaarei Teshuva, he describes five categories of _leitzanut_.
> The fifth category [and less grave] involves **making fun of people or their behavior simply for the sake of amusement** , even if it is clear from the jokes that the speaker actually respects both the people involved and their conduct.
>
> Rabbeinu Yonah points out that this type of _leitzanus_ is occasionally found in many people, including otherwise upright Jews. Therefore, it is important to make a great effort to work on eliminating any belittlement of others from one's speech.
|
stackexchange-judaism
|
{
"answer_score": 4,
"question_score": 6,
"tags": "halacha, sources mekorot, rabbis, lashon hara slander, humor"
}
|
How can I define roll over file size in Azure Data Factory for Blob sink?
I want to copy a large Database table to Azure Blob Storage, but I want each file in the Azure Blob Storage to not be more than a certain size. Is there a way in Azure Data Factory to define such roll over size? Because I can't see any.
|
Microsoft Azure does not provide limit per container. The Azure provides Maximum number of blocks in a block blob or append blob is (50,000 blocks), Maximum size of a block in a block blob is (4000 MiB) and Maximum size of a block blob is (50,000 X 4000 MiB (approximately 190.7 TiB)). As Per your requirement, You have to restrict the certain data in large Database table before moving to azure blob. Pls refer from Azure subscription limits and quotas - Azure Resource Manager | Microsoft Docs
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "azure, azure blob storage, azure data factory"
}
|
Rename columns in dataframe using bespoke function python pandas
I've got a data frame with column names like 'AH_AP' and 'AH_AS'.
Essentially all i want to do is swap the part before the underscore and the part after the underscore so that the column headers are 'AP_AH' and 'AS_AH'.
I can do that if the elements are in a list, but i've no idea how to get that to apply to column names.
My solution if it were a list goes like this:
columns = ['AH_AP','AS_AS']
def rejig_col_names():
elements_of_header = columns.split('_')
new_title = elements_of_header[-1] + "_" + elements_of_header[0]
return new_title
i'm guessing i need to apply this to something like the below, but i've no idea how, or how to reference a single column within df.columns:
df.columns = df.columns.map()
Any help appreciated. Thanks :)
|
You can do it this way:
Input:
df = pd.DataFrame(data=[['1','2'], ['3','4']], columns=['AH_PH', 'AH_AS'])
print(df)
AH_PH AH_AS
0 1 2
1 3 4
Output:
df.columns = df.columns.str.split('_').str[::-1].str.join('_')
print(df)
PH_AH AS_AH
0 1 2
1 3 4
Explained:
* Use string accessor and the split method on '_'
* Then using the str accessor with index slicing reversing, [::-1], you can reverse the order of the list
* Lastly, using the string accessor and join, we can concatenate the list back together again.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, pandas, dataframe"
}
|
Strange outcome with Enumerate .inject in Ruby
Hello guys I just encountered something strange with inject in Ruby.
(1..6).inject(1) { |sum, c| puts c % 2 == 0 ? c + 1 : c * 2 }
Output:
2
3
6
5
10
7
Shouldn't it be:
2
3
6
7
14
15
Why is this subtracting 1 and 3 instead of adding 1?
|
No, this is correct:
1 * 2 = 2
2 + 1 = 3
3 * 2 = 6
4 + 1 = 5
5 * 2 = 10
6 + 1 = 7
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ruby"
}
|
How to provide feedback on technical debt after first day in role
I've just joined a startup (first day finished). And there's a few things i've already noticed are a little off kilter.
The major is that a fundamental piece of the engineering (RPC) is a framework that one of the previous engineers rolled on his own - It's JSON over HTTP POST... the mind boggles as to why they didn't choose Thrift/gRPC/ProtoBuf etc..
(My apologies for the tech references.. my hunch is that there are many techies here and it may help..)]
Anyway, I feel like I need to raise this as an issue sooner rather later. Should I take it to the tech lead or straight to the CTO or raise it for chat on the Slack channel.. Now, it's a small startup so the CTO is involved in most stuff.
As opposed to just crying about it I am going to propose some problems and suggest that I work hard to solve on my work and have the solution trickle out to others..
What have you done in this case? Thanks.
|
> What have you done in this case?
Do not assume that what was done was _plucked out of thin air_. I might hold on to my opinions if I were you until you are **100% clear as to why things are done they way they are**.
This is not to imply that you are wrong, I just suggest you be 100% sure of your correctness, which you cannot be after 1 day.
After you have been there a bit, and know all the in's and out's, then bring on the suggestions using an incremental approach. Your delivery of these suggestions without crapping on the current implementations, and indirectly the people who implemented, will be critical in terms of how well your input is received.
|
stackexchange-workplace
|
{
"answer_score": 7,
"question_score": 1,
"tags": "teamwork"
}
|
get a list of posts from Custom Taxonomy
I can get a category id or slug for my custom taxonomy just fine, but I then need to be able to get all the posts as an array for that taxonomy entry. My code is as follows:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
endwhile;
When I add 'category_name'=>'my_taxonomy_name' to the args array, it just causes the $the_query to be empty although I know that there is post in there. I have also tried changing it to 'cat'=>22, but this also has the same fault.
Can anyone help?
Cheers John
|
Check out the Taxonomy Parameters.
<?php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'taxonomy_name',
'field' => 'id',
'terms' => '22'
)
)
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
//content
endwhile;
?>
|
stackexchange-wordpress
|
{
"answer_score": 4,
"question_score": 1,
"tags": "custom post types, custom taxonomy"
}
|
How do I gracefully handle hibernate/sleep modes in a winforms application?
I am writing a windows form application in .net using C#.
I am running into a problem that if my program is running when the computer goes into the sleep and/or hibernate state (I am not sure at this time which one, or if both, cause the problem), when the machine wakes up again the program just hangs. The only way to exit out of it is to kill the process from the task manager.
This is, for obvious reasons, not the way I want the program to function. Even if I just shut the program down when it goes into these states, that would be fine, but I am not quite sure how to do this or if there is a more graceful way altogether of handling this.
|
You need:
using Microsoft.Win32;
And this is the code:
void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if(e.Mode == PowerModes.Suspend)
{
this.GracefullyHandleSleep();
}
}
This is what I went with.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 17,
"tags": "c#, .net, winforms, events, hibernate mode"
}
|
python log view application
I want to have GUI application or Web app where I can view the python log information. I can choose any formatter required. But it should work with standard logging module.
I have configured my logs to file. But I wanted to have log to be stored to mysql db (it is possible) but I badly need user interface to view the log from remote place.
Any recommended tool or approach?
|
You can write a database handler for logging as in this example using any Python DB-API 2.0 compliant database interface. Then, of course, you can view the logs using any framework which allows you to get and display data via the Web.
Or, you can use log4j's Chainsaw GUI using the approach outlined here. Here's a screenshot:

Just two approaches - there are no doubt numerous others.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "python, mysql, logging"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.