text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Copy div to a popup
How can I copy an entire div to a popup window?
What I`m trying to do:
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript' />\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
text += $("#divDadosBasicos").html($(querySelector).html());
text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n/body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
I dont know if this is the better way to do it. If you think/know a easier way to do it, please share
Thanks in advance!
A:
Fix some of these errors and it will work fine
Script tag is not closed properly
body tag not closed properly
querySelector is not defined. (I am commenting that portion)
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript'></script>\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
//define querySelector
//text += $("#divDadosBasicos").html($(querySelector).html());
//text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n</body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find the second element in a stream satisfying some condition?
I want to display the second element of the stream for which the name starts with 's'.
I tried:
employees.stream()
.filter(e -> e.getName().charAt(0) == 's')
.findAny()
.ifPresent(e -> System.out.println("Employee : " + e));
However, when I use findAny(), it returns the first element in the stream (same as findFirst()) and I want the second one.
A:
You can skip the first match by adding skip(1) after the filter:
employees.stream()
.filter(e -> e.getName().charAt(0) == 's')
.skip(1)
.findAny()
.ifPresent(e -> System.out.println("Employee : " + e));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is seconds not converting to hours and days
I created a function to display how much time has elapsed, but for some reason the conditional statement does not return at specific statements after the first elif. Adding a print statement shows that the function is flowing however as objects are printed out. I am not sure why this is happening as the time elapsed since some posts were made are greater than 3600 seconds in elapsed time. It is therefore converting all elapsed time solely to minutes, but I will say that the time elapsed in seconds is working properly. Am I doing my conversion wrong or is it a syntax or type error? Also, is there a better way to go about this?
def time_diff(self):
if self.date_pub:
now = datetime.datetime.utcnow().replace(tzinfo=utc)
diff = now - self.date_pub
total_time = diff.total_seconds()
if total_time < 60:
return str(int(total_time)) + "s ago."
elif total_time > 60 or total_time <= 3600:
return str(int(total_time / 60)) + "m ago."
elif total_time >= 3600 or total_time <= 86400:
return str(int(total_time / 3600)) + "h ago."
elif total_time >= 86400 or total_time <= 604800:
return str(nt(total_time / 86400)) + "d ago."
else:
return date_pub
A:
First up, you should fix the cases where you have gaps, such as 60 which will not be caught by any of the if/elif clauses. It should be < 60 the >= 60 in the first two condition checks.
Additionally, all of those or keywords should definitely be and. Think of what happens for a day (86,400 seconds):
elif total_time > 60 or total_time <= 3600:
return str(int(total_time / 60)) + "m ago."
Since 86,400 is greater than 60, this will fire, resulting in 1440 m ago. being returned. In fact (once you've fixed the gap issue referred to in the first paragraph), every value is either less-than or greater-than-or-equal-to 60, you'll only ever see seconds or minutes output.
In fact, since the whole if something return else construct is redundant (return means the else is superfluous), you could get away with the simpler:
if total_time < 60:
return str(int(total_time)) + "s ago."
if total_time < 3600:
return str(int(total_time / 60)) + "m ago."
if total_time < 86400:
return str(int(total_time / 3600)) + "h ago."
if total_time < 604800:
return str(int(total_time / 86400)) + "d ago."
return self.date_pub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clickable div acting as a button function react js
I have a button function inside the component 'CZButton', the button is used in "personlist" for a pop up, I am trying to make the div card inside of either 'personlist' or 'person' clickable so that instead of clicking the button, the div would be clicked and shows the drawer pop up.
I tried adding onclick inside divs and but it did not seem to reach the drawer function. here is a sandbox snippet, would appreciate the help.
https://codesandbox.io/s/l9mrzz8nvz?fontsize=14&moduleview=1
A:
You can add an onClick listener in React just by writing something like:
// omitting the rest of the render function for brevity
return (
<div className="row" onClick={e => console.log("Clicked")}></div>
);
Just be careful with the HTML semantics. Although it is possible, I wouldn't really recommend adding onClick events to a div. There are good resources online about HTML5 standards and what you should adhere too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to reset form only when data in inserted successfully ? (Ajax)
I have a form. I am processing the form through ajax
Below php file is called through ajax and it validates data. If there are errors, they are displayed. If not data is inserted into the database. Success result is also displayed
if (!empty($errors)) {
echo "<div class='alert alert-danger'>"
foreach($errors as $error) {
echo "<p>".$error."</p>";
}
echo "</div>";
} else {
//no errors
$result = $database - > create("customer", $data);
if ($result) {
echo "<div class='alert alert-success'>"
echo "<p>New customer created successfully</p>";
echo "</div>";
}
}
Everything works as I expected, but I want to make an enhancement. I need to clear the form only when success result is displayed.
If there are errors I do not want to reset the form.
I can check whether output string is equal to the whole success message and if yes reset the form, but I am looking for some solution which does not depend on the output string.
$(function () {
$("#create-form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
context: this,
url: "create_process.php",
data: $(this).serialize(),
success: function (data) {
$("#update").html(data);
$('#create-form').trigger("reset");
//How to check whether output data is either
//an error or a success and call above reset function
}
});
});
});
A:
Return a JSON from your php...
$res['html'] = "";
$res['status'] = "";
if (!empty($errors)) {
$res['html'] .= "<div class='alert alert-danger'>";
foreach($errors as $error) {
$res['html'] .= "<p>".$error."</p>";
}
$res['html'] .= "</div>";
$res['status'] = "error";
} else {
//no errors
$result = $database - > create("customer", $data);
if ($result) {
$res['html'] .= "<div class='alert alert-success'>";
$res['html'] .= "<p>New customer created successfully</p>";
$res['html'] .= "</div>";
}
$res['status'] = "success";
}
echo json_encode($res);
In your jquery:
$.ajax({
method:"POST",
context:this,
dataType: "json",
url:"create_process.php",
data:$(this).serialize(),
success:function(data){
$("#update").html(data.html);
if (data.status == "success") {
$('#create-form').trigger("reset");
}
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to save (cvWrite or imwrite) an image in OpenCV 2.4.3?
I am trying to save an OpenCV image to the hard drive.
Here is what I tried:
public void SaveImage (Mat mat) {
Mat mIntermediateMat = new Mat();
Imgproc.cvtColor(mRgba, mIntermediateMat, Imgproc.COLOR_RGBA2BGR, 3);
File path =
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
String filename = "barry.png";
File file = new File(path, filename);
Boolean bool = null;
filename = file.toString();
bool = Highgui.imwrite(filename, mIntermediateMat);
if (bool == true)
Log.d(TAG, "SUCCESS writing image to external storage");
else
Log.d(TAG, "Fail writing image to external storage");
}
}
Can any one show how to save that image with OpenCV 2.4.3?
A:
Your question is a bit confusing, as your question is concerning OpenCV on the desktop, but your code is for Android, and you ask about IplImage, but your posted code is using C++ and Mat. Assuming you're on the desktop using C++, you can do something along the lines of:
cv::Mat image;
std::string image_path;
//load/generate your image and set your output file path/name
//...
//write your Mat to disk as an image
cv::imwrite(image_path, image);
...Or for a more complete example:
void SaveImage(cv::Mat mat)
{
cv::Mat img;
cv::cvtColor(...); //not sure where the variables in your example come from
std::string store_path("..."); //put your output path here
bool write_success = cv::imwrite(store_path, img);
//do your logging...
}
The image format is chosen based on the supplied filename, e.g. if your store_path string was "output_image.png", then imwrite would save it was a PNG image. You can see the list of valid extensions at the OpenCV docs.
One caveat to be aware of when writing images to disk with OpenCV is that the scaling will differ depending on the Mat type; that is, for floats the images are expected to be within the range [0, 1], while for say, unsigned chars they'll be from [0, 256).
For IplImages, I'd advise just switching to use Mat, as the old C-interface is deprecated. You can convert an IplImage to a Mat via cvarrToMat then use the Mat, e.g.
IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
//now can use cv::imwrite with newC
alternately, you can convert an IplImage to a Mat just with
Mat newC(oldC0); //where newC is a Mat and oldC0 is your IplImage
Also I just noticed this tutorial at the OpenCV website, which gives you a walk-though on loading and saving images in a (desktop) environment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Code Completion Xamarin Studio
Is there a way to enable automatic generation of a closing curly bracket when an opening curly bracket is typed in Xamarin Studio?
In other words, when I type },in all the other IDE's I've used a { is automatically generated. That doesn't seem to be the case in Xamarin Studio.
A:
You can configure Xamarin Studio to automatically insert a closing curly brace when an opening curly brace is entered in Preferences - Text Editor - Behaviour - Insert matching brace.
Going the other way of entering a closing brace and having Xamarin Studio automatically insert an opening brace does not seem to work though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как обновить страницу не перезагружая ее
Я в Javascript полный ноль.
У меня такая задача. обновить страницу не перезагружая ее.
Например настранице есть Messages (0) и нужно если пришло письмо поменять значение 0 на пример 2. или вариант такой добавить результат формы в базу данных.
Вообщем основная задача выташить или запихать в базу инфу без перезагрузки страницы.
Как я понял вставить можно методом загрузки второго файла типа router.php. А вот как выташить и поменять инфу вообще понятия не имею.
Cам метод вставки и вытаскивания методами из базы данных через php.
A:
Вот на этом сайте есть подробные уроки по JavaScript - Ajax.
Удачи в изучении материала :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are the 11 rudras mentioned in the Vedas?
Do Vedas describe about the 11 rudras?
What are the names of those rudras according to Vedas?
How did they emerge from the supreme Rudra?
A:
No, they are not 11 Rudras mentioned in the Vedas. This is a concept invented in the Puranas. Specifically, Matsya(५.२९-३॰), (Harivamśa (१.३.४९-५२) and has no support in the Vedas.
Rig Veda reveals Rudra as श्वितीचे (śvitīce) (२.३३.८) which is translated by Sāyaṇa as of white complexion.
He is one among two or three gods who are invoked as having or assuming all forms. Another epithet for Rudra is varāha (१.११४.५) दिवो वराहमरुषं कपर्दिनं त्वेषं रूपं नमसा नि ह्वयामहे which is explained by Sāyaṇa one who has good food.
Rudra bestows happiness on the sons and grandsons of the invoker (२.३३.१४) परि णो हेती रुद्रस्य वृज्याः परि त्वेषस्य दुर्मतिर्मही गात् ।अव स्थिरा मघवद्भ्यस्तनुष्व मीढ्वस्तोकाय तनयाय मृळ and grants a longer life and progeny (२.३३.१-२) अभि नो वीरो अर्वति क्षमेत प्र जायेमहि रुद्र प्रजाभिः
Another important aspect of Rudra is his power to heal.
Prayers are presented to Rudra to provide medicines (२.३३.१२) कुमारश्चित्पितरं वन्दमानं प्रति नानाम रुद्रोपयन्तम् । भूरेर्दातारं सत्पतिं गृणीषे स्तुतस्त्वं भेषजा रास्यस्मे and he is the Chief among all the physicians (२.३३.४ and १.११४.१). मा त्वा रुद्र चुक्रुधामा नमोभिर्मा दुष्टुती वृषभ मा सहूती । उन्नो वीराँ अर्पय भेषजेभिर्भिषक्तमं त्वा भिषजां शृणोमि ॥४॥
Rudra is described as the Lord of the world (२.३३.३-४) श्रेष्ठो जातस्य रुद्र श्रियासि and nobody is possessing more power than him (२.३३.१॰). अर्हन्निदं दयसे विश्वमभ्वं न वा ओजीयो रुद्र त्वदस्ति
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Algorithm/Data Structure to determine if a word is a valid English word
I'm designing an HTML5 game that requires me to validate that a word a user enters is a valid English word. I know I can perform the validation by sending the word to the server, however, since I want to do validation as the user types, server side validation is not an optimal solution. I therefore need to perform validation in the game, running in the user's browser.
What is the most efficient way for me to validate a user entered word, as the user types, against every word in the English language?
A:
Yes you can use data structure such as trie where we make a tree of the searchable words and finds elements in O(|P|) time. Why trie is a better option if you ask yourself..you will see whenever user enters one character at a time you can traverse letter by letter on the fly and give fast feedback as per your game rule.
P: pattern you are searching for.
Also you said server side validation is not possible but I have seen games where they make ajax calls to validate words and at that time they create some thing that pops up on the screen or some game story or component to make you feel that it is happening instantly or in some interesting way,
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TypeScript: How to cast a generic object?
I have the following interfaces:
interface AppState {
readonly grid : IGridSettings;
readonly selected : ISelectedSettings;
}
interface IGridSettings {
readonly extents : number;
readonly isXY : boolean;
readonly isXZ : boolean;
readonly isYZ : boolean;
readonly spacing : number;
}
interface ISelectedSettings {
readonly bodyColor : number;
readonly colorGlow : number;
readonly lineColor : number;
readonly selection : number[] | undefined;
}
interface Action<T = any> {
type: T
}
interface SetPropertyValueAction<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]> extends Action {
type : string;
payload : {
property : [KAction, KActionProp];
value : IUserActions[KAction][KActionProp];
};
}
Eventually my redux reducer gets called when the setPropertyValue function is emitted:
const setPropertyValue = <KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>( property : [KAction, KActionProp], value : AppState[KAction][KActionProp] ) : SetPropertyValueAction<KAction, KActionProp> => ( {
type: 'SET_PROPERTY_VALUE',
payload: {
property,
value,
}
} );
function myReducer( state : AppState = INITIAL_STATE, a : Action ) : AppState {
switch( a.type ) {
case 'SET_PROPERTY_VALUE': {
const action = a as SetPropertyValueAction; // <- error here
return createNewState( state, action.payload.property, action.payload.value );
}
}
return states;
}
The problem that I'm having is I don't know how to fix the cast from Action to SetPropertyValueAction. TypeScript tells me the error is:
Generic type 'SetPropertyValueAction<KAction, KActionProp>' requires 2 type argument(s).
I tried changing the line of code that has the error to the following:
const action = a as SetPropertyValueAction<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>;
...but this gives me two errors saying 'Cannot find name KAction and KActionProp'
How can I cast an Action object to the generic SetPropertyValueAction ??
This is a follow up question to my other question that has been answered here: How to add TypeScript type safety to my redux action?
A:
We need to specify the type parameters for the type. Since we don't really know them, we need something that is compatible with keyof T but represent is not an actual key of T. unknown will not do since it does not satisfy the constraint, the one type we can use is any or never (which is a subtype of any type)
interface AppState {
readonly grid: IGridSettings;
readonly selected: ISelectedSettings;
}
interface IGridSettings {
readonly extents: number;
readonly isXY: boolean;
readonly isXZ: boolean;
readonly isYZ: boolean;
readonly spacing: number;
}
interface ISelectedSettings {
readonly bodyColor: number;
readonly colorGlow: number;
readonly lineColor: number;
readonly selection: number[] | undefined;
}
interface Action<T = any> {
type: T
}
interface SetPropertyValueAction<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]> extends Action {
type: string;
payload: {
property: [KAction, KActionProp];
value: AppState[KAction][KActionProp];
};
}
const setPropertyValue = <KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>(property: [KAction, KActionProp], value: AppState[KAction][KActionProp]): SetPropertyValueAction<KAction, KActionProp> => ({
type: 'SET_PROPERTY_VALUE',
payload: {
property,
value,
}
});
declare const INITIAL_STATE: AppState;
// implementation if necessary
function createNewState<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>(state: AppState, property: [KAction, KActionProp], value: AppState[KAction][KActionProp]): AppState {
return Object.assign({ ...state }, {
[property[0]]: Object.assign({ ...state[property[0]] }, {
[property[1]]: value,
})
});
}
function myReducer(state: AppState = INITIAL_STATE, a: Action): AppState {
switch (a.type) {
case 'SET_PROPERTY_VALUE': {
const action = a as SetPropertyValueAction<never, never>; // we don't know the actual type, never will have to do
return createNewState(state, action.payload.property, action.payload.value);
}
}
return state;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using GhostScript 9.10 in Windows with Unicode characters in parameters
I want to use Ghostscript in a .NET / C# application to convert a .tiff file to PDF.
My problem: When the file path contains non-ansi characters (e.g. Umlaute), the function
gsapi_init_with_args
fails. (With GS 8.x, it works fine!).
I found information that the behaviour was changed in 9.x, and I also found a function called
gsapi_init_with_argsW
And this function should work with .NET without any problems (see http://permalink.gmane.org/gmane.comp.printing.ghostscript.cvs/31721)
So I use the following DLLImport:
[DllImport(@"gsdll32.dll")]
public static extern int gsapi_init_with_argsW( IntPtr instace, int argc, string[] argv);
but this still does not work, I get the error:
Error: /undefinedfilename
in (C:\\304NDERUNGEN\\TEST.PDF)
The name of the file schould be
C:\\ÄNDERUNGEN\\TEST.PDF
so the umlaut "Ä" is not recognized correctly.
I´ve search the web a lot but did not found a solution.
Any idea?
Thank you!
A:
I suspect that you will need to use UTF-8 here. Make a call to gs_set_arg_encoding passing GS_ARG_ENCODING_UTF8.
Any strings that you pass to Ghostscript should be declared as IntPtr. To convert from a C# string to a null-terminated UTF-8 encoded string use this function provided by Hans Passant:
public static IntPtr NativeUtf8FromString(string managedString)
{
int len = Encoding.UTF8.GetByteCount(managedString);
byte[] buffer = new byte[len + 1]; // null-terminator allocated
Encoding.UTF8.GetBytes(managedString, 0, managedString.Length, buffer, 0);
IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
return nativeUtf8;
}
Make sure that you remember to clean up with a call to Marshal.FreeHGlobal.
The overall code might look a little like this:
public class Ghostscript
{
public const int GS_ARG_ENCODING_LOCAL = 0;
public const int GS_ARG_ENCODING_UTF8 = 1;
[DllImport("gsdll32.dll")]
private static extern int gsapi_new_instance(out IntPtr inst, IntPtr handle);
[DllImport("gsdll32.dll")]
private static extern int gsapi_set_arg_encoding(IntPtr inst, int encoding);
[DllImport("gsdll32.dll")]
private static extern int gsapi_init_with_args(IntPtr inst, int argc, IntPtr[] argv);
[DllImport("gsdll32.dll")]
private static extern int gsapi_exit(IntPtr inst);
[DllImport("gsdll32.dll")]
private static extern void gsapi_delete_instance(IntPtr inst);
private static void checkReturnValue(int retval)
{
if (retval != 0)
throw ...; // implement error handling here
}
public static void run(string[] argv)
{
IntPtr inst;
checkReturnValue(gsapi_new_instance(out inst, IntPtr.Zero));
try
{
IntPtr[] utf8argv = new IntPtr[argv.length];
for (int i=0; i<utf8argv.Length; i++)
utf8argv[i] = NativeUtf8FromString(argv[i]);
try
{
checkReturnValue(gsapi_set_arg_encoding(inst, GS_ARG_ENCODING_UTF8));
checkReturnValue(gsapi_init_with_args(inst, utf8argv.Length, utf8argv));
checkReturnValue(gsapi_exit(inst));
finally
{
for (int i=0; i<utf8argv.Length; i++)
Marshal.FreeHGlobal(utf8argv[i]);
}
}
finally
{
gsapi_delete_instance(inst);
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UTF 8 String remove all invisible characters except newline
I'm using the following regex to remove all invisible characters from an UTF-8 string:
$string = preg_replace('/\p{C}+/u', '', $string);
This works fine, but how do I alter it so that it removes all invisible characters EXCEPT newlines? I tried some stuff using [^\n] etc. but it doesn't work.
Thanks for helping out!
Edit: newline character is '\n'
A:
Use a "double negation":
$string = preg_replace('/[^\P{C}\n]+/u', '', $string);
Explanation:
\P{C} is the same as [^\p{C}].
Therefore [^\P{C}] is the same as \p{C}.
Since we now have a negated character class, we can substract other characters like \n from it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plot 3 categorical variables with dependencies on previous column
I have the following data that i want to plot using r (ggplot2 or any other package)
QUESTION IS: What is the best method to visualize in R, to understand the relationship between those who are Happy = Yes, Pay = No and Donate = Yes (and other combinations).
AreYouHappy | WouldYouPay | WouldYouDonate
Yes | No | Yes
Yes | No | No
Yes | No | Yes
Yes | Yes | Yes
Yes | No | No
No | Yes | Yes
Yes | No | No
Yes | No | Yes
...[58 data points]
[Reproducible code]
df <- data.frame(
cbind(AreYouHappy = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.75,.25)),
WouldYouPay = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.25,.75)),
WouldYouDonate = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.50,.50))))
I tried VennDiagram, SankeyDiagram, Bar, Mosiac Plot, using ggplot2/plotluck but I can't get a handle on any of them. I've tried using reshape2, but i can't understand how to change these data point into a matrix of count and then plot it. I searched all over. Please do help-- where am I going wrong?
A:
If it's dataset concerning happiness then why not to use upset :-)
# Data
df <- data.frame( cbind(AreYouHappy = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.75,.25)), WouldYouPay = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.25,.75)), WouldYouDonate = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.50,.50))))
# Transform original data into 0 and 1
df01 <- apply(df, 2, function(x) ifelse(x == "Yes", 1, 0))
# Plot using UpSetR
library(UpSetR)
upset(data.frame(df01))
More about UpSetR in the vignette.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Arrivals based on database
I am trying to retrieve arrival rates from a excel spreadsheet in my model but I don't have the option to select the specific row and column i want. How can I ensure that a specific cell is chosen? (For example i want the value 5 corresponding to "limeConveyor" row and "red" column.
This is the sample spreadsheet
This is the properties window
Thank you in advance for your help! :)
Edit 1:
I am currently unable to select "red" from the
dropdown list of value column. Is my program bugged or something?
A:
Maybe to clarify Felipe's reply: I suspect your dbase table is not setup correctly and doesn't match your xls screenshot.
First, load your spreadsheet into an AnyLogic dbase table using the wizard. It should then look like this (note the column properties: the column type is important):
Now in your source, you can easily load the required column-row combination and the valuer-dropdown allows you to select "red" if you want:
You can find the example model that I used for the screens here, hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Como adicionar o Account no projeto Asp.Net Core
Sou novato no asp.net core mvc e estou tendo uma dificuldade, tenho um projeto que no visual studio tenho uma solução para 4 projetos diferentes.
Digamos que seja apenas o projeto A e projeto B.
O projeto A seria o site antigo da empresa e o projeto B seria um novo sistema, por padrão no projeto A veio a configuração de account conforme a imagem abaixo.
Já o projeto B não veio o account conforme a imagem.
Como posso utilizar o account para meu novo projeto(B)?
OBS: Esse projeto A seria deletado futuramente.
A:
No projeto B, você está utilizando a versão mais nova do ASP.NET Core Identity que já traz a parte de autenticação em funcionamento, e então você pode customizar de acordo com sua necessidade, porém de uma forma diferente do que estavamos acostumados na versão anterior.
Você pode especificar no momento da criação do projeto, ou então adicionar posteriormente.
Na criação do projeto, você deve clicar em "Change Authentication" e selecionar "Individual User Accounts".
Depois você clique em cima do seu projeto e vá Add -> New Scaffolded Item -> Selecione Identity e clique e clique em Identity.
Sugiro que você leia a documentação oficial do ASP.NET Core Identity, existem vários cursos abordando o assunto na internet.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
After casting my votes to candidates of my choice should I downvote other candidates?
Question is what title says. I am not sure what to do actually.
A:
Upvote the candidates you support.
Downvote the candidates you absolutely don't want to see as moderators.
Don't vote on any other candidates.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to determine if user is currently active on site in Django
Is there a way to see if a user is currently logged in and active on a site?
For example, I know you can check the authentication token of the user and see if he is still 'actively logged in', but this doesn't tell me much, since the user could technically be logged in for two weeks, though only actively on the site for one minute of that duration. last_login would be equally unhelpful.
What would be a good method in django to check to see if the user is currently active? I have done this in Google Analytics, but was wondering how I could do an entirely-django approach.
A:
There are several ways to determine user activity:
1) Use javascript to send periodic requests to server.
+: You will be able to determine user activity despite he actively working on site or just keep open window.
-: Too many requests.
2) Use django middleware
-: Can`t determine user activity if he keeps only open window
3) Use asynchronous framework to keep long-lived connection. For example tornado.
It is cleanest way but the most labor-intensive.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How Infinadeck Omnidirectional Treadmill works
I have seen this paper about the Omnidirectional Treadmill With CAD model ( with tiny rollers on it):
Which compered its prototype with infinadeck as shown below:
but don't see those roller in infinadeck as seen here:
So does the rollers in infinadeck (more zoomed video) are so small that can not be seen or that company use another mechanism for this device, for example like this:
Update:
By seeing this video i guess Thanks, infinadeck don't have tiny rollers and only have the chain show in the CAD model of paper like this:
But i don't know i am right?!
Thanks.
A:
The infinadeck is literally a treadmill made of treadmills. The sideways motion works in the same way as a regular treadmill with belts stretched over rollers and driven by a motor. See https://m.youtube.com/watch?v=fvu5FxKuqdQ for more details
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как изменить имя пакета в проекте AndroidStudio?
При создании проекта AndroidStudio спрашивает каким будет пакет. Как этот пакет изменить без геморроя? Неужели нет инструмента?
A:
Единственное что нашлось на просторах, это советы делать рефакторинг имён папок внутри студии, создавать новые папки, удалять старые, делать реплейс старого пакета на новый. Это ужасно. Ужасно что не было до сих пор ни одного инструмента который бы помог разработчику просто взять и ввести в текстовое поле нужное ему имя пакета, и моментально поменять его.
Но теперь такой инструмент есть, потому что мне надоело всё время делать рефакторинг и самому создавать директории, и я решил сам сделать такой инструмент:
https://github.com/PrincessYork/AndroidProjectRenamer
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Write text on a div padding
I currently have a div called testLine used for displaying a color triangle effect using css:
#testLine {
width: 0;
height: 0;
padding-bottom: 47.5%;
padding-left: 47.5%;
overflow: hidden;
}
#testLine:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left: -1000px;
border-bottom: 1000px solid transparent;
border-left: 1000px solid #4679BD;
}
This works fine but the issue is the following:
How can I do to have a text over that triangle? I mean, I've tried with z-index but with no success (css it is not my strong point) and I didn't know if it is even possible to write text on it. What can be other possibilities? (I really don't want to use a resource consuming image for the background). I really appreciate any help that can lead me to a solution.
PrintScreen - http://i.imgur.com/dRCKVNO.jpg
edit, html code:
<div id="testLine"></div>
<div id="text">Testing Testing</div>
A:
use position with alignment...something like:
#text {
position: absolute;
/* this will make div fall out of
page flow anad align to viewports dimension*/
top:0;
/* position to top*/
left:20px;
right:0
/*if needed*/
bottom:0
/*if needed*/
}
working demo
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why can't we superpose two quantum vacuum states?
i read in this paper (Spontaneous Symmetry Breaking as the Mechanism of Quantum Measurement by Michael Grady) that we are not allowed to consider the superposition of two vacuum states. i do not understand (page 4) why the superposition would violate a quantum property? what would be the problem of such a violation?
A:
(In this answer, "different vacuum states" refers to different states that all have the the same minimum energy. This should not be confused with the "false vacuum" versus "true vacuum" language that is common in inflationary cosmology, for example.)
In principle, we can superpose two vacuum states, in the sense that quantum theory allows it. The catch is that we would never know that they were superposed — no experiment would ever be able to confirm it. That's because different vacuum states are more than just orthogonal to each other: they are prolifically orthogonal to each other, in the sense that no local operator can make them non-orthogonal to each other. In symbols, if $|a\rangle$ and $|b\rangle$ denote the two vacuum states, then we have
$$
\langle a|X|b\rangle=0
\tag{0}
$$
for all local operators $X$.
To see why this kind of "prolific orthogonality" implies that we can never experimentally confirm the existence of the superposition, work in the Heisenberg picture and suppose that we measure some sequence of local observables $A,B,C,...,Z$ associated with times $t_A,t_B,t_C,$ and so on. Let $A_1,A_2,...$ denote the projection operators associated with the possible outcomes of an $A$-measurement; let $B_1,B_2,...$ denote the projection operators associated with the possible outcomes of a $B$-measurement, and so on. According to Born's rule, if the system's configuration is described by the state-vector $|\psi\rangle$, then the "probability" (yeah, I know; it's just convenient slang) of obtaining the sequence of outcomes $A_i, B_j, C_k,...,Z_m$ is
$$
p = \frac{\langle\hat\psi|\hat\psi\rangle}{\langle\psi|\psi\rangle}
\tag{1}
$$
with
$$
|\hat\psi\rangle \equiv Z_m\cdots C_k B_j A_i|\psi\rangle.
\tag{2}
$$
The product
$$
Z_m\cdots C_k B_j A_i
\tag{3}
$$
is a product of local operators associated with different (successive) times, and if we're using a quantum field theory that satisfies the usual causality principles, then this product is still a local operator — it is still a member of an algebra of operators associated with a bounded region of spacetime that encompasses the localization regions of all of the operators in the product [1]. Therefore, if we take
$$
|\psi\rangle=|a\rangle+|b\rangle
\tag{4}
$$
(using un-normalized state-vectors so that we don't need to write explicit coefficients), then (1) becomes
$$
p =
\frac{\langle\hat a|\hat a\rangle}{\langle a|a\rangle}
\frac{\langle a|a\rangle}{\langle\psi|\psi\rangle}
+
\frac{\langle\hat b|\hat b\rangle}{\langle b|b\rangle}
\frac{\langle b|b\rangle}{\langle\psi|\psi\rangle},
\tag{5}
$$
where each hat again denotes the result of applying the operator (3) to the unhatted version of the state-vector. Equation (5) says that no matter what sequence of measurements we consider, the "probabilities" of the possible outcome-sequences are always the same as if we had started with a mixed state given by a weighted sum of $|a\rangle\langle a|$ and $|b\rangle\langle b|$. In other words, we might as well have only $|a\rangle$ or only $|b\rangle$, even if we couldn't have predicted in advance which one we would have.
(Minor caveat: the preceding analysis assumed that the occurrence of the $B$-measurement is not contingent on the outcome of the preceding $A$-measurement, and likewise for the other measurements in the sequence. That assumption is not essential, but it simplifies the argument.)
By the way, such "prolifically orthogonal" states are sometimes said to belong to different superselection sectors. This is related to the fact that even a mixed state can always be represented as a single state-vector, by working in a direct-sum Hilbert space whose summands can't be mixed with each other by any observables. (This is the idea behind the GNS construction.)
The cited paper alludes to the cluster property, which is closely related to the idea that I just described. To see why they're related, use the abbreviation
$$
\psi(X)\equiv\frac{\langle\psi|X|\psi\rangle}{\langle\psi|\psi\rangle}.
\tag{6}
$$
A state $|\psi\rangle$ is said to satisfy the cluster property if
$$
\psi(XY)\approx\psi(X)\psi(Y)
\tag{7}
$$
whenever $X,Y$ are local operators separated by a sufficiently large spacelike distance (loosely speaking). If $|a\rangle$ and $|b\rangle$ both satisfy the cluster property, and if the condition (0) holds for all local observbles $X$, then $|\psi\rangle \equiv |a\rangle+|b\rangle$ is not expected to satisfy the cluster property (that's the connection between the two ideas). This is because any local operator $X$ satisfies
$$
\psi(X)= a(X)\frac{\langle a|a\rangle}{\langle\psi|\psi\rangle}
+b(X)\frac{\langle b|b\rangle}{\langle\psi|\psi\rangle}
\tag{8}
$$
(and likewise for $Y$ and for $XY$). Therefore, the product $\psi(X)\psi(Y)$ involves cross-terms with both $a$ and $b$, but $\psi(XY)$ does not have any such cross-terms, suggesting that $\psi$ can't satisfy the condition (7). This is analyzed more carefully in [2] and [3].
The impossibility of experimentally confirming a superposition of two vacuum states can be regarded as an extreme special case of the practical impossibility of confirming a superposition of outcomes after a high-quality measurement. This perspective and its relationship to spontaneous symmetry breaking is addressed in another post:
What does spontaneous symmetry breaking have to do with decoherence?
The relationship is also addressed in the paper cited by the OP. I haven't studied that paper carefully, but it seems at least roughly consistent with the perspective I used here: SSB is one example of a (naturally-occurring) measurement, and idealized SSB (infinite volume, infinite settling time, etc) is a mathematically-convenient limiting case that only occurs on paper, not in a laboratory. The statement that different vacuum states belong to different strict superselection sectors is a statement about that idealized limiting case.
[1] Haag (1996), Local Quantum Physics
[2] In the context of spin systems (like the Ising model): Section 23.3, "Order Parameter and Cluster Properties", of Zinn-Justin's book Quantum Field Theory and Critical Phenomena.
[3] In the context of relativistic QFT: Section 19.1 in Weinberg, The Quantum Theory of Fields, Volume II.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CheckBoxList multiple selections: how to model bind back and get all selections?
This code:
Html.CheckBoxList(ViewData.TemplateInfo.HtmlFieldPrefix, myList)
Produces this mark-up:
<ul><li><input name="Header.h_dist_cd" type="checkbox" value="BD" />
<span>BD - Dist BD Name</span></li>
<li><input name="Header.h_dist_cd" type="checkbox" value="SS" />
<span>SS - Dist SS Name</span></li>
<li><input name="Header.h_dist_cd" type="checkbox" value="DS" />
<span>DS - Dist DS Name</span></li>
<li><input name="Header.h_dist_cd" type="checkbox" value="SW" />
<span>SW - Dist SW Name </span></li>
</ul>
You can check multiple selections. The return string parameter Header.h_dist_cd only contains the first value selected. What do I need to do to get the other checked values?
The post method parameter looks like this:
public ActionResult Edit(Header header)
A:
I'm assuming that Html.CheckBoxList is your extension and that's markup that you generated.
Based on what you're showing, two things to check:
The model binder is going to look for an object named Header with string property h_dist_cd to bind to. Your action method looks like Header is the root view model and not a child object of your model.
I don't know how you are handling the case where the checkboxes are cleared. The normal trick is to render a hidden field with the same name.
Also a nit, but you want to use 'label for="..."' so they can click the text to check/uncheck and for accessibility.
I've found that using extensions for this problem is error prone. You might want to consider a child view model instead. It fits in better with the EditorFor template system of MVC2.
Here's an example from our system...
In the view model, embed a reusable child model...
[AtLeastOneRequired(ErrorMessage = "(required)")]
public MultiSelectModel Cofamilies { get; set; }
You can initialize it with a standard list of SelectListItem...
MyViewModel(...)
{
List<SelectListItem> initialSelections = ...from controller or domain layer...;
Cofamilies = new MultiSelectModel(initialSelections);
...
The MultiSelectModel child model. Note the setter override on Value...
public class MultiSelectModel : ICountable
{
public MultiSelectModel(IEnumerable<SelectListItem> items)
{
Items = new List<SelectListItem>(items);
_value = new List<string>(Items.Count);
}
public int Count { get { return Items.Count(x => x.Selected); } }
public List<SelectListItem> Items { get; private set; }
private void _Select()
{
for (int i = 0; i < Items.Count; i++)
Items[i].Selected = Value[i] != "false";
}
public List<SelectListItem> SelectedItems
{
get { return Items.Where(x => x.Selected).ToList(); }
}
private void _SetSelectedValues(IEnumerable<string> values)
{
foreach (var item in Items)
{
var tmp = item;
item.Selected = values.Any(x => x == tmp.Value);
}
}
public List<string> SelectedValues
{
get { return SelectedItems.Select(x => x.Value).ToList(); }
set { _SetSelectedValues(value); }
}
public List<string> Value
{
get { return _value; }
set { _value = value; _Select(); }
}
private List<string> _value;
}
Now you can place your editor template in Views/Shared/MultiSelectModel.ascx...
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WebUI.Cofamilies.Models.Shared.MultiSelectModel>" %>
<div class="set">
<%=Html.LabelFor(model => model)%>
<ul>
<% for (int i = 0; i < Model.Items.Count; i++)
{
var item = Model.Items[i];
string name = ViewData.ModelMetadata.PropertyName + ".Value[" + i + "]";
string id = ViewData.ModelMetadata.PropertyName + "_Value[" + i + "]";
string selected = item.Selected ? "checked=\"checked\"" : "";
%>
<li>
<input type="checkbox" name="<%= name %>" id="<%= id %>" <%= selected %> value="true" />
<label for="<%= id %>"><%= item.Text %></label>
<input type="hidden" name="<%= name %>" value="false" />
</li>
<% } %>
</ul>
<%= Html.ValidationMessageFor(model => model) %>
Two advantages to this approach:
You don't have to treat the list of items separate from the selection value. You can put attributes on the single property (e.g., AtLeastOneRequired is a custom attribute in our system)
you separate model and view (editor template). We have a horizontal and a vertical layout of checkboxes for example. You could also render "multiple selection" as two listboxes with back and forth buttons, multi-select list box, etc.
A:
when you have multiple items with the same name you will get their values separated with coma
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is meant by an HTML5 application?
Since HTML5 is still only a markup language, what is meant when people say "HTML5 application"? Please explain.
A:
An HTML5 application is an application that uses HTML5/Javascript/CSS3 as its primary means of achieving a User Interface.
The term is significant, largely because this is considered a platform-independent way to get an application onto as many different mobile devices as possible. Android and iOS are pretty much completely different, but both platforms will work with applications written in HTML5/Javascript/CSS3. All you need is an HTML5 compliant browser.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to properly parse numbers in an arithmetic expression, differentiating positive and negative ones?
I have an assignment in my Data Structures class in which I have to program a calculator that solves arithmetic expressions with the 4 basic operations and parenthesis, the input is done via the stdin buffer and the same with the output.
It was easy at the beginning, the teacher provided us the algorithms (how to transform the expression from the infix to the postfix and how to evaluate it) and the only goal was for us to implement our own stack and use it, but the calculator itself does not work quite well, and I think it is because of my parser.
This is the algorithm, and my code, used to parse the numbers, operators and parenthesis while putting them into an array to store the expression in a way that it is easier to evaluate later.
// saida is an array of pairs of integers, the first value of the pair is the value of the info (the number itself or the ASCII value of the operator)
// The second value is an indicator of whether it is a number or a operator
for (i = 0; i < exp_size; i++) {
c = expression[i];
// If the current char is a digit, store it into a helper string and keep going until a non-digit is found
// Then atoi() is used to transform this string into an int and then store it.
if (c >= '0' && c <= '9') {
j = 1, k = i+1;
tempInt[0] = c;
while(expression[k] >= '0' && expression[k] <= '9') {
tempInt[j++] = expression[k];
k++;
}
tempInt[j] = '\0';
saida[saidaIndex][0] = atoi(tempInt);
saida[saidaIndex++][1] = 0;
i = k-1;
}
// If the character is an operator, the algorithm is followed.
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while(pilha->size > 0 && isOpBigger( stack_top(pilha), c )) {
saida[saidaIndex][0] = stack_pop(pilha);
saida[saidaIndex++][1] = 1;
}
stack_push(c, pilha);
}
else if (c == '(') stack_push(c, pilha);
else if (c == ')') {
j = stack_pop(pilha);
while(j != '(') {
saida[saidaIndex][0] = j;
saida[saidaIndex++][1] = 1;
j = stack_pop(pilha);
}
}
}
The problem is, in this code I can't tell if a minus sign indicates a subtraction operator or a negative number (I know that a minus operator is a sum with a negative number, but it didn't helped me solving this problem), I thought of the following, none with success:
Every time there is a minus sign, store a plus sign instead and let the next number be itself * -1. Wouldn't work in case the next number is already a negative one or if the minus sign is before an expression with parenthesis like 1 + 2 - (3 * 4).
If there is a space after the minus sign, it is an operator, if not, it is a negative number. Wouldn't work because there are not those rules on the input.
I have no experience whatsoever in interpreters and I really don't know how to proceed. The code works perfectly with valid expressions without negative numbers, but not with weird ones like () + 3 - (), but that's another problem.
Thanks for any help.
A:
That is the problem called "unary minus" and can in your case (no variables) get solved by substitution.
The operator - is an unary minus if it is
preceded by a left parenthesis
preceded by another operator
the first character of the input
Now instead of storing a - you store a different character like, say m and assign it a higher precedence than the other operators (or the same as the exponentiation operator if you have one).
Another tip: don't use spaces to indicate anything, an arithmetic expression must work without any spaces or it is not correct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiprecision Arithmetic; The Carry Flag
Intel 8085: I'm having big troubles understanding addition or subtraction with more than 16-bit numbers in Intel 8085:
1.) If I execute ADC M instruction then this should happen: (A)<--(A)+((H)(L))+(CY) , right? How can be 16-bit data (HL) transfered to 8-bit register (A)?
A:
How can be 16-bit data (HL) transfered to 8-bit register (A)?
M is not the contents of the HL register. M is the 8-bit byte stored at the memory location pointed to by the HL register.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
read() and write() sending excess output to Vim
I'm using read() and write() syscalls to get input from stdin and print it back to stdout.
From inside Vim I exeute the command to run my program
:!./lowio
The buffer array then gets printed out, however the discarded chars that didn't get put into my array are sent to Vim. Vim then interperts the chars as a command.
#include <unistd.h>
#define BUFSIZE 3
int main()
{
char low[BUFSIZE + 1];
read(0, low, BUFSIZE);
low[BUFSIZE + 1] = '\0';
write(1, low, BUFSIZE);
return 0;
}
For example, typing
abcdG
Will print abc to stdin but will send dG to Vim which goes and deletes from my cursor to the end of the file.
What is going on here?
A:
Your stdin is your terminal (/dev/tty) and you typed abcdG<NL>. Your read(0,...,3) call requested only 3 characters (abc) from the terminal device driver's buffer. The remaining characters remained in the buffer. When you then returned control to vim, it proceeded to read from stdin and get the remaining, buffered characters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I specify which protocol to use (IPv4 or IPv6) when pinging a website (bash)?
I currently have a shell script which simply takes a URL as an argument and then sends a ping request to it as follows:
ping -c 5 $1
It is required of me to ping to the site using IPv4 and IPv6 where possible, I will then compare results. I have read the man page of ping and cannot see a flag which specifies which protocol to use, I was expecting it to accept a flag -4 for IPv4 and -6 for IPv6 but this does not seem to be the case.
I came across the DNS lookup utility dig which looks promising but have not managed to implement it in my code. My script must take a URL as an argument and no other arguments. I hope this is clear and thanks for your help.
A:
Use ping and ping6 that are available in most distributions.
/tmp $ dig google.com A google.com AAAA +short
172.217.4.174
2607:f8b0:4007:801::200e
/tmp $ ping -c 2 172.217.4.174
PING 172.217.4.174 (172.217.4.174): 56 data bytes
64 bytes from 172.217.4.174: icmp_seq=0 ttl=53 time=35.619 ms
64 bytes from 172.217.4.174: icmp_seq=1 ttl=53 time=34.220 ms
/tmp $ ping6 -c 2 2607:f8b0:4007:801::200e
PING6(56=40+8+8 bytes) 2602:306:b826:68a0:f40e:abca:efdb:71f --> 2607:f8b0:4007:801::200e
16 bytes from 2607:f8b0:4007:801::200e, icmp_seq=0 hlim=55 time=77.735 ms
16 bytes from 2607:f8b0:4007:801::200e, icmp_seq=1 hlim=55 time=81.518 ms
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Count Duplicate URLs, fastest method possible
I'm still working with this huge list of URLs, all the help I have received has been great.
At the moment I have the list looking like this (17000 URLs though):
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=3
I can filter out the duplicates no problem with a couple of methods, awk etc. What I am really looking to do it take out the duplicate URLs but at the same time taking a count of how many times the URL exists in the list and printing the count next to the URL with a pipe separator. After processing the list it should look like this:
url | count
http://www.domain.com/page?CONTENT_ITEM_ID=1 | 2
http://www.domain.com/page?CONTENT_ITEM_ID=2 | 2
http://www.domain.com/page?CONTENT_ITEM_ID=3 | 3
What method would be the fastest way to achieve this?
Cheers
A:
This is probably as fast as you can get without writing code.
$ cat foo.txt
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=3
$ sort foo.txt | uniq -c
2 http://www.domain.com/page?CONTENT_ITEM_ID=1
2 http://www.domain.com/page?CONTENT_ITEM_ID=2
3 http://www.domain.com/page?CONTENT_ITEM_ID=3
Did a bit of testing, and it's not particularly fast, although for 17k it'll take little more than 1 second (on a loaded P4 2.8Ghz machine)
$ wc -l foo.txt
174955 foo.txt
vinko@mithril:~/i3media/2008/product/Pending$ time sort foo.txt | uniq -c
54482 http://www.domain.com/page?CONTENT_ITEM_ID=1
48212 http://www.domain.com/page?CONTENT_ITEM_ID=2
72261 http://www.domain.com/page?CONTENT_ITEM_ID=3
real 0m23.534s
user 0m16.817s
sys 0m0.084s
$ wc -l foo.txt
14955 foo.txt
$ time sort foo.txt | uniq -c
4233 http://www.domain.com/page?CONTENT_ITEM_ID=1
4290 http://www.domain.com/page?CONTENT_ITEM_ID=2
6432 http://www.domain.com/page?CONTENT_ITEM_ID=3
real 0m1.349s
user 0m1.216s
sys 0m0.012s
Although O() wins the game hands down, as usual. Tested S.Lott's solution and
$ cat pythoncount.py
from collections import defaultdict
myFile = open( "foo.txt", "ru" )
fq= defaultdict( int )
for n in myFile:
fq[n] += 1
for n in fq.items():
print "%s|%s" % (n[0].strip(),n[1])
$ wc -l foo.txt
14955 foo.txt
$ time python pythoncount.py
http://www.domain.com/page?CONTENT_ITEM_ID=2|4290
http://www.domain.com/page?CONTENT_ITEM_ID=1|4233
http://www.domain.com/page?CONTENT_ITEM_ID=3|6432
real 0m0.072s
user 0m0.028s
sys 0m0.012s
$ wc -l foo.txt
1778955 foo.txt
$ time python pythoncount.py
http://www.domain.com/page?CONTENT_ITEM_ID=2|504762
http://www.domain.com/page?CONTENT_ITEM_ID=1|517557
http://www.domain.com/page?CONTENT_ITEM_ID=3|756636
real 0m2.718s
user 0m2.440s
sys 0m0.072s
A:
Are you're going to do this over and over again? If not, then "fastest" as in fastest to implement is probably
sort </file/of/urls | uniq --count | awk '{ print $2, " | ", $1}'
(not tested, I'm not near a UNIX command line)
A:
In perl
[disclaimer: not able to test this code at the moment]
while (<>) {
chomp;
$occurences{$_}++;
}
foreach $url (sort keys %occurences) {
printf "%s|%d\n", $url, $occurences{$url};
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dark matter mass and weak interactions
If dark matter forms halos around galaxies, it must have invariant mass. In the Standard Model, elementary particles acquire mass usually through the weak interactions with the Higgs field. Does this mean that dark matter must interact weakly? What are possible alternative mechanisms of dark matter particles to acquire invariant mass?
A:
First I'd like to correct a point of your question: Standard Model (SM) particles do not acquire mass through weak interaction with the Higgs field. You make the very common confusion between the Higgs field and the Higgs boson. But this is only tangential to your question and I won't elaborate on that.
So onto your question. In short, after which I will elaborate, we need the Higgs mechanism because the SM particles are subject to the electroweak interaction. Since as far as we know, dark matter particles may not interact with either SM particles or with dark matter particles (see this answer of mine for a highlight on the experimental evidences that dark matter behaves as a dust of non-interacting particles), there is actually no need of the Higgs mechanism and we could very well go for the simpler solution of just hardwiring the mass directly in the theory.
The simplest mechanism to give a mass to a particle is simply to hardwire that mass directly into the theory: technically we just add what is called a mass term to the Lagrangian. That works fine for Quantum Electrodynamics (QED) for example. As you surely know, QED is called a gauge theory, because it has an internal symmetry, called gauge symmetry, which is $U(1)$, since it consists in multiplying the electron field by a complex number of modulus 1, i.e. adding a phase to that field, while removing the derivative of that phase from the electromagnetic field. The essential point is that the electron mass term, which is conceptually like the electron field times its complex conjugate, is invariant under that gauge symmetry. So it's all fine and we can leave it at that. This explains why QED happily lived through the 50's and the 60's without any need of a Higgs mechanism. Note however that a mass term for the photon would not be gauge invariant, so QED only works with massless photon, and again, that's fine because it fits very well with experimental results.
Onto the electroweak theory. As you have surely heard, this is a gauge theory too, responding to the sweet name of $SU(2)_L\times U(1)_Y$ because we transform some components of the fields with $2\times 2$ unitary matrices and multiply others with a complex of modulus 1. The problem now is that a fermion mass term is not gauge invariant: this answer on this very site may be readable without too much formal background. This can't be right: we know electrons have a mass. Moreover, as for QED, any mass term for the new bosons $Z$ and $W$ is also forbidden. That can't be right either because experimental results require $Z$ and $W$ to have masses of the order of 100 GeV: we knew that before they were discovered, I mean. The solution of this conundrum is the Higgs mechanism: it kinds of save the day for the electroweak theory by giving masses to some of the fermions, to $Z$, to $W$ but not to the photon.
Now what happens with $SU(2)_L\times U(1)_Y$ could happen with other similarly twisted gauge theories, and if you assume one of those for your dark matter particles, then indeed a Higgs mechanism would be the simplest manner to get massive particles. But this is a very big "if" as you should be able to understand by now. First, there is no a priori reason to postulate such a mass-term-breaking gauge theory. If dark matter particles interact, this could be through theory like QED with a new dark electric charge. But they may actually not interact at all, and so far, experimental evidences lean in that direction actually.
This is the point at which I should then start talking about Supersymmetry (SUSY) as supersymmetry particles have been considered as some of the best candidates for dark matter for a long while, and then that would have me discuss about how supersymmetric particles get their mass, but that answer is already long enough. Feel free to ask another question about that as there are plenty of SUSY aficionados in these waters!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange "line" appears in GridView -- is it CSS or border or what?
I see a "strange line" in my gridview.
Here is the screen-shot of the "strange line" at the right-edge of the cyan-blue selected gridview row:
I have used F12-developer tool and there is no reference to this "line" as shown in the image, below.
What is also strange is when I change the browser VIEW/ZOOM to 300%, the "strange line" moves down to the last row visible in the screen-shot image. Further, changing the VIEW/ZOOM to 200%, the "strange line" is no longer visible.
I have searched my code for underscores (2, 3 and 4 adjacent underscores) -- no finds.
I have searched for "border", not finding anything odd with those declarations.
I have searched my CSS for "-top" and "-bottom", nothing odd with those declarations.
I am seeking anyone's advice or solution.
Thanks...John
A:
It probably has something to do with the active or hover css, and the last cell not being empty. Put the hidden input in another cell and see if that helps.
You could also do without the HiddenField by using DataKeyNames or even better, strongly typed GridView
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID">
Or strongly typed
<asp:GridView ID="GridView1" runat="server" ItemType="Namespace.Class1.Class2">
With the last one you have access to the originating class and have type safety everywhere. I recommend the last one
https://www.sitepoint.com/asp-net-4-5-strongly-typed-data-controls-model-binding/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB data directory transfer and upgrade
I just transferred my data directory (of Mongo 1.6.5) to a new server and installed Mongo 2.0 on it. I set the data directory path and did sudo server mongod restart.
It failed, and the log file output says this -
***** SERVER RESTARTED *****
Sun Oct 9 07:51:47 [initandlisten] MongoDB starting : pid=8224 port=27017 dbpath=/database/mongodb 64-bit host=domU-12-31-39-09-35-81
Sun Oct 9 07:51:47 [initandlisten] db version v2.0.0, pdfile version 4.5
Sun Oct 9 07:51:47 [initandlisten] git version: 695c67dff0ffc361b8568a13366f027caa406222
Sun Oct 9 07:51:47 [initandlisten] build info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41
Sun Oct 9 07:51:47 [initandlisten] options: { auth: "true", config: "/etc/mongod.conf", dbpath: "/database/mongodb", fork: "true", logappend: "true", logpath: "/var/log/mongo/mongod.log", nojournal: "true" }
Sun Oct 9 07:51:47 [initandlisten] couldn't open /database/mongodb/local.ns errno:1 Operation not permitted
Sun Oct 9 07:51:47 [initandlisten] error couldn't open file /database/mongodb/local.ns terminating
Sun Oct 9 07:51:47 dbexit:
Sun Oct 9 07:51:47 [initandlisten] shutdown: going to close listening sockets...
Sun Oct 9 07:51:47 [initandlisten] shutdown: going to flush diaglog...
Sun Oct 9 07:51:47 [initandlisten] shutdown: going to close sockets...
Sun Oct 9 07:51:47 [initandlisten] shutdown: waiting for fs preallocator...
Sun Oct 9 07:51:47 [initandlisten] shutdown: closing all files...
Sun Oct 9 07:51:47 [initandlisten] closeAllFiles() finished
Sun Oct 9 07:51:47 [initandlisten] shutdown: removing fs lock...
Sun Oct 9 07:51:47 dbexit: really exiting now
I have already run it with --upgrade once.
A:
I had to change the owner of the file to mongod and it worked.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Merge Two uiimageview into single a single uiimageview in iOS
I found given below code for Merge two image if any one has another code merge this two image into a single image.
When i Merge two uiimageview into a single uiimageview then the Final image getting black or white shade.. Actual Color of masking image not coming in final image
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.navigationController.navigationBarHidden = YES;
imgBack = [UIImage imageNamed:@"img1.jpg"];
imgMask = [UIImage imageNamed:@"img2.png"];
imgBackground.image = imgBack;
imgMasking.image = imgMask;
imgFinally = [self maskImage:imgBack withMask:imgMask];
imgFinal.image = imgFinally;
imgBackground.image= nil;
imgMasking.image = nil;
}
- (UIImage *) maskImage:(UIImage *)image
withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
A:
Put your All the Images in One View and call this method, it merges all the images and give new image
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
js заболкировать прокуртку (onmousewheel event passive) без warning в консоли
Если написать такой код:
document.querySelector('select[name=month]').onmousewheel = function (e) {
e.preventDefault();
};
То в консоль получаю такую ошибку:
Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive. See https://www.chromestatus.com/feature/5745543795965952
Намекая на то чтоб я делал "пасивную" не блокирующую оброботку события, чтоб увеличить скорость прокрутки. Чтоб я делал типа так:
document.querySelector('select[name=month]').addEventListener('mousewheel', onmousewheel, {passive: true});
Но дело в том что мне как раз таки нужно блочить прокрутку. И я не хочу в консоль ворнинги. Пример такого случая (код можно запустить, нужно крутить колесиком на select-е):
document.querySelector('select[name=month]').onmousewheel =
document.querySelector('select[name=year]').onmousewheel = function (e) {
e.preventDefault();
const options = this.options;
const newSelectIndex = options.selectedIndex
+ ((e.deltaY < 0) ? -1 : 1);
if (options[newSelectIndex]) {
options.selectedIndex = newSelectIndex;
}
};
<form style="text-align:center">
<select name="month">
<option value="1"> January</option>
<option value="2"> February</option>
<option value="3"> March</option>
<option value="4">April</option>
<option value="5"> May</option>
<option selected="selected" value="6"> June</option>
<option value="7"> July</option>
<option value="8"> August</option>
<option value="9"> September</option>
<option value="10"> October</option>
<option value="11"> November</option>
<option value="12"> December</option>
</select>
<select name="year">
<option value="2019">2019</option>
<option selected="selected" value="2018">2018</option>
<option value="2017">2017</option>
</select>
</form>
Подскажите как блочить прокрутку без ворнингов. Большое спасибо!
A:
Ребята, извините, это на столько тупо))
Методом тыка выяснилось что нужно выставить просто {passive: false} тогда отдично работает e.preventDefault(); и не ругается
document.querySelector('select[name=month]')
.addEventListener('mousewheel', onmousewheel, {passive: false});
Всем большое спасибо!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why did lego stop the Ninjago Spinjitzu Flyer and switch to the Ninjago Spinjitzu Spinner?
A while ago Lego ran a Ninjago Flyer line of products:
Now there seems to be a 'dumbed down' version of this that doesn't fly, it just spins along the ground.
It seems like maybe there was an Health and Safety issue with the flying ones, or maybe kids were getting them lost on the roof or in the next door neighbor's yards or something. But surely that's part of what makes them so fun!
My question is: Why did Lego stop the Ninjago Spinjitzu Flyer and switch to the Ninjago Spinjitzu Spinner?
A:
The flyers were released in 2015, 2 years is an average production run for LEGO sets. Note that spinners have been released before, in 2011 and 2012 with expansion packs like cards and weapons.
I think the most likely reason that the flyers were discontinued is that LEGO did not see enough marketing potential in a second wave.
As to being more "fun", that is entirely subjective. These flying plastic rings were around in my childhood as well and I hated them.
To me they seem now old fashioned compared to the myriads of flying drone toys that are available today.
Update: Apparently, it was a bit premature to state that the flyers line of ninjago had ended: https://brickset.com/sets/theme-Ninjago/subtheme-Dragon-Masters
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to control font size with changing output resolution
Often I am in a position when I have to adjust the size of the output image. Unfortunately, it means that usually I have to adjust font size, to make things readable.
For example, if the following plot
library(ggplot2)
library(tibble)
library(stringi)
set.seed(1)
df <- tibble(
x = stri_rand_strings(10, 20),
y = runif(10) * 10,
label = stri_rand_strings(10, 10)
)
p <- ggplot(df, aes(x, y)) +
geom_text(aes(label = label)) +
scale_x_discrete(position = "top") +
theme(axis.text.x = element_text(angle = 90, hjust = 0))
is saved to 12'' x 6'' image things look pretty good:
p + ggsave("test_small.png", width = 12, height = 6, unit = "in")
12'' x 6'' output
however if I increase dimensions to 36'' x 18'' the fonts are unreadble:
p + ggsave("test_large.png", width = 36, height = 18, unit = "in")
36'' x 18''
Is there any general strategy which allows us to change output resolution without constant tinkering with the font sizes?
A:
You need to define the size of your text items as well as the plotting environment.
Since you want to dynamically scale it will likely be easiest to scale your fonts and save sizes to the same values. See ggplot2 - The unit of size for the divide by 2.834646 value to correct for font sizes.
base = 6 # set the height of your figure (and font)
expand = 2 # font size increase (arbitrarily set at 2 for the moment)
ggplot(df, aes(x, y)) +
geom_text(aes(label = label), size = base * expand / 2.834646) +
scale_x_discrete(position = "top") +
theme(axis.text.x = element_text(angle = 90, hjust = 0, size = base * expand ),
axis.text.y = element_text(size = base * expand ))
ggsave("test_large.png", width = base * 2, height = base, unit = "in", dpi = 300)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pull request conflict when making a change by code instead of manually
OS X workstation
Linux build machine
GitHub Enterprise
In a Jenkins pipeline, the following works:
Manually change the version number in package.json
Commit and push
Create a pull request from feature branch to develop branch
Jenkins checkouts, run tests, npm publishes to a dev scope, and merges
Create a pull request from develop branch to master branch
Jenkins checkouts, run tests, and npm publishes to a prod scope
If I replace the manual version manipulation to be part of the pipeline by using npm version patch, and commit this version change back to the develop branch...
... then once creating the pull request from the develop branch to the master branch, the pull request cannot be created due to a conflict. The conflict appears in the version line in package.json that was changed via the npm version patch command.
I am pretty sure it is related to line endings. I do not know how to approach this problem.
Should we change a package's version number manually before deciding to publish, or increment it automatically? Obviously right now the latter will fail due to the above...
A solution would be to somehow preserve the line ending of "version": "0.0.8", exactly as it were before changing it from .7 to .8...
A:
Adding a .gitattributes file with the following has seemingly solved it.
*.json text eol=lf
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to do one-liner if else statement?
Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example:
$var = ( $a > $b )? $a: $b;
Currently I have to use the following:
var c int
if a > b {
c = a
} else {
c = b
}
Sorry I cannot remember the name if this control statement and I couldn't find the info in-site or through google search. :/
A:
As the comments mentioned, Go doesn't support ternary one liners. The shortest form I can think of is this:
var c int
if c = b; a > b {
c = a
}
But please don't do that, it's not worth it and will only confuse people who read your code.
A:
I often use the following:
c := b
if a > b {
c = a
}
basically the same as @Not_a_Golfer's but using type inference.
A:
As the others mentioned, Go does not support ternary one-liners. However, I wrote a utility function that could help you achieve what you want.
// IfThenElse evaluates a condition, if true returns the first parameter otherwise the second
func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
if condition {
return a
}
return b
}
Here are some test cases to show how you can use it
func TestIfThenElse(t *testing.T) {
assert.Equal(t, IfThenElse(1 == 1, "Yes", false), "Yes")
assert.Equal(t, IfThenElse(1 != 1, nil, 1), 1)
assert.Equal(t, IfThenElse(1 < 2, nil, "No"), nil)
}
For fun, I wrote more useful utility functions such as:
IfThen(1 == 1, "Yes") // "Yes"
IfThen(1 != 1, "Woo") // nil
IfThen(1 < 2, "Less") // "Less"
IfThenElse(1 == 1, "Yes", false) // "Yes"
IfThenElse(1 != 1, nil, 1) // 1
IfThenElse(1 < 2, nil, "No") // nil
DefaultIfNil(nil, nil) // nil
DefaultIfNil(nil, "") // ""
DefaultIfNil("A", "B") // "A"
DefaultIfNil(true, "B") // true
DefaultIfNil(1, false) // 1
FirstNonNil(nil, nil) // nil
FirstNonNil(nil, "") // ""
FirstNonNil("A", "B") // "A"
FirstNonNil(true, "B") // true
FirstNonNil(1, false) // 1
FirstNonNil(nil, nil, nil, 10) // 10
FirstNonNil(nil, nil, nil, nil, nil) // nil
FirstNonNil() // nil
If you would like to use any of these, you can find them here https://github.com/shomali11/util
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get HP LaserJet 2100 PCL6 printer working with Win7 x64?
I have a Debian server with cups installed to serve up my HP LaserJet 2100 PCL6 to all machines connected to the network. I can print test pages from cups, but cannot seem to find the correct driver for Win7 x64. I have been to HP site and downloaded their recommended drivers, and choose them (via "Have Disk") when adding the printer but when I print a test page it prints a page saying "protocol not supported". Any idea?
A:
Found it. Have to use the HP LaserJet 2200 Series PCL 5 driver included with win 7. The 2100 series drivers provided by HP did not work for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ionic 4 android app not connecting to local node js server when running on real android device
I am trying to implement a client-server communication for my Ionic 4 android app. I have a local node js server implementation on my pc and I am using socket.io to establish the communication. The problem is that when I am running the app on browser or on emulator the communication between the app and local server is ok but when I am trying to run the app on a real android device (samsung galaxy s9+) the app cannot connect to the local server. More specific the message 'User Connected' is not appeared on the server console to indicate that app is connected to the server and therefore user never gets back his userid.
Can anyone help me to find out why?
Server side
index.js
let app = require('express')();
let server = require('http').createServer(app);
let io = require('socket.io')(server);
// Allow CORS support and remote requests to the service
app.use(function(req, res, next)
{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
next();
});
// Set up route
app.get('/', (req, res) =>
{
res.json({ message: 'You connected to panic Shield server' });
});
var port = process.env.PORT || 8080;
server.listen(port, function(){
console.log('listening in http://192.168.x.x:' + port);
});
const uuidv4 = require("uuid/v4");
// User connected to the server
io.on('connection', (socket) => {
console.log('User Connected');
socket.on('disconnect', function(){});
socket.on('set-credentials', (credentials) => {
let userId = uuidv4();
...
// server informs user for his unique id
socket.emit('your user id', userId);
...
}
});
Client side
app.module.ts
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://192.168.x.x:8080', options: { secure: true } };
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule,
SocketIoModule.forRoot(config)
],
...
home.page.ts
import { Socket } from 'ngx-socket-io';
constructor(private socket: Socket) { }
async ngOnInit() {
this.socket.connect();
...
}
async connectToServer(name, surname, gender, speech) {
const str = name.concat(' // ').concat(surname).concat(' // ').concat(gender).concat(' // ').concat(speech);
this.socket.emit('set-credentials', str);
this.socket.on('your user id', (data) => {
this.userId = data.toString();
// save the userId
set('userId', this.userId);
// Refresh the page
window.location.reload();
});
}
A:
I found the problem. In my case, the firewall of my pc doesn't allow any other device on local network connect to the server. When I turned off the firewall the connection between client-server was established!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Count(Distinct x) and Group By y
I have entries with date and time. I want the results to be grouped by the hour (00, 01, 02) and that works, but when i want to get the distinct counts of users, there is an error.
Select Substr(time, 0, 2) as Hour,
Count(date) as Hits,
Count(Distinct ip) as Users,
Count(Distinct X-Forwarded-For) as ForwardedUsers
From table
Group By Hour
EDIT:
I am using the LogParser from Microsoft and i am able to use Group By Hour as it is and X-Forwarded-For is also no problem.
The question is how i can use Count(Distinct ip) within the group by
A:
Unfortunately LogParser does not support DISTINCT aggregate functions together with GROUP BY. This should have been clear from the error message you get with the query above:
Error: Semantic Error: aggregate functions with DISTINCT arguments are
not supported with GROUP BY clauses
One trick you could do is to remove the GROUP BY clause altogether and calculate instead COUNT DISTINCT(hourlyIp) where hourlyIp is a string built concatenating the hour with the IP address. You'll have then to breakup the hourlyIp field back into its components when you process the results.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Software for converting mp4 files from 720p to 480p
I have some videos I want to convert into 480p since my netbook can't handle 720p videos and higher. Do you guys know any free software that can do so? Thanks!
A:
the best software for your usage willl be Handbrake. It is a very advanced software with lots of options for you to choose.
As shown in image you can set any value of width or height of video, in your case height=480p
Installation
download deb from here. (easy way to go, but you wont get updates)
or go by PPA ( for Ubuntu 14.10 and previous versions; no ppa available for ubuntu 15.04) from here ( you need to select the Ubuntu version to get ppa). After this, run either of these:
for GUI software:
apt-get install handbrake-gtk
for command line tool:
apt-get install handbrake-cli
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mostrar formato Hora con JS
Tengo la siguiente funcion:
$_parseData_time (data) {
var d = new Date()
var time = ( /(\d+)(?::(\d\d))?\s*(p?)/ )
d.setHours( parseInt( time[3] ? 12 : 0) )
d.setMinutes( parseInt( time[2]) || 0 )
return d
}
Estoy intentando que me devuelva la hora formateada en un componente de Vue que pueden ver en la pregunta anterior
Error en computed properties Vue
pero me trae tambien lo siguiente:
Fri May 10 2019 00:00:21 GMT-0300 (Argentina Standard Time)
como deberia corregirla para obtener solo el horario?
A:
Hay una mezcla interesante entre VueJs y MomentJS
new Vue({
el: '#app',
data: {
items: [
new Date(2018, 11, 24, 10, 3, 31, 0),
new Date(2017, 10, 23, 11, 13, 2, 0),
new Date(2016, 9, 22, 12, 34, 40, 0),
]
},
methods: {
moment: function (date) {
return moment(date);
},
date: function (date) {
return moment(date).format('hh:mm:ss');
}
},
filters: {
moment: function (date) {
return moment(date).format('hh:mm:ss');
}
}
})
.method {
color: grey;
}
.filter {
color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="item in items">
<p>{{ moment(item).format('hh:mm:ss') }}</p>
<p class="method">{{ date(item) }}</p>
<p class="filter">{{ item | moment }}</p>
</li>
</ul>
</div>
En este ejemplo, tienes 2 métodos y un filtro para formatear los datos en horas minutos segundos.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What counts as a "Neighbor" in Conways' game of life?
I have looked everywhere but I cannot find an answer for this.
Since I am bored, I am trying to create this game, but I can't seem to figure out what is considered a "Neighbor". Is it only directly above/below/right/left? or is it above, above and to the right, right, below and to the right, etc.?
A:
Conway's Game of Life uses the 8-cell Moore neighborhood, which includes the diagonal neighbors. Not all CAs use this; others use the 4-cell Von Neumann neighborhood, which excludes diagonal neighbors.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change Seaborn Data Labels to show two decimal places
How do I code data labels in a seaborn barplot (or any plot for that matter) to show two decimal places?
I learned how to show data labels from this post:
Add data labels to Seaborn factor plot
But I can't get the labels to show digits.
See example code below:
#make the simple dataframe
married = ['M', "NO DATA", 'S']
percentage = [68.7564554, 9.35558, 21.8879646]
df = pd.DataFrame(married, percentage)
df.reset_index(level=0, inplace=True)
df.columns = ['percentage', 'married']
#make the bar plot
sns.barplot(x = 'married', y = 'percentage', data = df)
plt.title('title')
plt.xlabel('married')
plt.ylabel('Percentage')
#place the labels
ax = plt.gca()
y_max = df['percentage'].value_counts().max()
ax.set_ylim(1)
for p in ax.patches:
ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' %
int(p.get_height()),
fontsize=12, color='red', ha='center', va='bottom')
Thank you for any help you can provide
A:
Use, string formatting with https://docs.python.org/3.4/library/string.html#format-specification-mini-language:
married = ['M', "NO DATA", 'S']
percentage = [68.7564554, 9.35558, 21.8879646]
df = pd.DataFrame(married, percentage)
df.reset_index(level=0, inplace=True)
df.columns = ['percentage', 'married']
#make the bar plot
sns.barplot(x = 'married', y = 'percentage', data = df)
plt.title('title')
plt.xlabel('married')
plt.ylabel('Percentage')
#place the labels
ax = plt.gca()
y_max = df['percentage'].value_counts().max()
ax.set_ylim(1)
for p in ax.patches:
ax.text(p.get_x() + p.get_width()/2., p.get_height(), '{0:.2f}'.format(p.get_height()),
fontsize=12, color='red', ha='center', va='bottom')
Output:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the difference between Visitors and Viewers in SharePoint 2013
I was reading about the Determine permission levels and groups in SharePoint 2013 and there I saw two words :- Visitors & Viewers. SO what's the difference between them?
A:
By looking to the term it seems like both the permissions are same but when we talk in terms of programming then there is allot difference between these two permission level.
Visitors: This user has the permission to only read(not modify) the content of SharePoint, it means if you are trying to fetch the contents from SharePoint in your program using any object model then it will allow you to read the contents.
While
Viewer: This user has the permission to only view(Not modify/Download) the content of SharePoint, it means if you are trying to fetch the contents from SharePoint in your program using any object model then it will give you access denied error and you cannot read the SharePoint contents in your program.
This is just basic difference I am telling just to clear your confusion.
Let me know if you want to go more in depth.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the difference between greedy and heuristic algorithm?
What's the difference between greedy and heuristic algorithm?
I have read some articles about the argument and it seems to me that they are more or less the same type of algorithm since their main characteristic is to choose the best (local) option at each iteration to solve a problem.
A:
The way that Heuristics have been described to me is that they are "rules of thumb". Their ability to produce a globally optimal solution may not be directly provable but typically, they do a good job. They're often used when the cost of determining an optimal solution is too high. Furthermore, Heuristics often encode a degree of experience on how the problem was solved in the past. A better way to describe a Heuristic is a "Solving Strategy".
A Greedy algorithm is one that makes choices based on what looks best at the moment. In other words, choices are locally optimum but not necessarily globally optimum (it might be if lucky but you can't prove it). Furthermore, a Greedy algorithm doesn't typically refine its solution based on new information. This is but one solving strategy (a.k.a a heuristic).
To provide an example of how a greedy algorithm might work, if you were to use one to help you plan a route to drive from one side of the country to the other in the shortest distance, it would likely choose the short slow roads. It wouldn't necessarily understand that a motorway, although longer and perhaps more direct, would be the better option.
An alternative strategy (heuristic) might seek to cover as much of the journey using motorways (because for most destinations, they tend to be more direct), and then resort to use normal roads to transition between. In some circumstances, it would probably perform quite lousy but in most, it would do quite well, and to be honest, it's probably a similar heuristic we all use when commuting (if not using a satnav).
Wrapping up...
Are all Heuristics, Greedy Algorithms - No
Are all Greedy Algorithms, Heuristics - In general, yes.
To help provide some background, one of the first problems I was taught in my algorithms class at university was the Traveling Salesman Problem. It belongs to the NP-complete class of problems meaning that there exists no efficient means of solving. That is to say as the size of the problem grows, the time taken to find a solution grows substantially. There exists a number of proveable algorithms but their performance isn't great and in real world applications, we tend to favour heuristics (which include Greedy Algorithms - see link).
A:
their main characteristic is to choose the best (local) option at each iteration
Not at all true for heuristics. Heuristic algorithms are making choices that are know to be suboptimal in theory, but have been proved in practice to produce reasonable results. Heuristics usually find an approximate solution:
In computer science, artificial intelligence, and mathematical optimization, a heuristic is a technique designed for solving a problem more quickly when classic methods are too slow, or for finding an approximate solution when classic methods fail to find any exact solution. This is achieved by trading optimality, completeness, accuracy, or precision for speed.
Greedy is an example of heuristic (make the best local choice and hope for the optimal global result), but that does not mean heuristics are greedy. There are many heuristics completely unrelated to greedy, eg. genetic algorithms are considered heuristic:
In the computer science field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the process of natural selection.
A:
Greedy is said when you aggregate elements one by one to the solution (following some choice strategy) and never backtrack. Example: straight selection sort can be considered a greedy procedure.
Heuristic is a generic term that denotes any ad-hoc/intuitive rule used with the hope of improving the behavior of an algorithm, but without guarantee. Example: the median-of-three rule used to choose the pivot in Quicksort.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to import primary secret key from backup into GnuPG?
I've seen "Re-import secret primary key in GnuPG" which is pretty much the issue I'm seeing, but I haven't had any luck with GnuPG 1.4.20 (from GPGTools) or GnuPG 2.1.
Even if I delete my entire ~/.gnupg and try the import again, I can't seem to get the primary key secret to import. I'm assuming no keys are being merged when starting from scratch, so I don't understand why this wouldn't work even on GnuPG 1.4.
My backup file does contain the private key:
➜ ~ gpg --list-packets master-secret-key.gpg
:secret key packet:
version 4, algo 1, created 1459961571, expires 0
skey[0]: [4096 bits]
skey[1]: [17 bits]
gnu-dummy S2K, algo: 3, SHA1 protection, hash: 2
protect IV:
keyid: DBDE1E0253A3B420
...
Starting from scratch with an empty ~/.gnupg:
➜ ~ gpg --allow-secret-key-import --import master-secret-key.gpg public-key.asc
gpg: key 53A3B420: secret key imported
gpg: key 53A3B420: public key "Rodrigo López Dato <[email protected]>" imported
gpg: key 7C4C5564: public key "Rodrigo López Dato <[email protected]>" imported
gpg: Total number processed: 2
gpg: imported: 2 (RSA: 2)
gpg: secret keys read: 1
gpg: secret keys imported: 1
➜ ~ gpg -K
/Users/rolodato/.gnupg/secring.gpg
----------------------------------
sec# 4096R/53A3B420 2016-04-06
uid Rodrigo López Dato <[email protected]>
uid Rodrigo López Dato <[email protected]>
ssb 2048R/00E7B480 2016-04-06
ssb 2048R/7D9F38D2 2016-04-06
sec# means the private master key wasn't imported, why is that?
FWIW, I need the master key to generate a revocation certificate and to eventually renew my subkeys once they expire. If there's a way to do this from the backup directly without needing to import it, that would work too.
A:
The file you're trying to import does not contain the actual private key, as indicated by this line in the output of gpg --list-packets:
gnu-dummy S2K, algo: 3, SHA1 protection, hash: 2
The special "dummy" S2K algorithm is applied when GnuPG actually exported a secret key stub to still enable using secret subkeys, but having an offline primary key (on another computer, a disconnected thumb drive, an OpenPGP smartcard, ...). This key stub is also what you observe in the --list-secret-keys/-K output:
sec# 4096R/53A3B420 2016-04-06
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is this a bug of TThread under android?
on windows, we can call several time MyThread.waitfor on the same thread. if the thread is already terminated no problem this will not raise any exception and return immediatly (normal behavior).
on Android, it's different, if we call twice MyThread.waitfor then we will have an exception on the second try with "No such process".
function TThread.WaitFor: LongWord;
{$ELSEIF Defined(POSIX)}
var
X: Pointer;
ID: pthread_t;
begin
if FExternalThread then
raise EThread.CreateRes(@SThreadExternalWait);
ID := pthread_t(FThreadID);
if CurrentThread.ThreadID = MainThreadID then
while not FFinished do
CheckSynchronize(1000);
FThreadID := 0;
X := @Result;
CheckThreadError(pthread_join(ID, X));
end;
{$ENDIF POSIX}
the error is made because on call to waitfor they set FThreadID := 0 so off course any further call will failled
i think it's must be written like :
function TThread.WaitFor: LongWord;
{$ELSEIF Defined(POSIX)}
begin
if FThreadID = 0 then exit;
...
end;
{$ENDIF POSIX}
what do you think ? did i need to open a bug request at emb ?
A:
The documentation for pthread_join says:
Joining with a thread that has previously been joined results in undefined behavior.
This explains why TThread takes steps to avoid invoking undefined behavior.
Is there defect in the design? That's debatable. If we are going to consider the design of this class, let's broaden the discussion, as the designers must. A Windows thread can be waited on by multiple different threads. That's not the case for pthreads. The linked documentation also says:
If multiple threads simultaneously try to join with the same thread, the results are undefined.
So I don't think Embarcadero could reasonably implement the same behaviour on Posix platforms as already exists on Windows. For sure they could special case repeated waits from the same thread, as you describe. Well, they'd have to persist the thread return value so that WaitFor could return it. But that would only get you part way there, and wouldn't be very useful anyway. After all, why would you wait again from the same thread?
I suspect that FThreadID is set to 0 in an effort to avoid the undefined behaviour and fail in a more robust way. However, if multiple threads call WaitFor then there is a data race so undefined behaviour is still possible.
If we were trying to be charitable then we could
Leaving those specific details to one side, it is clear that if WaitFor is implemented by calling pthread_join then differing behaviour across platforms is inevitable. Embarcadero have tried to align the TThread implementations for each platform, but they cannot be perfectly equivalent because the platform functionality differs. Windows offers a richer set of threading primitives than pthreads.
If Embarcadero had chosen a different path they could have aligned the platforms perfectly but would have needed to work much harder on Posix. It is possible to replicate the Windows behaviour there, but this particular method would have to be implemented with something other than pthread_join.
Facing the reality though, I think you will have to adapt to the different functionality of pthreads. In pthreads the ability to wait on a thread is included merely as a convenience. You would do better to wait on an event or a condition variable instead, if you really do want to support repeated waits. On the other hand you might just re-create your code to ensure you only wait once.
So, to summarise, you should probably raise an issue with Embarcadero, if there isn't one already. It is possible that they might consider supporting your scenario. And it's worth having an issue in the system. But don't be surprised if they choose to do nothing and justify that because of the wider platform differences that cannot be surmounted, and the extra complexity needed in the class to support your somewhat pointless use case. One thing I expect we can all agree on though is that the Delphi documentation for TThread.WaitFor should cover these issues.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Trying to overlay videos with different start times
I'm trying to overlay two videos with different start times, and mix together their audio tracks.
These input files are WebRTC recordings, and each contains a single audio or video track.
Inputs:
RTc0.webm: audio, Opus 40k, start time 9.078 sec
RT5f.webm: audio, Opus 40k, start time 1.262 sec
RT8c.mkv: video, H.264, start time 9.078 sec
RTf7.mkv: video, H.264, start time 1.298 sec
I want to draw these videos side-by-side and mix together their audio.
First try, using -copyts
My initial thought was to use -copyts and just allow everything to align using their shared common timecode.
My command line looks like:
ffmpeg \
-copyts \
-ss 224.1 -i RTc0.webm -t 60 \
-ss 224.1 -i RT5f.webm -t 60 \
-ss 224.1 -i RTf7.mkv -t 60 \
-ss 224.1 -i RT8c.mkv -t 60 \
-filter_complex "
color=c=black:s=1280x480 [background];
[2:v] scale=640x480 [left];
[3:v] scale=640x480 [right];
[background][left] overlay [background+left];
[background+left][right] overlay=x=640 [vout];
[1:a][0:a] amix [aout]
" -c:v libx264 -preset veryfast -crf 28 -c:a aac -map "[vout]" -map "[aout]" -y \
-f matroska combined.mkv
Running this, I get an output where the video is correct (one video starts at 0 sec, one starts 7 seconds later), but both audio tracks start at 0 sec. The expected behavior is one audio track starts at 0 secs and the other starts 7 seconds later synchronized with the second video track.
Second try, using -itsoffset and asetpts
I also tried using -itsoffset to shift the video tracks. This worked but -itsoffset didn't do anything for my audio tracks. It had strange effects, sometimes putting it for one shifted them both in time.
ffmpeg \
-ss 0.00000000 -itsoffset 0 -i RTf7.mkv -t 60 \
-ss 0.00000000 -itsoffset 7.781 -i RT8c.mkv -t 60 \
-ss 0.00000000 -itsoffset 7.816 -i RT5f.webm -t 60 \
-ss 0.00000000 -itsoffset 0 -i RTc0.webm -t 60 \
-filter_complex "
color=c=black:s=1280x480 [background];
[0:v] scale=640x480 [left];
[1:v] scale=640x480 [right];
[background][left] overlay=shortest=1 [background+left];
[background+left][right] overlay=shortest=1:x=640 [vout];
[2:a][3:a] amix=inputs=2:duration=longest [aout]
" -c:v libx264 -preset veryfast -crf 28 -c:a aac -map "[vout]" -map "[aout]" -y \
-f matroska combined.mkv
I then tried using the asetpts filter to shift the audio track to preserve alignment, but it didn't work. The command asetpts=PTS+(7.816/TB) was just ignored:
ffmpeg \
-copyts \
-ss 0 -i RTc0.webm -t 60 \
-ss 0 -i RT5f.webm -t 60 \
-ss 0 -itsoffset 0 -i RTf7.mkv -t 60 \
-ss 0 -itsoffset 7.781 -i RT8c.mkv -t 60 \
-filter_complex "
color=c=black:s=1280x480 [background];
[2:v] scale=640x480 [left];
[3:v] scale=640x480 [right];
[background][left] overlay [background+left];
[background+left][right] overlay=x=640 [vout];
[1:a] asetpts=PTS+(7.816/TB), [0:a] amix [aout]
" -c:v libx264 -preset veryfast -crf 28 -c:a aac -map "[vout]" -map "[aout]" -y \
-f matroska segment_0.mkv
What am I doing wrong?
A:
The amix filter syncs all inputs to start at the same time. Way around is to skip the -ss for the audio inputs, apply aresample=async=1,atrim=225.398 to each audio input and then amix those filtered streams.
225.398 is 224.1+1.298 - your ss value + start time of the earlier starting video stream. I've used the video stream value since the corresponding audio starts earlier, so you may lose sync if you used its value.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dropzone.js proccess file after upload and monitor progress
Title says it all, I need to monitor data processing progress. For example I doing some chunked inserts to MySQL and echo'ing progress after every chunk, how to print progress in front-end? I'm using Dropzone.js and my current JS code is (simplify version):
Dropzone.options.importdropzone = {
init: function() {
// I need something like
this.on("backendProccessing",function(response){
return response
})
this.on("success", function(file, response) {
// Success only return after backend finish process
})
}
};
Also tried (doesn't work, nothing returned, only success):
this.on('xhr',function(){
// get the native XmlHttpRequest object
var xhr = $.ajaxSettings.xhr() ;
// set the onprogress event handler
xhr.onprogress = function(evt){ console.log('Doing') } ;
// set the onload event handler
xhr.onload = function(){ console.log('DONE!') } ;
// return the customized object
return xhr ;
});
So I need something like this:
this.on("backendProccessing",function(response){
return response
})
A:
Well it's seams that not realy possible, i need to change backend a little bit.
So I created another method in backend wich monitors current progress, progress is set bu session so I need 2 AJAX cals, 1 for upload ant start proccessing file and another to check status.
For excample proccessing URL is http://example.com/import
For status check http://example.com/import/status
I can check status till it return specific value, like
{
"status":"done"
}
I calling check status funcion every 1 second in
this.on('sending',function() {
// calling another ajax here every x sec.
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I get a solution from this Java Program to solve algorithm?
for(int=0; i<1,000,000; i++)
{
if(data[i]< 0)
data[i]= data[i] * 2;
}
Hello Everyone,
I would like to know is it possible to calculate the absolute speed of this algorithm below if the time it takes to execute a memory access is 100 nanoseconds and that all other operations (arithmetic, register accesses, etc.) take 10 nanoseconds? I am pretty sure this problem can be used to calculate the absolute speed. I know that we do have one of variables already which is Ta= 100 nanoseconds, right? The rest of the missing variables could be found through the lines of code I have provided after I compile this in Java program? I compiled and ran it, but it doesn't tell what I need to solve this problem. Any suggestions?
Here is the formula that I am using to calculate the absolute speed of this algorithm:
T=Tna X Nna + Ta X Na;
Tna= the time to execute a memory nonaccess instruction;
Nna= the number of memory nonaccess machine language instructions executed;
Ta= the time to execute a memory access instruction;
Na= the number of memory access machine language instructions executed;
Here is the code that I will compile and run to see if it will give some of the missing variables I need to solve this problem.
A:
@dorakta if your concern on classification of operations in the the code block. Following might be a starting point.
Line 1: for(int=0; i<1,000,000; i++)
i variable in for loop, needs memory access and rest operations.
This executs 1,000,000 times
You have:
1000000 times of
2 - memory access (1 read and 1 assign)
1 - compare
1 - incr (depends. It could be -> 1 read and 1 add)
Line 3: if(data[i]< 0)
data[i] in if statement is a memory reference and a compare operation.
This executs 1,000,000 times
You have:
1000000 times of
2 - memory access
1 - compare
Line 4: data[i]= data[i] * 2
You have: 0 to 1000000 times depending on value of the data.
You may want to calculate the worst case.
Hence, 1000000 times.
2 - memory access (1 read and 1 assign)
1 multiply
Hope it helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring AOP + AspectJ maven plugin - Internal method call doesn't work
Java + Spring + Maven application.
Unable to make Internal call from annotation based public method.
Prerequisite
Java-Version: 1.7.
Project: AspectProject > Post build it will create jar file.
Client: AspectClient : which has dependency of "AspectProject".
AspectProject
pom.xml
<properties>
<java.version>1.7</java.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.1.2.RELEASE</springframework.version>
<org.aspectj-version>1.7.0</org.aspectj-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- AspectJ dependencies -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<!-- compile for Java 1.7 -->
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.4</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
<configuration>
<complianceLevel>${maven.compiler.source}</complianceLevel>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
AspectProvider
@Aspect
public class AspectProvider {
/**
* This is the point cut for all get Method with @TestAnnotation annotation
*/
@Pointcut("execution(* get*()) && @annotation(aTestAnnotation)")
public void getMethodPointcut(TestAnnotation aTestAnnotation) {}
@Around("getMethodPointcut(aTestAnnotation)")
public Object getConfiguration(ProceedingJoinPoint iJoinPoint, TestAnnotation aTestAnnotation) throws Throwable {
return getValueFromISTCompositeConfiguration(iJoinPoint, aTestAnnotation);
}
private Object getValueFromISTCompositeConfiguration(final ProceedingJoinPoint iProceedingJoinPoint, TestAnnotation aTestAnnotation) throws Throwable {
Object aReturnValue = null;
if (aTestAnnotation.value() != null) {
System.out.println("ASPECT: Returning annotation value.");
aReturnValue = aTestAnnotation.value();
} else {
System.out.println("MISSING_GETTER_PROPERTY");
}
if(aReturnValue == null){
aReturnValue = iProceedingJoinPoint.proceed();
}
return aReturnValue;
}
}
Annotation "TestAnnotation"
@Component
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value();
}
AspectClient
pom.xml
<properties>
<java.version>1.7</java.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aspectProject.version>0.0.1-SNAPSHOT</aspectProject.version>
<spring-framework.version>4.1.2.RELEASE</spring-framework.version>
<org.aspectj-version>1.7.0</org.aspectj-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- AspectProject dependencies -->
<dependency>
<groupId>com.example.aop</groupId>
<artifactId>AspectProject</artifactId>
<version>${aspectProject.version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java/</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<!-- compile for Java 1.7 -->
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.4</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<aspectLibraries>
<aspectLibrary>
<groupId>com.example.aop</groupId>
<artifactId>AspectProject</artifactId>
</aspectLibrary>
</aspectLibraries>
<complianceLevel>${maven.compiler.source}</complianceLevel>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
Service Class
@Component
public class TestService {
private String value;
public void internalCall() {
System.out.println("INTERNAL_CALL :"+ getValue());
}
@TestAnnotation("RETURNED_FROM_ASPECT_CALL")
public String getValue() {
return value;
}
public void setValue(String iValue) {
this.value = iValue;
}
}
Spring context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- Enable AspectJ style of Spring AOP -->
<context:component-scan base-package="com.example.aop.client" />
<aop:aspectj-autoproxy />
<bean name="TestService" class="com.example.aop.client.service.TestService" />
<!-- Configure Aspect Beans, without this Aspects advice wont execute -->
<bean name="aspectProvider" class="com.example.aop.aspect.AspectProvider"/>
</beans>
Main class
public class SpringMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
TestService aTestService = ctx.getBean("TestService", TestService.class);
System.out.println("EXTERNAL_CALL: "+aTestService.getValue());
aTestService.internalCall();
ctx.close();
}
}
OUTPUT:
ASPECT: Returning annotation value.
EXTERNAL_CALL:RETURNED_FROM_ASPECT_CALL
INTERNAL_CALL: **null**
Expected:
ASPECT: Returning annotation value.
EXTERNAL_CALL: RETURNED_FROM_ASPECT_CALL
INTERNAL_CALL: **RETURNED_FROM_ASPECT_CALL**
Please advice in case if I am missing any entry or required to change configuration.Thanks in advance for your valuable time.
A:
What you do is a bit strange because on the one hand you configure Spring to use (auto) proxy-based Spring AOP, on the other hand you use AspectJ Maven Plugin to use native AspectJ and do compile-time weaving. Please decide which way you want to go:
For Spring AOP you do not need the AspectJ compiler, but then you are stuck with the proxy-based "AOP lite" approach which comes at the cost of internal calls not being intercepted by aspects because they do not go through proxies but through this (the original object).
For full-blown AspectJ you can configure Spring to use LTW (load-time weaving) as described in manual chapter Using AspectJ with Spring applications. Alternatively, you can also use compile-time weaving, but this is not necessary unless you have performance problems during application start-up.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to calculate quantity on hand for every lot (mysql)
This is the transaction details table
I am trying to design a Mysql inventory database.
I consider every type: 1 row a product lot (batch).
The type column has 1 for IN and 0 for OUT for each transaction.
detail_id is referencing the id column.
How can I get this result:
id item sum(quantity)
1 1 3 [10-(5+2)]
4 1 0 (5-5)
6 2 20 20
A:
You can use this:
SELECT
lots.id,
MIN(lots.item) AS item,
MIN(lots.quantity) - IFNULL(SUM(details.quantity), 0) AS quantity
FROM (
SELECT id, item, quantity
FROM details
WHERE type = 1
) lots LEFT JOIN details ON lots.id = details.detail_id
GROUP BY lots.id
ORDER BY lots.id
demo on dbfiddle.uk
|
{
"pile_set_name": "StackExchange"
}
|
Q:
multiple file uploader in reactjs form
I have a list of items in database and I want to render it in table and will add input type=file for each to upload file for each item
on handle click i want to send item name to handle function but i couldn't,
to make it clearer i want send value item.documentname to file1MadChangedHandler function, every time i click
{this.props.Organizations.listDocs
?
<div>
{ this.props.Organizations.listDocs.map(function (item, index) {
return(
<tr key={item.documentName}>
{item.documentName}
<td>
<td>
<input component="input"
type="file"
id="{item.documentName}"
onChange={(event,item)=> {
this.file1MadChangedHandler(event,item) }}
// onChange={this.file1MadChangedHandler}
ref={fileInput => ref.fileInput = fileInput}
style={{ display: "None" }}
/>
<button onClick={(item) => this.fileInput.click(item.documentName)}>Pick File</button>
</td>
</tr>
)
})
}
</div>
:
""
}
A:
With inputs from your repl.it/repls/MutedFunnyBlog code.
To get file name of uploaded item, you need to change your data slightly like below:
data: [
{ id: 1, name: "Copy of Applicant's Identification Card / Passport", "file": "" },
{ id: 2, name: "Copy of Business Registration Certificate (eg. SSM)", "file": "" },
{ id: 3, name: "Copy of Business Registration File 1", "file": "" },
{ id: 4, name: "Copy of Business Registration File 2", "file": "" }
] //added file
then render each row like below:
data.map((item, index) => {
return(
<tr key={`${this.state.inputkey}${item.id}`}>
<td width="100">{item.id}</td>
<td width="300">{item.name}</td>
<td width="200">{item.file}</td> /* your third column */
<td>
<input
key={this.state.inputkey} /*unique key */
type="file"
id={item.id} /*unique id cus every row should have unique input file type*/
className="inputfile"
onInput ={(e) => this.handleChange(e,item.id)}
data-name={item.id} />
<label htmlFor ={item.id} > /* unique id for file upload*/
<figure>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/>
</svg>
</figure>
</label>
</td>
</tr>
);
});
and in handleChange event:
handleChange(event, i) {
const newData = this.state.data.map(item => ({...item}) ); //copy state.data to new data
newData.map(item => item.file = i === item.id ? event.target.files[0].name: item.file); //set file based on uploaded file in each row
this.setState({
data: newData,
inputkey: Math.random().toString(36) //set new unique key here
}, () => console.log(this.state.data));
}
Demo , Hope It clears your issues.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My Batch File keeps looping, but why?
I have written a batch file from a VB.NET program I'm creating.
When I double click on the file in Windows XP it brings up a Command Prompt and appears to be running over and over again.
My batch file is as follows
REG ADD "HKCU\Software\Classes\*\shell\Open Folder In Rename" /ve /t REG_SZ /d "Open With Rename" /f
REG ADD "HKCU\Software\Classes\*\shell\Open Folder In Rename\Command" /ve /t REG_SZ /d "P:\Misc\Rename v2.0\Rename v2.0\bin\Debug\Rename v2.0.exe ""%1""" /f
EXIT
I can't understan what I've done wrong, but if I open a command prompt and run it from there, it runs once.
Any help would be gratly appreciated!
Thanks
A:
In windows, if you have a command line executable with the same name of your bat filename, and the batch file contains this command, the batch file keeps looping.
Example:
Create the file net.bat on your desktop.
In your file write this text: net
Double click the file and it will keep looping.
The cause of this behaviour is the order of execution of the commands. The command you want to execute is in one of the folders in your path. But the batch file is in your current folder so it gets executed first, causing the loop.
A:
make sure:
your script is not named like a build-in command or programm
make sure the scripts your script calls are not named like a build-in command or programm
e.g. if your script is called: reeeeeboooot.bat that calls shutdown -t 10 -r, but in the SAME FOLDER resides a shutdown.cmd
reeeeeboooot.bat will actually call shutdown.cmd INSTEAD of the build-in command.
sometimes the easiest things are the hardest. (pretty often actually :-D)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to check document.getElementbyId contains null or undefined value in it?
if(typeof (document.getElementById("courseId").value!=="undefined") || document.getElementById("courseId").value!==null)
{
Courseid = document.getElementById("courseId").value;
}
A:
rewrite it that way:
if(document.getElementById("courseId") && document.getElementById("courseId").value)
{
CourseId = document.getElementById("courseId").value;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the non repeating number in the integer array
The program finds the non repeated number in a int array. I am using a count for the duplicates and making a Numcounts[] to store the count values. I am assuming the array is sorted. Then I can check the Numcounts[] for 1, and that would be the non-repeating number. The complexity is \$O(n^2)\$.
Can you tell me how to do the same thing using hashmaps? I haven't used hashmaps and I know the complexity can be reduced to \$O(n))\$ using them.
#include<stdafx.h>
#include<stdio.h>
int main()
{
int n=6;
int * Numcounts = new int[n];
int count = 0;
int a[6] = {1,1,1,2,2,3}; // sort the array before proceeding.Because in the else part count is set to zero.
//If the array is unsorted then count will be reset in middle and will not retain the previous count.
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]==a[j])
{
count = count+1;
Numcounts[i] = count;
}
else{
count = 0;
}
}
}
}
A:
If the array is sorted you do not need hashmaps to achieve O(n). If you have a random/unsorted array you can use hashmaps to achieve the purpose, see Paulo's answer for that. Note that sorting requires O(n log(n)).
If you want to know how often each integer is in the original collection you will also need hashmaps, but if you only want to know a nonduplicate number in a sorted array the following code will work:
// N is the number of ints in sorted
int nonduplicate(int sorted[], const int N){
//To prevent segfaulting when N=1
if(N==1){ return sorted[0]; };
for(int i=0;i < N-1;i++){
if(sorted[i] == sorted[i+1]){
// Next number in collection is the same so the current number is not unique
// Set i to the first location of the next different number
do{
i++;
}while(i < N-1 && sorted[i] == sorted[i+1]);
}else{
// The next number is different so the current is unique
return sorted[i];
}
}
// Is the last number unique?
if(sorted[N-1] != sorted[N-2]){
return sorted[N-1];
}
// No unique numbers
return -1; // Or some other value you reserve for it
}
Note that this code is faster because it doesn't have the overhead of a hashmap and may stop before traversing the whole array, but does have the same big-O limit.
A:
Since you are using C++ and not C, there are a few things that you could clean up.
First of all, your code leaks memory: you are newing memory but you are not deleteing. In order to avoid this manual memory management, you should use the std::vector class template instead of new[].
Furthermore, stdio.h is a legacy C header. Use cstdio in C++. But in fact, your code doesn’t need that header anyway.
A hash map implementation is available in the std::tr1 namespace. If your compiler supports this (modern compilers do), the following code works:
#include <iostream>
#include <unordered_map>
#include <vector>
int main() {
std::unordered_map<int, unsigned> occurrences;
int a[6] = { 1, 1, 1, 2, 2, 3 };
unsigned const size = sizeof a / sizeof a[0];
// First pass: count occurrences.
for (unsigned i = 0; i < size; ++i)
++occurrences[a[i]];
// Second pass: search singleton.
for (unsigned i = 0; i < size; ++i)
if (occurrences[a[i]] == 1)
std::cout << a[i] << " only occurred once." << std::endl;
}
(To enable TR1 support on GCC, pass the std=c++0x flag to the compiler.)
Point of interest: the first pass works because the values inside the unordered map (= hash map) are initialised with the default value, 0. We are using this fact to increment the values directly without bothering to check whether the value existed in the map beforehand. This makes the code more concise and is actually also more efficient.
A:
A hashmap is a structure that maps a key (the hash) to a value.
In your example you'd want the key to be the number and the value to be the count of each number.
If you are using a compiler that that supports C++0x, you can add
#include <unordered_map>
and then modify the body of your main loop to something like:
std::unordered_map<int, int> hashMap;
for(int i=0;i<n;i++)
{
int number = a[i];
// check if this number is already in the map
if(hashMap.find(number) != hashMap.end())
{
// it's already in there so increment the count
hashMap[number] += 1;
}
else
{
// it's not in there yet so add it and set the count to 1
hashMap.insert(number, 1);
}
}
I wrote this code down from memory so it might not even compile, although it should be straightforward to fix.
As you can see we only run through the array once so you now have the O(n) complexity.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
gotoSimple() seems to reload to current action before redirecting
Somehow it seems that when I use gotoSimple in the following setup, my data will be saved twice by $object->save() in secondAction().
public function firstAction(){
// get data
// process postdata, if any
if( $form->isValid( $postdata ) ) {
$this->_helper->getHelper( 'Redirector' )->gotoSimple( 'second' );
}
}
public function secondAction(){
// get data
// process postdata, if any
if( $form->isValid( $postdata ) ) {
if( $object->save( $postdata ) ) {
// set flashmessage
$this->_helper->getHelper( 'Redirector' )->gotoSimple( 'index' );
}
}
}
After hours of debugging I have come to the conclusion that somehow the gotoSimple() command in secondAction() triggers secondAction() before it redirects to indexAction(). I have made sure that it is in no way possible for indexAction() to redirect back to secondAction().
Even more interesting: this only occurs in IE7 and in IE8. Can anyone point me in any possible direction to where this strange behavior may come from and how I can solve this?
UPDATE
By using the following lines of code in secondAction() right before the gotoSimple() command, I can be 100% sure of the fact that somehow the secondAction() is called twice when I press my submit button:
if( isset( $_SESSION['xyz-zyx'] ) ) {
$this->_helper->getHelper( 'flashMessenger' )->addMessage( 'I\'ve already been here!' );
unset( $_SESSION['xyz-zyx'] );
}
$_SESSION['xyz-zyx'] = true;
Any ideas?
A:
It seems that the problem was caused by using Zend_DataGrid (BvBGrid). Rewrote the entire action and fixed the problem :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel route redirecting with data
I have a basic route that looks like this:
Route::prefix('/group')->group(function () {
// Some routes here
Route::prefix('/{uuid}')->group(function () {
// Some routes here
Route::get('/user/{id}', 'Controller@preview')->name('view-user')->where('id', '[0-9]+');
}
}
The logic is that I want the id to be only numerical value. What I want to do now is, to declare a redirection to this, if the value is non-numerical. Let's say the input of id is fs. In that case I would want it to redirect to id with value 1.
I tried using Route:redirect, but could not make it work. It looks something like this:
Route::redirect('/group/{uuid}/user/{id}', '/group/{uuid}/user/1')->where('id', '[^0-9]+');
I would prefer to put the redirect inside the groups, but it can be outside if this is the only way. Any help will be greatly appreciated.
What happens is, that I get a 404 error if I have the route redirect declared.
EDIT: I want to do it in the routes/web.php file. I know how to do it in the controller, but it is not what I need in the current case.
Closures are not an option either, because that would prevent routes caching.
A:
You declared it inverted.
In Laravel you can redirect passing parameters in this way:
You can pass the name instead of the url and simply pass variables.
Redirect::route('view-user', [$uuid, $id])
A:
I think that you can do it inside of the controller of the router, with a logic like this:
class Controller {
// previous code ..
public function preview($uuid, $id) {
if(! is_numeric($id))
return redirect("/my-url/1");
// run the code below if $id is a numeric value..
// if not, return to some url with the id = 1
}
}
I think that there is no way to override the 'where' function of laravel, but I guess that have something like that in Routing Bindings:
Alternatively, you may override the resolveRouteBinding method on your Eloquent model. This method will receive the value of the URI segment and should return the instance of the class that should be injected into the route:
/**
* Retrieve the model for a bound value.
*
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value)
{
return $this->where('name', $value)->first() ?? abort(404);
}
But it's require that you manage consise model's values instead of ids of whatever you want.
A:
Following up on the comment
You can create a Route in routes/web.py that catches non-digit ids and redirect this to 'view-user' with id=1
It would look something like this
Route::get('/group/{uuid}/user/{id}', function ($uuid, $id) {
return redirect('view-user', ['uuid' => $uuid, 'id' => 1]);
})->where('id', '[^0-9]+');
// and then below have your normal route
Route::get('/group/{uuid}/user/{id}', 'Controller@preview')->name('view-user')->where('id', '[0-9]+');
Update
Following you comment that you do not want to use closures.
Change the "bad input route" to
Route::get('/group/{uuid}/user/{id}', 'Controller@redirectBadInput')->where('id', '[^0-9]+');
and then add the method in class Controller:
public function redirectBadInput ($uuid, $id) {
return redirect('view-user', ['uuid' => $uuid, 'id' => 1]);
}
You can see more in this SO thread about redirects and caching.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Counting common nodes between two nodes with igraph in R
Suppose I've generated an undirected graph(you can think about the graph of my friends on facebook). I would like to know, for each couple of nodes(taken two friends), the number of common "nodes" they have(the "mutual friends" of them). Is there a function in igraph that I can use?
Or in network or sna packages?
Thank you.
A:
If v_1 and v_2 are the two nodes in the graph g, then:
cocitation(g, v_1)[v_2]
will give you the number of "mutual friends" they have.
Obviously is the same of
cocitation(g, v_2)[v_1]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Handling loss of precision in subtracting two doubles that are close to each other
I have a project to do where we are to solve the matrix equation AX=B for x, given that A is a tridiagonal matrix. I did this project in C++, got the program to produce the right Matrix X, but when trying to report the error back to the user, A*X-B, I get an erroneous error!! It is due to the fact that I am subtracing A*X and B, whose entries are arbitrarily close to each other. I had two ideas on how to handle this, element-by-element:
According to this article, http://en.wikipedia.org/wiki/Loss_of_significance, there could be as many as -log2(1-y/x) bits lost in straight subtraction x-y. Let's scale both x and y by pow(2,bitsLost), subtract the two, and then scale them back down by dividing by pow(2,bitsLost)
Stressed so much in the numeric methods course this is for: take the arithmetic conjugate! Instead of double difference = x-y; use double difference = (x*x-y*y)/(x+y);
OK, so why haven't you chose a method and moved on?
I tried all three methods (including straight subtraction) here: http://ideone.com/wfkEUp . I would like to know two things:
Between the "scaling and descaling" method (for which I intentionally chose a power of two) and the arithmetic conjugate method, which one produces less error (in terms of subtracting the large numbers)?
Which method is computationally more efficient? /*For this, I was going to say the scaling method was going to be more efficient with a linear complexity versus the seemed quadratic complexity of the conjugate method, but I don't know the complexity of log2()*/
Any and all help would be welcomed!!
P.S.: All three methods seem to return the same double in the sample code...
Let's see some of your code
No problem; here is my Matrix.cpp code
#include "ExceptionType.h"
#include "Matrix.h"
#include "MatrixArithmeticException.h"
#include <iomanip>
#include <iostream>
#include <vector>
Matrix::Matrix()
{
//default size for Matrix is 1 row and 1 column, whose entry is 0
std::vector<long double> rowVector(1,0);
this->matrixData.assign(1, rowVector);
}
Matrix::Matrix(const std::vector<std::vector<long double> >& data)
{
this->matrixData = data;
//validate matrixData
validateData();
}
//getter functions
//Recall that matrixData is a vector of a vector, whose elements should be accessed like matrixData[row][column].
//Each rowVector should have the same size.
unsigned Matrix::getRowCount() const { return matrixData.size(); }
unsigned Matrix::getColumnCount() const { return matrixData[0].size(); }
//matrix validator should just append zeroes into row vectors that are of smaller dimension than they should be...
void Matrix::validateData()
{
//fetch the size of the largest-dimension rowVector
unsigned largestSize = 0;
for (unsigned i = 0; i < getRowCount(); i++)
{
if (largestSize < matrixData[i].size())
largestSize = matrixData[i].size();
}
//make sure that all rowVectors are of that dimension
for (unsigned i = 0; i < getRowCount(); i++)
{
//if we find a rowVector where this isn't the case
if (matrixData[i].size() < largestSize)
{
//add zeroes to it so that it becomes the case
matrixData[i].insert(matrixData[i].end(), largestSize-matrixData[i].size(), 0);
}
}
}
//operators
//+ and - operators should check to see if the size of the first matrix is exactly the same size as that of the second matrix
Matrix Matrix::operator+(const Matrix& B)
{
//if the sizes coincide
if ((getRowCount() == B.getRowCount()) && (getColumnCount() == B.getColumnCount()))
{
//declare the matrixData
std::vector<std::vector<long double> > summedData = B.matrixData; //since we are in the scope of the Matrix, we can access private data members
for (unsigned i = 0; i < getRowCount(); i++)
{
for (unsigned j = 0; j < getColumnCount(); j++)
{
summedData[i][j] += matrixData[i][j]; //add the elements together
}
}
//return result Matrix
return Matrix(summedData);
}
else
throw MatrixArithmeticException(DIFFERENT_DIMENSIONS);
}
Matrix Matrix::operator-(const Matrix& B)
{
//declare negativeB
Matrix negativeB = B;
//negate all entries
for (unsigned i = 0; i < negativeB.getRowCount(); i++)
{
for (unsigned j = 0; j < negativeB.getColumnCount(); j++)
{
negativeB.matrixData[i][j] = 0-negativeB.matrixData[i][j];
}
}
//simply add the negativeB
try
{
return ((*this)+negativeB);
}
catch (MatrixArithmeticException& mistake)
{
//should exit or do something similar
std::cout << mistake.what() << std::endl;
}
}
Matrix Matrix::operator*(const Matrix& B)
{
//the columnCount of the left operand must be equal to the rowCount of the right operand
if (getColumnCount() == B.getRowCount())
{
//if it is, declare data with getRowCount() rows and B.getColumnCount() columns
std::vector<long double> zeroVector(B.getColumnCount(), 0);
std::vector<std::vector<long double> > data(getRowCount(), zeroVector);
for (unsigned i = 0; i < getRowCount(); i++)
{
for (unsigned j = 0; j < B.getColumnCount(); j++)
{
long double sum = 0; //set sum to zero
for (unsigned k = 0; k < getColumnCount(); k++)
{
//add the product of matrixData[i][k] and B.matrixData[k][j] to sum
sum += (matrixData[i][k]*B.matrixData[k][j]);
}
data[i][j] = sum; //assign the sum to data
}
}
return Matrix(data);
}
else
{
throw MatrixArithmeticException(ROW_COLUMN_MISMATCH); //dimension mismatch
}
}
std::ostream& operator<<(std::ostream& outputStream, const Matrix& theMatrix)
{
//Here, you should use the << again, just like you would for ANYTHING ELSE.
//first, print a newline
outputStream << "\n";
//setting precision (optional)
outputStream.precision(11);
for (unsigned i = 0; i < theMatrix.getRowCount(); i++)
{
//print '['
outputStream << "[";
//format stream(optional)
for (unsigned j = 0; j < theMatrix.getColumnCount(); j++)
{
//print numbers
outputStream << std::setw(17) << theMatrix.matrixData[i][j];
//print ", "
if (j < theMatrix.getColumnCount() - 1)
outputStream << ", ";
}
//print ']'
outputStream << "]\n";
}
return outputStream;
}
A:
You computed two numbers x and y which are of a limited precision floating point type. This means that they are already rounded somehow, meaning loss of precision while computing the result. If you subtract those numbers afterwards, you compute the difference between those two already rounded numbers.
The formula you wrote gives you the maximum error for computing the difference, but this error is with regard to the stored intermediate results x and y (again: rounded). No method other than x-y will give you a "better" result (in terms of the complete computation, not only the difference). To put it in a nutshell: the difference can't be more accurate using any formula other than x-y.
I'd suggest taking a look at arbitrary precision arithmetic math libraries like GMP or Eigen. Use such libraries for computing your equation system. Don't use double for the matrix computations. This way you can make sure that the intermediate results x and y (or the matrices Ax and B) are as precise as you want them to be, for example 512 bits, which should definitely be enough for most cases.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pairs Trading situation Spread changes
I'm setting up and following a pair trading operation by the method of summing the distances squared (SSD). After determining the best pairs, I have to track the spread between the normalized prices.
Am I noticing something that is bothering me or am I doing it wrong?
When I opened the transaction it is not cash neutral: the long goes, for example, \$26,628.00 and the short goes \$ 29,886.00.
This way it is not a neutral cash trade.
Whatching the Spread between normalized prices, can there be situations where my spread is moving towards the mean(further away from the average) and I have losses?
The fact that my trade didn open as a cash neutral can offer me situation like this? Where I will have to wait until the mean-reverting process complete?
PS: 1)so the spread will depend on the amount of stocks I bought and the size of their prices. That would have influence on the behavior of the spread, right?
A:
Of course. Even if you started dollar neutral, the spread can continue to move away from its mean resulting in losses. Pairs trading isn't an arbitrage situation, it simply asserts that given correlated assets, their spread will revert to the long run mean if and when it does deviate.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nginx 405 Not Allowed - PHPMAILER
I uploaded a website with a PHPMailer v5. It works well in localhost but when I tried it online, Nginx-405-not-allowed page shows. below is my configuration for my mail function.
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'mypassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
A:
I found my answer. The problem is in the web server provider. It seems like there are some web servers don't accept smtp.gmail.com and thus I created an email from the domain and set the host, username, password and as well as the port to what the web server provider provides. Hope you guys visit here will solve your questions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where Ruby get date, time from?
I am working in ruby, I have an object containing today's date, time from DB and only want time truncating the date. I can get,
DateTime.now.strftime("%H:%M")
I'm curious about where Ruby get date and time from? From internet, device or browser?
A:
https://ruby-doc.org/core-2.2.0/Time.html#method-c-new
Unless given a time during initialization of a Time instance, Ruby uses the type from the system it is running on.
If you want the current time on a user's device in a Rails project, you'll need to capture it with Javascript and pass it back to your Rails application.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select only the feature that overlapses its correspondant in another layer - Leaflet, qgis2web
I have 2 identical layers overlapping, each containing identical FeatureCollection values.
Only one of them is added into the map.
Is it possible that when clicking on a specific feature of the visible layer, to bring up the correspondant one from the other layer?
For the moment I am using the below but this brings up the entire layer, not just the desired feature.
layer_tt2_0.on('click', function(ev) {
layer_tt1_1.addTo(map)});
The features have separate ids. 1a, 1b etc. The same ID is present in both layers for the same features.
"features": [ { "type": "Feature", "properties": { "name": "1a" }, "geometry": { "type": "LineString", "coordinates": [[coordinates here]],
The code obtained with qgis2web is below, added TomazicM's suggestion as well. I'm receiving an error in the console "Uncaught TypeError: Cannot read property 'properties' of undefined" and I cannot identify the cause.
var map = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[45.505788666842555,25.183138708143936],[45.620566687311815,25.392037287580678]]);
var hash = new L.Hash(map);
map.attributionControl.setPrefix('<a href="https://github.com/tomchadwin/qgis2web" target="_blank">qgis2web</a> · <a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a> · <a href="https://qgis.org">QGIS</a>');
var autolinker = new Autolinker({truncate: {length: 30, location: 'smart'}});
var bounds_group = new L.featureGroup([]);
function setBounds() {
}
function pop_tt2_0(feature, layer) {
var popupContent = '<table>\
<tr>\
<td colspan="2">' + (feature.properties['name'] !== null ? autolinker.link(feature.properties['name'].toLocaleString()) : '') + '</td>\
</tr>\
</table>';
layer.bindPopup(popupContent, {maxHeight: 400});
}
function style_tt2_0_0() {
return {
pane: 'pane_tt2_0',
opacity: 1,
color: 'rgba(125,139,143,1.0)',
dashArray: '',
lineCap: 'square',
lineJoin: 'bevel',
weight: 8.0,
fillOpacity: 0,
interactive: true,
}
}
map.createPane('pane_tt2_0');
map.getPane('pane_tt2_0').style.zIndex = 400;
map.getPane('pane_tt2_0').style['mix-blend-mode'] = 'normal';
var layer_tt2_0 = new L.geoJson(json_tt2_0, {
attribution: '',
interactive: true,
dataVar: 'json_tt2_0',
layerName: 'layer_tt2_0',
pane: 'pane_tt2_0',
onEachFeature: pop_tt2_0,
style: style_tt2_0_0,
});
bounds_group.addLayer(layer_tt2_0);
map.addLayer(layer_tt2_0);
function pop_tt1_1(feature, layer) {
var popupContent = '<table>\
<tr>\
<td colspan="2">' + (feature.properties['name'] !== null ? autolinker.link(feature.properties['name'].toLocaleString()) : '') + '</td>\
</tr>\
</table>';
layer.bindPopup(popupContent, {maxHeight: 400});
}
function style_tt1_1_0() {
return {
pane: 'pane_tt1_1',
opacity: 1,
color: 'rgba(133,182,111,1.0)',
dashArray: '',
lineCap: 'square',
lineJoin: 'bevel',
weight: 8.0,
fillOpacity: 0,
interactive: true,
}
}
map.createPane('pane_tt1_1');
map.getPane('pane_tt1_1').style.zIndex = 401;
map.getPane('pane_tt1_1').style['mix-blend-mode'] = 'normal';
var layer_tt1_1 = new L.geoJson(json_tt1_1, {
attribution: '',
interactive: true,
dataVar: 'json_tt1_1',
layerName: 'layer_tt1_1',
pane: 'pane_tt1_1',
onEachFeature: pop_tt1_1,
style: style_tt1_1_0,
});
bounds_group.addLayer(layer_tt1_1);
layer_tt2_0.on('click', function(ev) {
var layer = ev.target;
layer_tt1_1.eachLayer(function(layer2) {
if (layer2.feature.properties.name == layer.feature.properties.name) {
layer2.addTo(map);
}
});
});
setBounds();
A:
Since GeoJSON layer is actually a group layer consisting of individual layers representing features, it's possible to add individual feature layer to the map, it just has to be identified by some id.
When clicking on the feature of the layer_tt2_0 layer, corresponding feature from the layer_tt1_1 is found with the help of group layer .eachLayer method, using feature property name.
In your case that could look something like this:
layer_tt2_0.on('click', function(ev) {
var layer = ev.propagatedFrom;
layer_tt1_1.eachLayer(function(layer2) {
if (layer2.feature.properties.name == layer.feature.properties.name) {
layer2.addTo(map);
}
});
});
Here is working JSFiddle (based on official Leaflet choropleth example): https://jsfiddle.net/TomazicM/bw5ymgda/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I encounter an AUTHENTICATIONFAILED error when connecting to email with imaplib library
How can I connect to imaplib library without encountering AUTHENTICATIONFAILE error !?
My Gmail inbox shows me a serious security alert (login attempt blocked) when logging in through the web browser.
IMAP_SERVER = 'imap.gmail.com'
USERNAME = '******@gmail.com'
PASSWORD = '******'
client = imaplib.IMAP4_SSL(IMAP_SERVER)
client.login(USERNAME, PASSWORD)
A:
This is most likely gmail blocking "less secure apps" from connecting to your account. This blocking is enabled, by default.
From a google support page:
You can block sign-in attempts from some apps or devices that are less secure. Apps that are less secure don't use modern security standards, such as OAuth. Using apps and devices that don’t use modern security standards increases the risk of accounts being compromised. Blocking these apps and devices helps keep your users and data safe.
If you would like to turn on access to less secure apps (which will make your account more vulnerable to being attacked), then you can follow these steps:
Sign into your google account normally. (https://myaccount.google.com/)
Once signed in, go to the "Security" page.
Scroll down until you see a window with "Less secure app access". If you want to access your email using python code like you posted, this needs to be turned on.
Personally, I think this is acceptable on a throwaway/testing account but I would never do this to my main/personal account or any account involving communicating with clients.
In fact, take a look at this page: https://developers.google.com/gmail/api/quickstart/python
Gmail has a dedicated API for connecting to your google mail account. Their api implements proper security measures which means you won't need to enable less secure app access... protecting your account!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How will ADA Boost be used for solving regression problems?
I have an idea of how ADABOOST will be used for classification but I want to get the idea of how to re-weight and thus use ADABOOST in case of regression problems.
A:
Here are link to some famous boost of regressor.
Adaboost.R2: Improving Regressors using Boosting Techniques
Adaboost.RT: Experiments with AdaBoost.RT, an Improved Boosting
Scheme for Regression
Scikit-Learn have many implementations:
AdaBoostRegressor
Decision Tree Regression with AdaBoost
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MVC Master-Detail CRUD
I'm starting with MVC and i have some basic questions that maybe you can orient me a little bit:
I'm Using MVC5 with Razor and EntityFramework 6. No AngularJS skills here.
I have a classic Master-Detail CRUD where i need to create Order and OrderItems. My idea es that when you create the order, you can add the items in the same form and then with one SAVE button create both records on the database (The Order and the Items).
I've created the "Orders" CRUD very good with scaffolding, and it works perfect. But now i need to add to the same VIEW the items, and here is what i'm getting lost and try different ways to do this:
BINDING ISSUE: I thought that probably i could add the list of OrderItems to the binding header on the CREATE event. My OrderController has this method:
public ActionResult Create([Bind(Include = "Id,Date,*other fields*")] Order order) and it works fine with the ORDER CRUD operations. But, now, if need to add a List to the list of fields binded on that header, is that possible? How should i save the data in the View then?
JSON: Another way i thought, was to remove the Binding header and use Json, but all the examples i've seen was using AngularJS and i have all the site done except for this CRUD, i preffer to let that option for the real last chance. On the other hand, i've found this: https://www.youtube.com/watch?v=ir9cMbNQP4w and it's exactly what i need to do, but: It's on MVC4 and not MVC5, and also i have all my entities validation in my model (extended) class and some of them in the controller as well (exclusively the ones related to the Creation or editing the order). Tell me if i'm wrong here please!
PARTIAL VIEW: The last way i've just tried was with Partial View. I've created succesfully the Initial data load based on this tutorial: http://dotnetmentors.com/mvc/render-partialview-with-model.aspx , but after that, i need to add new items to my order, or edit/delete the existing ones and here is where i get lost: Should i have different CREATE/EDIT methods for the partial views? How i send the data then? How i can use only one SAVE button that saves everything at the same time?
I'm getting more lost when i look for more information.... so, here i am asking for help to you guys !
Thanks a lot in advance !!
A:
Create a custom view model:
public class NewOrderViewModel
{
public Order order { get; set; }
public OrderItem[] orderItems { get; set; }
}
Then you can use this in the view by changing @model NewOrderViewModel at the top and you will be able to use like:
@Html.TextBoxFor(m => m.order.Phone);
@Html.TextBoxFor(m => m.orderItems[0].ItemName);
You will need some javascript to copy the html and create new form elements for each new orderItem the user wants to add.
Then your controller signature would look like:
public ActionResult Create(NewOrderViewModel content)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select an entity from database based on nested list item match?
I have a DbSet that contains a list of Item, Now I want to search an Item from the database based on its nested list item matching.
Item Model
public int ItemID{ get; set; }
public string Cover { get; set; }
public List<SlideModel> Slides { get; set; }
Slide Model
public int SlideID{ get; set; }
public int ItemID{ get; set; }
public string Slide{ get; set; }
Now I will pass a search string of Slide and it will search for the Item who have the Slide in its List<SlideModel> and return the Item
item = await context.Items
.Include(i => i.Slides)
.Where(...todo-maybe...)
.FirstOrDefaultAsync();
How should I write the Query method to get the item based on the slide
A:
That's the thing that you want? Hope to help, my friend :))
string inputSlide = "abc";
item = await context.Items
.Include(i => i.Slides)
.Where(i => i.Slides.Any(i => i.Slide.ToLower() == inputSlide.ToLower()))
.FirstOrDefaultAsync();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way of measuring how far the group of homotopy equivalences is from the mapping class group of $X$?
$[X,X]$ is the collection of homotopy equivalences from $X$ to itself, with $X$ a $CW$ complex.
To start, suppose that $X$ is a $1$-dimensional $CW$ complex. As usual, let $\mathcal{M}(X):=Homeo^+(X)/Homeo_0$ be the mapping class group.
For surfaces $\Sigma_g$ with $g \geq 1$, we know that a homotopy equivalence of $X$ with itself is homotopic to some homeomorphism, but there are spaces for which this fails, such as the wedge of two circles. In general, I want to measure how far $[X,X]$ is from $\mathcal{M}(X)$
I know that for any eilenberg-maclane space, $[X,X] \cong Out(\pi_1(X))$, so for any rose, $[X,X] \cong Out(F_n)$, whereas the mapping class group is finite.
$Q1:$ Is $\mathcal{M}(X)$ normal in $[X,X]$, and if so, what can be said of the quotient? Is there a class of spaces that makes $\mathcal{M}(X)$ normal?
$Q2:$ Are there references for this sort of question?
$Q3:$ how about for higher dimensional $CW$ complexes?
A:
I'll turn my comments about the 1-dimensional case into a partial answer addressing only that case, and I'll add a proof that normality fails.
When $X$ is a 1-dimensional CW complex, also known to topologists as a "graph", then calculation of the mapping class group $\mathcal{M}(X)$ can be reduced to a discrete problem. Let $\mathcal{E}$ be the set of oriented edges; let $r : \mathcal{E} \to \mathcal{E}$ be the involution that reverses orientation; let $V$ be the set of vertices, and let $i : \mathcal{E} \to V$ be the map which assigns to each oriented edge its initial vertex. Then $\mathcal{M}$ is isomorphic to the group of permutations $\sigma$ of the disjoint union $\mathcal{E} \coprod V$ such that $\sigma(\mathcal{E})=\mathcal{E}$, $\sigma \circ r = r \circ \sigma$, and $\sigma \circ i = i \circ \sigma$. The proof of this boils down to the 1-dimensional version of a theorem of Alexander: every homeomorphism of $[0,1]$ that fixes $0$ and $1$ is isotopic to the identity.
To address the question of normality, the image of the natural homomorphism $\mathcal{M}(X) \to [X,X]$ is not a normal subgroup. One way to see this is to use two facts: the group $[X,X]$ acts on the set of conjugacy classes of the free group $\pi_1(X)$; and every conjugacy class is uniquely represented by a "circuit" in $X$, meaning a cyclically ordered sequence of edges without cancellation, modulo cyclic permutation. When $X$ is a finite graph, it contains only finitely many embedded circuits, corresponding to a finite set of conjugacy classes that is invariant under $\mathcal{M}(X)$. But $[X,X]$ contains an element $\Phi$ which takes an embedded circuit to a non-embedded circuit (up to homotopy), hence
$$\Phi \mathcal{M}(X) \Phi^{-1} \ne \mathcal{M}(X)
$$
In fact if $X$ has rank $\ge 3$ one can show that $[X,X]$ contains an element $\Phi$ that has no periodic conjugacy classes. If $X$ has rank $2$, then the conjugacy class of $aba^{-1}b^{-1}$ is periodic for every element of $[X,X]$, and similarly for $ab^{-1}a^{-1}b$, and for the inverses of those two, and for all their powers. However, all you have to do is to take one embedded circuit in $X$ and find one $\Phi \in [X,X]$ which takes that embedded circuit to a nonembedded one, and that's pretty straightforward.
By the way, I like this normality question, I'm going to make it an exercise in my $\text{Out}(F_n)$ book.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android webview doesn't display web page in some cases
I have an application that's based on alfresco android sdk. After user login to the server MainActivity starts. The MainActivity has few fragments in itself. One fragment contains webview, some buttons and textview. Here is the code of xml layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/prop"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/video_layout"
android:layout_width="match_parent"
android:layout_height="192dp"
android:orientation="horizontal"
android:gravity="center" >
<WebView
android:id="@+id/video_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
.
.
.
</LinearLayout>
</ScrollView>
When the layout is displayed webview should load url of page with HTML5 video but only blank page is shown. After a while blank page changes to grey. I observed that it means page is load and it show the page with html5 video after user scroll layout. This happens with every url what I've try.
In the test activity I use the same layout and the page with video is loaded and displayed correctly.
In the fragment and in the test activity I use the same code for setting webview and loading the url. Javascript is enabled and I use WebChromeClient like is recommended in WebView docummentation. Also i have INTERNET permission in applications Manifest.
Here is the code from onCreate method from test activity :
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_video);
web = (WebView)findViewById(R.id.video_web_view);
.
.
.
web.setWebChromeClient(new WebChromeClient());
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setPluginState(PluginState.ON);
webSettings.setDomStorageEnabled(true);
web.setHorizontalScrollBarEnabled(false);
web.setVerticalScrollBarEnabled(false);
webSettings.setRenderPriority(RenderPriority.HIGH);
webSettings.setUseWideViewPort(false);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
web.loadUrl(someUrl);
}
The same code contains onCreateView in fragment. Only difference is that user have to be login to the server for displaying fragment.
I almost forgotten on errors from Logcat :
02-28 09:34:20.832: V/chromium(9079): external/chromium/net/host_resolver_helper/host_resolver_helper.cc:66: [0228/093420:INFO:host_resolver_helper.cc(66)] DNSPreResolver::Init got hostprovider:0x5354b220
02-28 09:34:20.832: V/chromium(9079): external/chromium/net/base/host_resolver_impl.cc:1515: [0228/093420:INFO:host_resolver_impl.cc(1515)] HostResolverImpl::SetPreresolver preresolver:0x018ee018
02-28 09:34:21.182: V/WebRequest(9079): WebRequest::WebRequest, setPriority = 1
02-28 09:34:21.382: V/chromium(9079): external/chromium/net/disk_cache/hostres_plugin_bridge.cc:52: [0228/093421:INFO:hostres_plugin_bridge.cc(52)] StatHubCreateHostResPlugin initializing...
02-28 09:34:21.392: V/chromium(9079): external/chromium/net/disk_cache/hostres_plugin_bridge.cc:57: [0228/093421:INFO:hostres_plugin_bridge.cc(57)] StatHubCreateHostResPlugin lib loaded
02-28 09:34:21.392: V/chromium(9079): external/chromium/net/disk_cache/hostres_plugin_bridge.cc:63: [0228/093421:INFO:hostres_plugin_bridge.cc(63)] StatHubCreateHostResPlugin plugin connected
02-28 09:34:21.392: V/chromium(9079): external/chromium/net/http/http_cache.cc:1167: [0228/093421:INFO:http_cache.cc(1167)] HttpCache::OnBackendCreated HostStat created
02-28 09:34:21.392: E/chromium(9079): external/chromium/net/disk_cache/stat_hub.cc:213: [0228/093421:ERROR:stat_hub.cc(213)] StatHub::Init - App org.alfresco.mobile.android.samples isn't supported.
02-28 09:34:21.392: E/chromium(9079): external/chromium/net/disk_cache/stat_hub.cc:213: [0228/093421:ERROR:stat_hub.cc(213)] StatHub::Init - App org.alfresco.mobile.android.samples isn't supported.
02-28 09:34:22.222: D/skia(9079): notifyPluginsOnFrameLoad not postponed
Does anyone know what i do wrong? Have anyone some suggestion taht could help me?
Thanks for your answer and sorry for my bad english.
A:
So I figured out what I did wrong. It had something to do with acceleration. I simply added following line to my code:
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
and It solved my problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Raspberry Pi watchdogging C++ program
I have C++ app is running on my device which is a bit modified version of Raspberry PI. Application is reading data from a serial port and I need a device to reboot after some particular data is received. I've been wondering about integrating this functionality with watchdog but have no idea how to do it. Maybe there is a possibility to send some signal from my app to watchdog to tell that it's time to reboot?
P.S. Application starts as systemd service.
A:
Call
std::system("sudo reboot");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
While in beta, why does my reputation need to be so high to suggest tag synonyms?
I have been working on cleaning up the tags on the main freelancing site by suggesting tag wiki entries. I then came across two tags that were obviously synonyms - but I do not have a high enough reputation to suggest it (need 1250).
It seems that in its current state, anyone can create a new tag, but very few of us (if any) have the ability to suggest synonyms and clean up tags.
I suggest we allow current (invite-only) members more moderation privileges, for things like this (keeping the site clean and un-cluttered).
Is there a reason why we don't allow this (is vandalism an issue for invitees)?
How can we go about making this change?
A:
Tag synonyms used to be something that only developers on Stack Exchange could put in place. When it was given to the community, the high rep-barrier was to discourage vandalism or incorrect tag synonyms.
It is higher still on established sites; the lowered reputation barriers are already present on beta sites (in private beta, you need 2999 less rep to cast close votes, for example)
We don't have any moderators pro tem yet, by the way. These would be the people given moderator privileges "for the time being" later into the beta when we go public.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Saving matplotlib subplot figure to image file
I'm fairly new to matplotlib and am limping along. That said, I haven't found an obvious answer to this question.
I have a scatter plot I wanted colored by groups, and it looked like plotting via a loop was the way to roll.
Here is my reproducible example, based on the first link above:
import matplotlib.pyplot as plt
import pandas as pd
from pydataset import data
df = data('mtcars').iloc[0:10]
df['car'] = df.index
fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
# plt.show()
# plt.savefig('file.png')
Uncommenting plt.show() yields what I want:
Searching around, it looked like plt.savefig() is the way to save a file; if I re-comment out plt.show() and run plt.savefig() instead, I get a blank white picture. This question, suggests this is cause by calling show() before savefig(), but I have it entirely commented out. Another question has a comment suggesting I can save the ax object directly, but that cuts off my legend:
The same question has an alternative that uses fig.savefig() instead. I get the same chopped legend.
There's this question which seems related, but I'm not plotting a DataFrame directly so I'm not sure how to apply the answer (where dtf is the pd.DataFrame they're plotting):
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
Thanks for any suggestions.
Edit: to test the suggestion below to try tight_layout(), I ran this and still get a blank white image file:
fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
fig.tight_layout()
plt.savefig('test.png')
A:
Remove the line plt.figure(figsize=(12, 9)) and it will work as expected. I.e. call savefig before show.
The problem is that the figure being saved is the one created by plt.figure(), while all the data is plotted to ax which is created before that (and in a different figure, which is not the one being saved).
For saving the figure including the legend use the bbox_inches="tight" option
plt.savefig('test.png', bbox_inches="tight")
Of course saving the figure object directly is equally possible,
fig.savefig('test.png', bbox_inches="tight")
For a deeper understanding on how to move the legend out of the plot, see this answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Building a Chat Application using Ruby
I am trying to build a chat application purely using Ruby. There is a similar question posted earlier, but I have different and related queries. I have looked at this example(Same as referred by the person who posted a similar question earlier) . The code in the example doesn't seem to be working for me. On running the ruby script on the terminal, and connecting to the url: http://localhost:1234 in my browser, I indefinitely encounter a "Transferring data from localhost..." message.
Here 1234 is the port number used in the example provided. I am not able to figure out what is the reason behind my unsuccessful run. May be I need to specify something in the command line while executing the script or I am supposed to start the chat(input output) through some other place(probably the browser). I am not able to figure out what exactly to do. Could you please help me out on this?
I am running the chat server code pretty much unmodified. I am running the web service and the chat server on the same host.
I was able to partially get the code working for me upto the point where the loop starts. The modified code which worked for me upto a certain point is given below.
require 'gserver'
class BasicServer < GServer
def initialize(*args)
super(*args)
# Keep an overall record of the client IDs allocated
# and the lines of chat
@@client_id = 0
@@chat = []
end
def serve(io)
# io.puts("Hello world!")
# Increment the client ID so each client gets a unique ID
@@client_id += 1
my_client_id = @@client_id
my_position = @@chat.size
# io.puts(@@chat.size)
# Give the total number of people who are currently on chat.. for e.g. 0 => 1 person on chat
# Leave a message on the chat queue to signify this client
# has joined the chat
@@chat << [my_client_id, ""]
# io.puts(@@chat)
end
end
server = BasicServer.new(1234)
server.start
#sleep 120
#server.shutdown
For every browser instance a new client is connected to the chat queue(they have unique client id's to identify them). I wanted to reuse the code in the example by adding a text box(something similar to what we use in html) to the browser instance(s) running wherein a user(s) can enter their message and post it say using the click of a button(which is also integrated in the browser). This reflects in all other browser instances of various clients and the chat goes on like this until users enter a string "quit" to leave the chat room.
I am not sure how to implement the above feature too in Ruby, any suggestions or related articles to refer would be really helpful.
Thanks a lot!!
A:
I'm guessing that this is the only code you're using. The way HTTP (the protocol your web browser uses when talking to your server) works, is that the browser connects to your servers, sends some lines saying which page it wants to get, what cookies it has, etc. The server then responds, and in most cases, closes the connection. So in your case, when you connect to the chat server in your web browser, the browser connects, BasicServer#serve gets called, some stuff is sent back, and the web browser closes the connection, so the server can't send more data to the browser. The easiest way to "fix" this is to use a different way of connecting to your server (either telnet or nc (netcat)). If you want this to be in a browser, you need to make your server respond to HTTP requests, and then return a page that regularly polls the server (read up on AJAX or WebSockets). You can look at this for inspiration, although it isn't written in Ruby: https://github.com/ry/node_chat.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The Downside to addEventListener Versus onClick Property
I understand the difference between an addEventListener and the onclick property and know how to use both. I am wondering if there is a draw back to always using EventListener's instead of using the onclick property. The EventListener appears to be much more powerful than just using the onclick atleast when dynamically generating the HTML from javascript.
Is there a memory/cpu drawback or am I safe to only use EventListeners?
A:
This probably isn't the direction you were going in, but there are a few instances where you would be unable to remove an event listener.
Event handlers are completely public, and can be modified (to a certain extent) by anyone:
// You do this
myLink.onclick = function () {
alert('hello, world');
};
// Another developer who hates you because
// he thinks that you're hitting on his girlfriend
// but you're not, you're just friends, but
// he's jealous so he doesn't understand
// does this
myLink.onclick = function () {
alert('muahahahaha');
};
// Someone else could even get rid of
// the handler entirely:
myLink.onclick = null;
But there is no publically accessible list of event listeners. The only way to remove an event listener is if you still have access to the original function:
myLink.addEventListener('click', function () {
alert('hello, world');
}, false);
There is now no way to remove that event listener. You gave it an anonymous function, so even you wouldn't be able to remove it if you wanted to.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python: Chequear Varios Ficheros de Texto
¿Es posible comprobar que los valores obtenidos en un fichero .csv llamado A son los mismos que en otro fichero .csv B e imprimir los casos diferentes en un fichero salida.txt? Yo he hecho esto:
import time
# En primer lugar debemos de abrir el fichero que vamos a leer.
# y abrir el fichero donde vamos a guardar la informacion.
infile = open('Intercambio Modbus v11 - RGA.csv', 'r')
outfile = open("salida.txt","w")
# Mostramos por pantalla lo que leemos desde el fichero
print('>>> Lectura del fichero línea a línea')
# Timer de 2 segundos para probar si funciona, podemos meter timer para que espere unos segundos antes de comprobar una salida.
# time.sleep(2)
for line in infile:
line = line[:-1]
split_line = line.split(";")
if split_line[5] == split_line[11]:
outfile.write("La línea es correcta\n")
#time.sleep(3)
else:
outfile.write("NO COINCIDEN LOS VALORES --> " + line + "\n")
# Cerramos el fichero.
infile.close()
outfile.close()
Con este fichero compruebo los valores que me interesa saber si son iguales dentro del mismo fichero pero....¿Que pasada si en lugar de split_line[11] del mismo fichero quisiera comprobar de otro fichero distinto?¿Como puedo hacerlo?
A:
Si tus dos ficheros tienen el mismo numero de lineas puedes usar la función preconstruida zip() que retorna un iterador con tuplas formadas por las parejas de dos iterables. Si alguno de los ficheros tiene más lineas que el otro solo se compararán aquellas que tengan pareja en el otro, es decir, las lineas de más no se tienen en cuenta. Sería algo así:
import time
# En primer lugar debemos de abrir el fichero que vamos a leer.
# y abrir el fichero donde vamos a guardar la informacion.
infile1 = open('a.csv', 'r')
infile2 = open('b.csv', 'r')
outfile = open("salida.txt","w")
# Mostramos por pantalla lo que leemos desde el fichero
print('>>> Lectura del fichero línea a línea')
# Timer de 2 segundos para probar si funciona, podemos meter timer para que espere unos segundos antes de comprobar una salida.
# time.sleep(2)
for line1, line2 in zip(infile1, infile2):
line1 = line1[:-1]
line2 = line2[:-1]
if line1.split(";")[5] == line2.split(";")[11]:
outfile.write("La línea es correcta\n")
#time.sleep(3)
else:
outfile.write("NO COINCIDEN LOS VALORES --> " + line1 + "\n")
# Cerramos el fichero.
infile1.close()
infile2.close()
outfile.close()
Podrías usar with para simplificar si quieres:
with open('a.csv') as infile1, open('b.csv') as infile2, open('salida.txt', 'w') as outfile:
for line1, line2 in zip(infile1, infile2):
line1 = line1[:-1]
line2 = line2[:-1]
if line1.split(";")[5] == line2.split(";")[11]:
outfile.write("La línea es correcta\n")
else:
outfile.write("NO COINCIDEN LOS VALORES --> " + line1 + "\n")
Si trabajas a menudo con archivos csv te recomiendo que mires el módulo csv que pertenece a la biblioteca estandar de Python y facilita la lectura/escritura de este tipo de archivos.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maven and Eclipse : loading default properties in maven library project and use it in runnable Jar
I believe this problem has been asked before on stackoverflow. And I'd like to mention that I tried the solutions that came with the questions related to mine. The one that came the closest to my problem was:
Load properties file in JAR?. Sadly the solution described there didn't work for me. And due the age of the question I thought asking it again is the way to go.
Heading on to describing my problem.
So currently I'm working on a library project which has been setup with maven and creates an extension for the current Spring AMQP project.
The goal here is to supply a JAR file which can be included into another project to support a specific way of communicating over a message broker.
At this point I'm implementing the configuration option to allow users to configure the messaging client to their liking. But while i was testing the functionality of this feature I hit a problem while using the library in an executable JAR.
While running it in the Eclipse workspace everything seems to work just fine. But when I try to run it from my desktop (as a runnable JAR) the properties file does not seem to be found anywhere.
Just to give a quick overview of the workspace/projects setup as described above:
The project structure of both project reflects the Maven default one:
- src/main/java
- java source files
- src/main/resources
- resource files
- src/test/java
- java test files
- src/test/resources
- test resource files
Where the library file contains a default.properties file in the src/main/resources folder and the chatclient project a custom.properties file.
Once the runnable JAR file has been build it has the following structure in it.
- com
- junit
- META-INF
- org
- resources
- default.resources
- custom.resources
I believe the resource files should not be located there. but in the META-INF/maven folder instead. After trying out stuff like:
Adding a META-INF folder into my src/main/resources folder and putting the property files there.
Adding a MANIFEST file with Class-Path: . in it.
Loading the file in multiple ways in code.
But nothing seems to work. I guess it is Maven related and a simple change in the pom.xml could fix it. Sadly my knowledge on the Maven project setup and pom related subjects is very basic (this is my first project using maven). And I can't seem to find any documentation on it, even though I know it should be there (probably a problem caused by me).
Before I forget to mention it. I load the property files using this way:
Properties props = new Properties();
prop.load(<custom static class>.class.getResourceAsStream(filename));
return props;
Also the pom.xml for my library looks like:
-- Artifact stuff --
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
-- Dependency stuff --
And the one for the project that uses the library look like:
-- Artifact stuff --
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.maxxton</groupId>
<artifactId>async-amqp-messaging</artifactId>
<version>0.2</version>
</dependency>
</dependencies>
-- Other stuff --
I hope there is someone who's a little more advanced on this subject and could help find a solution for this problem. And if you need any additional information on the project files/structure, please let me know. I'd gladly share it with you.
Update (28-04-2015 {1})
For testing I created a sample project which tries to load property files the same way as the scenario described above.
Even while following the Maven documentation (Using the META-INF folder) I was not able to load the properties.
For the sake of this question I uploaded the testing workspace here.
I hope someone could help me fix this, as the normal way as described on the Maven website does not seem to work for me.
Update (28-04-2015 {2})
Well I managed to fix a part of the problem.
Since I added the configuration for the maven-assembly-plugin (building runnable JAR with deps), I was able to get the correct structure within my JAR file.
The thing I added was:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<finalName>project</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>com.test.project.Application</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Then when running clean compile assembly:single I managed to get the right structure.
JAR root
- com
- META-INF
- MANIFEST.MF
- default.properties
- custom.properties
While this fixes a part of the problem. The file loading still results in a NullPointerException.
Final Update (04-05-2015)
After a long Maven struggle I managed to get everything the way I want it to be.
Following the advice given by both @Deepak and @Joop Eggen, I did some research on how to have all the dependencies in a lib folder as jar instead of unpacking them in a 'uber' jar. After trying loads of stuff I stumbled upon this answer. Following the instruction there seems to create this structure:
- runnable.jar
- lib
- spring-amqp.jar
- spring-core.jar
...
When following @Joop Eggen's advice I managed to get the property loaded the way I want to. So it seems this question has been answered. Currently I'm still figuring out how to award each answer as I'm not able to split the bounty into two pieces. I'll get back on that.
Side Note
Although I awarded both the bounty and the answer to @Joop Eggen does not mean that @Deepak's answer did not contribute. It did give some great information on best practice, but was not as complete as the accepted answer. So please when finding your answer here give him some of the credit too.
A:
There are two ways to get resources,
with a ClassLoader against the entire class path using absolute paths (without /...),
with a class, using a relative (...) or absolute (/...) path inside the jar of that class.
The latter seems more direct, and can be used as:
getClass().getResource("/...");
ClassInJar.class.getResource("/...");
Now getClass() is only possible in a non-static object and is dangerous too: the actual class might be some child, not in the library jar.
On the actual structure of your application. I know a maven directory convention:
src/main/java/...
src/main/resources/...
where /... gets into the jar/war; the package directory.
Reassembling jars is not good. There always is the Class-Path: ... entry in META-INF/MANIFEST.MF. Following the basic maven conventions is best.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ponteiro Inválido
Tenho um projeto em Asp.Net MVC com Entity Framework 4.5, que criei limpo, mas ao tentar criar uma View recebo o seguinte mensagem:
Erro :
There was an error running the selected code generator : 'Ponteiro
inválido (Exception from HRESULT: 0x80004003 (E_POINTER))'
Você também pode visualizar o erro clicando aqui.
Procurei algo com o código apresentado, mas não encontrei nada.
Versão utilizada :
Community 2015 v 14.0.24720.00 Update 1.
A:
O problema estava sendo causado por alguma extensão, fiz a remoção e reinstalação de algumas delas, além da reinstalação do Visual Studio, e tudo passou a funcionar normalmente.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Locust command not found" returns even after I have installed Locust on Ubuntu
I have installed locust using the pip command and when I move forward towards verifying the installation using this command: locust -v , it throws the following line back: Command Not Found
Secondly, when i installed Locust, some statements showed up on console as can be seen in the image attached. Please share solutions!
enter image description here
A:
The message in yellow is the problem. add that directory to your PATH variable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Caldav server answers with 403
I am trying to connect to the Caldav server with a PHP client. I found this client library http://repo.or.cz/w/davical.git/blob/HEAD:/inc/caldav-client.php and I'm trying to follow the example, domain/username/password exchanged here.
$cal = new CalDAVClient( "http://192.168.10.11/caldav/users/domain.com/user-name/", "user-name", "password" );
$options = $cal->DoOptionsRequest();
if ( isset($options["PROPFIND"]) ) {
// Fetch some information about the events in that calendar
$cal->SetDepth(1);
$folder_xml = $cal->DoXMLRequest("PROPFIND", '<?xml version="1.0" encoding="utf-8" ?><propfind xmlns="DAV:"><prop><getcontentlength/><getcontenttype/><resourcetype/><getetag/></prop></propfind>' );
}
var_dump($folder_xml);exit;
That already gives me some 403 Forbidden back:
string(1928) "HTTP/1.1 207 Multi status
Connection: Close
Content-Type: text/xml; charset="utf-8"
Date: Fri, 2 Oct 2015 07:02:28 GMT
DAV: 1, access-control, calendar-access, calendar-schedule, calendar-proxy, calendar-availability, calendarserver-private-events, calendar-auto-schedule, calendarserver-principal-property-search, calendarserver-sharing, calendarserver-sharing-no-scheduling, addressbook, calendar-default-alarms
Server: Kerio Connect 8.5.1
Transfer-Encoding: chunked
X-UA-Compatible: IE=edge
584
<?xml version="1.0" encoding="UTF-8"?><a:multistatus xmlns:a="DAV:" xmlns:c="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/" xmlns:b="xml:"><a:response><a:href>/caldav/users/domain.com/user-name/</a:href><a:propstat><a:status>HTTP/1.1 200 OK</a:status><a:prop><a:resourcetype><a:collection/><a:principal/></a:resourcetype></a:prop></a:propstat><a:propstat><a:status>HTTP/1.1 403 Forbidden</a:status><a:prop><a:getcontentlength/><a:getcontenttype/><a:getetag/></a:prop></a:propstat></a:response><a:response xmlns:d="http://calendarserver.org/ns/"><a:href>/caldav/users/domain.com/user-name/calendar-proxy-write/</a:href><a:propstat><a:status>HTTP/1.1 200 OK</a:status><a:prop><a:resourcetype><a:collection/><a:principal/><d:calendar-proxy-write/></a:resourcetype></a:prop></a:propstat><a:propstat><a:status>HTTP/1.1 403 Forbidden</a:status><a:prop><a:getcontentlength/><a:getcontenttype/><a:getetag/></a:prop></a:propstat></a:response><a:response xmlns:e="http://calendarserver.org/ns/"><a:href>/caldav/users/domain.com/user-name/calendar-proxy-read/</a:href><a:propstat><a:status>HTTP/1.1 200 OK</a:status><a:prop><a:resourcetype><a:collection/><a:principal/><e:calendar-proxy-read/></a:resourcetype></a:prop></a:propstat><a:propstat><a:status>HTTP/1.1 403 Forbidden</a:status><a:prop><a:getcontentlength/><a:getcontenttype/><a:getetag/></a:prop></a:propstat></a:response></a:multistatus>
0
"
Any idea where I could look to fix the forbidden errors? I got no clue why I'm not getting anything.
edit:
I finally found some time to look further into this, but only found some logs, no solution yet. Can't figure out what goes wrong yet, but this is what I found in the logs
[07/Dec/2015 15:29:51][21240] {https} Task 202600 handler BEGIN
[07/Dec/2015 15:29:51][21240] {https} Task 202600 handler starting
[07/Dec/2015 15:29:51][21240] {https} HTTPS connection from 192.168.10.91:59937 started
[07/Dec/2015 15:29:51][21240] {https} PROPFIND request for URI /caldav/users/mydomain.com/myuser/
[07/Dec/2015 15:29:51][21240] {https} User-Agent header: DAViCalClient
[07/Dec/2015 15:29:51][21240] {webdav} PROPFIND /caldav/users/mydomain.com/myuser/ received from remote host='192.168.10.91', user-agent='DAViCalClient'
[07/Dec/2015 15:29:51][21240] {webdav} PropertyRequestReader: found property "getcontentlength" from namespace "DAV:"
[07/Dec/2015 15:29:51][21240] {webdav} PropertyRequestReader: found property "getcontenttype" from namespace "DAV:"
[07/Dec/2015 15:29:51][21240] {webdav} PropertyRequestReader: found property "resourcetype" from namespace "DAV:"
[07/Dec/2015 15:29:51][21240] {webdav} PropertyRequestReader: found property "getetag" from namespace "DAV:"
[07/Dec/2015 15:29:51][21240] {webdav} (B)PROPFIND: User [email protected] is listing properties of principal: myuser<_at_>mydomain.com
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontentlength" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontenttype" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getetag" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} (B)PROPFIND: User [email protected] is listing properties of principal: myuser<_at_>mydomain.com
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontentlength" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontenttype" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getetag" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} (B)PROPFIND: User [email protected] is listing properties of principal: myuser<_at_>mydomain.com
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontentlength" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getcontenttype" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {webdav} User: myuser<_at_>mydomain.com refers to an unsupported property: "getetag" of resource: "" using handler: "PrincipalHandler"
[07/Dec/2015 15:29:51][21240] {https} Response: HTTP/1.1 207 Multi status
[07/Dec/2015 15:29:51][21240] {https} Request finished in 0.00 s, received 373 bytes, sent 1916 bytes
[07/Dec/2015 15:29:51][21240] {https} Task 202600 handler END
A:
The problem is that you send the request to the user principal path, not to a calendar collection nor to the calendar home.
The properties DAV:getcontentlength, DAV:getcontenttype and DAV:getetag don't need to be defined for resources that don't support the GET request. As you can see in the response, the property DAV:resourcetype actually has a value which says it's a DAV:collection and a DAV:principal.
I think the developers at Kerio decided to return 403 instead of 404 for these properties, because these properties are not just absent because they have not been set yet, but because they are not applicable to the resource as such.
To find the calendars of your user you need to find the calendar home first. The user's calendars are located beneath his calendar-home.
To find the calendar-home just do a PROPFIND for the property CALDAV:calendar-home-set on the same path. This will return all calendar-homes (usually that's just one) the user owns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SilverStripe Blog GridfieldConfig Lumberjack Sort
SSTR 3.1.16, Blog 2.3.0 and lumberjack as required by blog -> ~1.1
I don't know how I am supposed to alter the GridfieldConfig in the Blog module generated by Lumberjack.
here it's generated:
https://github.com/silverstripe/silverstripe-blog/blob/master/code/model/Blog.php#L528
and overrides what is set here:
https://github.com/silverstripe/silverstripe-lumberjack/blob/1.1/code/extensions/Lumberjack.php#L131
Since I didn't get how to modify without hacking it, I tried Injector like this:
<?php
class BlogInj extends Blog {
public function getLumberjackGridFieldConfig() {
$ljgfc = GridFieldConfig_Lumberjack::create();
// $ljgfc->addComponent(new GridFieldOrderableRows('Sort'));
// $ljgfc->getComponentByType("GridFieldPaginator")->setItemsPerPage(100);
return $ljgfc;
}
}
config.yml
Injector:
Blog:
class: BlogInj
This shows the GF with the options set (commented out above) but as soon as a getLumberjackGridFieldConfig function exists on BlogInj Blog throws an Error on save like:
Error at line 763 of .../framework/core/Object.php
https://github.com/silverstripe/silverstripe-framework/blob/3.1/core/Object.php#L763
How am I supposed to modify Lumberjacks GF-Config in the first place? Or is Injector really what I should use an if so, what am I doing wrong?
A:
As Blog just returns a GridFieldConfig_BlogPost object you could try to subclass this instead.
class GridFieldConfig_MyBlogPost extends GridFieldConfig_BlogPost
{
public function __construct($itemsPerPage = null)
{
parent::__construct($itemsPerPage);
// do what you want...
}
}
And in your config.yml
Injector:
GridFieldConfig_BlogPost:
class: GridFieldConfig_MyBlogPost
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Polar coordinate double integral
I have to integrate the following integral:
$$
\iint \limits_A sin({x_1}^2 + {x_2}^2) dx_1dx_2
$$
over the set: $A=\{x \in \mathbb{R}^2: 1 \leq {x_1}^2 + {x_2}^2 \leq 9,x_1 \geq -x_2\}$
I understand geometrically what I have to do (i.e. subtract one half of a circle with of radius 1 from half of a circle of radius 3) but how do I use polar coordinates to calculate this interal?
A:
Hint: You can use that $1\le r\le 3 \text{ and } -\frac{\pi}{4}\le\theta\le\frac{3\pi}{4}$ to set up the integral.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why is this div below the other and not beside it?
I'm looking to get the yellow div containing 'vending machines | distributors etc' positioned next to the logo (right of the logo). Not sure why it's not working as it's floating left, but for some reason falls below the logo div. Can anybody tell me what mistake I am making?
body{
background-color:#fff;
padding:0px;
margin:0 auto;
}
#header-wrap{
width:100%;
height:100px;
margin: 0 auto;
background:#BABABA;
border-bottom: 1px solid #211c20;
border-top: 1px solid #211c20;
}
#header{
width:960px;
height:auto;
margin: 0 auto;
background:#72A1D9;
padding-top:15px;
}
.logo{
width:130px;
height:50px;
border:1px solid black;
padding-top:20px;
padding-left:50px;
font-size:24px;
}
.links{
background:#FFFD00;
float:left;
height:50px;
width:820px;
font-size:24px;
}
<div id="header-wrap">
<div id="header">
<div class="logo">LOGO</div>
<div class="links">VENDING MACHINES | DISTRIBUTORS | SUPPORT | CONTACT</div>
</div>
</div>
A:
Your class logo has to be float left too, and then your header width is 960 and your logo+links size is superior than 960px (130+50+2+820=1002px)
Correct css is
`
#header{
width:960px;
height:auto;
margin: 0 auto;
background:#72A1D9;
padding-top:15px;
}
.logo{
width:130px;
height:50px;
border:1px solid black;
padding-top:20px;
padding-left:50px;
font-size:24px;
float:left;
}
.links{
background:#FFFD00;
float:left;
height:50px;
width:778px;
font-size:24px;
}
`
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Inverse Modular Arithmetic
or example I have this expression:
$x^{11} \mod 41 = 10$
I need to find the value of x, never mind about the process of getting the answer.
What I need to know is how do I find the inverse of the expression?
I assume it would be something along the line $x = 10^{1/11} \mod 41$ if it is, how simplify the exponent? How can I get rid of it so I can work with integer exponent?
Thank you.
A:
$41$ is a prime number, so we know that, for $x\not\equiv0\pmod{41}$, $x^{40}\equiv1\pmod{41}$ (Fermat's little theorem).
Since $11$ is prime with $40$, we know there are $a$ and $b$ such that $11a+40b=1$: take $a=11$ and $b=-3$. Thus we see that
$$
(x^{11})^{11}=x^{121}=x^{3\cdot 40+1}\equiv x\pmod{41}
$$
So, if $x^{11}\equiv 10\pmod{41}$, we also have
$$
x\equiv 10^{11}\pmod{41}
$$
It's not hard to see that $10^{11}\equiv 10\pmod{41}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Betting after all-in/showdown
No limit Texas Holdem, 100/200, 4 players, preflop
player 1 stack - 600,
player 2 stack - 700,
player 3 stack - 5000,
player 4 stack - 3500
First player goes all in for 600 chips
Second player goes all in for 700 chips
Third player calls
Fourth player calls
Should players 1 and 2 show their cards (as there are no actions available for them) or the next betting round will go with all the player cards facing down the table?
A:
As long as other active players are in the hand, the cards should be kept face down, so as not to influence the decisions of the other players.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MS Access : Can we edit the Macro in VBA? and how?
The Scenario:
So I have a form called FormA, and that form has a button called buttonA. When I click buttonA it runs a Macro that will open a form, FormB.
The Question:
Can I edit the Macro in VBA? Making it open FormC instead.
A:
You can export the code from a macro using;
Application.SaveAsText acMacro, <MacroName>, <Filename>
and then you can import code back after editing using;
Application.LoadFromText acMacro, <MacroName>, <Filename>
The text content of the macro isn't VBA but you could probably edit it successfully.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it a good idea to use NSDecimalNumber for floating point arithmetics instead of plain double?
I wonder what's the point of NSDecimalNumber. It offers some arithmetics methods, but why should I use NSDecimalNumber and not just double or NSNumber? Did apple take care of some floating point arithmetics uglyness there? Would it make life easier when making heavy use of high precision and big floating point maths?
A:
This all depends or your needs.
It is a trade off between precision, speed and size of data.
If you are writing an accounting application you cannot lose any precision and so might well use NSDecimal number.
Ig you are doing complex numerical analysis the speed could matter and so NSDecimalNumber would be too slow. But even in that case your analysis would look at the precision and errors you could afford and here could be cases where you need more precision that doubles etc give you.
NSNumber is a separate case it is a class cluster to allow storage of C type numbers in other objects and other use in Cocoa.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Let's move some negatively scored answers from the top spot
Internally, we've been discussing how we can deal with obsolete or out-of-date answers. A few weeks ago, I requested some feedback on how to encourage edits to these types of answers, while I'm still wading through everything on that post but now I'm focusing my attention on the problem of negatively scored accepted answers.
There are three sorting options to display answers on a question:
active – based on last activity/edit
oldest – based on date posted
votes – score based
In each of these options the accepted answer is pinned to the top of the sorting order, unless it’s a self-answer by the OP. The "pinning" also applies to negatively scored answers. No matter which sorting option is selected by a user the accepted answer appears at the top. If you have the same question and the accepted answer is negatively scored, you’ll end up with a view like this:
Over the years, there have been many requests to change the behavior of these types of answers:
Can we exempt downvoted accepted answers from getting the top spot?
Keeping special status for Accepted Answers without sticking them to top forever?
Why are negative score accepted answers still at the top?
Don't put heavily downvoted accepted answers at the top
Plus many, many others.
Well, I think it might be time to implement a change to some of these negatively-scored accepted answers.
Proposed Solution
An accepted answer will no longer be pinned to the top spot if it is negatively scored and has hit the threshold to get the lightened greyish color (e.g., ≤ −3 on Stack Overflow)
When the accepted answer is unpinned, it will be sorted naturally based on the sort order selected by the user (active, oldest, votes)
If an accepted answer accumulates upvotes and gets ungreyed, it will take the top, “pinned” spot again
Here are a few numbers of the questions that would be impacted by this change.
+----------------+------------------------------+------------------------------------+
| Site Name | Questions w/ Accepted Answer | Questions w/ <=-3 & Another Higher |
| | <=- 3 | Scoring Other Answer |
+----------------+------------------------------+------------------------------------+
| Stack Overflow | 1097 | 897 |
| Mathematics | 17 | 12 |
| Super User | 14 | 9 |
| ELU | 20 | 13 |
| Server Fault | 14 | 11 |
| SO in Russian | 11 | 7 |
| Physics | 14 | 11 |
| Gaming | 10 | 8 |
+----------------+------------------------------+------------------------------------+
Currently on Stack Overflow, there are 1097 questions that have an answer that is ≤ −3. Of these 897 questions have another answer that is scored higher, so these accepted answers would no longer be pinned to the top spot in the default view (votes). Additionally, they would not appear before newly- posted or updated answers in the "active" sort, which might aid somewhat in giving attention to answers that have been created or edited specifically to address problems with the accepted answer.
While this doesn't handle all negatively scored accepted answers, it's a start to get the eyesore of heavily downvoted stuff out of the way for other answers.
A:
I feel this does too much (move accepted answers way down, where an unpopular but valuable dissenting advice may be lost), and simultaneously not enough (still keeping lackluster fastest-typist accepted answer on top).
Jeff Atwood wrote way back in the days:
in the default sort order (votes), the answer the community likes best will be either:
Directly under the question
Directly under the accepted answer, if there is an accepted answer
I suggest just flipping the order here:
in the default sort order (votes), the answer the OP likes best will be either:
Directly under the question
Directly under the top voted answer, if it isn't top voted itself.
This could be applied in all cases (no need for an arbitrary -3 threshold), without risk of burying unpopular dissenting voices.
As for the active and oldest sorts, I never understood the logic of pinning accepted answers there: the user explicitly asks for a chronological list, not for what's the best solution. Accepted answers should not have any special treatment in those sorts.
A:
I don't have too much of a problem with this proposal. It mitigates any problems with the OP being careless, but does it in a way that doesn't really take away the OP's ability to pin a tested answer.
I don't, however, want to remove the OP's power to pin an answer too much. The OP is the one who has to actually implement the solution. Other voters might just read the answer over, say "that looks all right" and upvote without truly testing the answer.
Counterpoint:
The above applies to Stack Exchanges like Super User and Stack Overflow, but there are other SEs, such as Skeptics where answers tend to be more informational.
On these SEs, The OP is not actually expected to implement the answer in the way they would on SO. The OP can only evaluate the answer's correctness academically, like everyone else does.
On these kinds of Stack Exchange sites, it actually would make more sense to take some power away from the OP and give it to the community.
A:
I like this idea, and I especially like it as a first step toward possibly revamping how we handle accepted answers more broadly. Ideally, answers would be sorted by score, period, like they are when there's a self-acceptance. The usual objection to that is "but the accepted answer needs to be easy to find" (this argument doesn't have a good response for self-answers).
To address that and move us closer to better sorting overall, maybe an idea I proposed on an earlier question would help here: Add a link under the question to jump to the accepted answer, wherever it is on the page:
Perhaps it would be a different shade of green (or different color), and maybe it should be bigger. And maybe it has a graphical component, like the check mark, and isn't just text. This is a rough mockup, not a precise proposal. Consult actual designers for implementation.
This allows the reader to jump straight to the accepted answer -- whether it was a lower-scoring self-answer, a significantly-downvoted answer, or whatever other criteria come into play later.
For consistency I would do this on all questions that have accepted answers, even where the accepted answer is first -- you might still want to skip past 23 comments and a post notice, after all.
If you make this small change (in advance of larger changes), the metrics gathered from it might inform the larger discussion of whether to unpin all accepted answers. Knowing how many people use the link to jump straight to it seems helpful. Granted, there's no way to know how many people scroll/page for it, so it's an imperfect metric -- the absence of clicks doesn't tell us as much as we'd like, but the presence of them would.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java "pool" of longs or Oracle sequence that reuses released values
Several months ago I implemented a solution to choose unique values from a range between 1 and 65535 (16 bits). This range is used to generate unique Route Targets suffixes, which for this customer massive network (it's a huge ISP) are a very disputed resource, so any released value needs to become immediately available to the end user.
To tackle this requirement I used a BitSet. Allocate a suffix on the RT index with set and deallocate a suffix with clear. The method nextClearBit() can find the next available value. I handle synchronization / concurrency issues manually.
This works pretty well for a small range... The entire index is small (around 10k), it is blazing fast and can be easy serialized and stored in a blob field.
The problem is, some new devices can handle RT suffixes of 32 bits unsigned (range 1 / 4294967296). Which can't be managed with a BitSet (it would, by itself, consume around 600Mb, plus be limited to int - 32 bits signed - range). Even with this massive range available, the client still wants to free Route Target suffixes that become available to the end user, mainly because the lowest ones (up to 65535) - which are compatible with old routers - are being heavily disputed.
Before I tell the customer that this is impossible and he will have to conform with my reusable index for lower RTs (up to 65550) and use a database sequence for the other ones (which means that when the user frees a Route Target, it will not become available again), would anyone shed some light?
Maybe some kind soul already implemented a high performance number pool for Java (6 if it matters), or I am missing a killer feature of Oracle database (11R2 if it matters)... Just some wishful thinking :).
Thank you very much in advance.
A:
This project may be of some use.
A:
I would combine the following:
your current BitSet solution for 1-65535
PLUS
Oracle-based solution with a sequence for 65536 - 4294967296 which wraps around defined as
CREATE SEQUENCE MyIDSequence
MINVALUE 65536
MAXVALUE 4294967296
START WITH 65536
INCREMENT BY 1
CYCLE
NOCACHE
ORDER;
This sequence gives you ordered values in the specified range and allows for reuse of any values but only after the maximum is reached - which should allow enough time for the values being released... if need be you can keep track of values in use in a table and just increment further if the returned value is already in use - all this can be wrapped nicely into a stored procedure for convenience...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails, getting each routes "parts" array
I'm trying to output the "parts" for each route in my application, I have some code like this:
route = Rails.application.routes.routes.first
puts route.path.build_formatter
I see the output:
=> #<ActionDispatch::Journey::Format:0x007ff2c8f0c748
@children=[6],
@parameters=[],
@parts=
["/",
"rails",
"/",
"info",
"/",
"properties",
#<ActionDispatch::Journey::Format:0x007ff2c8f0c928
@children=[],
@parameters=[1],
@parts=
[".",
#<struct ActionDispatch::Journey::Format::Parameter
name=:format,
escaper=
#<Proc:0x007ff2c1c02c70@/Users/{..}/lib/action_dispatch/journey/visitors.rb:6 (lambda)>>]>]>
In the output I see this array:
["/",
"rails",
"/",
"info",
"/",
"properties",
How can I get that array for each route in my application? It's easy for me to get it as a string, and then split it all back out, but I would like to know how to get this more directly from Rails, any tips?
A:
instance_variable_get("@parts")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
d3.js dynamically setting "stroke-width" on a path
I have a question very similar to this one regarding dynamically setting the "stroke-width" attribute on a path. The solution offered was to pass the results of a function to the "stroke-width" attr for each path, which makes perfect sense but I cannot manage to get this to work.
Here is the statement that has me stumped:
.attr("stroke-width", function(d) { return (d.interest * 50); })
(The above works just fine and sets the path attr if a substitute an number like "5" for the function.)
Here is the full code:
<!doctype html></html>
<meta charset="utf-8" />
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 16px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var width = 800;
var height = 500;
var cluster = d3.layout.cluster()
.size([height, width-200]);
var diagonal = d3.svg.diagonal()
.projection (function(d) { return [d.y, d.x];});
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height)
.append("g")
.attr("transform","translate(100,0)");
d3.json("data.json", function(error, root){
var nodes = cluster.nodes(root);
var links = cluster.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class","link")
.attr("stroke-width", function(d) { return (d.interest * 50); })
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class","node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
node.append("circle")
.attr("r", function(d) { return d.interest * 50 ;});
node.append("text")
.attr("dx", function(d) { return (d.interest * 50) ;})
.attr("dy", function(d) { return -(d.interest * 50) ;})
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text( function(d){ return d.name + " ("+ d.interest*100 + "%)";});
});
</script>
And here is sample JSON:
{
"name": "Root",
"date": 1950,
"interest": 1.0,
"children": [
{
"name": "Anne",
"date": 1970,
"interest": 0.5,
"children": [
{
"name": "Charles",
"date": 1988,
"interest": 0.25,
"children": [
{
"name": "Frank",
"date": 2010,
"interest": 0.125,
"children": []
},
{
"name": "Gina",
"date": 2010,
"interest": 0.125,
"children": []
}
]
},
{
"name": "Diane",
"date": 1995,
"interest": 0.25,
"children": [
{
"name": "Harley",
"date": 2015,
"interest": 0.25,
"children": []
}
]
}
]
},
{
"name": "Ben",
"date": 1970,
"interest": 0.5,
"children": [
{
"name": "Erin",
"date": 1970,
"interest": 0.5,
"children": [
{
"name": "Ingrid",
"date": 1970,
"interest": 0.16665,
"children": []
},
{
"name": "Jack",
"date": 1970,
"interest": 0.16665,
"children": []
},
{
"name": "Kelsey",
"date": 1970,
"interest": 0.16665,
"children": []
}
]
}
]
}
]
}
A:
Thanks to @AmeliaBR I was able to get the stroke-width to work as I desired. I changed the reference to the value from d.interest to d.target.interest as follows:
.attr("stroke-width", function(d) { return (d.target.interest * 50); })
I really appreciate the guidance and help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CryptoJS cannot compare with pre-hashed data
i have a password table which containes SHA1 hashed data. so i want to make a validation input with CryptoJS. it went error.. but when i try to display it, the result matched.. did i code a wrong function?
here's my code
function checkCurPass()
{
var hash = CryptoJS.SHA1("<?php echo $selected->password ?>");
var currentPass = document.getElementById('users-profile-currentpassword');
var hashedPass = CryptoJS.SHA1(currentPass.value);
var message = document.getElementById('mesas');
message.innerHTML = hashedPass;
if (hashedPass == hash)
{
$('#currentPassForm').addClass('has-success').removeClass('has-error');
}
else
{
$('#currentPassForm').addClass('has-error').removeClass('has-success');
}
}
screenshot with hashed 'default'
A:
Your hashes are no strings, but objects. If you console.log(hash), you'll see this. In order to get a proper hex string from these hashes, call hash.toString(CryptoJS.enc.Hex) and hashedPass.toString(CryptoJS.enc.Hex) respectively.
When you display your hash in your message element, toString is called implicitly, thats why the displayed strings were equal.
See http://codepen.io/anon/pen/BNxjGm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Express: How to require a file in node js express and pass a parameter value to it?
This question has a big relation with How to require a file in node.js and pass an argument in the request method, but not to the module?
-- Question.
I have a node js Express app. when visitor visits http://localhost/getPosts, the main node js file requires ./routes/posts file and sends a database connection to the required file.
app.use('/getPosts', require('./routes/posts')(myDatabase));
the content of ./routes/posts file is given below:
var express = require('express');
var router = express.Router();
//Do something with myDatabase here
router.get('/', (req, res, next) => {
res.render('index');
});
module.exports = router;
My website has multiple pages that is, database connection is required on multiple pages. But it is not possible to make mutiple connection to the same database with the same client(Node JS server). that is why I tried adding the connection code in the main page.
how do I get the myDatabase variable on the commented area of the code ?
A:
You should export a function that returns the router, like that:
module.exports = dbConnection => {
var express = require('express');
var router = express.Router();
router.get('/', (req, res, next) => {
res.render('index');
});
return router;
};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# While Loop vs For Loop?
In C# a question has been bugging me for a while and its what is that actual major difference between a While and For Loop. Is it just purely readability ie; everything you can essentially do in a for loop can be done in a while loop , just in different places. So take these examples:
int num = 3;
while (num < 10)
{
Console.WriteLine(num);
num++;
}
vs
for (int x = 3; x < 10; x++)
{
Console.WriteLine(x);
}
Both code loops produce the same outcome and is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start? Maybe I'm missing something else in terms of any major differences but it would good if someone can set me straight regarding this. Thanks.
A:
is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start?
The for loop forces you to nothing. You can omit any of the 3 elements. The smallest form is
for(;;) // forever
{
DoSomething();
}
But you can use the 3 elements to write more concise code:
for(initializer; loop-condition; update-expression)
{
controlled-statements;
}
is equivalent to:
{
initializer;
while(loop-condition)
{
controlled-statements;
continue_target: // goto here to emulate continue
update-expression;
}
}
Note the outer {} braces, in for(int i = 0; ...; ...) the i is local to the for-loop. A clear benefit.
But the major difference in usage is when you call continue; inside the loop, much easier to get the logic wrong in a while-loop than in a for-loop.
A:
Yes, they're exactly the same in the background (in Assembly, that is).
Usually, it is more common to use the for loop when the number of repeats is known and we're not going to change our counter(index).
while loop also has the advantage of a sentinel loop which is easier for example when taking inputs from a user until something specific is given.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GMT retorna -0306 ao invés de -0300, qual o motivo?
Locale ptBR = new Locale("pt", "BR");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy", ptBR);
SimpleDateFormat iso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ");
GregorianCalendar calendar = new GregorianCalendar(ptBR);
String data = "31/12/1900";
calendar.setTime(sdf.parse(data));
iso.setTimeZone(calendar.getTimeZone());
System.out.println(iso.format(calendar.getTime()));
Saida: 1900-12-31T00:00:00.000-0306
Alguém sabe me explicar por que o GMT retorna -0306 ao invés de -0300?
A:
Até 1914, o Brasil utilizava o LMT (Local Mean Time) como referência de horário. A partir desse ano, passou a adotar diferentes zonas horárias, com diferenças em horas redondas em relação ao UTC. O LMT é baseado na longitude, por isso havia diferenças de frações de hora de uma localidade para outra.
Com a regulamentação das zonas horárias oficiais por decreto em 1913 (vigente a partir de 1/1/1914), as pequenas diferenças entre as localidades foram normalizadas, como se vê na tabela constante de tal decreto:
Repare que em 1/1/1914 o horário de São Paulo deveria ser corrigido em 6m35s. Acredito que seja essa diferença que o seu código está mostrando.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simple regex to match strings containing chars
I'm writing this regexp as i need a method to find strings that does not have n dots,
I though that negative look ahead would be the best choice, so far my regexp is:
"^(?!\\.{3})$"
The way i read this is, between start and end of the string, there can be more or less then 3 dots but not 3.
Surprisingly for me this is not matching hello.here.im.greetings
Which instead i would expect to match.
I'm writing in Java so its a Perl like flavor, i'm not escaping the curly braces as its not needed in Java
Any advice?
A:
You're on the right track:
"^(?!(?:[^.]*\\.){3}[^.]*$)"
will work as expected.
Your regex means
^ # Match the start of the string
(?!\\.{3}) # Make sure that there aren't three dots at the current position
$ # Match the end of the string
so it could only ever match the empty string.
My regex means:
^ # Match the start of the string
(?! # Make sure it's impossible to match...
(?: # the following:
[^.]* # any number of characters except dots
\\. # followed by a dot
){3} # exactly three times.
[^.]* # Now match only non-dot characters
$ # until the end of the string.
) # End of lookahead
Use it as follows:
Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Boy finds cave with ruins of a tiny civilization
About 25 years ago I read a book that for years I've tried to find. I remember nothing of the title or author, but I do remember the plot. My last question about a novel worked out so well I thought I'd try again.
A boy moves and has to live with his grandparents I think? And as he's exploring the outskirts of the new little town he's living in he stumbles across a cave, and in the cave buried in the sand he finds this kind of Native American pueblo type place but at a miniature scale. He thinks it's a model but at some point he comes to the conclusion that it was a real town of little people.
He has trouble at school and I remember at one point some of the bullies from school find and kind of threaten to destroy the place.
Any one read this one?
A few other odd details I remember:
He either bought, or was given a derringer, where the safety was a jewel in the handle of the gun, which at one point saves him as someone that tries to shoot him doesn't know how to deactivate the safety.
There was a "jail" or...cage of some sort in this miniature town made from rattlesnake fangs, which I think continued to have poison and which scratched a kid and nearly killed him.
A:
I found it. It was called Through the Hidden Door, by Rosemary Wells, first published in 1987.
Before I posted this question, I hadn't bothered merely Googling. I didn't, because I have many times over the years and never found anything. After posting the question I decided I probably should have tried again. Eventually I searched for "book about a boy who finds a cave with a miniature native american ruin" and one of the results was the goodreads.com link I posted above. As soon as I saw the title of the book I knew that was it.
As can happen when you read a book as a kid, the disturbing parts of this story didn't seem that odd. Now, when I think how harsh it was, combined with kind of a whimsical fantasy element like finding a cave of little people ruins, it seems odd that I liked it so much. Many of the reviews on that page note that parts of the book are disturbing, and it is more of a book about bullying and being bullied than fantasy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Identify loops in java byte code
I am trying to instrument java byte code.
I want to recognize the entry and exit of a java loop, but I have found the identification of loops to be quite challenging.
I have spent a good few hours looking at ASM and open source de-compilers (whom I thought must solve this problem all the time), however, I came up short.
The tool I am augmenting / extending, is using ASM, so ideally I would like to know how to instrument the entry and exit of the different loop constructs in java via ASM. However, I would also welcome a recommendation for a good open source de-compiler, as clearly they would have solved the same problem.
A:
EDIT 4: A bit of background/preamble.
"The only way to jump backward in the code is via a loop." in Peter's answer isn't strictly true. You could jump back and forth without it meaning it's a loop. A simplified case would be something like this:
0: goto 2
1: goto 3
2: goto 1
Of course, this particular example is very artificial and a bit silly. However, making assumptions as to how the source-to-bytecode compiler is going to behave could lead to surprises. As Peter and I have shown in our respective answers, two popular compilers can produce a rather different output (even without obfuscation). It rarely matters, because all of this tends to be optimised rather well by the JIT compiler when you execute the code.
This being said, in the vast majority of cases, jumping backwards will be a reasonable indication as to where a loop starts. Compared with the rest, finding out the entry point of a loop is the "easy" part.
Before considering any loop start/exit instrumentation, you should look into the definitions of what entry, exit and successors are. Although a loop will only have one entry point, it may have multiple exit points and/or multiple successors, typically caused by break statements (sometimes with labels), return statements and/or exceptions (explicitly caught or not). While you haven't given details regarding the kind of instrumentations you're investigating, it's certainly worth considering where you want to insert code (if that's what you want to do). Typically, some instrumentation may have to be done before each exit statement or instead of each successor statement (in which case you'll have to move the original statement).
Soot is a good framework to do this. It has a number of intermediate representations that make bytecode analysis more convenient (e.g. Jimple).
You can build a BlockGraph based on your method body, for example an ExceptionalBlockGraph. Once you've decomposed the control flow graph into such a block graph, from the nodes, you should be able to identity the dominators (i.e. blocks that have an arrow coming back to them). This will give you the start of the loop.
You may find something similar done in sections 4.3 to 4.7 of this dissertation.
EDIT:
Following the discussion with @Peter in comments to his answer. Talking the same example:
public int foo(int i, int j) {
while (true) {
try {
while (i < j)
i = j++ / i;
} catch (RuntimeException re) {
i = 10;
continue;
}
break;
}
return j;
}
This time, compiled with the Eclipse compiler (no specific option: simply autocompilation from within the IDE).
This code hasn't been obfuscated (apart from being bad code, but that's a different matter).
Here is the result (from javap -c):
public int foo(int, int);
Code:
0: goto 10
3: iload_2
4: iinc 2, 1
7: iload_1
8: idiv
9: istore_1
10: iload_1
11: iload_2
12: if_icmplt 3
15: goto 25
18: astore_3
19: bipush 10
21: istore_1
22: goto 10
25: iload_2
26: ireturn
Exception table:
from to target type
0 15 18 Class java/lang/RuntimeException
There is a loop between 3 and 12 (jumped in starting a 10) and another loop, due to the exception occurring from the division by zero at 8 to 22.
Unlike the javac compiler result, where one could make as guess that there was an outer loop between 0 and 22 and an inner loop between 0 and 12, the nesting is less obvious here.
EDIT 2:
To illustrate the kind of problems you may get with a less awkward example. Here is a relatively simple loop:
public void foo2() {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
After (normal) compilation within Eclipse, javap -c gives this:
public void foo2();
Code:
0: iconst_0
1: istore_1
2: goto 15
5: getstatic #25; //Field java/lang/System.out:Ljava/io/PrintStream;
8: iload_1
9: invokevirtual #31; //Method java/io/PrintStream.println:(I)V
12: iinc 1, 1
15: iload_1
16: iconst_5
17: if_icmplt 5
20: return
Before doing anything within the loop, you jump straight from 2 to 15. Block 15 to 17 is the header of the loop (the "entry point"). Sometimes, the header block could contain far more instructions, especially if the exit condition involves more evaluation, or if it's a do {} while() loop.
The concept of "entry" and "exit" of a loop may not always reflect what you'd write sensibly as Java source code (including the fact that you can rewrite for loops as while loops, for example). Using break can also lead to multiple exit points.
By the way, by "block", I mean a sequence of bytecode into which you can't jump and out of which you can't jump in the middle: they're only entered from the first line (not necessarily from the previous line, possibly from a jump from somewhere else) and exited from the last (not necessarily to the following line, it can jump somewhere else too).
EDIT 3:
It seems that new classes/methods to analyse loops have been added since last time I had looked at Soot, which make it a bit more convenient.
Here is a complete example.
The class/method to analyse (TestLoop.foo())
public class TestLoop {
public void foo() {
for (int j = 0; j < 2; j++) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
}
When compiled by the Eclipse compiler, this produces this bytecode (javap -c):
public void foo();
Code:
0: iconst_0
1: istore_1
2: goto 28
5: iconst_0
6: istore_2
7: goto 20
10: getstatic #25; //Field java/lang/System.out:Ljava/io/PrintStream;
13: iload_2
14: invokevirtual #31; //Method java/io/PrintStream.println:(I)V
17: iinc 2, 1
20: iload_2
21: iconst_5
22: if_icmplt 10
25: iinc 1, 1
28: iload_1
29: iconst_2
30: if_icmplt 5
33: return
Here is a program that loads the class (assuming it's on the classpath here) using Soot and displays its blocks and loops:
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.toolkits.annotation.logic.Loop;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.BlockGraph;
import soot.toolkits.graph.ExceptionalBlockGraph;
import soot.toolkits.graph.LoopNestTree;
public class DisplayLoops {
public static void main(String[] args) throws Exception {
SootClass sootClass = Scene.v().loadClassAndSupport("TestLoop");
sootClass.setApplicationClass();
Body body = null;
for (SootMethod method : sootClass.getMethods()) {
if (method.getName().equals("foo")) {
if (method.isConcrete()) {
body = method.retrieveActiveBody();
break;
}
}
}
System.out.println("**** Body ****");
System.out.println(body);
System.out.println();
System.out.println("**** Blocks ****");
BlockGraph blockGraph = new ExceptionalBlockGraph(body);
for (Block block : blockGraph.getBlocks()) {
System.out.println(block);
}
System.out.println();
System.out.println("**** Loops ****");
LoopNestTree loopNestTree = new LoopNestTree(body);
for (Loop loop : loopNestTree) {
System.out.println("Found a loop with head: " + loop.getHead());
}
}
}
Check the Soot documentation for more details on how to load classes. The Body is a model for the body of the loop, i.e. all the statements made from the bytecode. This uses the intermediate Jimple representation, which is equivalent to the bytecode, but easier to analyse and process.
Here is the output of this program:
Body:
public void foo()
{
TestLoop r0;
int i0, i1;
java.io.PrintStream $r1;
r0 := @this: TestLoop;
i0 = 0;
goto label3;
label0:
i1 = 0;
goto label2;
label1:
$r1 = <java.lang.System: java.io.PrintStream out>;
virtualinvoke $r1.<java.io.PrintStream: void println(int)>(i1);
i1 = i1 + 1;
label2:
if i1 < 5 goto label1;
i0 = i0 + 1;
label3:
if i0 < 2 goto label0;
return;
}
Blocks:
Block 0:
[preds: ] [succs: 5 ]
r0 := @this: TestLoop;
i0 = 0;
goto [?= (branch)];
Block 1:
[preds: 5 ] [succs: 3 ]
i1 = 0;
goto [?= (branch)];
Block 2:
[preds: 3 ] [succs: 3 ]
$r1 = <java.lang.System: java.io.PrintStream out>;
virtualinvoke $r1.<java.io.PrintStream: void println(int)>(i1);
i1 = i1 + 1;
Block 3:
[preds: 1 2 ] [succs: 4 2 ]
if i1 < 5 goto $r1 = <java.lang.System: java.io.PrintStream out>;
Block 4:
[preds: 3 ] [succs: 5 ]
i0 = i0 + 1;
Block 5:
[preds: 0 4 ] [succs: 6 1 ]
if i0 < 2 goto i1 = 0;
Block 6:
[preds: 5 ] [succs: ]
return;
Loops:
Found a loop with head: if i1 < 5 goto $r1 = <java.lang.System: java.io.PrintStream out>
Found a loop with head: if i0 < 2 goto i1 = 0
LoopNestTree uses LoopFinder, which uses an ExceptionalBlockGraph to build the list of blocks.
The Loop class will give you the entry statement and the exit statements. You should then be able to add extra statements if you wish. Jimple is quite convenient for this (it's close enough to the bytecode, but has a slightly higher level so as not to deal with everything manually). You can then output your modified .class file if needed. (See the Soot documentation for this.)
A:
The only way to jump backward in the code is via a loop. So you are looking for a goto,if_icmplt etc which goes to a previous byte code instruction. Once you have found the end of the loop and where it jumps back to is the start of the loop.
Here is a complex example, from the document Bruno suggested.
public int foo(int i, int j) {
while (true) {
try {
while (i < j)
i = j++ / i;
} catch (RuntimeException re) {
i = 10;
continue;
}
break;
}
return j;
}
The byte-code for this appears in javap -c as
public int foo(int, int);
Code:
0: iload_1
1: iload_2
2: if_icmpge 15
5: iload_2
6: iinc 2, 1
9: iload_1
10: idiv
11: istore_1
12: goto 0
15: goto 25
18: astore_3
19: bipush 10
21: istore_1
22: goto 0
25: iload_2
26: ireturn
Exception table:
from to target type
0 15 18 Class java/lang/RuntimeException
You can see there is an inner loop between 0 and 12, a try/catch block between 0 and 15 and an outer loop between 0 and 22.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.