source
list | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0019068695.txt"
] |
Q:
using dialog inside of onitemclicklistener, getting unfortunately stopped
I'm trying to create dialog inside of onitemclicklistener.
public void onItemClick(AdapterView<?> av, View view, int position, long arg3) {
String data = values[position];
Dialog d = new Dialog(null);
TextView t = new TextView(null);
t.setText(data);
d.setTitle("Okey!");
d.show();
}
There is no problem with other things. Problem is dialog. I know because when I remove dialog everything is done. I've looked here. That say something about context class. I'm newbie and I can't get what is that. What is the problem? and how can i use dialog, right?
A:
Both Dialog and TextView constructors should be passed a Context object, but you are passing them null.
Since your activity extends Context, you may pass an instance of your activity.
Assuming the name of your activity is MainActivity then you would do this:
Dialog d = new Dialog(MainActivity.this);
TextView t = new TextView(MainActivity.this);
//...
|
[
"stackoverflow",
"0052126615.txt"
] |
Q:
Layering masks in CSS
I'm trying to figure out if it is possible layer masks in CSS. Basically I have an SVG which denotes some kind of stage. This is displayed as a mask using mask-image and has a black background-color. Something along the lines of:
mask-image: url(image.svg);
background-color: #000;
...
Depending on some related state, I need to draw attention to that masked svg by layering another svg over it, for example and exclamation mark. This would have another colour, for example red, but could change depending on the circumstance.
A crude example is shown below where I have a button with some text. The square is an svg which only appears when some state (state A) exists, in which case a class is added to the div. The circle inside the square is the related state and only appears when square is state A is true, plus some additional state. So in a Less/BEM structure, this extra state would be implemented as a modifier as such:
&__state {
mask-image: url(state.svg);
background-color: #000;
...
&--inner-state {
mask-image: url(inner-state.svg);
background-color: red;
...
}
}
The button doesn't know anything about the svgs as I am dynamically adding divs and the above CSS depending on the state.
Is this easily doable in CSS? As mentioned, I'm using Less with a BEM structure but I don't necessarily need an answer related to those. I'm more interested in the concept.
Feel free to ask for more info if required and I would appreciate any help!
A:
(Posting another answer because this is super different)
Demo:
(Ideally you should read explanation first but in case you want to see the final result first...)
Frontend: https://codepen.io/devanshj/pen/OomRer
Backend: https://glitch.com/edit/#!/mature-teller?path=server.js:8:0
Explanation:
I was unable understand what are you trying to achieve with those masks and backgrounds (instead of direct svgs) till I came across this article: Coloring SVGs in CSS Background Images...
The reason solution(s) in this article doesn't work for you is because you want multiple colored svgs (and the solution in the article is for single svg only)
Combining the problem that the article tackles, with what you want as a final goal, I would reframe the question something like this:
I want to have multiple svg backgrounds on an element
I also want to control the color of the each svg
Only css solution. You are not allowed to change html.
This is pretty impossible. "pretty" I said, hence it's possible (with super extra-ordinary solution).
The pretty impossible part is coloring the svg. Multiple svg backgrounds with only css is simple.
But what if I do something that colors the svg from the url itself, like url(my-icon.svg?fill=#f00) If I can do this your problem is solved and we can do something like:
.icon-a{
background-image: url("a.svg?fill=%23000"); // # encoded to %23 so that server doesn't think #000 is the hash part of the request
&.icon-b{
background-image: url("a.svg?fill=%23000"), url("b.svg?fill=%23fff");
&:hover{
background-image: url("a.svg?fill=%23000"), url("b.svg?fill=%23f00");
}
}
}
This can be done with a little server code (using express and nodejs here, similar code can be written for other languages/frameworks too):
app.get("/icons/*.svg", async (req, res) => {
let svgCode = await readFileAsync(path.join(__dirname, req.path), {encoding: "utf8"});
svgCode = svgCode.replace(/{{queryFill}}/g, req.query.fill);
res.set("Content-Type", "image/svg+xml");
res.send(svgCode);
});
and svg:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
.query-fill{
fill: {{queryFill}};
}
</style>
<rect x="0" y="0" width="100" height="100" class="query-fill"></rect>
</svg>
Alternative:
If you allow me to change the html, the solution will be super easy by using inline svg and <use>... But I guess you want css-only solution...
PS: In case you are wondering is there any solution without any server code? No.
PPS : If the reframed question is not what you want, then the thing that you are looking for (layered masks) is not possible with only css.
|
[
"stackoverflow",
"0016072433.txt"
] |
Q:
C# Font display OpenGL
I am developing a 2D CAD application by using Tao framework in windows. I would like to use the fonts from windows libraries to display the drawing information. In addition to that I would like to rotate scale my text. With Bitmap fonts I could not do this.
I went through OpenGL font survey [http://www.opengl.org/archives/resources/features/fontsurvey/] but most of them are C++ based APIs.
Could you guide me what are the available solutions in C#?
A:
For 3D I have followed the examples I found with relation to OpenTK which is compatible with the Tao.Framework.
public void AddTexture(Bitmap texture, bool mipmaped)
{
this.tex_id = World.LoadTexture(texture, mipmaped);
}
public void AddText(string text, Color color, float x, float y, float scale)
{
const int side = 256;
Bitmap texture = new Bitmap(side, side, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(texture);
using (Brush brush = new SolidBrush(Color))
{
g.FillRectangle(brush, new Rectangle(Point.Empty, texture.Size));
}
using (Font font = new Font(SystemFonts.DialogFont.FontFamily, 12f))
{
SizeF sz = g.MeasureString(text, font);
float f = 256 / Math.Max(sz.Width, sz.Height) * scale;
g.TranslateTransform(256 / 2 + f * sz.Width / 2, 256 / 2 - f * sz.Height / 2);
g.ScaleTransform(-f, f);
using (Brush brush = new SolidBrush(color))
{
g.DrawString(text, font, brush, 0, 0);
}
}
AddTexture(texture, true);
}
public static int LoadTexture(Bitmap texture, bool mipmaped)
{
int id = gl.GenTexture();
gl.BindTexture(TextureTarget.Texture2D, id);
int wt = texture.Width;
int ht = texture.Height;
gl.TexParameter(TextureTarget.Texture2D,
TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
gl.TexParameter(TextureTarget.Texture2D,
TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
System.Drawing.Imaging.BitmapData data = texture.LockBits(
new Rectangle(0, 0, wt, ht),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
gl.TexImage2D(TextureTarget.Texture2D, 0,
PixelInternalFormat.Rgba, wt, ht, 0,
PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
texture.UnlockBits(data);
if (mipmaped)
{
gl.GenerateMipmap(GenerateMipmapTarget.Texture2D);
gl.TexParameter(TextureTarget.Texture2D,
TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
}
else
{
gl.TexParameter(TextureTarget.Texture2D,
TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
}
gl.TexParameter(TextureTarget.Texture2D,
TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
return id;
}
|
[
"sharepoint.stackexchange",
"0000092251.txt"
] |
Q:
Can CSOM set portal url of a site collection?
Can CSOM be used to set the portal url of a site collection?
This is possible using server-side object model via SPSite.PortalUrl:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.portalurl(v=office.14).aspx
A:
No, it is not exposed as part of the CSOM api: http://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.site_members(v=office.15).aspx
|
[
"stackoverflow",
"0056228549.txt"
] |
Q:
R: apply functions that contain Excel-like relative references to other columns
dplyr has lag and lead functions to access preceding and subsequent rows within tables. I'm looking for a similar functionality across columns.
For example, here is a table:
library(tidyverse)
df <- data.frame('score1' = 1:5, 'score2' = 10:6, dif21 = NA_integer_,
'score3' = 11:15, 'score4' = 20:16, dif43 = NA_integer_)
# score1 score2 dif21 score3 score4 dif43
# 1 1 10 NA 11 20 NA
# 2 2 9 NA 12 19 NA
# 3 3 8 NA 13 18 NA
# 4 4 7 NA 14 17 NA
# 5 5 6 NA 15 16 NA
The table has a pattern of columns that repeats twice: two columns of scores, followed by an empty "dif" column that will hold calculated values.
I can operate on the "dif" columns using mutate_at:
df_calc <- df %>%
mutate_at(
vars(dif21),
~ score2 - score1
) %>%
mutate_at(
vars(dif43),
~ score4 - score3
)
# score1 score2 dif21 score3 score4 dif43
# 1 1 10 9 11 20 9
# 2 2 9 7 12 19 7
# 3 3 8 5 13 18 5
# 4 4 7 3 14 17 3
# 5 5 6 1 15 16 1
This gets me the calculated scores that I want in the "dif" columns. In general, the formula is to subtract the column two positions to the left of "dif" from the column one position to the left of "dif". This sort of relative column referencing is easily handled in Excel, but I don't know how to do it in R.
The actual application is a table with scores of columns, so a method for using a single formula with relative column references would be a huge efficiency.
Thanks in advance for any help!
A:
Here is a baseR option
idx <- which(startsWith(names(df), "dif"))
df[idx] <- df[idx - 1] - df[idx - 2]
Result
df
# score1 score2 dif21 score3 score4 dif43
#1 1 10 9 11 20 9
#2 2 9 7 12 19 7
#3 3 8 5 13 18 5
#4 4 7 3 14 17 3
#5 5 6 1 15 16 1
The idea is first to get the positions of the column that start with "dif".
Then we simply subtract the column two positions to the left of each "dif" column from the column one position to the left of each "dif" column.
|
[
"bitcoin.stackexchange",
"0000004796.txt"
] |
Q:
What happens once the mining reward gets cut in half?
Sometime around the end of 2012 the mining reward is expected to be cut in half from 50BTC/block to 25BTC/block.
What effect will this have? Doesn't this mean that it will be less economic to run a Bitcoin miner? Will the hashing power be severely reduced? Will BTC prices soar (or alternatively, crash)?
A:
Assuming blocks are solved at the targeted rate of one block every six minutes going forward from today, the date the block block reward subsidy drop will occur happens in late November.
http://www.BitcoinClock.com
Currently the target rate is 7,200 BTC per day. Starting with block 210,000, this will drop to a targeted rate of 3,600 BTC per day.
This event has been known (and anticipated) since Bitcoin was first released to the world in 2009.
Whether this will cause the exchange rate to rise or fall or the amount of hashing power to rise or fall is mostly speculation.
If investors are counting on the price going up, maybe to $20 let's say, and instead it sticks at around $12, then maybe they sell as it didn't deliver the gains they were hoping for. So the lowered new supply of coins doesn't necessarily guarantee a corresponding rise in the exchange rate.
The amount of hashing that occurs will roughly approximate miner's profitability. As long as miners can mine profitably, they will continue to mine. If their revenue drops by half but it still exceeds the cost of electricity and other operating costs, then they will leave the equipment operating, bringing in mined coins.
Those miners whose costs put them among the least profitable will likely be forced to drop out. These are those who currently mine with a GPU and pay avergage (e.g., $0.12 per kWh) or above average electric rates. Unless the future exchange rate rises faster than difficulty from here, come block 210,000, possibly 50% or more of GPU miners will be dropping out -- either immediately if the have done the math, or within weeks when the total revenue calculation for the first month after the drop gets matched up against the monthly electric bill.
FPGA miners operate 5X or more efficiently in terms of electrical consumption so they are still producing positive cash flows and thus most will continue mining even after the drop.
A:
The four basic laws of supply and demand are:
If demand increases and supply remains unchanged, then it leads to higher equilibrium price and higher quantity
If demand decreases and supply remains unchanged, then it leads to lower equilibrium price and lower quantity.
If demand remains unchanged and supply increases, then it leads to lower equilibrium price and higher quantity.
If demand remains unchanged and supply decreases, then it leads to higher equilibrium price and lower quantity.
Now the big questions to answer are "What will happen with demand" and "What will happen with supply".
At first glance it looks like that due to the decrease of the block level award the supply of BTC will be halved. At the same time there are no signals that demand will change. You could argue that demand goes up, as more and more entrants get into the market to try out the Bitcoin ecosystem. Some will conclude that prices will go up.
However supply is not only determined by the amount of newly created BTC's. We still have a stock of 10 million BTC's. It is fair to say that 80% of these BTC's are hoarded. There is unfortunately still no real economy based on BTC's. They are not commonly used to pay salaries and pay bills of suppliers. All the ASIC suppliers quote and invoice their Asics in US$ (and yes, you could buy them in BTC as well). As long as even the larger players do pay their suppliers, investors, tax bills and employees in fiat currencies it is fair to assume that we have a overhang stock of at least 8 million BTC. Of course people will argue that MTGOX is trading 50.000 BTC/day. Yes, true, but this is nothing else of transferring BTC from one hoarding wallet to another one.
Once pricing goes up, more and more of these speculative BTC will come on the market, driving prices immediately down. My simple conclusion is that demand is going slightly up, supply remains the same, pricing of Bitcoin will raise slowly.
Now what will happen after all these ASICs comes on board of the Bitcoin network. Well, something interesting will happen. Total demand will again slightly improve. Supply will remain the same at 3600BTC/day plus supply from "stock". So nothing structural will change.
There will be at least 15.000 ASICs on the market, assuming three manufacturers will eventually get there, each of them at least supplying 5000 ASICs. With 3600 BTC/day available, this will give each of the ASIC 0.24 BTC per day, at today's BTC pricing something like $3/day/ASIC.
At the moment these ASICs comes at the doorstep of a miner they have a limited time to cash. The resale value will be zero, as these ASICs do not have an alternative use (may be a heating device for a cup of t). This means you have to fully write them off at once. To get any ROI these miners can do two things: Speculate (and hoard) or sell their Bitcoins asap. Hoarding doesn't guarantee a ROI, so they will have to start selling their Bitcoins.
The minimum price they want to see for their BTC's is at least the price which covers their variable costs (Their electricity bill). Everything above this price will support their write-off and the time they are devoting to the project. With the power consumption of 50W per ASIC you will get a electricity bill of 1.2 KWh per day. This will be the minimum price per ASIC. By 15.000 ASIC's, each ASIC in average gets 0.24BTC, so 1 BTC will have a variable costs of 5KwH/day. Say 1 KwH costs you 0.2$, it is fair to say that the variable costs will be $1/BTC. This will be the case until new technology with a higher efficiency will get into the market.
Now with 15.000 ASICS in the market, an unlimited amount of more ASICs able to enter the market, electricity bills to be paid and a "hangover" stock of more than 10 million BTC's miners are forced to sell. This will drive prices down to $1/BTC, as soon as ASICs will be connected to the Bitcoin network.
|
[
"stackoverflow",
"0009285584.txt"
] |
Q:
Matrixes in contiguous position of memory
I often use to memorize all matrixes in a single vector, because my book says it's faster to use a single vector.And the access to a matrix is slower in time.
If I have a code like this one:
int main(int argc, char **argv)
{
int mat[10][10],i;
for(i=0;i<10;i++)
mat[i][0]=99;
int *ptr=&mat[0][0];
for(i=0;i<10;i++)
{
printf("%d\n",*ptr);
ptr+=10;
}
return 0;
}
I tried to run it 4/5 times and all times prints 10 times 99.
So also matrixes are memorized in contigous positions of memory? Always?
If yes, why the access to a vector is faster?
A:
Well, arrays (in C) are stored in contiguous memory, and since that your mat is array of arrays, it also stored in a contiguous memory. I think that dereferencing by one index (when you have some separating 1D arrays) may be a little faster than dereferencing by two indexes (in matrix), but the difference is too small to worry about.
|
[
"math.stackexchange",
"0002535648.txt"
] |
Q:
Number Theory and Inverse Modulo
Suppose $m$ is a two-digit positive integer such that $6^{-1}\pmod m$ exists and $6^{-1}\equiv 6^2\pmod m$. What is $m$?
I know that the question is asking to compute "m". I have a rough sketch in my mind of what do. However, I'm not fully sure.
I think that there's a number "m", which when multiplied by 6, leaves a remainder of 1 (after being divided by m). That doesn't really make sense though because it would not leave any remainder, Next, I thought that "m", when divided by 6, left a remainder of 1. This, I feel, makes more sense. Then, I thought that when divided by 36, it left a remainder of 1. So I think the answer would be 37 or 73.
Can someone either verify my answer or tell me if I'm completely wrong. If I'm completely wrong, can someone guide me through the answer?
A:
Note that $6^2 \equiv 6^{-1} \pmod m \iff 6^3 \equiv 1 \pmod m \iff m \mid 6^3 - 1 = 215$
But $215 = 43 \cdot 5$, so we must have $m=43$
|
[
"rus.stackexchange",
"0000024796.txt"
] |
Q:
Разница "я это хочу" и "мне это нужно"
Интуитивно чувствую, что в этих формулировках смысловая разница есть. И заключается она не только в прихоти (мол, в первом случае — действительно, прихоть, а во втором — необходимость), но в чем-то еще. Но сформулировать никак не могу.
A:
Если говорить о смысле, то помимо Вами же сформулированной никакой "другой разницы" я тут не вижу. Может, конечно, она и есть, но на фоне главного искать еще чего-то просто не хочется - да и бессмысленно.
Впрочем, попробуйте подобрать синонимы к каждому выражению, может поймете, что Вы хотите сказать.
Кстати, "хочу" - не обязательно прихоть.
Я хочу пить = мне нужна вода. Какая уж тут прихоть...
A:
Согласна, что есть противопоставление прихоть - необходимость(хочу коньки-мне нужны коньки), но,по-моему, есть ещё противопоставления: желание- требование (хочу, чтобы ты пришёл-нужно, чтобы ты пришёл); субъективное желание,требование-объективная необходимость(Хочу, чтобы Вы это сделали-это нужно сделать).
"нужно" имеет два значения:1.следует,полезно, необходимо,( нужно, чтобы все явились)2. требуется, следует иметь(мне нужно 5 рублей)
|
[
"stackoverflow",
"0008698552.txt"
] |
Q:
What is the best way to get progress from static non-Android class?
I have an Android application which calls a long-lasting (several hours) static class method. This class is a general purpose class and should know nothing about Android and its API. My application obviously should display the progress of this action. What is the best way to organize interaction between Activity and this class? I consider defining some IProgress interface, implement it in Activity and let static class use it to update its status. But may be there is a better approach?
A:
I would call the long-lasting operation within an AsyncTask.
You could take in the IProgress callback as a constructor to your
AsyncTask.
In the doInBackground(), do your long-lasting task,
get its status and publish it using publishProgress() In your
onProgressUpdate, do a callback.displayProgress().
This displayProgress() would have the UI code to display the progress.
|
[
"stackoverflow",
"0033784941.txt"
] |
Q:
Check if T object has a property and set property
Hello i am having a generic method
public async Task<T> MyMethod<T>(...)
{
//logic here...
}
i would like inside this method to check if the T object has a specific property and then set a value to this property:
I've tried creating a dynamic object and do something like this:
var result = default(T);
dynamic obj = result;
Error error = new Error();
error.Message = "An error occured, please try again later.";
error.Name = "Error";
obj.Errors.Add(error);
result = obj;
return result;
But it doesnt seem to work.
A:
You should get a runtime type of the object with object.GetType, then you can check if it has a particular property with Type.GetProperty , and if yes, call PropertyInfo.SetValue :
PropertyInfo pi = obj.GetType().GetProperty("PropertyName");
if (pi != null)
{
pi.SetValue(obj, value);
}
|
[
"stackoverflow",
"0019064385.txt"
] |
Q:
Parse Json to String
I want to parse Json to string, to show it on a listView. I search and read lots of Articles and questions but I can't find the solution
I've tried this parser JSON From: Android JSON Parsing Tutorial
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And another one from How to parse JSON in Android :
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://someJSONUrl.com/jsonWebService");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
but in both of them when I use a string Json , everything is ok , but when I want to Read Json from a Web API (ex: http://api.androidhive.info/contacts/) this errors comes to me:
09-27 23:47:11.015: E/AndroidRuntime(28635): FATAL EXCEPTION: main
09-27 23:47:11.015: E/AndroidRuntime(28635): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mas.forcheksulotion/com.mas.forcheksulotion.MainActivity}: java.lang.NullPointerException
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1666)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1682)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.os.Handler.dispatchMessage(Handler.java:99)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.os.Looper.loop(Looper.java:130)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.main(ActivityThread.java:3744)
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.lang.reflect.Method.invokeNative(Native Method)
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.lang.reflect.Method.invoke(Method.java:507)
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
09-27 23:47:11.015: E/AndroidRuntime(28635): at dalvik.system.NativeStart.main(Native Method)
09-27 23:47:11.015: E/AndroidRuntime(28635): Caused by: java.lang.NullPointerException
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.io.StringReader.<init>(StringReader.java:46)
09-27 23:47:11.015: E/AndroidRuntime(28635): at org.json.simple.JSONValue.parse(JSONValue.java:33)
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.mas.forcheksulotion.MainActivity.onCreate(MainActivity.java:57)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1630)
09-27 23:47:11.015: E/AndroidRuntime(28635): ... 11 more
And still I don't know for using Json on android I should work with JSONArray , or JSONObject or parse Json to String ?!
A:
I found the problem
two solutions is great and useful , but my mistake was about the uses-permission.
i should add this to the AndroidManifest :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
|
[
"stackoverflow",
"0034899379.txt"
] |
Q:
TCP/IP client incorrectly reading inputstream byte array
I'm creating a Java Client program that sends a command to server and server sends back an acknowledgement and a response string.
The response is sent back in this manner
client -> server : cmd_string
server -> client : ack_msg(06)
server -> client : response_msg
Client code
public static void readStream(InputStream in) {
byte[] messageByte = new byte[20];// assuming mug size -need to
// know eact msg size ?
boolean end = false;
String dataString = "";
int bytesRead = 0;
try {
DataInputStream in1 = new DataInputStream(in);
// while ctr==2 todo 2 streams
int ctr = 0;
while (ctr < 2) {//counter 2 if ACK if NAK ctr=1 todo
bytesRead = in1.read(messageByte);
if (bytesRead > -1) {
ctr++;
}
dataString += new String(messageByte, 0, bytesRead);
System.out.println("\ninput byte arr "+ctr);
for (byte b : messageByte) {
char c=(char)b;
System.out.print(" "+b);
}
}
System.out.println("MESSAGE: " + dataString + "\n bytesread " + bytesRead + " msg length "
+ dataString.length() + "\n");
char[] chars = dataString.toCharArray();
ArrayList<String> hex=new ArrayList<>();
// int[] msg ;
for (int i = 0; i < chars.length; i++) {
int val = (int) chars[i];
System.out.print(" " + val);
hex.add(String.format("%04x", val));
}
System.out.println("\n"+hex);
} catch (Exception e) {
e.printStackTrace();
}
// ===
}
Output
client Socket created ..
response:
input byte arr 1
6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
input byte arr 2
2 -77 67 79 -77 48 -77 3 -116 0 0 0 0 0 0 0 0 0 0 0
MESSAGE: ##³CO³0³##
(where # is some not supported special character )
bytesread 9 msg length 10
dec: 6 2 179 67 79 179 48 179 3 338
hex: [0006, 0002, 00b3, 0043, 004f, 00b3, 0030, 00b3, 0003, 0152]
bytes: 2 -77 67 79 -77 48 -77 3 -116 0 0 0 0 0 0 0 0 0 0 0 (bytes recieved in 2nd packet)
connection closed
Problem: I'm reading the last value incorrect, I have verified using wireshark the server has sent back the response as 06 02 b3 43
4f b3 30 b3 03 8c
Some how I'm reading the last value in correctly. Is there some issue with the reading stream?
EDIT
Rest of the response is read correctly but the last character should be 8c But is read as 0152Hex
Response from server : 06 02 b3 43 4f b3 30 b3 03 8c
Read by program : [0006, 0002, 00b3, 0043, 004f, 00b3, 0030, 00b3, 0003, 0152]
issue with reading the last character
EDIT 2
Response is received as 2 packets/streams
packet 1 byte arr : 6 (ACK)
packet 2 byte arr: 2 -77 67 79 -77 48 -77 3 -116 (response)
complete response read by client
dec: 6 2 179 67 79 179 48 179 3 338
hex: [0006, 0002, 00b3, 0043, 004f, 00b3, 0030, 00b3, 0003, 0152]
Thanks
A:
The problem in this question was a matter of signed variables versus unsigned variables. When you have a number in computer memory, it is represented by a bunch of bits, each of them 0 or 1. Bytes are generally 8 bits, shorts are 16 etc. In an unsigned number, 8 bits will get you from positive 0 to 255, but not to negative numbers.
This is where signed numbers come in. In a signed number, the first bit tells you whether the following bits represent a negative or positive value. So now you can use 8 bits to represent -128 to +127. (Notice that the positive range is halved, from 255 to 127, because you "sacrifice" half of your range to the negative numbers).
So now what happens if you convert signed to unsigned? Depending on how you do it, things can go wrong. In the problem above, the code char c=(char)b; was converting a signed byte to an unsigned char. The proper way to do this is to "make your byte unsigned" before converting it to a char. You can do that like this: char c=(char)(b&0xFF); more info on casting a byte here.
Essentially, you can just remember that except for char, all java numbers are signed, and all you need to do is paste the &0xFF to make it work for a byte, 0xFFFF to make it work for a short, etc.
The details about why this works are as follows. Calling & means a bitwise and, and 0xFF is hexadecimal for 255. 255 is above the limit of a signed byte (127), so the number b&0xFF gets upgraded to a short by java. However, the short signed bit is on bit 16, while the byte signed bit is on bit 8. So now the byte signed bit becomes a normal 'data' bit in the short, and so the sign of your byte is essentially discarded.
If you do a normal cast, java recognizes that doing direct bitconversion like above would mean that you lose the sign, and java expects you don't like that (at least, that is my assumption), so it preserves the sign for you. So if this isn't what you want, you explicitly tell java what to do.
|
[
"mathematica.stackexchange",
"0000058049.txt"
] |
Q:
Change appearance of ConvexHullMesh
I'm struggling to understand the behaviour of ConvexHullMesh (or rather the non-behaviour). I have a polygon p
p = { {0, 0}, {1, 0}, {1/2, 1/2}, {1, 1}, {0, 1}}
which I can display in a nice way like by e.g.:
Show[Graphics[{LightBlue, EdgeForm[Gray], Polygon[p]}], Graphics[ {PointSize[Large], Red, Point[#]}] & /@ p]
Now I construct the convex hull
q = ConvexHullMesh[p];
which displays a somewhat featureless rectangle. Having a closer look at q
q // InputForm
I get
BoundaryMeshRegion[{{0., 0.}, {0., 1.}, {1., 0.}, {1., 1.}}, {Line[{{1, 3}, {3, 4}, {4, 2}, {2, 1}}]}, Method -> {"EliminateUnusedCoordinates" -> True, DeleteDuplicateCoordinates" -> Automatic, "VertexAlias" -> Identity, "CheckOrientation" -> True, "CoplanarityTolerance" -> Automatic, "CheckIntersections" -> Automatic, "BoundaryNesting" -> {{0, 0}}, "SeparateBoundaries" -> False, "PropagateMarkers" -> True, "Hash" -> 1136472811504667718}]
so the obvious (?) idea is to replace the head of q (i.e. BoundaryMeshRegion) by a suitably defined function f that uses the argument to display the convex hull in a 'nicer' way. Ignoring the exact implementation of f, the 'usual' way fails, as
f @@ q
just redisplays the rectangle. Head[q] gives the expected BoundaryMeshRegion, but Apply (or @@) somehow fails to replace the head. Similarly, the alternative q[[1]] to access the argument of the head fails.
What am I missing?
Or to be more precise:
How do I change the appearance of ConvexHullMesh?
Why does the above solution not work?
A:
While the answers provided so far are nice, it seems like there should be easier ways to achieve this. And there are, I will show two ways: 1) Keeping your ConvexHullMesh as a BoundaryMeshRegion object and (2 converting to a Graphics object.
SeedRandom[0]
pts = RandomReal[4, {200, 3}];
chull = ConvexHullMesh[pts];
First we use HighlightMesh with no need to recreate the MeshRegion:
HighlightMesh[chull, {Style[0, Directive[PointSize[0.015], Red]],
Style[1, Thin, Blue], Style[2, Opacity[0.5], Yellow]}]
Note the use of Style to style the various dimensions (0 for vertices, 1 for edges and 2 for facets. Also note that this object is still a BoundaryMeshRegion and you can compute other nice mesh-related properties from it.
Now the Graphics object approach.
Graphics3D[GraphicsComplex[MeshCoordinates[chull], {PointSize[0.02], Red,
MeshCells[chull, 0], Blue, MeshCells[chull, 1], Green, MeshCells[chull, 2]}],
Boxed -> False]
Note the use of the already available properties of the MeshRegion. No need to use Show here.
A:
Show allows you to convert to Graphics object:
Graphics[Show[ConvexHullMesh[p]][[1]] /. {Directive[x_] :>
Directive[{Red, EdgeForm[{Black, Thickness[0.02]}]}]}]
Or perhaps a little more interesting:
pts = RandomReal[{0, 1}, {50, 2}];
g = Graphics[{Red, PointSize[0.03], Point[pts]}];
ch = Show[ConvexHullMesh[pts]][[1]] /. {Directive[x_] :>
Directive[{Yellow, EdgeForm[{Black, Thickness[0.02]}]}]};
Show[Graphics[ch], g]
A:
Why the above solution (f@@q) doesn't work?
Because a MeshRegion is an AtomQ.
How do I change the appearance of ConvexHullMesh?
Because
The convex hull region is the smallest convex region that includes the points
the computed and returned ConvexHullMesh is of course correct. Because you are computing the convex hull, maybe it's because you are interested to show the input list of points and their convex hull. You can use Show to combine directly a MeshRegion with another Graphics.
Maybe you are interested to DelaunayMesh, related with but different from ConvexHullMesh (returns a MeshRegion instead of a BoundaryMeshRegion).
p = {{0, 0}, {1, 0}, {1/2, 1/2}, {1, 1}, {0, 1}};
q = ConvexHullMesh[p];
{Show[q, Graphics@Point@p], HighlightMesh[DelaunayMesh[p], Style[0, Red]]}
|
[
"security.stackexchange",
"0000031205.txt"
] |
Q:
What is the purpose of the hashcode used in Exchange OWA HTTP requests?
This blog describes the URLs that are used in OWA and webservices. It also says that there is a hashcode that is used in conjunction with the throttling policy.
Is this hashcode responsible for "securing" the throttling policy, and its current values for later processing by a CAS server?
What format is this hashcode? (is it MD5, SHA1, etc?)
A:
My (wild) guess is that the "hashcode" is just a reference key used by whatever system enforces the throttling, to quickly locate in an internal database (which could be an in-RAM hash table) the entry which keeps track of the "budget" allocated to each entity. Thus not a cryptographic hash at all.
|
[
"askubuntu",
"0000916204.txt"
] |
Q:
what are the different default application in different ubutnu flavours?
I have installed Ubuntu MATE and Ubuntu with Unity.
In Ubuntu with Unity, there is Nautilus file manager, Gedit text editor, and others.
In Ubuntu MATE, there is the file manager Caja, Pluma a text editor and additional software. Such as Synapse, gdebi package installer as well as others.
What are the different default applications in other Ubuntu flavors?
A:
You can easily find them by looking at each flavor's Wikipedia page. Here are the applications included in the four most popular Ubuntu flavors:
Lubuntu
Abiword – word processor
Audacious – music player
Evince – PDF reader
File-roller – archiver
Firefox – web browser
Galculator – calculator
GDebi – package installer
GNOME Software – package manager
Gnumeric – spreadsheet
Guvcview – webcam
LightDM – log-in manager
Light-Locker – screen locker
MPlayer – video player
MTPaint – graphics painting
Pidgin – instant messenger and microblogging
Scrot – screenshot tool
Simple Scan – scanning
Sylpheed – email client
Synaptic and Lubuntu Software Center – package managers
Transmission – bittorrent client
Update Manager
Startup Disk Creator – USB ISO writer
Wget – command line webpage downloader
XChat – IRC
Xfburn – CD burner
Xpad – notetaking
source
Xubuntu
Catfish - desktop search
Common Unix Printing System - printer utility and PDF creator
Evince - PDF reader
Firefox - web browser
GIMP - graphics editor
LibreOffice Calc - spreadsheet
LibreOffice Writer - word processor
Mousepad - text editor
Orage - calendar
Parole - media player
Pidgin - internet messenger
Thunderbird - e-mail client
XChat - IRC client
Simple Scan - scanner utilities
source
Thunar as file manager as I know
Kubuntu
Okular - pdf viewer
Gwenview - image viewer
KSnapshot - desktop screenshots.
Firefox is the default browser shipped with Kubuntu
Kmail as mail client
Kate - editor
Ark - archive manager
Konsole - terminal
Dolphin - filemanager
source + more info
ubuntu mate
pluma - text editor
caja- file manager
synapse- serch tool
welcome - introduce the OS and to download softwares
galculator - calculator
gdebi packadge installer - package installer
mate terminal - terminal
atril document viewer - document viewer
mate dictonary - dictionary
Eye of MATE - image viewer
vlc media player - to play videos
Disk Usage Analyzer -A graphical tool to analyze disk usage
dconf editor -low level configuration system and settings management
Firefox - web browser
|
[
"stackoverflow",
"0031004952.txt"
] |
Q:
Read JSON double dimensional array in Java
I'm trying to get a string from a JSONObject.
My JSON looks like this :
{
"agent":
[
{"name":"stringName1", "value":"stringValue1"},
{"name":"stringName2", "value":"stringValue2"}
]
}
I want to get the values from stringName1 and stringName2. So first, I tried to get the "agent" using this :
JSONObject agent = (JSONObject) jsonObject.get("agent");
However, this throws me an error.
Have you got any idea on how to process ?
A:
You're trying to parse a JSON array into a JSON object. Of course it's going to give you errors.
Try this instead:
JSONArray agent = jsonObject.getJsonArray("agent");
// To get the actual values, you can do this:
for(int i = 0; i < agent.size(); i++) {
JSONObject object = agent.get(i);
String value1 = object.get("name");
String value2 = object.get("value");
}
|
[
"stackoverflow",
"0039069188.txt"
] |
Q:
These patterns look exhaustive to me, "Non-exhaustive patterns error" ? Why?
Problem
While taking notes from a Haskell book, this code example should return: Left [NameEmpty, AgeTooLow], but it only returns the first case Left [NameEmpty]. Then when I pass the function mkPerson2 results to which it should return Right Person _ _, I get back a `Non-exhaustive pattern``` error. I've looked over this code for quite some time, but it looks right to me. What am I missing here? Any explanation on the subject would be absolutely appreciated, thanks!
Book I'm using
Code
module EqCaseGuard where
type Name = String
type Age = Integer
type ValidatePerson a = Either [PersonInvalid] a
data Person = Person Name Age deriving Show
data PersonInvalid = NameEmpty
| AgeTooLow
deriving Eq
ageOkay :: Age -> Either [PersonInvalid] Age
ageOkay age = case age >= 0 of
True -> Right age
False -> Left [AgeTooLow]
nameOkay :: Name -> Either [PersonInvalid] Name
nameOkay name = case name /= "" of
True -> Right name
False -> Left [NameEmpty]
mkPerson2 :: Name -> Age -> ValidatePerson Person
mkPerson2 name age = mkPerson2' (nameOkay name) (ageOkay age)
mkPerson2' :: ValidatePerson Name -> ValidatePerson Age -> ValidatePerson Person
mKPerson2' (Right nameOk) (Right ageOk) = Right (Person nameOk ageOk)
mKPerson2' (Left badName) (Left badAge) = Left (badName ++ badAge)
mkPerson2' (Left badName) _ = Left badName
mkPerson2' _ (Left badAge) = Left badAge
Error
*EqCaseGuard> mkPerson2 "jack" 22
*** Exception: eqCaseGuard.hs:(54,1)-(55,53): Non-exhaustive patterns in function mkPerson2'
*EqCaseGuard> mkPerson2 "" (-1)
Left [NameEmpty]
*EqCaseGuard>
A:
You used a capital K in the first two definitions:
mKPerson2' (Right nameOk) (Right ageOk) = Right (Person nameOk ageOk)
^
mKPerson2' (Left badName) (Left badAge) = Left (badName ++ badAge)
^
|
[
"stackoverflow",
"0002346826.txt"
] |
Q:
Data structure for fast filtering (Delphi)?
I am optimizing a part of a Delphi application where lists of objects are frequently filtered using different criteria. The objects are kept in TObjectList structures and it is common to select a very small percentage (ex. 1%) of the entire set with each filter. The total number of objects can be in the 100k range and during computations the main set doesn't change. Although the filters are applied for only a few properties, the lists cannot be sorted in such a way that would optimize all the possible criteria.
I am looking for suggestions on how to organize the objects (data structures) or an algorithm that can be used to approach this problem. Thank you!
Filter example:
((Object.A between 5 and 15) AND
(Object.B < 20) AND
(Object.C(AParam) > 0)) OR
(Object.IsRoot(...))
A:
You can use a sorted list using the field, which constricts your search/filtering at most, and then perform a binary search to get the index/indexes of this criteria.
Referring to your example above: Generate an A-sorted list, search for the indexes of 5 and 15 and so you will get a (much) smaller list (all the indexes between the two), where you have to check the other fields (B, C and IsRoot).
Delphi (2009+) implementation of a sorted list: DeHL.Collections.SortedList
A:
I know you don't use tiOPF, but there is a lot to learn from the source code of this project. Since you probably will be looping over the filtered objects, why not create a filter iterator?
This unit is a good start, but I think it is easier to download the complete source and browse through the files: http://tiopf.svn.sourceforge.net/viewvc/tiopf/tiOPF2/Trunk/Core/tiFilteredObjectList.pas?revision=1469&view=markup
This solution probably uses a lot of RTTI: just create a list with filters (property names and values) and loop over the objects. It will provide you with maximum flexibility but at the cost of some speed. If you need speed I think the solution provided by Ulrichb will be better.
A:
Idea #1
Run your code in a profiler. Find out if there are any slow spots.
Idea #2
Possibly you could take advantage of cache effects by storing your objects sequentially in memory. (I'm assuming you are walking your list sequentially from beginning to end.)
One way to do it might be to use an array of records instead of a list of objects. If that's possible in your case. Remember that records in Delphi 2006 can have methods (but not virtual ones).
Another idea might be to write your own class allocator. I've never tried that, but here's an article I found. Maybe try walking the objects using a pointer instead of using the TObjectList.
|
[
"stackoverflow",
"0024399943.txt"
] |
Q:
PHPMailer IsHTML(true) not working
I am trying to send emails from PHPMailer. Everything is working but the problem is it is sending emails along with HTML tags even after writing $mail->IsHTML(true); . Below is my code for sending emails.
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = EMAIL_COMPOSE_SECURE;
$mail->Host = EMAIL_COMPOSE_SMTP_HOST;
$mail->Port = EMAIL_COMPOSE_PORT;
$mail->Username = EMAIL_COMPOSE_OUTGOING_USERNAME;
$mail->Password = EMAIL_COMPOSE_OUTGOING_PASSWORD;
$mail->SetFrom(EMAIL_COMPOSE_INCOMING_USERNAME);
$mail->Subject =$subject;
$mail->Body = $message;
$mail->IsHTML(true);
$mail->AddAddress($email_to);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}
else{
echo "Message has been sent";
}
And one more thing I will mention, in my application text editor for writing the emails is ckeditor. Will that cause any problem? Please help.
A:
Why would you not expect it to use HTML if you call IsHTML(true)? That's how you tell PHPMailer to treat your message body as HTML! If you don't want HTML as the content type, call IsHTML(false), or just don't call it at all since plain text is the default.
If you want both HTML and plain text, call msgHTML($html) instead and it will also handle the HTML->text conversion for you.
As Chris said, call IsHTML before setting Body.
And as Dagon said, if you put HTML in $message, it will send HTML...
|
[
"stackoverflow",
"0034583796.txt"
] |
Q:
Android @Intdef for flags how to use it
I am not clear how to use @Intdef when making it a flag like this:
@IntDef(
flag = true
value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
this example is straight from the docs. What does this actually mean ? does it mean all of them are initially set to true ? if i do a "or" on the following:
NAVIGATION_MODE_STANDARD | NAVIGATION_MODE_LIST
what does it mean ...im a little confused whats happening here.
A:
Using the IntDef#flag() attribute set to true, multiple constants can be combined.
Users can combine the allowed constants with a flag (such as |, &, ^ ).
For example:
public static final int DISPLAY_OP_1 = 1;
public static final int DISPLAY_OP_2 = 1<<1;
public static final int DISPLAY_OP_3 = 1<<2;
@IntDef (
flag=true,
value={
DISPLAY_OP_1,
DISPLAY_OP_2,
DISPLAY_OP_3
}
)
@Retention(RetentionPolicy.SOURCE)
public @interface DisplayOptions{}
public void setIntDefFlag(@DisplayOptions int ops) {
...
}
and Use setIntDefFalg() with '|'
setIntDefFlag(DisplayOptions.DISPLAY_OP1|DisplayOptions.DISPLAY_OP2);
|
[
"stackoverflow",
"0050615564.txt"
] |
Q:
JAVA TCP Server Error
Server : package Server;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen(){
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true){
if((image = ImageIO.read(min)) != null){
while(min.read() != 'y');
System.out.println("received");
mout.write('y');
mout.flush();
Main.drawImage(image);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client :package Client;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] buffer = new byte[10];
while(true){
ImageIO.write(webcam.getImage(), "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This Program works well about 10sec. But after that It doesn't work. Socket is Connected but It doesn't send anything. I guess it doesn't match sync, so I match sync, but it's not work too. I don't have an idea. why It doesn't work. please help. I can't find problem
A:
Your client needs to send the size of transfered image to server prior to sending the image itself, because your server needs to know how long the image is, in order to read it from socket and start receiving the char data coming right after the image.
And since "ImageIO" has no means of specifying the number of bytes supposed to be read from the input stream, you should use InputStream instead.
See the modified code below (I put comments whenever added a new line, everything else is identical with yours):
Server:
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; //<--- added
import java.io.DataInputStream; //<--- added
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
private DataInputStream din; //<--- added DataInputStream
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
din = new DataInputStream(min); //<--- initialized DataInputStream
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen()
{
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true)
{
int arrlen = din.readInt(); //<--- receive image size in order to prepare a buffer for it
byte[] b = new byte[arrlen]; //<--- prepare a buffer
din.readFully(b); //<--- receive image data
while(min.read() != 'y');
mout.write('y');
mout.flush();
InputStream bais = new ByteArrayInputStream(b); //<--- get ByteArrayInputStream from buffer
BufferedImage image = ImageIO.read(bais); //<--- prepare BufferedImage from ByteArrayInputStream
bais.close(); //<--- close ByteArrayInputStream
Main.drawImage(image);
}//end while true
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client:
import java.awt.image.BufferedImage; //<--- added
import java.io.ByteArrayOutputStream; //<--- added
import java.io.DataOutputStream; //<--- added
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
DataOutputStream dos = new DataOutputStream(out); //<--- added DataOutputStream
BufferedImage image = null; //<--- added BufferedImage to keep image from webcam
while(true){
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //<--- create ByteArrayOutputStream
image = webcam.getImage(); //<--- get BufferedImage from webcam
ImageIO.write(image, "png", baos); //<--- write image into ByteArrayOutputStream
dos.writeInt(baos.size()); //<--- send image size
dos.flush(); //<--- flush DataOutputStream
baos.close(); //<--- close ByteArrayOutputStream
ImageIO.write(image, "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
|
[
"math.stackexchange",
"0002587996.txt"
] |
Q:
How to solve (in)equality of three variables with trigonometric solutions
I'm working through a set of inequality problems and I'm stuck on the following question:
Find all sets of solutions for which $$(a^2+b^2+c^2)^2=3(a^3b+b^3c+c^3a)$$ holds. Note that $a,b,c\in\mathbb{R}$.
Firstly, one can easily see that when $a=b=c$ then the equality holds: $$\text{LHS}=(a^2+a^2+a^2)^2=(3a^2)^2=9a^4$$ and $$\text{RHS}=3(a^4+a^4+a^4)=3(3a^4)=9a^4.$$
A hint is given to use the substitutions $a=x+2ty$, $b=y+2tz$ and $c=x+2tz$ for real $t$. The LHS is rather nice in that it simplifies to $$(4t(xy+xz+yz)+(1+4t^2)(x^2+y^2+z^2))^2$$ but I can't find a similar simplification for the RHS. I guess this is a type of uvw question but I don't know where to start.
There are actually four sets of solutions: $$a=b=c,$$ $$\frac{a}{\sin^2\frac{4\pi}7}=\frac{b}{\sin^2\frac{2\pi}7}=\frac{c}{\sin^2\frac{\pi}7},$$ $$\frac{b}{\sin^2\frac{4\pi}7}=\frac{c}{\sin^2\frac{2\pi}7}=\frac{a}{\sin^2\frac{\pi}7},$$ and $$\frac{c}{\sin^2\frac{4\pi}7}=\frac{a}{\sin^2\frac{2\pi}7}=\frac{b}{\sin^2\frac{\pi}7}$$ I have no idea how the trigonometric expressions are obtained. How could the equality be solved?
A:
The hint.
Let $b=a+u$,$c=a+v$ and $u=xv$.
Hence, $$(a^2+b^2+c^2)^2-3(a^3b+b^3c+c^3a)=\sum_{cyc}(a^4+2a^2b^2-3a^3b)=$$
$$=(u^2-uv+v^2)a^2+(u^3-5u^2v+4uv^2+v^3)a+u^4-3u^3v+2u^2v^2+v^4\geq0$$
because
$$(u^3-5u^2v+4uv^2+v^3)^2-4(u^2-uv+v^2)(u^4-3u^3v+2u^2v^2+v^4)=$$
$$=-3(u^3-u^2v-2u^2+v^3)^2=-3v^6(x^3-x^2-2x+1)^2\leq0.$$
The equality occurs for $x^3-x^2-2x+1=0$,
which gives $$x\in\left\{2\cos\frac{\pi}{7},-2\cos\frac{2\pi}{7},2\cos\frac{3\pi}{7}\right\}.$$
For example, $x=2\cos\frac{\pi}{7}$ gives the following case.
$$\frac{b}{\sin^2\frac{4\pi}7}=\frac{c}{\sin^2\frac{2\pi}7}=\frac{a}{\sin^2\frac{\pi}7}.$$
My solution by $uvw$ see here:
https://artofproblemsolving.com/community/c6h6026p5329091
There is also the following nice solution.
https://gbas2010.wordpress.com/2010/01/08/problem-19vasile-cirtoaje/
|
[
"drupal.stackexchange",
"0000191829.txt"
] |
Q:
Watchdog messages and string replacement
Hello I would like to know which of the following ways (or some other) of logging messages is better and why.
I am writing lots of .install files since I create content types and fields programmatically and I often write statements as following:
$t = get_t();
watchdog('mymodule',$t('Field !field_name created.', array('!field_name' => $file_field_name)));
OR
$t = get_t();
watchdog('mymodule',$t('Field !field_name created.'), array('!field_name' => $file_field_name));
Note: in the first example I am doing string replacement in the $t function in the second in the watchdog() function.
A:
Just use this:
watchdog('mymodule', 'Field !field_name created.', array('!field_name' => $file_field_name));
watchdog() function will translate the string you pass as the second parameter. You shouldn't translate the message before passing it to the watchdog().
Check out this answer for more information and references.
Or consult the following document from Drupal's documentation.
|
[
"stackoverflow",
"0041601458.txt"
] |
Q:
Accessing $scope date inside a http.get callback
I need to store the data returned by $http.get in a $scope variable to be used by my ui-grid control.
I´m sure I´m missing something very simple, but I can´t find out what. Here is my code:
app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {
$http.get('/api/admin/user')
.success(function (response, $scope) {
$scope.myData = response;
})
.error(function (error) {
console.log(error);
});
console.log($scope.myData);
$scope.gridOptions = {
data: 'myData',
enableFiltering: true,
columnDefs: [
{ field: 'firstName' },
{ field: 'lastName' },
{ field: 'jobTitle'},
{
field: 'email',
filter: {
condition: uiGridConstants.filter.ENDS_WITH,
placeholder: 'ends with'
}
},
{
field: 'phone',
filter: {
condition: function(searchTerm, cellValue) {
var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
return strippedValue.indexOf(searchTerm) >= 0;
}
}
},
]
};
});
My console inside success prints undefined. How can I access the original $scope inside the $http.get success function ?
A:
My console inside success prints undefined
But, your console is NOT inside the success method. This is inside:
$http.get('/api/admin/user')
.success(function (response) {
$scope.myData = response;
console.log($scope.myData);
})
.error(function (error) {
console.log(error);
});
This is not:
// order of events..
// #1...first $http
$http.get('/api/admin/user')
.success(function (response) {
//... #3 third. Now finally response is defined. the end
$scope.myData = response;
})
.error(function (error) {
console.log(error);
});
//... #2 second. $scope.myData definitely IS undefined
console.log($scope.myData);
Huge difference. There is also no need to include $scope in your success callback. I've never seen that before. Where did you get that from?
|
[
"stackoverflow",
"0001425023.txt"
] |
Q:
How can I preserve whitespace when I match and replace several words in Perl?
Let's say I have some original text:
here is some text that has a substring that I'm interested in embedded in it.
I need the text to match a part of it, say: "has a substring".
However, the original text and the matching string may have whitespace differences. For example the match text might be:
has a
substring
or
has a substring
and/or the original text might be:
here is some
text that has
a substring that I'm interested in embedded in it.
What I need my program to output is:
here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.
I also need to preserve the whitespace pattern in the original and just add the start and end markers to it.
Any ideas about a way of using Perl regexes to get this to happen? I tried, but ended up getting horribly confused.
A:
Been some time since I've used perl regular expressions, but what about:
$match = s/(has\s+a\s+substring)/[$1]/ig
This would capture zero or more whitespace and newline characters between the words. It will wrap the entire match with brackets while maintaining the original separation. It ain't automatic, but it does work.
You could play games with this, like taking the string "has a substring" and doing a transform on it to make it "has\s*a\s*substring" to make this a little less painful.
EDIT: Incorporated ysth's comments that the \s metacharacter matches newlines and hobbs corrections to my \s usage.
A:
This pattern will match the string that you're looking to find:
(has\s+a\s+substring)
So, when the user enters a search string, replace any whitespace in the search string with \s+ and you have your pattern. The, just replace every match with [match starts here]$1[match ends here] where $1 is the matched text.
|
[
"stackoverflow",
"0015146706.txt"
] |
Q:
@each loop with index
I was wondering if you can get an element index for the @each loop.
I have the following code, but I was wondering if the $i variable was the best way to do this.
Current code:
$i: 0;
$refcolors: #55A46A, #9BD385, #D9EA79, #E4EE77, #F2E975, #F2D368, #F0AB55, #ED7943, #EA4E38, #E80D19;
@each $c in $refcolors {
$i: $i + 1;
#cr-#{$i} strong {
background:$c;
}
}
A:
First of all, the @each function is not from Compass, but from Sass.
To answer your question, this cannot be done with an each loop, but it is easy to convert this into a @for loop, which can do this:
@for $i from 1 through length($refcolors) {
$c: nth($refcolors, $i);
// ... do something fancy with $c
}
A:
To update this answer: yes you can achieve this with the @each loop:
$colors-list: #111 #222 #333 #444 #555;
@each $current-color in $colors-list {
$i: index($colors-list, $current-color);
.stuff-#{$i} {
color: $current-color;
}
}
Source: http://12devs.co.uk/articles/handy-advanced-sass/
A:
Sometimes you may need to use an array or a map. I had an array of arrays, i.e.:
$list = (('sub1item1', 'sub1item2'), ('sub2item1', 'sub2item2'));
I found that it was easiest to just convert it to an object:
$list: (
'name': 'thao',
'age': 25,
'gender': 'f'
);
And use the following to get $i:
@each $property, $value in $list {
$i: index(($list), ($property $value));
The sass team also recommended the following, although I'm not much of a fan:
[...] The above code is how I'd like to address this. It can be made more efficient by adding a Sass function like range($n). So that range(10) => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Then enumerate can become:
@function enumerate($list-or-map) {
@return zip($list-or-map, range(length($list-or-map));
}
link.
|
[
"stackoverflow",
"0009096469.txt"
] |
Q:
setGridParam({datatype:'json', page:1}).trigger('reloadGrid') not Working
I'm not sure whats wrong but this is not working with me, below is my code but hitting reload dont create any request to server.
$("#timecard-summary-grid").jqGrid({
url:'grid/grid_timecard_summary.php',
datatype: 'xml',
mtype: 'GET',
colNames:['Date','Day','Time In','Time Out','Normal','Late','Undertime'],
colModel :[
{name:'date', index:'date', width:90, editable:false, align:"center", editrules:{required:true}},
{name:'day', index:'day', width:70, editable:false, align:"center", editrules:{required:true}},
{name:'t_in', index:'t_in', width:80, editable:false, align:"center", editrules:{required:true}},
{name:'t_out', index:'t_out', width:80, editable:false, align:"center", editrules:{required:true}},
{name:'tdiff', index:'tdiff', width:80, editable:false, align:"center", editrules:{required:true}},
{name:'late', index:'late', width:80, editable:false, align:"center", editrules:{required:true}},
{name:'undertime', index:'undertime', width:80, editable:false, align:"center", editrules:{required:true}}
],
height: 'auto',
pager: '#timecard-summary-pager',
rowNum:10,
rowList:[10,20],
sortname: 'date',
sortorder: 'desc',
loadonce: true, // to enable sorting locally
viewrecords: true,
gridview: true,
editurl: 'grid_summary_editurl.php',
caption: '<span style="margin-left:10px;">Timecard Summary</span>',
});
$("#timecard-summary-grid").jqGrid('navGrid',"#timecard-summary-pager",
{edit:false,add:false,del:false,search:true,refresh:true},
{zIndex:5234}, //option for edit
{zIndex:5234}, // for add
{zIndex:5234}, // del
{zIndex:5234, multipleSearch:true, multipleGroup:true} // search
);
$("#timecard-summary-id").jqGrid("setGridParam",{datatype:"xml"}).trigger("reloadGrid");
Where should I put the trigger?
A:
First of all the code which you posted (jqGrid("setGridParam",datatype:"xml"})) contains syntax error: there are no opened '{'. I hope that the problem exists only in the text of your question and not in your original code.
The next problem: you tried to change the datatype and reload the grid directly after the grid will be created. The problem is that you use datatype: 'xml' in the jqGrid. So immediately after the grid will be created the request to the server will be send per ajax. Request to reload the grid during pending Ajax request will be just ignored and no reloading will take place.
After the Ajax request to the server will be finished the datatype will be changed from 'xml' to 'local' corresponds to the option loadonce: true. So only after the first response will be full processed one can execute the code
$("#timecard-summary-id").jqGrid("setGridParam", {datatype: "xml"})
.trigger("reloadGrid");
|
[
"stackoverflow",
"0058743658.txt"
] |
Q:
Scrapy filter identical urls differ in "http" and "https"
I notice that scrapy will crawl both pages that only differ in scheme, e.g. "http://www.google.com" and "https://www.google.com", which will actually double my request. Is there a way I can filter half of them?
A:
There is no generic way. Depending on your specific circumstances different solutions may apply, or there may be no good solution.
If the issue is with a specific domain, you can just write your spider so that it will use the right protocol when yielding a new request.
If it is for a broad crawl targeting an arbitrary number of domains, it may be a bit tricky. Most domains will redirect HTTP to HTTPS, but some domains will redirect HTTPS traffic to HTTP.
In that latter case, if the problem is that while on an HTTPS page you get HTTP links that then redirect back to HTTPS, you could change your spider to read the protocol from response.url and using that when building a request instead of whatever the URL that you found uses. But it’s possible that some of the content is actually HTTP, and you will get bad responses due to the protocol change.
|
[
"stackoverflow",
"0009356925.txt"
] |
Q:
WinRT as a replacement of Win32 API
Over internet there are many blogs saying that winrt is a replacement of win32 api. IS this is really true? Even i read that application developed for Metro Application uses winrt. So do i understand correctly, those application which are metro application they has to go through winrt & classic applications has to go through win32 api's. Please someone validate my conclusions.
A:
Disclaimer: I am not involved in any way in the design or implementation of Windows 8, and I have only kept up on the Windows 8 news. I possess no privileged information.
winrt is a replacement of win32 api
Microsoft has made clear that WinRT is not a replacement for Win32, but another way to develop applications. That said, there is no Win32 implementation on ARM (at least that third-party developers can access). Windows on ARM will only support WinRT, and not Win32, as Steve Sinofsky explains here.
those application which are metro application they has to go through winrt & classic applications has to go through win32 api's
Absolutely correct.
A:
Win32 still exists. WinRt wraps them and converts their types to be native for the consuming language. C++ metro application can still access a limited set of Win32 APIs
A:
WinRT is basically a wrapper for Win32 (COM) to be consumed by Metro Stype applications (Projections for Native, CLR, Javascript) which are designed for a sandboxed environment mostly for Touch-Screen aware applications (although one can hack them to work on the desktop). Some APIs for Metro Style applications are still using the classic COM APIs (DirectX for example).
So, how can WinRT replace Win32 if it is built upon it? ;-)
|
[
"math.stackexchange",
"0002955786.txt"
] |
Q:
Is $2\pi$ not in the same equivalence class as $\pi$?
Is $2\pi$ not in the same equivalence class as $\pi$? This is my first encounter with equivalence classes, so I'm just trying to make sure I understand the definition.
We write $x \sim y$, when $x-y \in \mathbb{Q}$.
$2\pi -\pi = \pi \notin \mathbb{Q} \implies 2\pi \nsim \pi$
Seems simple enough. However, it doesn't sound right. This is, in my mind, the same thing as saying: every irrational number belongs to a different equivalence class than all other irrational numbers, besides rational translations of itself. That just seems, I don't know, too trivial of a property. I would expect, for example, something like $2\sqrt{5} \sim \sqrt 5$.
A:
Yes, you are right - for this equivalence relationship $2\pi$ and $\pi$ are not equivalent to each other.
There is no one definitive equivalence relationship on any set; we can (and do) study multiple different equivalence relationships depending on the problem we're trying to solve. The particular equiv. rel. you've given here does strike me as on the trivial side, and you don't need to understand anything deeper about it. Although (SPOILER!) this equiv. rel. is used to prove the existence of unmeasurable sets, but you'll only see this if you go on to study measure theory and Lebesgue integration.
BTW, if you wanted $2\sqrt{5} \sim_2 \sqrt{5} $ you could define
$$x \sim_2 y \iff x/y \in \mathbb{Q}$$ (for $x,y \in \mathbb{R} \setminus \{0\}$), which would be a second, different equivalence relationship. Of course now $1+\pi$ and $\pi$ are no longer equivalent.
|
[
"stackoverflow",
"0059757296.txt"
] |
Q:
Ignore failure on Source command in Bash script
So I know there are plenty of answers on stack overflow for ignoring errors in a bash script. None of them seem to work for the source command though.
I have tried the tried and true source ../bin/activate || true
I have tried setting set -e before running the command
I have tried source ../bin/activate 2>&1 /dev/null
I have tried setting set +e before running the command. This did not work either.
but on every run-through of this code, I receive
run.01: line 12: ../bin/activate: No such file or directory
The context for this problem is that I'm creating a simple bash script that runs some python code. The user is instructed for how to create a specific virtual environment and this line will automatically activate it if they set it up correctly, otherwise, this should ignore failing to activate running and continue running the commands in whatever environment is currently activated.
# Try virtual environment
source ../bin/activate || true
## Run.
code="../src-01/driver.v01.py"
## --------------------
graphInputFile="undirected_graph_01.inp"
graphType="undirected"
srcColId="0"
desColId="1"
degreeFind="2"
outFile="count.undirected.num.nodes.out"
python $code -inpGraphFile $graphInputFile -graphFormat $graphType -colSrcId $srcColId -colDesId $desColId -degreeFind $degreeFind -output_file $outFile
The python command should execute regardless of whether or not the source ../bin/activate command succeeds or not. I'm a little a loss for why none of these solutions are working and am currently under the assumption that source might do something different than a normal command given the circumstances.
EDIT:
I added the shebang #!/bin/bash -x to my file as requested but this did not do anything.
I this is my exact terminal output when I run this script.
Lucas-Macbook:test-01 lucasmachi$ sh run.01
run.01: line 14: ../bin/activate: No such file or directory
Lucas-Macbook:test-01 lucasmachi$
Where run.01 is the name of the bash script.
Also to clarify, the code I showed is not censored. that is the entire script (except now with the mentioned shebang at the top.)
A:
This is a bug in Bash versions before 4.0 (macOS is stuck on 3.2).
Given this script:
#!/bin/bash
set -e
echo "Running $BASH_VERSION"
source "does not exist" || true
echo "Continuing"
Running on macOS will say:
macos$ ./myscript
Running 3.2.57(1)-release
./myscript: line 3: does not exist: No such file or directory
While on a modern system with an updated bash version, you get the expected behavior:
debian$ ./myscript
Running 5.0.11(1)-release
./myscript: line 3: does not exist: No such file or directory
Continuing
If you need to support macOS and Bash 3.2, run set +e first to disable errexit, and optionally re-enable it afterwards.
A:
You could add a validation in your code to check whether the file exists before sourcing it :
[[ -f "../bin/activate" ]] && source ../bin/activate
Using the -f flag before a path will return true if the path file exists, and false if it doesn't.
The one liner syntax for bash if statements is as follow :
[[ Condition that returns true or false ]] && Exec if true
|
[
"superuser",
"0000000151.txt"
] |
Q:
How to keep iTunes libraries in sync?
I have a couple of PCs and a Mac that I have my music libraries on them. Occasionally, I add files, edit artworks and ID3 tags on one of them. I want to keep them synchronized on all of my computer. Any organizational change I make (e.g. update album name, which will reorganize the folder structure) should automatically propagate to others.
What's the best way to do that? Please suggest a free (as in beer) solution (bonus points if it's free as in speech). Better yet, one that doesn't require third party software.
Note that sharing iTunes libraries is not a solution for me as I want to have all my files when I take only one of them and go out.
The issue is resolved with the advent of iTunes 9.0.
A:
This answer is obsolete. myTuneSync has since been declared end-of-life and is no longer available to download from the developer. Please see the other answers in this question for up-to-date answers.
myTuneSync will synchronize files, metadata, and playlists between multiple iTunes libraries. It uses the iTunes APIs to update your library so you don't run the risk of corrupting your library file.
There is a 15 day free trial if you only need to synchronize once, and a 3-pack of licenses is only $30.
A:
Update iTunes to 9.0. It let's you sync up to 5 computers in your home.
A:
I'm pretty sure you can use DropBox for this. Dropbox is free, and will allow all your computers to share your files, and file structure. Changes are made, almost at the same time, and you can even access your files over the web.
The only problem is that you can only share 2GB of files, before you need to upgrade (for a fee).
More info and discussion on DropBox can be found at this question.
|
[
"stackoverflow",
"0014979787.txt"
] |
Q:
Activity LaunchMode
This is the Activity tag i have in my Manifest:
<activity
android:name=".Activity_B"
android:label="@string/app_name"
android:launchMode="singleTop"/>
What i want to accomplish is:
Activity_A ---> Activity_B ---> Activity_C ---> Activity_B
When I go from Activity_B to Activity_C, i don't want to finish Activity_B.
But when I click a button in Activity_C, I want to launch Activity_B, which must be re-created (data changed because of some action in Activity_C) and the previous instance of Activity_B which is in the backstack must be finished.
android:launchMode="singleTask" which worked almost as required, but Activity_B is not being re-created.
android:launchMode="singleTop" re-creates Activity_B but doesn't remove its previous instance from the backstack
android:launchMode="singleInstance" this is working same as singleTask
A:
transforming comment into answer
The workflow you describe is the perfect one for using startActivityForResult(). You should use that to call Activity-C from Activity-B and when the data was changed, set the result to RESULT_OK and if the user goes back, you can modify/update the Activity-B.
That is the way it is meant to be done.
|
[
"stackoverflow",
"0051095689.txt"
] |
Q:
Not able to run Harmonize flow in Data Hub Framework MarkLogic
I am trying to run Harmonize flow using Gradle in DHF and getting the below error-
RESTAPI-SRVEXERR: (err:FOER0000) Extension Error: code: 404 message: Not
Found document: The requested flow was not found
2018-06-29 11:57:22.627 Notice: in
/marklogic.rest.resource/flow/assets/resource.xqy, at 72:14,
2018-06-29 11:57:22.627 Notice: in function() as item()*() [1.0-ml]
2018-06-29 11:57:22.627 Notice: $entity-name = "Order"
2018-06-29 11:57:22.627 Notice: $flow-name = "HarmonizeFlow"
2018-06-29 11:57:22.627 Notice: $flow-type = "harmonize"
2018-06-29 11:57:22.627 Notice: $flow = ()
Data Hub Framework version -2.0.4
MarkLogic Version-9.0.3
The files for harmonize flow has been created successfully but not able to run the flow.
Any suggestions ?
A:
have you deployed your modules with the mlLoadModules task? They need to be copied from your filesystem into MarkLogic.
|
[
"stackoverflow",
"0050208241.txt"
] |
Q:
Fill Dataset Async
Below method is getting used to fill Dataset.
if we are calling this method in synchronous way it is working fine.
But now we need to call this method in Asynchronous way.so what changes i need to do so that below method should work properly without any issue.
public DataSet Filldata(string ProcName, string TableName)
{
DataSet ds = new DataSet();
try
{
da = new SqlDataAdapter(ProcName, con);
if (con.State != ConnectionState.Open)
{
con.Open();
}
da.SelectCommand.CommandTimeout = 15000;
da.Fill(ds, TableName);
}
catch (Exception ex)
{
ErrorMsg = ex.Message.ToString();
HMISLogger.logger.Error(ex.Message.ToString() + " " + ProcName, ex);
}
finally
{
con.Close();
da.Dispose();
}
return ds;
}
A:
You can declare the class level static object as below
private static object lockObject = new object();
And modify the your method as below , As Fill method takes care of connection open and close we can add lock statement before it.
public DataSet Filldata(string ProcName, string TableName)
{
DataSet ds = new DataSet();
try
{
da = new SqlDataAdapter(ProcName, con);
da.SelectCommand.CommandTimeout = 15000;
lock (lockObj)
{
da.Fill(ds, TableName);
}
}
catch (Exception ex) {
ErrorMsg = ex.Message.ToString();
HMISLogger.logger.Error(ex.Message.ToString() + " " + ProcName, ex);
}
finally {
con.Close();
da.Dispose();
}
return ds;
}
|
[
"stackoverflow",
"0030180521.txt"
] |
Q:
What is the alternative to getopt function on Windows c++?
The code below I'm using Posix C:
while ((opt = getopt(argc, argv, "a:p:h")) != -1)
How can I port this code to Windows C++ using an alternative function?
Thanks
A:
Microsoft has provided a nice implementation (as well as some other helpers) inside the open source IoTivity project here you could possibly re-use (pending any licensing requirements you may have):
Take a look at the "src" and "include" directories here for "getopt.h/.c".
https://github.com/iotivity/iotivity/tree/master/resource/c_common/windows
|
[
"stackoverflow",
"0007072591.txt"
] |
Q:
codeigniter base url not working correctly
I just launched a new site and I have the base url as:
$config['base_url'] = 'http://x.com/';
which works but when i go to www.x.com in my browser I get page not found error.
When I set the base url to 'http://www.x.com/'. Now the site does not work anymore.
Does anyone know how to fix this? I am lost on how to get this going.
A:
It sounds like you actually have an issue with your VirtualHosts. That would explain why you're getting 404's. Try adding this to your httpd.conf or equivalent and then restart Apache:
# Place this in the virtualhost listening to x.com.
ServerAlias www.x.com
|
[
"stackoverflow",
"0019902767.txt"
] |
Q:
Read-only (visually) CheckBox
I need to have 2 groups of controls on the screen: inputs and outputs (so they have 2 states: On or Off). Thus CheckBox seems to be a good choice. Checking any output will set it.
However, when displaying inputs there will be no user interaction with it. User is only allowed to see its value, not to change it.
Question: how to make checkbos visually appears as read-only ?
Could think about possible solutions:
Make CheckBox disabled. Bad: there will be no tooltip (possible to solve it? by fake panel on top?) and visually disabled CheckBox is not nice (and I don't want to make user think it is disabled).
Use different control. Which one? Label doesn't have nice placeholder for the On/Off value. RadioButton look differently, but they usually means there is a single choice out of many, while values of inputs are independent.
Making own component. Drawing the whole CheckBox is a bit overkill (and honestly, I don't know how to do it to have Win7 appearance). Would it be possible to add only ReadOnly appearance to the box part easily?
What do you guys think?
A:
There is a solution that is combination of the existing answers.
checkBox.ForeColor = Color.Gray; // Read-only appearance
checkBox.AutoCheck = false; // Read-only behavior
// Tooltip is possible because the checkbox is Enabled
var toolTip = new ToolTip();
toolTip.SetToolTip(checkBox, "This checkbox is read-only.");
The result is a CheckBox that
appears disabled with gray text
prevents the Checked value from changing when clicked
supports a Tooltip
A:
You have to draw everything yourself. I think you should use some controls with correct layout to mimic it. Here is the demo code for you, note that it does not support AutoSize correctly. Because the drawn stuff is always wider than the default stuff (which the AutoSize works with), implementing the AutoSize is not easy, If you don't care too much about AutoSize, this would be the great control for you:
public class XCheckBox : CheckBox
{
public XCheckBox()
{
SetStyle(ControlStyles.Opaque, false);
ReadOnlyCheckedColor = Color.Green;
ReadOnlyUncheckedColor = Color.Gray;
}
public bool ReadOnly { get; set; }
public bool AlwaysShowCheck { get; set; }
public Color ReadOnlyCheckedColor { get; set; }
public Color ReadOnlyUncheckedColor { get; set; }
protected override void OnPaint(PaintEventArgs pevent)
{
if (ReadOnly)
{
pevent.Graphics.SmoothingMode = SmoothingMode.HighQuality;
pevent.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
if (AlwaysShowCheck || Checked)
{
RenderCheck(pevent.Graphics);
}
RenderText(pevent.Graphics);
}
else base.OnPaint(pevent);
}
private void RenderCheck(Graphics g)
{
float fontScale = Font.Size / 8.25f;
Size glyphSize = CheckBoxRenderer.GetGlyphSize(g, System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal);
glyphSize.Width = (int) (glyphSize.Width * fontScale);
glyphSize.Height = (int)(glyphSize.Height * fontScale);
string checkAlign = CheckAlign.ToString();
using (GraphicsPath gp = new GraphicsPath())
using (Pen pen = new Pen(Checked ? ReadOnlyCheckedColor : ReadOnlyUncheckedColor, 1.5f)
{
LineJoin = LineJoin.Round,
EndCap = LineCap.Round,
StartCap = LineCap.Round
})
{
gp.AddLine(new Point(3, 7), new Point(5, 10));
gp.AddLine(new Point(5, 10), new Point(8, 3));
float dx = checkAlign.EndsWith("Right") ? Math.Max(-4*fontScale, ClientSize.Width - glyphSize.Width - 4 * fontScale) :
checkAlign.EndsWith("Center") ? Math.Max(-4*fontScale, (ClientSize.Width - glyphSize.Width) / 2 - 4 * fontScale) : -4;
float dy = checkAlign.StartsWith("Bottom") ? Math.Max(-4*fontScale, ClientSize.Height - glyphSize.Height - 4*fontScale) :
checkAlign.StartsWith("Middle") ? Math.Max(-4*fontScale, (ClientSize.Height - glyphSize.Height) / 2 - 4*fontScale) : 0;
g.TranslateTransform(dx, dy);
g.ScaleTransform(1.5f*fontScale, 1.5f*fontScale);
g.DrawPath(pen, gp);
g.ResetTransform();
}
}
private void RenderText(Graphics g)
{
Size glyphSize = CheckBoxRenderer.GetGlyphSize(g, System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal);
float fontScale = Font.Size / 8.25f;
glyphSize.Width = (int)(glyphSize.Width * fontScale);
glyphSize.Height = (int)(glyphSize.Height * fontScale);
string checkAlign = CheckAlign.ToString();
using (StringFormat sf = new StringFormat())
{
string alignment = TextAlign.ToString();
sf.LineAlignment = alignment.StartsWith("Top") ? StringAlignment.Near :
alignment.StartsWith("Middle") ? StringAlignment.Center : StringAlignment.Far;
sf.Alignment = alignment.EndsWith("Left") ? StringAlignment.Near :
alignment.EndsWith("Center") ? StringAlignment.Center : StringAlignment.Far;
sf.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
Rectangle textRectangle = ClientRectangle;
if (checkAlign.EndsWith("Left"))
{
textRectangle.Width -= glyphSize.Width;
textRectangle.Offset(glyphSize.Width, 0);
}
else if (checkAlign.EndsWith("Right"))
{
textRectangle.Width -= glyphSize.Width;
textRectangle.X = 0;
}
g.DrawString(Text, Font, new SolidBrush(ForeColor), textRectangle, sf);
}
}
bool suppressCheckedChanged;
protected override void OnClick(EventArgs e)
{
if (ReadOnly) {
suppressCheckedChanged = true;
Checked = !Checked;
suppressCheckedChanged = false;
}
base.OnClick(e);
}
protected override void OnCheckedChanged(EventArgs e)
{
if (suppressCheckedChanged) return;
base.OnCheckedChanged(e);
}
}
NOTE: The code is not fully implemented, everything is kept as simple as possible. You can change the AlwaysShowCheck property to choose the ReadOnly unchecked state, it can be a gray tick mark or nothing. You can set the ReadOnly to true to make it Read-only visual.
AlwaysShowCheck is set to true (the ReadOnly unchecked state is indicated by a gray tick mark)
AlwaysShowCheck is set to false (the ReadOnly unchecked state is indicated by nothing)
|
[
"stackoverflow",
"0006470126.txt"
] |
Q:
Building Per User Customizable Systems
I am building a web application where I want to build a form that is per-user configurable. For example, the user should be able to specify "I want a select box with a list of values I give you for input A, a textbox for input B, and another select box with a list of values I give you for input C". Then, the user can later fill out the form based on how they customized it. To be clear, this is not a system to build html forms for your own webpage. The form lives and integrates with the rest of the application.
I have a couple of ideas in my head on how to implement this, but I am curious how others who have built similar applications have dealt with similar problems (i.e. per-user customizable systems). I don't care about a specific language or framework, although you can point to some if it helps explain your solution.
A) creating a fairly complex relational database schema (needs a User table, a User_Fields table, a Fields_SelectValues table, and then for record keeping a SubmittedRecord table that includes the fields with their actual values on a submit. Actually, there will need to be another table SubmittedRecord_FieldValues that maps the user specific field values to a given SubmittedRecord). The results of a submit will then be used throughout another part of the application, so lookups on submitted values will be done a lot. This is the most robust, but likely the slowest to use (good # of joins to get all of the date you may need) and hardest to implement. Also, this could be overkill since most users will have a significant overlap in the way they want things setup.
B) Instead of building all of the data needed to build everything like above, I store an HTML blob for each user. Then I can have a field in a SubmittedRecord table called "Values" that is just a delimited string of their field names and submitted values. This makes for quick lookups, but slow to select on an individual field later. But mostly, I am concerned that this anti-relational schema has some unforseen issues that I haven't yet thought about.
How have you seen this kind of thing done before?
Note: I am not necessarily looking for a solution to my exact problem, just general advice on this type of problem.
A:
Option B sounds like a security risk and a maintenance nightmare.
Option A sounds much better.
Depending on your platform / framework there should already be mechanisms built-in which help with user profile related capabilities; so I'd see what currently exists in your chosen platform first.
I know that ASP.NET has a couple of mechanisms that provide solutions in this space.
A big consideration(which will impact design and implementation of such a system) will be how to build the "schema" of the profile in the first place; is it "baked-in" to the system or can admins dynamically (through the UI) modify the schema?
|
[
"askubuntu",
"0001096811.txt"
] |
Q:
Windows emulator on ubuntu with GPU passthrough?
I have a Ubuntu and Windows dual boot, I use Ubuntu for everything except gaming.(Wine/dxvk doesn't cut it) Now I'd like to not have to reboot when I feel like playing a game, which sometimes is only 10 minutes. So I want to have a Windows 10 emulator, with GPU passthrough. My machine has a Titan Xp, but I have an additional RX480 which I am willing to use for Windows 10. So is what I want possible?
And if so, does anyone have a tutorial for it?
Thanks!
Edit:
I of course mean having an emulator(e.g. virtualbox) run Windows 10, and also have the emulator(virtualbox in this case) also pass the GPU to the VM(Windows 10). So I can just install the AMD driver on Windows, and have Windows be in full controll over it.(And thus get excellent performance)
A:
what you call an "emulator" is actually called a "Virtual Machine".
I believe you have all the right HW to achieve what you want, so you're starting on the right foot. Basically you have to:
verify you have a IOMMU compatible system
have a UEFI compatible second GPU
install your Amd second GPU in a PCI port on your motherboard
blacklist amdgpu drivers and load a couple of kernel functions (using GRUB it's easier)
"detach" the amd GPU via software using VFIO module
create a VM (my advise is KVM + libvirt) and configure your system to pass the detached AMD gpu to it.
Start the VM and install Windows 10 and drivers as usual. (You also have to attach the second GPU to a second monitor, and pass another mouse and keyboard through USB to the VM: host and guest will be as two whole different PCs)
Don't expect the same performance as you run everything in dual boot anyway, but with patience and some tweaks you can easily reach 80%. It's a good idea to have different GPUs for the host and the guest (nvidia and ATI), like you do. this is a good starting point.
|
[
"english.stackexchange",
"0000334685.txt"
] |
Q:
Name for the ceiling support rods
What is the actual name of those rods, which are hung from the ceiling, used to support walkways or overhead catwalks ?
Note: I'm not talking about curtain or shower rods, I'm talking about the kind capable of handling a huge load.
A:
I believe they're called tie rods - https://en.wikipedia.org/wiki/Tie_rod
There's a famous case of a massive engineering failure involving walkways held up by steel rods - the 1981 Hyatt Regency disaster:
https://en.wikipedia.org/wiki/Hyatt_Regency_walkway_collapse
The walkways collapsed onto the people below, and it turned out to be because the steel rods holding up the walkway had not been attached to the walkways in the precise way detailed in the plans. This deviation introduced a terrible structural weakness which led to the collapse.
In that Wikipedia article, the rods are variously referred to as "tie rods", "steel rods" or "steel tie rods". If we use this as evidence, I'd say that the name of the component is a "tie rod", and the ones used in this incident were made of steel, hence "steel tie rods".
|
[
"stackoverflow",
"0050940593.txt"
] |
Q:
Integrate swashbuckle swagger with odata in ASP.Net Core
I have tried to implement both ( swagger and odata ) in asp.net core, but it's not working.
I'm unable to integrate the route given for odata.
I have the following Configuration and I receive a generic error.
This is the error
A:
We ran into the same issue when adding OData to our .Net Core project. The workarounds shown in the code snippet on this post fixed our API error(s) when Swagger UI loads.
As far as I can tell, OData isn't supported in Swashbuckle for AspNetCore. So after adding the workaround code in the link above, our Swagger UI works, but none of the OData endpoints show.
Code snippet from the link:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOData();
// Workaround: https://github.com/OData/WebApi/issues/1177
services.AddMvcCore(options =>
{
foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Product>("Products");
app.UseMvc(routebuilder =>
{
routebuilder.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
// Workaround: https://github.com/OData/WebApi/issues/1175
routes.EnableDependencyInjection();
});
}
}
A:
I was able to do this using a DocumentFilter. Create a class like the example below, then add it to your Swagger configuration as:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "Your title API v1.0", Version = "v1.0" });
options.DocumentFilter<CustomDocumentFilter>();
});
Github Example
A:
You can integrate Swagger a couple of different ways. For barebones support, you can use the ODataSwaggerConverter provided by OData. This will effectively convert the EDM to a Swagger document. To wire this up to a Swagger generator library like Swashbuckle, you just need create and register a custom generator. The UI and client side of things should remain unchanged. If the generated Swagger document isn't sufficient, the base implementation of the ODataSwaggerConverter is still a reasonable start.
If you're using API Versioning for OData with ASP.NET Core, you need only add the corresponding API Explorer package. Swashuckle will light up with little-to-no additional work on your part. The ASP.NET Core with OData Swagger sample application has an end-to-end working example.
|
[
"stackoverflow",
"0009237083.txt"
] |
Q:
Git Moving Files into Folders
I am quite new to git and version control in general, and have question about moving files around. I have a master repo on GitHub, with 6 source files.
I've done a lot of work on the project and now my local branch contains two folders with the sources in those.
The directory structure used to be like:
Master:
File 1
File 2
File 3
File 4
File 5
File 6
Where as my local branch now looks like this:
New Folder 1:
New File 1
New File 2
New File 3
New Folder 2:
File 1
File 2
File 3
File 4
File 5
File 6
How can I move my local structure to the master branch without losing my commit history on the old files?
A:
Just commit. Git blame etc will generally do a pretty good job of automatically detecting moves.
A:
git doesn't actually track "moves" of files, it infers it on demand from similar content. So, just make the move and add / remove files as appropriate. (You will make life easier for the tools in future if you avoid making changes to the content as well as moving them in a single commit.)
Then, to see the log accounting for moves, use -M, -C, or their variants to git log. Similar flags apply to other tools, and you should read the help to understand the detail of what they do.
If you use git mv on a file, it just does the git rm and git add for you.
A:
The other posters are correct, however if you want to confirm that git is going to see these as moves (and not a combination of delete/create), run a git status. You should see:
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: oldfile.txt -> newFolder/newfile.txt
|
[
"stackoverflow",
"0007199396.txt"
] |
Q:
A good Lua editor for Mac?
Whats a good Lua text editor for the Mac? All I need is just to edit the code. Not a Compiler or anything.
A:
BBEdit is the best all-around editor for the Mac. Lua is one of the default languages for the syntax colorizer.
|
[
"stackoverflow",
"0023059791.txt"
] |
Q:
FlexTable with Uibinder or alternatives
What's the best way to use flextable in corperation with uiBinder, I already know that I have to provide it and initiate it befor initWidget
@UiField(provided = true) FlexTable contentTable;
But I simply need a table with as an input matrix like:
pseudo:
Label."Name: " TextBox()
Label."Password: " TextBox()
Know is it a good idea to even consider FlexTable or is there a better Alternativ?
Thanks for any help.
A:
I'll pass on the fact that using a table for a form layout is not your best option nor a good practice.
You can just use an HTMLPanel with UiBinder, and do everything in HTML like you would with a "normal" page, with some additional GWT tags for widgets :
<g:HTMLPanel>
<div class="formInput">
<g:Label text="First Name - W3C style : ">
<g:TextBox ui:field="firstNameTextBox">
</div>
<table>
<tbody>
<tr>
<td>Last name - table style :</td>
<td><g:TextBox ui:field="lastNameTextBox" /></td>
</tr>
<tr>
<!-- Other form fields -->
</tr>
</tbody>
</table>
</g:HTMLPanel>
|
[
"stackoverflow",
"0009836273.txt"
] |
Q:
Naming multiple plots with original name
I am plotting multiple plots:
a <- dir(pattern="stuff.*\\.txt$")
for (i in 1:length(a)) {
b <- read.table(a[i])
jpeg(paste("/../.../", i, ".jpg"))
plot(b$V1,b$V2, main=?)
dev.off()
}
I want to name all jpg & main=? with original file name. All jpgs from this code are named from 1 to N. Is their any way to do this?
A:
Perhaps I'm missing something, but the variable a[i] is the original data file name. So you just need to do:
plot(b$V1, b$V2, main=a[i])
In your 'paste' function, the default separator is a space, so:
paste("A", "B")
gives A B. Instead, you want: paste(A,B, sep=""). When creating the jpeg file you should remove the .txt or .csv file extension from your data. So something like:
library(tools)
fname = file_path_sans_ext(a[i])
jpeg(paste("/../.../", fname, ".jpg", sep=""))
Should work
|
[
"math.stackexchange",
"0000892011.txt"
] |
Q:
How to find the area of an isosceles triangle without using trigonometry?
I have an isosceles triangle with equal sides $10$ unit, angle between them is $30^\circ$. I need to be confirmed that the area of this triangle can be found in any method other than using any kind of trigonometry. I tried Heron's formulae, but did not get any fruitful result.
A:
Consider circumscribed circle and it's radius $R$. By inscribed angle theorem you get, that $|c|=|R|$, where $c$ is third side of your triangle $a=b=10$. Now you have formula $\displaystyle S=\frac{abc}{4R}$, where $S$ is area of triange. So:
$$S=\frac{10 \cdot 10 \cdot c}{4R}=\frac{100}{4}=25$$
|
[
"stackoverflow",
"0007343834.txt"
] |
Q:
how to write custom query in symfony
I am using symfony framework for my project, but many time i'm very confused to write mysql query in doctrine mode, so, please suggest me how to write custom query in symfony,
like
SELECT * FROM USER WHERE A.ID = 'X3B8882'
A:
$query="SELECT * FROM USER WHERE A.ID = 'X3B8882'"
$conn = Doctrine_Manager::getInstance()->connection();
$stmt = $conn->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch()) {
$results[] = $row['sm_mnuitem_webpage_url'] ;
}
|
[
"stackoverflow",
"0060156430.txt"
] |
Q:
jQuery .find('li').length must be from sibling/child?
I'm trying to make a counter to count the number of li, but what I want to count lies in another element (section), and my jQuery setup with .find('li').length; don't want to work (I took it from another counter my teacher made for me, that works). Must the elements I want to count be siblings or children for it to work?
it's like, the one that works is basically built like this in html
<div>
<div><span>0</span></div>
<ul>
<li></li>
</ul>
</div>
while what I'm trying to do is more like this
<section>
<footer>
<div><span>0</span></div>
</footer>
</section>
<section>
<ul>
<li></li>
</ul>
</section>
my jQuery is currenly like this
var $name1 = $('.classname1 span'),
$name2 = $('.classname2 ul');
var name3 = $name2.find('li').lenght;
$name1.text(name3);
fair warning, I'm a newbie. I've only studied coding for 1,5 year.
A:
don't want to work That's one way of putting it :)) .
element.find('li') will find all the li which are descendants of that element. This includes children, grandchildren and so on. It's similar to children() method but this one only searches in the ' first ' level of descendants.
Second, the name is length not lenght as you write it.
See below
// will return all 8 li
let liCount = $('ul.top-level').find('li').length
console.log(liCount)
// will return just the top 5 ( direct children )
liCount = $('ul.top-level').children('li').length
console.log(liCount)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='top-level'>
<li></li>
<li></li>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li></li>
</ul>
|
[
"math.stackexchange",
"0000505573.txt"
] |
Q:
Infinite Series $\sum\limits_{n=2}^{\infty}\frac{\zeta(n)}{k^n}$
If $f\left(z \right)=\sum_{n=2}^{\infty}a_{n}z^n$ and $\sum_{n=2}^{\infty}|a_n|$ converges then,
$$\sum_{n=1}^{\infty}f\left(\frac{1}{n}\right)=\sum_{n=2}^{\infty}a_n\zeta\left(n\right).$$
Since if we set $C:=\sum_{m=2}^{\infty}|a_m|<\infty$, then
$$\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}|a_m\frac{1}{n^m}|\leq\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}|a_m|\frac{1}{n^2}\leq C\sum_{n=1}^{\infty}\frac{1}{n^2}<\infty$$
and by Cauchy's double series theorem, we can switch the order of summation:
$$\sum_{n=1}^{\infty}f\left(\frac{1}{n}\right)=\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}a_m\frac{1}{n^m}=\sum_{m=2}^{\infty}a_m\sum_{n=1}^{\infty}\frac{1}{n^m}=\sum_{n=2}^{\infty}a_n\zeta\left(n\right).$$
This shows that $\sum_{n=2}^{\infty}\frac{\zeta(n)}{k^n}=\sum_{n=1}^{\infty}\frac{1}{kn(kn-1)}$.
My Questions:
1) It's obvious that $\sum_{n=1}^{\infty}\frac{1}{2n(2n-1)}=\log(2)$, but how can I evaluate $\sum_{n=1}^{\infty}\frac{1}{3n(3n-1)}$?
2) Is there another method to evaluate $\sum_{n=2}^{\infty}\frac{\zeta(n)}{k^n}$?
A:
Extended Harmonic Numbers
Normally, we think of Harmonic Numbers as
$$
H_n=\sum_{k=1}^n\frac1k\tag{1}
$$
However, an alternate definition is often useful:
$$
H_n=\sum_{k=1}^\infty\left(\frac1k-\frac1{k+n}\right)\tag{2}
$$
For integer $n\ge1$, it is not too difficult to see that the two definitions agree. However, $(2)$ is easily extendible to all $n\in\mathbb{R}$ (actually, to all $n\in\mathbb{C}$). We can say some things about $H_n$ for some $n\in\mathbb{Q}\setminus\mathbb{Z}$.
Note that for $m,n\in\mathbb{Z}$,
$$
\begin{align}
H_{mn}-H_n
&=\sum_{k=1}^\infty\left(\frac1k-\frac1{k+mn}\right)-H_n\\
&=\sum_{k=1}^\infty\sum_{j=0}^{m-1}\left(\frac1{km-j}-\frac1{km-j+mn}\right)-H_n\\
&=\frac1m\sum_{j=0}^{m-1}\sum_{k=1}^\infty\left(\left(\frac1k-\frac1{k-j/m+n}\right)-\left(\frac1k-\frac1{k-j/m}\right)\right)-H_n\\
&=\frac1m\sum_{j=0}^{m-1}\left(\left(H_{n-j/m}-H_n\right)-H_{-j/m}\right)\tag{3}
\end{align}
$$
Since $H_0=0$ and $H_n=\log(n)+\gamma+O\left(\frac1n\right)$, where $\gamma$ is the Euler-Mascheroni Constant, if we let $n\to\infty$ in $(3)$, we get
$$
\sum_{j=1}^{m-1}H_{-j/m}=-m\log(m)\tag{4}
$$
Using identity $(7)$ from this answer,
$$
\begin{align}
\pi\cot(\pi z)
&=\sum_{k\in\mathbb{Z}}\frac1{k+z}\\
&=\sum_{k=1}^\infty\left(\frac1{k-1+z}-\frac1{k-z}\right)\\
&=\sum_{k=1}^\infty\left(\frac1k-\frac1{k-z}\right)-\sum_{k=1}^\infty\left(\frac1k-\frac1{k+z-1}\right)\\
&=H_{-z}-H_{z-1}\tag{5}
\end{align}
$$
which implies
$$
H_{-j/m}-H_{-(m-j)/m}=\pi\cot\left(\frac{\pi j}{m}\right)\tag{6}
$$
Using $(4)$ and $(6)$ for $m=3$ yields
$$
H_{-1/3}+H_{-2/3}=-3\log(3)\tag{7}
$$
and
$$
H_{-1/3}-H_{-2/3}=\pi\cot\left(\frac\pi3\right)\tag{8}
$$
Averaging $(7)$ and $(8)$ yields
$$
H_{-1/3}=-\frac32\log(3)+\frac\pi{2\sqrt3}\tag{9}
$$
Finally,
$$
\begin{align}
\sum_{n=1}^\infty\frac1{3n(3n-1)}
&=-\frac13\sum_{n=1}^\infty\left(\frac1n-\frac1{n-1/3}\right)\\
&=-\frac13H_{-1/3}\\[6pt]
&=\frac12\log(3)-\frac\pi{6\sqrt3}\tag{10}
\end{align}
$$
Values for Future Reference
Using $(4)$ and $(6)$, we can also compute
$$
\begin{align}
H_{-1/4}&=\pi/2-3\log(2)\\
H_{-1/2}&=-2\log(2)\\
H_{-3/4}&=-\pi/2-3\log(2)
\end{align}\tag{11}
$$
A:
Answer to Second Question
We remark that
$$\Gamma(z)\zeta(z)=\int_0^\infty \frac{u^{z-1}}{e^u-1}du\tag{1}$$
$$\sum_{n=2}^\infty \frac{t^n}{(n-1)!}=(e^t-1)t \tag{2}$$
$$\psi_0(s+1)=-\gamma+\int_0^1 \frac{1-x^s}{1-x}dx \tag{3}$$
where $\psi_0(s)$ is Digamma Function and $\gamma$ is the Euler's Constant.
Then
$$\begin{align*}
\sum_{n=2}^\infty \frac{\zeta(n)}{k^n} &= \sum_{n=2}^\infty \frac{1}{k^n \Gamma(n)}\int_0^\infty \frac{u^{n-1}}{e^u-1}du\\
&=\int_0^\infty\frac{1}{u(e^u-1)}\left( \sum_{n=2}^\infty \frac{1}{(n-1)!}\left(\frac{u}{k}\right)^n\right)du \\
&= \frac{1}{k}\int_0^\infty \frac{e^{\frac{u}{k}}-1}{e^u-1}du \tag{4}
\end{align*}$$
Substituting $t=e^{-u}$, we get
$$
\begin{align*}
\sum_{n=2}^\infty \frac{\zeta(n)}{k^n}&=-\frac{1}{k}\int_0^1 \frac{1-t^{-1/k}}{1-t}dt \\
&= \frac{-1}{k}\left\{ \gamma+\psi_0 \left(1-\frac{1}{k} \right)\right\} \tag{5}
\end{align*}
$$
If $k(\geq 2)$ is an integer, equation $(5)$ can be further simplified using Gauss' Digamma Theorem.
$$\sum_{n=2}^\infty \frac{\zeta(n)}{k^n}=-\frac{\pi}{2k}\cot \left( \frac{\pi}{k}\right)+\frac{\log k}{k}-\frac{1}{k}\sum_{m=1}^{k-1}\cos \left(\frac{2\pi m}{k} \right) \log \left( 2\sin \frac{\pi m}{2}\right)$$
A:
Answering you first question.
Don't know whether it's simpler but still (since you'll have to deal with hypergeometric functions).
$$ \sum_{n=1}^{\infty}\frac{1}{3n(3n-1)}=\frac{1}{3}\sum_{n=1}^{\infty}\frac{1}{3n-1}\int_0^1x^{n-1} \mathrm dx=\frac{1}{3}\int_0^1\sum_{n=1}^{\infty}\frac{x^{n-1}}{3n-1}\mathrm dx$$
$$\sum_{n=1}^{\infty}\frac{x^{n-1}}{3n-1}=\frac{1}{2} \, _2F_1\left(\frac{2}{3},1;\frac{5}{3};x\right)$$
And $$\frac{1}{6} \int_0^1 \, _2F_1\left(\frac{2}{3},1;\frac{5}{3};x\right) \, \mathrm dx=\frac{1}{6} \left(3\log(3) -\frac{\pi }{\sqrt{3}}\right)$$
So $$\sum_{n=1}^{\infty}\frac{1}{3n(3n-1)}=\frac{1}{6} \left(3\log(3) -\frac{\pi }{\sqrt{3}}\right)$$
|
[
"stackoverflow",
"0015989098.txt"
] |
Q:
PHP str_ireplace in libreoffice basic
Does anybody know how to make function in Libreoffice basic like str_ireplace in PHP?
I want to use in my cell function.
str_ireplace(search - range of cells, replace - range of cells, text)
or at least str_replace
A:
I made really simple function
Function Str_ireplace(Search As Variant, Replace As Variant, Source As String)
Dim Result As String
Dim StartPos As Long
Dim CurrentPos As Long
Dim CurrentSearch As String
Dim CurrentReplace As String
Result = ""
For Row = Lbound( Search, 1 ) To Ubound( Search, 1 )
For Col = LBound(Search, 2) To UBound(Search, 2)
StartPos = 1
CurrentPos = 1
CurrentSearch = Search(Row, Col)
CurrentReplace = Replace(Row, Col)
Result = ""
Do While CurrentPos <> 0
CurrentPos = InStr(StartPos, Source, CurrentSearch)
If CurrentPos <> 0 Then
Result = Result + Mid(Source, StartPos, _
CurrentPos - StartPos)
Result = Result + CurrentReplace
StartPos = CurrentPos + Len(CurrentSearch)
Else
Result = Result + Mid(Source, StartPos, Len(Source))
End If ' Position <> 0
Loop
Source = Result
Next
Next
Str_ireplace = Result
End Function
I used this as example:
http://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/Strings_(Runtime_Library)
|
[
"stackoverflow",
"0021737771.txt"
] |
Q:
Can someone please explain the use of modulus in this code?
I know that modulus gives the remainder and that this code will give the survivor of the Josephus Problem. I have noticed a pattern that when n mod k = 0, the starting count point begins at the very beginning of the circle and that when n mod k = 1, the person immediately before the beginning of the circle survived that execution round through the circle.
I just don't understand how this recursion uses modulus to find the last man standing and what josephus(n-1,k) is actually referring to. Is it referring to the last person to get executed or the last survivor of a specific round through the circle?
def josephus( n, k):
if n ==1:
return 1
else:
return ((josephus(n-1,k)+k-1) % n)+1
A:
This answer is both a summary of the Josephus Problem and an answer to your questions of:
What is josephus(n-1,k) referring to?
What is the modulus operator being used for?
When calling josephus(n-1,k) that means that you've executed every kth person up to a total of n-1 times. (Changed to match George Tomlinson's comment)
The recursion keeps going until there is 1 person standing, and when the function returns itself to the top, it will return the position that you will have to be in to survive. The modulus operator is being used to help stay within the circle (just as GuyGreer explained in the comments). Here is a picture to help explain:
1 2
6 3
5 4
Let the n = 6 and k = 2 (execute every 2nd person in the circle). First run through the function once and you have executed the 2nd person, the circle becomes:
1 X
6 3
5 4
Continue through the recursion until the last person remains will result in the following sequence:
1 2 1 X 1 X 1 X 1 X X X
6 3 -> 6 3 -> 6 3 -> X 3 -> X X -> X X
5 4 5 4 5 X 5 X 5 X 5 X
When we check the values returned from josephus at n we get the following values:
n = 1 return 1
n = 2 return (1 + 2 - 1) % 2 + 1 = 1
n = 3 return (1 + 2 - 1) % 3 + 1 = 3
n = 4 return (3 + 2 - 1) % 4 + 1 = 1
n = 5 return (1 + 2 - 1) % 5 + 1 = 3
n = 6 return (3 + 2 - 1) % 6 + 1 = 5
Which shows that josephus(n-1,k) refers to the position of the last survivor. (1)
If we removed the modulus operator then you will see that this will return the 11th position but there is only 6 here so the modulus operator helps keep the counting within the bounds of the circle. (2)
|
[
"math.stackexchange",
"0000142974.txt"
] |
Q:
Why is this subgroup normal?
Let $G$ be a group of odd order and $H$ a subgroup of index 5, then $H$ is normal. How can I prove this? (there is an hint: use the fact that $S_5$ has no element of order $15$)
I took the usual homomorphism $\varphi:G\rightarrow S(G/H)\cong S_5$ and call $K$ its kernel, then $K\subset H$. I want to prove that they are equal (I don't know if that's true), if they are not equal I proved that then $[H:K]=3$, but I don't know how to go on, any idea?
A:
Use the fact that $[G:K] = [G:H][H:K]$ and that every group of order $15$ is cyclic.
|
[
"wordpress.stackexchange",
"0000240429.txt"
] |
Q:
how to force tag page layout to use same as search layout?
I have remarked that when clicking on a tag I have a list of posts displayed differently that when I use search box.
How to force tag page layout to use same as search layout for any template ?
A:
You can tell WordPress to use the search.php template whenever viewing tags by using the template_include. It works like this:
function wpse_240429() {
// IF we're planning on loading a tag template
if( is_tag() ) {
// Try to locate the search.php template
$search_template = locate_template( 'search.php' );
// If the search template exists
if( ! empty( $search_template ) ) {
// Use search.php for display purposes
return $search_template ;
}
}
}
add_action( 'template_include', 'wpse_240429' );
You shouldn't have to mess with things like pre_get_posts as the query should already be pulled.
|
[
"stackoverflow",
"0041516464.txt"
] |
Q:
Delphi check if double is an integer or not
I need to test if a double is an integer or not. Basically this is an example of the rule:
5.0 > true
5.2 > false
In order to do this I'd make an if (result mod 1) = 0 then and see the if it returns true or false. Consider that result is a double. By the way the compiler gives me this error:
[dcc32 Error] Unit1.pas(121): E2015 Operator not applicable to this
operand type
How can I solve this problem? Note that my numbers are in this format ##.##### so I haven't many problems with the floating point precision.
In general I'd use if (result % 1 == 0) {} but in Delphi this does not work.
A:
You can use the function frac declared in the System unit of Delphi. Try with this code:
if ( frac(result) = 0 ) then
ShowMessage('is zero')
else
ShowMessage('is NOT zero');
end;
Check the documentation for details about the function. What you are doing is wrong because in Delphi the keyword mod only works with Integers.
Note. I have tested this with numbers such as 45.1234 and the code is correct. I see that you have a little number of digits in your double so there shouldn't be problems. I am not sure how accurate that function is, but in this case you don't have to worry.
|
[
"stackoverflow",
"0050033794.txt"
] |
Q:
Using TypeScript's InstanceType generics with abstract classes?
TypeScript 2.8 added a new core type InstanceType which can be used to get the return type of a constructor function.
/**
* Obtain the return type of a constructor function type
*/
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;
This feature is pretty nice, but falls apart when using abstract classes, which don't have a new declaration according to TypeScript's type system.
At first, I thought I could get around this limitation by creating a similar but less-restrictive type (removing the extends new (...args: any[]) => any guard):
export type InstanceofType<T> = T extends new(...args: any[]) => infer R ? R : any;
But it too falls apart when passed an abstract class, as it cannot infer the return type and defaults to any. Here's an example using a mock DOM as an example, with attempted type casting.
abstract class DOMNode extends Object {
public static readonly TYPE: string;
constructor() { super(); }
public get type() {
return (this.constructor as typeof DOMNode).TYPE;
}
}
class DOMText extends DOMNode {
public static readonly TYPE = 'text';
constructor() { super(); }
}
abstract class DOMElement extends DOMNode {
public static readonly TYPE = 'text';
public static readonly TAGNAME: string;
constructor() { super(); }
public get tagname() {
return (this.constructor as typeof DOMElement).TAGNAME;
}
}
class DOMElementDiv extends DOMElement {
public static readonly TAGNAME = 'div';
constructor() { super(); }
}
class DOMElementCanvas extends DOMElement {
public static readonly TAGNAME = 'canvas';
constructor() { super(); }
}
// Create a collection, which also discards specific types.
const nodes = [
new DOMElementCanvas(),
new DOMText(),
new DOMElementDiv(),
new DOMText()
];
function castNode<C extends typeof DOMNode>(instance: DOMNode, Constructor: C): InstanceofType<C> | null {
if (instance.type !== Constructor.TYPE) {
return null;
}
return instance as InstanceofType<C>;
}
// Attempt to cast the first one to an element or null.
// This gets a type of any:
const element = castNode(nodes[0], DOMElement);
console.log(element);
Is there any way I can cast a variable to being an instance of the constructor that is passed, if that constructor is an abstract class?
NOTE: I'm trying to avoid using instanceof because JavaScript's instaceof is very problematic (2 different versions of the same module have different constructor instances).
A:
You can query type of the prototype of an abstract class to obtain the type of its instances. This does not require that the type have a new signature only that it has a prototype property. Abstract classes do not have a new signature but they do have a prototype property.
Here is what it looks like
function castNode<C extends typeof DOMNode>(
instance: DOMNode,
Constructor: C
): C['prototype'] | null {
if (instance.type !== Constructor.TYPE) {
return null;
}
return instance;
}
The expression C['P'] in type position is called an indexed access type. It is the type of the value of the property named P in the type C.
|
[
"stackoverflow",
"0023102786.txt"
] |
Q:
Regex, I want to select (word + anything + word)
I'm trying to select name="custom-custom-selected"
and this is my regex \w*(name=".*-selected)
What I'm trying to say is that I want to select every word starting wtih "name=" and ending with "-selected" and has anything in between (digits or letters)
How do i say that?
A:
You can use something like
name="(.*?)-selected"
*? is a lazy quantifier, it means it will eat up as little as possible (so that .* doesn't select custom-custom-selected"name="custom-custom in name="custom-custom-selected"name="custom-custom-selected")
The result is in the first capturing group.
|
[
"stackoverflow",
"0047722042.txt"
] |
Q:
How to reverse arrows (tails) in Diagrammer, R?
Let's create a very simple diagram:
niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <- c("B","C","D","B","C","A","E")
arr <- c(rep("normal",6), "inv")
temp <- data.table(from=factor(from, levels=niv),
to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
width=0.3)
edges <- create_edge_df(from = temp$from,
to = temp$to, rel = "leading_to", label=temp$from,
arrowhead=arr, penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)
The diagram shows edges from one node to another.
Usually people paint that edges with an arrow head, but I would like to paint some with the opposite symbol, a tail head.
I've found that by using the parameter arrowhead="inv" I can change the arrow to be a tail instead. (In my example the edge from D to E has a tail).
But there is a problem, the tail is painted on the wrong side. I would like to paint it at the beginning of the edge (arrow).
How can I change it?
There is a parameter rel = "leading_to" but I haven't been able to find what other values it can get.
Also there is a parameter "dir" but I don't know how to use it either.
Thanks.
A bonus question would be: How to prevent Diagrammer from writing the labels just above the edges? I would like they don't overlap.
A:
You can switch the dir to "back":
library(DiagrammeR)
library(data.table)
niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <- c("B","C","D","B","C","A","E")
temp <- data.table(from=factor(from, levels=niv),
to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
width=0.3)
edges <- create_edge_df(from = temp$from,
to = temp$to, dir = "back", label=temp$from,
arrowtail="inv", penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)
|
[
"stackoverflow",
"0035630366.txt"
] |
Q:
How can I cast the expression to get rid of QAC warning?
I'm using QAC and I get the below message for the respective source code line. How can I cast it in order for QAC to "understand" it ?
Compiler used is gcc - it doesn't warn about this issue, as it is set to "iso c99".
#define DIAGMGR_SIGNED_2_BYTES_178 ((s16)178)
sK = (s16)(sE1 / DIAGMGR_SIGNED_2_BYTES_178);
^
Result of signed division or remainder operation may be implementation
defined
.
A division ('/') or remainder ('%') operation is being performed in a
signed integer type and the result may be implementation-defined.
Message 3103 is generated for an integer division or remainder
operation in a signed type where:
One or both operands are non-constant and of signed integer type, or
Both operands are integer constant expressions, one of negative value and one of positive value
A signed integer division or remainder operation in which one operand
is positive and the other is negative may be performed in one of two
ways:
The division will round towards zero and any non-zero remainder will be a negative value
The division will round away from zero and any non-zero remainder will be a positive value In the ISO:C99 standard the first approach is
always used. In the ISO:C90 standard either approach may be used - the
result is implementation defined. For example:
/PRQA S 3120,3198,3408,3447 ++/
extern int r;
extern int si;
extern void foo(void)
{
r = -7 / 4; /* Message 3103 *//* Result is -1 in C99 but may be -2 in C90 */
r = -7 % 4; /* Message 3103 *//* Result is -3 in C99 but may be 1 in C90 */
si = si / r; /* Message 3103 */
}
A:
You need to configure the tool so that it understands that your code is C99. In the old C90 standard, division with negative numbers could be implemented in two different ways, see this. This was a known "bug" in the C90 standard, which has been fixed since C99.
This is a standard warning for most static analysis tools, particularly if they are set to check for MISRA-C compliance. Both MISRA-C:2004 and 2012 require that the programmer is aware of this C standard "bug".
Work-arounds in C90:
If you know for certain that the operands aren't negative, simply cast them to unsigned type, or use unsigned type to begin with.
If you know that the operands might be negative:
If either operand is negative, set flags to indicate which one(s) it was.
Take the absolute values of both operands.
Perform division on absolute values.
Re-add sign to the numbers.
That's unfortunately the only portable work-around in C90. Alternatively you could add a static assertion to prevent the code from compiling on systems that truncate negative numbers downwards.
If you are using C99, no work-arounds are needed, as it always truncates towards zero. You can then safely disable the warning.
|
[
"stackoverflow",
"0056275373.txt"
] |
Q:
Error: unable to spawn process (Argument list too long) Xcode 10.1
Error Log:
PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/../Script-A..B8.sh (in target: C..r)
cd /Projects/...
/bin/sh -c /Users/../Script-A..B8.sh
error: unable to spawn process (Argument list too long)**
I am getting this error while creating an Archive from Xcode (10.1). My build succeeds. I encountered this error after installing below mentioned pods,
pod 'Firebase/Analytics'
pod 'Firebase/Messaging'
My Xcode project is a multi target and multi configuration project managed using xconfig file.
I tried disintegrating, installing, updating pod again and again, but no luck.
A:
Enable Legacy System for workspace setting
|
[
"stackoverflow",
"0029586439.txt"
] |
Q:
Use RelayCommand with not only buttons
I am using MVVM Light in my project and I am wondering if there is any way to use RelayCommand with all controls (ListView or Grid, for example).
Here is my current code:
private void Item_Tapped(object sender, TappedRoutedEventArgs e)
{
var currentItem = (TechItem)GridControl.SelectedItem;
if(currentItem != null)
Frame.Navigate(typeof(TechItem), currentItem);
}
I want to move this code to Model and use RelayCommand, but the ListView, Grid and other controls don't have Command and CommandParameter attributes.
What does MVVM Light offer to do in such cases?
A:
Following on from the link har07 posted this might be of some use to you as I see you mention CommandParameter.
It is possible to send the "Tapped" item in the list to the relay command as a parameter using a custom converter.
<ListView
x:Name="MyListView"
ItemsSource="{Binding MyCollection}"
ItemTemplate="{StaticResource MyTemplate}"
IsItemClickEnabled="True">
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="ItemClick">
<core:InvokeCommandAction Command="{Binding ViewInMoreDetail}" InputConverter="{StaticResource TapConverter}" />
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
</ListView>
Custom converter class
public class TapConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var args = value as ItemClickEventArgs;
if (args != null)
return args.ClickedItem;
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
In your view model you then have a relaycommand.
public RelayCommand<MyObject> MyRelayCommand
{
get;
private set;
}
In your constructor initialise the relay command and the method you want to fire when a tap happens.
MyRelayCommand = new RelayCommand<MyObject>(HandleTap);
This method receives the object that has been tapped in the listview as a parameter.
private void HandleTap(MyObject obj)
{
// obj is the object that was tapped in the listview.
}
Don't forget to add the TapConverter to your App.xaml
<MyConverters:TapConverter x:Key="TapConverter" />
|
[
"stackoverflow",
"0043306977.txt"
] |
Q:
Get unique data with multiple column using google app script
I'm new to the google app script and also javascript. Need some help on this topic.
Current Data:
Week1 USA
Week1 Netherlands
Week1 South Africa
Week2 Turkey
Week2 UK
Week2 USA
Week1 USA
week2 UK
Modified to:
Week1 USA 2
Netherlands 1
South Africa 1
Week2 USA 1
UK 2
Turkey 1
A:
Here is one possible solution. Just copy the code into the script editor and save it.
Then you can use it in your spreadsheet like this: =countCountries(A1:B8)
function groupValues(array2D) {
var result = {};
for(var i = 0; i < array2D.length; i++) {
if(!(array2D[i] instanceof Array) || array2D[i].length < 2) throw new Error("two columns are needed");
if(!result[array2D[i][0]]) result[array2D[i][0]] = [];
result[array2D[i][0]].push(array2D[i][1]);
}
return result;
}
function countValues(array) {
var result = {};
for(var i = 0; i < array.length; i++) {
if(!result[array[i]]) result[array[i]] = 0;
result[array[i]] = result[array[i]] + 1;
}
return result;
}
function toArray(o) {
var result = [];
for(key in o) {
result.push([key, o[key]]);
}
return result;
}
function countCountries(range) {
var grouped = toArray(groupValues(range));
grouped.sort();
grouped.forEach(function(values) {
values[1] = toArray(countValues(values[1]));
});
var result = [];
for(var i = 0; i < grouped.length; i++) {
result.push([grouped[i][0], grouped[i][1][0][0], grouped[i][1][0][1]]);
for(var j = 1; j < grouped[i][1].length; j++) {
result.push(["", grouped[i][1][j][0], grouped[i][1][j][1]]);
}
}
return result;
}
|
[
"devops.stackexchange",
"0000009923.txt"
] |
Q:
Mitigate false positives due to daylight saving time in CloudWatch anomaly dectector
For monitoring, I set up CloudWatch alerts based on CloudWatch anomaly detection. Overall, they work quite nicely, but they got confused when the clock gets shifted (summer timer to winter time).
We have now recurring false-positives even though the recent time shift in the US and in Europe were weeks ago. I assume CloudWatch will eventually understand it, but then again, the clock shifts have on a regular basis, which will create some noisy.
Unfortunately, I did not find much in the documentation, only that CloudWatch provides to set the Time Zone Format. Before I leaved it empty, but now I set it to UTC.
Questions:
What is exactly the effect of setting the time zone? Does it have an impact on the prediction of the anomaly detector, or is it only for visualization and for other configurations such as excluding specified time periods?
Our user base is all over the world, but mostly in the US and in Europe. As this scenario is not too uncommon, I wonder if asking for one one time zone is even practical. What should be used? UTC? Or pick the time zone with the most users?
I understand that it difficult to avoid false-positives completely, especially, in the first or second week after a clock shift happened. Still, I wonder how to correctly setup up the anomaly detection model, so its prediction will be most accurate.
A:
My current understanding is that it is not possible to avoid false positives. At least not if traffic comes from different time zones around the world (as in the context of this question).
AWS operates on UTC times, but this is irrelevant for the anomaly detection. It does play a role if you set timers, but it is not taking into account for the predictions of AWS. In other words, switching to UTC will not make false-positives less likely.
When thinking about it, it is hard to avoid false-positives. If a time-shift in Europe or the US happens, you could take that into account and predict the new traffic. But that requires extra domain knowledge. The AWS predictor only sees a generic time series.
There are other events such as Christmas, which will impact the expected traffic. Again, with extra knowledge you could improve predictions. But the problem is too difficult for the AWS predictor, as it does not have that domain knowledge.
In our concrete case, we still kept the alerts, as they do have value even with the known false-positives. Humans with knowledge about the underlying system, can reject the false-positive. It is not ideal, but it is a trade-off that we are willing to make.
Note that other types of graphs are not susceptible for these types of problems. For example, error rates instead of total number of errors. It is not always possible, but if you can use rates, the system will be more stable in my experience.
AWS allows to set alerts on math expressions such as errors / requests. The advantage is that normalized rates tend to be agnostic of external events.
|
[
"stackoverflow",
"0028924348.txt"
] |
Q:
Sencha Touch selectfield change event not working with different value but same text
The selectfield change event not working with different value but same text.
Demo here:- https://fiddle.sencha.com/#fiddle/jat
Ext.create('Ext.form.Panel', {
fullscreen: true,
items: [
{
xtype: 'fieldset',
title: 'Select',
items: [
{
xtype: 'selectfield',
label: 'Choose one',
options: [
{text: 'First Option', value: 'first'},
{text: 'Second Option', value: 'second'},
{text: 'Second Option', value: 'third'}
],
listeners:{
change:function(selectfield,newValue,oldValue,eOpts){
alert(newValue);
}
}
}
]
}
]
});
A:
setValue: function(newValue) {
var oldValue = this._value;
this.updateValue(this.applyValue(newValue));
newValue = this.getValue();
//alert(newValue)
if (this.initialized) {
this.onChange(this, newValue, oldValue);
}
return this;
}
this is the working solution for this.
|
[
"stackoverflow",
"0022368164.txt"
] |
Q:
Method to find a factor of a number
I am trying to write a simple program that takes a non-prime number and returns the first factor of it. I have to use a method to do this. I think that I am really close to the correct code, but I keep running into variable definition issues in my method. Here is my (currently incorrect) code:
public class testing {
public static void main(String[] args) {
int a;
a = 42;
System.out.println(factor(a));
}
//This method finds a factor of the non-prime number
public static int factor(int m) {
for(int y=2 ; y <= m/2 ; y++) {
if(m%y==0) {
return y;
continue;
}
}
return y;
}
}
Please let me know what's incorrect!
A:
Regarding your code:
public static int factor(int m) {
for(int y=2 ; y <= m/2 ; y++) {
if(m%y==0) {
return y;
continue;
}
}
return y;
}
At the point of that final return y, y does not exist. Its scope is limited to the inside of the for statement since that is where you create it. That's why you're getting undefined variables.
In any case, returning y when you can't find a factor is exactly the wrong thing to do since, if you pass in (for example) 47, it will give you back 24 (47 / 2 + 1) despite the fact it's not a factor.
There's also little point in attempting to continue the loop after you return :-) And, for efficiency, you only need to go up to the square root of m rather than half of it.
Hence I'd be looking at this for a starting point:
public static int factor (int num) {
for (int tst = 2 ; tst * tst <= num ; tst++)
if (num % tst == 0)
return tst;
return num;
}
This has the advantage of working with prime numbers as well since the first factor of a prime is the prime itself. And, if you foolishly pass in a negative number (or something less than two, you'll also get back the number you passed in. You may want to add some extra checks to the code if you want different behaviour.
And you can make it even faster, with something like:
public static int factor (int num) {
if (num % 2 == 0) return 2;
for (int tst = 3 ; tst * tst <= num ; tst += 2)
if (num % tst == 0)
return tst;
return num;
}
This runs a check against 2 up front then simply uses the odd numbers for remainder checking. Because you've already checked 2 you know it cannot be a multiple of any even number so you can roughly double the speed by only checking odd numbers.
If you want to make it even faster (potentially, though you should check it and keep in mind the code may be harder to understand), you can use a clever scheme pointed out by Will in a comment.
If you think about the odd numbers used by my loop above with some annotation, you can see that you periodically get a multiple of three:
5
7
9 = 3 x 3
11
13
15 = 3 x 5
17
19
21 = 3 x 7
23
25
27 = 3 x 9
That's mathematically evident when you realise that each annotated number is six (3 x 2) more than the previous annotated number.
Hence, if you start at five and alternately add two and four, you will skip the multiples of three as well as those of two:
5, +2=7, +4=11, +2=13, +4=17, +2=19, +4=23, ...
That can be done with the following code:
public static long factor (long num) {
if (num % 2 == 0) return 2;
if (num % 3 == 0) return 3;
for (int tst = 5, add = 2 ; tst * tst <= num ; tst += add, add = 6 - add)
if (num % tst == 0)
return tst;
return num;
}
You have to add testing against 3 up front since it violates the 2, 4, 2 rule (the sequence 3, 5, 7 has two consecutive gaps of two) but that may be a small price to pay for getting roughly another 25% reduction from the original search space (over and above the 50% already achieved by skipping all even numbers).
Setting add to 2 and then updating it with add = 6 - add is a way to have it alternate between 2 and 4:
6 - 2 -> 4
6 - 4 -> 2
As I said, this may increase the speed, especially in an environment where modulus is more expensive than simple subtraction, but you would want to actually benchmark it to be certain. I just provide it as another possible optimisation.
|
[
"stackoverflow",
"0010032010.txt"
] |
Q:
How to improve drawRect performance to merge different UIImages together?
i need to improve my "drawRect" method. It´s so extremely slow.
I have 10 transparent png´s which i want to merge together with different blend modes.
I´ve read a post from the Apple Developer Lib and from Stackoverflow.
Now i want to know how to improve my code and the overall drawing performance.
Could you please help me? Loading all these images within a for loop makes it so slow, right?
How do i get the most performance?
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform matrix =CGContextGetCTM(context);
CGAffineTransformInvert(matrix);
CGContextConcatCTM(context,matrix);
CGRect contentRect;
// load each UIImage
for (i=0; i< [configurationArray count]; i = i + 1) {
image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:nil]];
contentRect = CGRectMake(x,y,image.size.width,image.size.height);
CGContextSetBlendMode (context, kCGBlendModeScreen);
CGContextSetAlpha (context, [layerData.layerAlpha floatValue]);
CGContextDrawImage (context,contentRect, image.CGImage);
}
}
UPDATE:
Now i´m using CALayers to put the pixel direct on the needed position.
But i need different blend modes, alpha and color fills for each layer.
Is there a way to avoid calling the expensive "CGContextDrawImage" method on each layer?
E.g i hope its possible to just update the context for the small size of the specific layer, right?
Or do i need to render the whole UIView for each context change?
I hope somebody can push me in the right direction.
I just have to learn on that topic.
Thanks for any help.
- (void)drawRect:(CGRect)rect {
// load each UIImage
for (int i=0; i< [myArray count]; i++) {
image = [[ImageCache sharedImageCache] imageForKey:imageName];
CALayer* sublayer = [CALayer layer] ;
[sublayer setPosition:CGPointMake(image.size.width/2, image.size.height/2)];
[sublayer setFrame:CGRectMake(x, y, image.size.width, image.size.height)];
CGImageRef layerImage = [image CGImage];
[sublayer setContents:(__bridge id) layerImage];
[sublayer setBackgroundColor:[[UIColor clearColor] CGColor]];
[self.layer addSublayer:sublayer];
// How can i set the blend mode, color fill & alpha value without
// calling the expensive "CGContextDrawImage" ? Possible?
}
}
A:
Per Brad's comment:
You probably shouldn't load your ten images within -drawRect:. Load and cache them somewhere else first. Be careful about memory usage with that many images, though.
I´ve ended with Brad's approach.
|
[
"stackoverflow",
"0043312596.txt"
] |
Q:
Check if optional byte argument was passed in
I want to let a user specify a custom color for a class in the constructor via passing in RGBA bytes. If they do not specify a custom color, a default color from the application settings will be used. If the Alpha is left out, however, assume fully opaque.
What I would like:
public MyClass(byte r_col = -1, byte g_col = -1, byte b_col = -1, byte a_col = 255)
{
if (r_col == -1 | g_col == -1 | b_col == -1)
{
// use default color
}
else
{
this.color = System.Windows.Media.Color.FromArgb(a_col, r_col, g_col, b_col);
}
}
However, there is no "wrong" value for a byte (-1 is invalid), so I am unable to detect if a byte was actually passed into the function. What options do I have? I'd like to avoid function overloading if possible.
A:
Function overloading is much more beautiful in this case:
public MyClass()
{
//Default color
}
public MyClass(byte r_col, byte g_col, byte b_col)
{
color = Color.FromArgb(r_col, g_col, b_col);
}
public MyClass(byte a_col, byte r_col, byte g_col, byte b_col)
{
color = Color.FromArgb(a_col, r_col, g_col, b_col);
}
Of course it is possible to do it without (as Micheal proofed), but it's (P.Kouverakis mentioned) not good API design. Because if you let the user type in parameters, which aren't allowed, this may result in difficult to trace bugs. Never fear more work for a greater result - so in this case, use function overloads.
|
[
"stackoverflow",
"0047777387.txt"
] |
Q:
Redraw the old donut and create a new one by clicking on each color Chart.js
I'm new to programming, I'm sorry if the question is silly. I'm doing some graphics with chart.js.
I have managed to create a donut inside another with the onclick event, the problem I have is that it generates one for each click and I need it to do it only once. For each click in a different area of the graphic that a donut generates one doughnut.
For example:
If you click on the red color that generates one red and grey doughnut.
If you click on green part to generate one green and grey and so on with all of them.
I would greatly appreciate the help.
var ctx = document.getElementById('canvasDoughnut').getContext('2d');
var backgroundColors = [
'#fd3f4a',
'#484848',
'#705bc9',
'#008ee5',
'#00c9d8',
'#5cc600',
'#ffd939',
'#ff8f00'
];
var newColors = ['#5cc600', '#ebe9e1'];
var newData = [48, 52];
var varData = [25, 18, 18, 18, 8, 48, 18, 12];
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
backgroundColor: backgroundColors,
data: varData
}]
},
options: {
cutoutPercentage: 70,
rotation: Math.PI * -0.7,
onClick: function(evt, elements) {
var datasetIndex;
var dataset;
if (elements.length) {
var index = elements[0]._index;
datasetIndex = elements[0]._datasetIndex;
// Reset old state
dataset = chart.data.datasets[datasetIndex];
dataset.backgroundColor = ['#5cc600', '#ebe9e1'];
dataset.value = [58, 42],
dataset.data = [58, 42]
}
// config. new data doughnut
chart.config.data.datasets.push({
backgroundColor: [
'#5cc600',
'#ebe9e1'
],
dataPoints: [48, 52],
data: [48, 52],
}),
chart.update();
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="canvasDoughnut" class="size-doughnut"></canvas>
A:
You just need to do a check before you push a new dataset to make sure you don't already have 2 datasets.
var ctx = document.getElementById('canvasDoughnut').getContext('2d');
var backgroundColors = [
'#fd3f4a',
'#484848',
'#705bc9',
'#008ee5',
'#00c9d8',
'#5cc600',
'#ffd939',
'#ff8f00'
];
var newColors = ['#5cc600', '#ebe9e1'];
var newData = [48, 52];
var varData = [25, 18, 18, 18, 8, 48, 18, 12];
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
backgroundColor: backgroundColors,
data: varData
}]
},
options: {
cutoutPercentage: 70,
rotation: Math.PI * -0.7,
onClick: function(evt, elements) {
var datasetIndex;
var dataset;
if (elements.length) {
var index = elements[0]._index;
datasetIndex = elements[0]._datasetIndex;
// Reset old state
dataset = chart.data.datasets[datasetIndex];
dataset.backgroundColor = ['#5cc600', '#ebe9e1'];
dataset.value = [58, 42],
dataset.data = [58, 42]
}
// config. new data doughnut
// check to make sure we haven't already pushed a dataset
if (chart.config.data.datasets.length < 2) {
chart.config.data.datasets.push({
backgroundColor: [
'#5cc600',
'#ebe9e1'
],
dataPoints: [48, 52],
data: [48, 52],
}),
chart.update();
}
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="canvasDoughnut" class="size-doughnut"></canvas>
|
[
"stackoverflow",
"0034809033.txt"
] |
Q:
Java/Android - https not working in apache http
So I wanted to use this XML parser class to parse an XML file from one of my sites, which acts as an API.
So I came across this XMLParser class over here: XMLParser.java
Since I use https over at my site, I quickly found out this isn't going to work with it, unless SSL is implemented within the code, where it fetches XML file from the URL using the following method:
getXmlFromUrl(String url)
So for my test environment I was quick to create a new httpClient method, which would accept any SSL certificate from.
public static HttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
So this is my final XMLParser.java after I did it.
XMLParser_New.java
But this all went in vain, as I am repeatedly getting the following exception.
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
Where have I gone wrong or what is it that I don't understand.
Thank you :)
A:
How are you implementing SSL. Have you followed these steps to implement it:
Need to create X.509 certificate on Server.
Store trusted CAs on terminal side.
Encrypt and decrypt messages on both ends.
Are you using self signed certificate. Then you need to store that certificate on device and load your own trust store to check the SSL certificates, rather than android default trust store.
Here is very good article to implement SSL on android:
http://www.codeproject.com/Articles/826045/Android-security-Implementation-of-Self-signed-SSL
I think in your case trust certificate on terminal side is missing. That's why it is throwing this exception.
|
[
"stackoverflow",
"0030130803.txt"
] |
Q:
Using std::function for memberfunctions
My question is about using std::function to class methods. Suppose I have the following class hierarchy:
class Foo {
public:
virtual void print() {
cout << "In Foo::print()" << endl;
}
virtual void print(int) {
cout << "In Foo::print(int)" << endl;
}
};
class Bar : public Foo {
public:
virtual void print() override {
cout << "In Bar::print()" << endl;
}
virtual void print(int) override {
cout << "In Bar::print(int)" << endl;
}
}
Now there is another function which is supposed to dynamically call one of the two class methods depends on its input:
void call(Foo* foo, void (Foo::*func)(void)) {
(foo->*func)();
}
Foo* foo = new Foo();
Bar* bar = new Bar();
call(foo, &Foo::print);
call(bar, &Foo::print);
When I compile the above code snippet using g++/clang++, it works as expected, where the output is:
In Foo::print()
In Bar::print()
My questions are then:
since there are two functions (overloaded) with the same name: print, when I pass the address of class function: &Foo::print, how did the compiler know that I am actually calling Foo::print(void) but not Foo::print(int)?
is there another way that I can generalize the code above such that the second parameter of void call(Foo*, xxx) can be passed using both Foo::print(void) and Foo::print(int)
is there anyway to achieve this feature using new feature in C++11 std::function ? I understand that in order to use std::function with a non-static class method, I have to use std::bind to bind each class method with a specific class object, but that would be too inefficient for me because I have many class objects to be bound.
A:
Since there are two functions (overloaded) with the same name: print, when I pass the address of class function: &Foo::print, how did the compiler knows that I am actually calling Foo::print(void) but not Foo::print(int)?
This is allowed because of [over.over]/p1:
A use of an overloaded function name without arguments is resolved in certain contexts to a function, a
pointer to function or a pointer to member function for a specific function from the overload set.
The compiler can use the target type of the parameter-type-list to determine which function from the overload set the pointer-to-member refers:
A use of an overloaded function name without arguments is resolved in certain contexts to a function, a
pointer to function or a pointer to member function for a specific function from the overload set. A function
template name is considered to name a set of overloaded functions in such contexts. The function selected
is the one whose type is identical to the function type of the target type required in the context. [ Note: .. ] The target can be
— an object or reference being initialized (8.5, 8.5.3, 8.5.4),
— the left side of an assignment (5.18),
— a parameter of a function (5.2.2),
— [..]
The name Foo:print represents an overload set which the compiler looks through to find a match. The target type Foo::print(void) is present in the overload set, so the compiler resolves the name to that overload.
Is there another way that I can generalize the code above such that the second parameter of void call(Foo*, xxx) can be passed using both Foo::print(void) and Foo::print(int)
There isn't a general way to do it with the name itself. The name has to be resolved to an overload. Instead, try changing the code to accept a function object like a lambda:
template<class Callable>
void call(Foo* foo, Callable&& callback) {
callback(foo);
}
int main()
{
call(foo, [] (Foo* f) { f->print(); f->print(1); });
}
|
[
"stackoverflow",
"0051255932.txt"
] |
Q:
Zoom Background Image with CSS or JavaScript
I would like to scale the background image of my div over time, so that it looks like it is zooming in and out (without hovering the mouse over - I'm just looking for the animation to start automatically). But, no matter what I try, the background animation just looks choppy.
If I set the div to scale, then the transition is smooth, but it scales the entire div, not just the background image. For additional information, I am running the most recent version of Chrome, and have tried on both Windows and OS. You can see an example here: https://jsfiddle.net/sdqv19a0/
<div class="site-main-banner">
<div class="caption">
<!-- Bootstrap -->
<div class="container">
<div class="row">
<div class="col-xs-12">
<!-- figure -->
<figure> <img src="images/signature.png" alt="signature"> </figure>
<!-- H1 Heading -->
<h1 class="typewrite" data-period="2000" data-type='[ "Purposeful design", "Data-driven marketing", "Dynamic branding", "I love it all." ]'> <span class="wrap"></span> </h1>
<!-- H2 Heading -->
<h2>graphic designer • web designer • analytical marketer</h2>
<div class="clearfix"> </div>
<!-- Button -->
<a href="#" class="theme-btn">view my portfolio</a>
</div>
</div>
</div>
</div>
CSS:
.site-main-banner {
float:left;
width:100%;
background:url(https://preview.ibb.co/m8kxST/static_banner_new.jpg) no-repeat center center;
background-attachment:fixed;
background-size:cover;
margin: 0;
padding: 0;
display: block;
clear: both;
position: relative;
text-align:center;
overflow: hidden;
animation: shrink 5s infinite alternate steps(60);
}
@keyframes shrink {
0% {
background-size: 110% 110%;
}
100% {
background-size: 100% 100%;
}
}
.site-main-banner a.theme-btn {
color: #FFFFFF;
border:#FFFFFF solid 1px;
background:none;
box-shadow:none;
}
.site-main-banner a.theme-btn:hover {
color: #bc6ca7;
border:#FFFFFF solid 1px;
background:#FFFFFF;
box-shadow:none;
}
.site-main-banner .caption {
position: relative;
float: left;
top: 50%;
left: 50%;
transform: translate(-50%);
padding:300px 0;
}
.site-main-banner figure {
float:left;
width:100%;
text-align:center;
padding:0 0 15px 0;
}
Suggestions? I am open to a js solution, as well, just am not as comfortable with javascript. Thanks!
A:
Separate your background into its own element behind the main banner so you can apply keyframe animations transforming the scale of the background individually instead.
body, html {
margin: 0;
padding: 0;
}
.site-space-background {
position: fixed; height: 100%; width: 100%;
background: #1A1939 no-repeat center center;
background-image: url(https://preview.ibb.co/m8kxST/static_banner_new.jpg);
background-attachment: fixed;
background-size: cover;
animation: shrink 5s infinite alternate steps(60);
}
@keyframes shrink {
0% {
transform: scale(1.2)
}
100% {
transform: scale(1.0)
}
}
<div class="site-space-background"></div>
<div class="site-main-banner">
<!-- The rest -->
</div>
|
[
"stackoverflow",
"0022499001.txt"
] |
Q:
Hana SQL help needed
I have a requirement like below. I have table like the below one :
ID SID VID VTXT
1 10 v_5 Five
1 10 v_5 asd
2 11 v_7 Seven
2 11 v_7 seven
3 12 v_9 NINE
3 12 v_9 Nine
3 12 v_9 nine
I need the output as :
ID SID VID VTXT
1 10 v_5 Five
2 10 v_5 asd
1 11 v_7 Seven
2 11 v_7 seven
1 12 v_9 NINE
2 12 v_9 Nine
3 12 v_9 nine
Please help me with this issue.
A:
i don't know the syntax of tags you made if this is for sql-server it'd be
update table
set ID=(select rn=row_number() over(partition by ID order by ID) from table)
|
[
"stackoverflow",
"0032989700.txt"
] |
Q:
How can I start my jquery function only on input change, not on page load?
I have a select box, which autoselects automatically the appropriate value of my input field. It works very well:
<input id="count" value="2.00" type="number">
<select class="autoselect">
<option data-number="1000000000000" selected value="dog">dog</option>
<option data-number="2000000000000" value="horse">horse</option>
<option data-number="4000000000000" value="cat">cat</option>
<option data-number="5000000000000" value="bird">bird</option>
</select>
Here is the query code:
$(document).ready(function(){
var count = 1000;
$('#count').change(function () {
var that = parseInt($(this).val()*Math.pow(count, 4), 10);
$('.autoselect option:gt(0)').each(function () {
$(this).prop('disabled', ($(this).data('number') < that))
.prop('selected', ($(this).data('number') >= that && $(this)
.prev().data('number') < that));
})
if (that <= $('.autoselect option:eq(1)').data('number')) $('.autoselect option:eq(1) ').prop('selected', true);
$('select.autoselect option[data-number=0]').prop('disabled', false);
}).change()
}
What I want to achieve is actually a simple thing. On page load, "dog" should always be selected. Only by changing the input, my script should start to work. But it is already selecting "horse" on page load, even if I wrote the function on input change.
A:
Your second .change() function is triggering this event on page load. jQuery event functions without callbacks are event triggers. Just remove second .change() at end of your code.
|
[
"stackoverflow",
"0025272015.txt"
] |
Q:
WiX Burn BootstrapperApplication: Is it possible to silence the Uninstall UI for the bundle and only display the UI for one of the MSI packages?
If you have a burn bundle that uses the built-in WiX Bootstrappre UI and this bundle contains many MSI packages. Is it possible to silence the Bootstrapper UI on uninstall and only display the UI of one the MSI packages?
A:
To do this, you need to create your own Managed Bootstrapper Application (MBA).
I recommend reading this book by Nick Ramirez. There is a great chapter that explains exactly how to do this and the source code that comes with this book can easily be modified to suit your needs.
There is also a good blog by Bryan Johnston that might be enough to get you on your way.
|
[
"stackoverflow",
"0042597791.txt"
] |
Q:
catch violates the semantic approximation order?
The semantic approximation order states that if a function f is defined when one its arguments is not, then f is constant in that argument (it doesn't use it). But consider this function,
import Control.Exception
handleAll :: SomeException -> IO ()
handleAll e = putStrLn "caught"
f :: String -> IO ()
f x = catch (putStrLn x) handleAll
f undefined displays caught in GHCi, so it looks defined. However f is not constant in its argument, because f "test" displays test.
Is there a mistake somewhere ?
A:
To model exceptions and catch properly you need a richer denotational semantics for terms, that distinguishes exceptions from nontermination (and that distinguishes different exceptions from each other). See A semantics for imprecise exceptions (pdf) for the semantics that GHC implements.
Note that this has no effect on the denotational semantics of the "pure fragment" of Haskell, since you have no way to observe distinctions between IO a values in pure code (aside from bottom vs. not-bottom).
To clarify what I mean by the "pure fragment" of Haskell, imagine defining the IO type as
data IO a = MkIO
and catch as
catch a h = MkIO
Now there's no problem with your f, since both f undefined and f "test" are equal to MkIO. From the viewpoint of denotational semantics this corresponds to the interpretation
[[IO t]] = {⊥ < ⊤}
Since the only operations we can do with IO actions are seqing them and combining them into other IO actions, it's a perfectly consistent denotational semantics which does not compromise your ability to talk about the semantics of things like length :: [Bool] -> Integer. It just happens to be useless for understanding what happens when you execute an IO action. But if you wanted to treat that in a denotational semantics, you'd encounter many difficulties besides exceptions.
|
[
"stackoverflow",
"0020058902.txt"
] |
Q:
(ggplot) facet_grid implicit subsetting not respected in geom_text (?)
In geom_text(...), the default dataset is only sometimes subsetted based on facet variables. Easiest to explain with an example.
This example attempts to simulate pairs(...) with ggplot (and yes, I know about lattice, and plotmatrix, and ggpairs – the point is to understand how ggplot works).
require(data.table)
require(reshape2) # for melt(…)
require(plyr) # for .(…)
require(ggplot2)
Extract mgp, hp, disp, and wt from mtcars, use cyl as grouping factor
xx <- data.table(mtcars)
xx <- data.table(id=rownames(mtcars),xx[,list(group=cyl, mpg, hp, disp, wt)])
Reshape so we can use ggplot facets.
yy <- melt(xx,id=1:2, variable.name="H", value.name="xval")
yy <- data.table(yy,key="id,group")
ww <- yy[,list(V=H,yval=xval), key="id,group"]
zz <- yy[ww,allow.cartesian=T]
In zz,
H: facet variable for horizontal direction
V: facet variable for vertical direction
xval: x-value for a given facet (given value of H and V)
yval: y-value for a given facet
Now, the following generates something close to pairs(…),
ggp <- ggplot(zz, aes(x=xval, y=yval))
ggp <- ggp + geom_point(subset =.(H!=V), size=3, shape=1)
ggp <- ggp + facet_grid(V~H, scales="free")
ggp <- ggp + labs(x="",y="")
ggp
In other words, the values of xvar and yvar used in geom_point are appropriate for each facet; they have been subsetted based on the value of H and V. However, adding the following to center the variable names in the diagonal facets:
ggp + geom_text(subset = .(H==V),aes(label=factor(H),
x=min(xval)+0.5*diff(range(xval)),
y=min(yval)+0.5*diff(range(yval))),
size=10)
gives this:
It appears that H has been subsetted properly for each facet (e.g. the labels are correct), but xvar and yvar seem to apply to the whole dataset zz, not to the subset corresponding to H and V for each facet.
My question is: In the above, why are xvar and yvar treated differently than H in aes? Is there a way around this? {Note: I am much more interested in understanding why this is happening, than in a workaround.]
A:
One observation is that actually the labels are overplotted:
ggp + geom_text(subset = .(H==V), aes(label=factor(H),
x=min(xval)+0.5*diff(range(xval))
+ runif(length(xval), max=10),
y=min(yval)+0.5*diff(range(yval))
+ runif(length(yval), max=20)), size=10)
adds some noise to the position of the labels, and you can see that for each observation in zz one text is added.
To your original question: From the perspective of ggplot it might be faster to evaluate all aesthetics at once and split later for faceting, which leads to the observed behavior. I'm not sure if doing the evaluation separately for each facet will ever be implemented in ggplot -- the only application I can think of is to aggregate facet-wise, and there are workarounds to achieve this easily. Also, to avoid the overplotting shown above, you'll have to build a table with four observations (one per text) anyway. Makes your code simpler, too.
|
[
"stackoverflow",
"0042596459.txt"
] |
Q:
Auto fill text-items after LOV selection for a text-item in an Oracle Form
Consider an Oracle Form having 3 text-items. First is a 'PO Number' field which is user entered through an LOV called upon a button next to the text-item. Second is a 'Supplier Code' text-item corresponding to the PO Number selected and third is a 'Supplier Name' text-item corresponding to that supplier code.
Actual _PO_Number_ and _Supplier_Code_ exist in the same table in the Database but _Supplier_Name_ resides in different table. All i want is that when i select a PO Number from the LOV then remaining 2 fields should auto-populate accordingly.
What trigger should i use ? where should i use it and what other things should i consider ? Please help me as i am a noob at Oracle Forms.
A:
You hava several posibilities with some consequences
Set _Supplier_Code_ and _Supplier_Name_ directly in WHEN-BUTTON-PRESSED trigger on your buttob after user selects _PO_Number_
Consequences - when user presses standard KEY-LISTVAL, the code will not run, Supplier*_ items remain empty
Write WHEN-VALIDATE-ITEM on _PO_Number_ like this
declare
cursor c is select _Supplier_Code_, _Supplier_Name_
from suppliers_table
where _PO_Number_ = :your_block._PO_Number_;
begin
open c;
fetch c into :your_block._Supplier_Code_, :your_block._Supplier_Name_;
close c;
end;
Consequences - this code runs always, when _PO_Number_ item changes. If _Supplier_Code_ is a database item, it will probably change its status to UPDATE after querying records from database.
select _Supplier_Code_ and _Supplier_Name_ items directly in LOV. Write your select as join of both tables. Set all three items as return items. If you don't want to show _Supplier_Code_ and _Supplier_Name_ to the user in LOV, simply set their width to 0
I preferre solution 3.
|
[
"stackoverflow",
"0038249895.txt"
] |
Q:
How to properly throw an Exception inside yield return method in C#
See edits below for reproducing the behavior that I describe in this problem.
The following program will never end, because the yield return construct in C# calls the GetStrings() method indefinitely when an exception is thrown.
class Program
{
static void Main(string[] args)
{
// I expect the Exception to be thrown here, but it's not
foreach (var str in GetStrings())
{
Console.WriteLine(str);
}
}
private static IEnumerable<string> GetStrings()
{
// REPEATEDLY throws this exception
throw new Exception();
yield break;
}
}
For this trivial example, I could obviously use return Enumerable.Empty<string>(); instead, and the problem goes away. However in a more interesting example, I'd expect the exception to be thrown once, then have the method stop being called and throw the exception in the method that's "consuming" the IEnumerable.
Is there a way to produce this behavior?
EDIT: ok, the problem is different than I first thought. The program above does NOT end, and the foreach loop behaves like an infinite loop. The program below DOES end, and the exception is displayed on the console.
class Program
{
static void Main(string[] args)
{
try
{
foreach (var str in GetStrings())
{
Console.WriteLine(str);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static IEnumerable<string> GetStrings()
{
throw new Exception();
yield break;
}
}
Why does the try ... catch block make a difference in this case? This seems very strange to me. Thanks to @AndrewKilburn for his answer already for pointing me to this.
EDIT #2:
From a Command Prompt, the program executes the same in both cases. In Visual Studio Enterprise 2015, Update 2, whether I compile in Debug or Release, the behavior above is what I am seeing. With the try ... catch, the program ends with an exception, and without it Visual Studio never closes the program.
EDIT #3: Fixed
For me, the issue was resolved by the answer by @MartinBrown. When I uncheck Visual Studio's option under Debug > Options > Debugging > General > "Unwind the call stack on unhandled exceptions" this problem goes away. When I check the box again, then the problem comes back.
A:
The behaviour being seen here is not a fault in the code; rather it is a side effect of the Visual Studio debugger. This can be resolved by turning off stack unwinding in Visual Studio. Try going into Visual Studio options Debugging/General and unchecking "Unwind the call stack on unhandled exceptions". Then run the code again.
What happens is that when your code hits a completely unhandled exception Visual Studio is unwinding the call stack to just before the line in your code that caused the exception. It does this so that you can edit the code and continue execution with the edited code.
The issue seen here looks like an infinite loop because when you re-start execution in the debugger the next line to run is the one that just caused an exception. Outside the debugger the call stack would be completely unwound on an unhandled exception and thus would not cause the same loop that you get in the debugger.
This stack unwinding feature can be turned off in the settings, it is enabled by default. Turning it off however will stop you being able to edit code and continue without first unwinding the stack yourself. This however is quite easy to do either from the call stack window or by simply selecting 'Enable Editing' from the Exception Assistant.
|
[
"stackoverflow",
"0022301351.txt"
] |
Q:
Dynamic textboxes, Jquery
<a href="#" id="AddMoreFileBox" class="btn btn-info">Add More Field</a>
<div id="InputsWrapper">
<div><input type="text" name="mytext[]" id="field_1" value="Text 1"><a href="#" class="removeclass">×</a></div>
</div>
Script:
<script type='Javascript'>
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><a href="#" class="removeclass">×</a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
</script>
I found this on jfiddle. I tried it on my browser it won't add.
Is there any declaration like loading of a the library?
http://jsfiddle.net/LYDuZ/
A:
Seems like you forgot to refer jquery in your code. Add this line in your head tag
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
|
[
"stackoverflow",
"0049552473.txt"
] |
Q:
Hide specific shipping method for specific products in Woocommerce
I have a few products in my WooCommerce store that are to heavy (more than 20kg) to be shipped by a certain shipping method. I would like to hide 'shipping_method_0_flat_rate2' for all cart items which contain a product that is heavier than 20kg.
I tried to adjust the snippet below, but it is not complete and working:
add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// specify the product id's you want to hide
$product_ID = array(
'113', // Product name
);
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the products. Switch to true if the product is found.
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ($terms as $term) {
if( in_array( $term->term_id, $product_ID ) ) {
$found = true;
break;
}
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the products.
if ( check_cart_for_share() ) {
// remove the method you want
unset( $available_methods['shipping_method_0_flat_rate2'] ); // Replace with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
Any help is appreciated.
A:
You are making things more complicated in your code and your shipping method ID is not the good one… Try this instead:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
$product_ids = array( 113 ); // HERE set the product IDs in the array
$method_id = 'flat_rate:2'; // HERE set the shipping method ID
$found = false;
// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_id] );
return $rates;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
You should need to refresh the shipping caches:
1) First this code is already saved on your function.php file.
2) In Shipping settings, enter in a Shipping Zone and disable a Shipping Method and "save". Then re-enable that Shipping Method and "save". You are done.
|
[
"stackoverflow",
"0058825643.txt"
] |
Q:
Will copying an object and changing this copy variable not change the original one?
Suppose I have this object:
const obj = {
a: {
b: {
c: {
d: 'hi'
}
},
g: 23
},
f: {
e: [1,2]
}
}
To change the variable "d" it without mutating it, will this:
const newObj = {...obj};
newObj.a.b.c.d = 'Bye';
return newObj;
work?
This is in regards to redux...
A:
No – only the first level of properties of obj will be copied when you spread it with the spread operator ....
This is called shallow copy, as opposed to deep copy.
const obj = {
a: {
b: {
c: {
d: "hi"
}
},
g: 23
},
f: {
e: [1, 2]
}
};
const newObj = { ...obj };
newObj.a.b.c.d = "Bye";
console.log(obj.a.b.c.d); // Bye
A:
As @ASDFGerge mentioned, you should play around with this to really internalize it.
But the short answer is no, your copy newObj is only a copy 1 level deep. Changing newObj.a will not modify the original, but changing newObj.a.b (or anything further down) will.
const original = {
one: {
two: {
three: 3
},
otherTwo: 2
},
otherOne: 1
}
const copy1LevelDeep = {...original};
copy1LevelDeep.one.two.three = 30;
copy1LevelDeep.one.two = {three: 300, four: 4};
copy1LevelDeep.one.otherTwo = 20;
copy1LevelDeep.one = 100;
copy1LevelDeep.otherOne = 10;
console.log(original);
console.log(copy1LevelDeep);
|
[
"stackoverflow",
"0042166958.txt"
] |
Q:
postgres 9.3+: constraint to ensure table and column exist in database
How can I ensure a new record contains values that refer to a schema, table, and column that currently exist in the database?
For example, given a table:
CREATE TEMP TABLE "column_reference" (
"gid" SERIAL PRIMARY KEY
, "val" INTEGER
, "schema" TEXT
, "table" TEXT
, "column" TEXT
);
how can I ensure schema.table.column exists?
I tried a fkey to information_schema.columns, but, of course, foreign keys to views are disallowed.
It also appears from the columns view definition that I need several tables in order to get the schema, table, and column names so I can't create a single foreign key to the source tables.
My current workaround is to manually create a __columns table from the information_schema.columns view and reference it instead. This works given the control I happen to have on this project at this point in time, but am looking for a permanent, dynamic solution.
Is there a different constraint or method I could use?
A:
You can create a trigger function that checks what you want, and associate this function with a trigger which is fired BEFORE an INSERT or an UPDATE of the table:
This could be your trigger function:
CREATE FUNCTION column_reference_check()
RETURNS trigger
LANGUAGE 'plpgsql'
AS
$BODY$
begin
/* Check for the existence of the required column */
if EXISTS (
SELECT *
FROM information_schema.columns
WHERE
table_schema = new.schema
AND table_name = new.table
AND column_name = new.column )
then
/* Everything Ok */
return new ;
else
/* This is approx. what would happen if you had a constraint */
RAISE EXCEPTION 'Trying to insert non-matching (%, %, %)', new.schema, new.table, new.column ;
/* As an alternative, you could also just return NULL
As a result, the row is *not* inserted, but execution continues */
return NULL ;
end if ;
end ;
$BODY$;
To associate this function with a trigger, you'd use:
CREATE TRIGGER column_reference_check_trg
BEFORE INSERT OR UPDATE OF "schema", "table", "column"
ON column_reference
FOR EACH ROW
EXECUTE PROCEDURE column_reference_check();
Now you can try to perform the following INSERT, that should succeed:
INSERT INTO column_reference
VALUES (2, 1, 'pg_catalog', 'pg_statistic', 'starelid');
But if you try this one:
INSERT INTO column_reference
VALUES (-1, 1, 'false_schema', 'false_table', 'false_column');
... you get an exception:
ERROR: Trying to insert non-matching (false_schema, false_table, false_column)
CONTEXT: PL/pgSQL function column_reference_check() line 16 at RAISE
|
[
"stackoverflow",
"0033413349.txt"
] |
Q:
Is there any way to access to the 2nd level of an array?
I've created a super array which have 4 levels.
Here is the beast :
array(4) {
["arrayCoordinateur"]=>
array(2) {
["siret"]=>
array(1) {
[0]=>
string(14) "44306184100039"
}
["sigle"]=>
array(1) {
[0]=>
string(3) "NdP"
}
}
["arrayGroupMember"]=>
array(2) {
["siret"]=>
array(2) {
[0]=>
string(14) "44306184100039"
[1]=>
string(14) "44306184100039"
}
["sigle"]=>
array(2) {
[0]=>
string(7) "rerzrez"
[1]=>
string(5) "Autre"
}
}
["arrayPartEnt"]=>
array(2) {
["sigle"]=>
array(3) {
[0]=>
string(6) "Blabla"
[1]=>
string(11) "CharbonBleu"
[2]=>
string(3) "JsP"
}
["siret"]=>
array(3) {
[0]=>
string(14) "77408201000034"
[1]=>
string(14) "51133834500024"
[2]=>
string(14) "40794236600011"
}
}
["arrayPartenExt"]=>
array(2) {
["sigle"]=>
array(2) {
[0]=>
string(3) "BNN"
[1]=>
string(5) "13456"
}
["siret"]=>
array(1) {
[0]=>
string(14) "00000000000000"
}
}
}
as you can see, the structure is comped of 4 Array who have all subs array called "siret" and "sigle".
I would like to be able to loop only on those siret and sigle without being annoyed by the first level, to put them into a table.
Here is my table :
$i = 0;
foreach ($allPartenaires as $partenaire=>$data) {
for ($i=0; $i < count($data) ; $i++) {
echo "<tr>
<td>
".$data['sigle'][$i]."
</td>
<td>
".$data['siret'][$i]."
</td>
</tr>";
}
}
$allPartenaires being the super array at the beginning of this post.
This code doesn't work since all the subarray dont have the same size...
Any help would be greatly appreciated
A:
I think this is what you need:
$data = array(
"arrayCoordinateur"=>array(
"siret"=>array(
"44306184100039",
),
"sigle"=>array(
"NdP",
),
),
"arrayGroupMember"=>array(
"siret"=>array(
"44306184100039",
"44306184100039",
),
"sigle"=>array(
"rerzrez",
"Autre",
),
),
"arrayPartEnt"=>array(
"siret"=>array(
"77408201000034",
"51133834500024",
"40794236600011",
),
"sigle"=>array(
"Blabla",
"CharbonBleu",
"JsP",
"Something",
),
),
);
echo '<table>';
foreach($data as $key => $value) {
$length = count($value['siret']) > count($value['sigle']) ? count($value['siret']) : count($value['sigle']);
for($i = 0; $i < $length; $i++) { //Now it works even if siret and single doesn't have same number of elemenets
$v1 = '-';
$v2 = '-';
if (isset($value['siret'][$i])) {
$v1 = $value['siret'][$i];
}
if (isset($value['sigle'][$i])) {
$v2 = $value['sigle'][$i];
}
echo
'
<tr>
<td>'.$v1.'</td>
<td>'.$v2.'</td>
</tr>
';
}
}
echo '</table>';
Result:
44306184100039 NdP
44306184100039 rerzrez
44306184100039 Autre
77408201000034 Blabla
51133834500024 CharbonBleu
40794236600011 JsP
- Something
|
[
"stats.stackexchange",
"0000133766.txt"
] |
Q:
What does a very high odds ratio in binary logistic regression indicate?
I am developing a predictive model to apply to raster layers for land cover classification.
So, I have a thematic category that is classified as agriculture but an accuracy assessment indicates commission error, savanna incorrectly classified as ag.
I randomly sampled the category and have 177 observations of ag and savanna. I extracted reflectance values from 6 predictive raster layers at the observation locations. So that's my dataset. I selected 4 variables that all significantly contribute to the model. Percentage correct for selected and unselected cases are approx 90% and Nagelkerke R square is 0.880. Odds ratios for the predictors are between .599 and 1.127 but the odds ratio for the constant is very high, 564830031.5. The predictors cannot all take the value of zero. I'm not sure what to make of the odds ratio. Any insight would be greatly appreciated.
Cheers
A:
The exponentiated coefficient of the constant is not an odds ratio but an odds, to be precise: the odds "success" when all predictors are 0. You say that some of your predictors cannot be 0, so that will be an extrapolation.
Say one of those predictors is year, so the constant refers to ground cover in the year 0, which is probably way way way outside the range of your data. In that case the fact that you get weird numbers is not surprising and not a problem. Personally, I still prefer to center those variables at some meaningful value within the range of your data. Say your earliest observation was in 1990, then I would just subtract 1990 from year. That way the value 0 refers to 1990, and your constant refers to the odds of success in 1990. Strictly speaking this is not necessary, but I find it easier to spot errors (I make lots of those, the trick is to find them before I publish...) if I make sure all coefficients are interpretable.
|
[
"stackoverflow",
"0002381998.txt"
] |
Q:
Asp.net web site and web service hosting
I have a web site and a web service and I would like to host them somewhere.
I need to use it mostly for testing and so that a some friends who are developing some applications to use the service have access to it. Also the service is using a MS SQL 2008 database.
Could you suggest any good free or cheap web hosting service for this. I would need about 1-2 months of hosting.
A:
winhost.com
OR
discountasp.net
|
[
"ja.stackoverflow",
"0000027261.txt"
] |
Q:
Android app で画像を複数枚並べて表示したい
Android Studioでアプリを作っています。
画像を複数枚並べて表示させたいのですが、現在1枚しか画面に表示されません。
今、2枚並べて表示させる処理を行っているのですが、どうして1枚しか表示されないのでしょうか?
activity_main.xmlには
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bigfig"
android:src="@drawable/bigfig" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/feminine"
android:src="@drawable/feminine" />
</RelativeLayout>
のように記載し、
MainActivity.java には
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView1 = (ImageView)findViewById(R.id.feminine);
ImageView imageView2 = (ImageView)findViewById(R.id.bigfig);
}
}
と記載しました。
最終的には7枚画像を画面に表示させたいのですが、どのようなメソッドを使えば表示させられますか?
A:
RelativeLayoutは表示位置を指定しない場合、子要素はすべて左上に配置されます。
画像が1枚しか表示されていないのは、画像が重なってしまい見えていないだけです。
おそらく最後のfeminineの画像だけが表示されている状態だと思いますが、その下にbigfigの画像とHello World!の文字列も存在しています(子要素は最初の要素から順番に描画されるためです)。
対策は2つあります。
RelativeLayoutをLinearLayoutに変更する
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bigfig"
android:src="@drawable/bigfig" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/feminine"
android:src="@drawable/feminine" />
</LinearLayout>
LinearLayoutを使う場合、orientationで並べる方向を指定する必要があります。
この場合は縦に並べる指定になります。
子要素の表示位置を指定する
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bigfig"
android:layout_below="@id/textView"
android:src="@drawable/bigfig" />
<ImageView
android:scaleType="centerCrop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/feminine"
android:layout_below="@id/bigfig"
android:src="@drawable/feminine" />
</RelativeLayout>
layout_belowで指定したIDを持つ要素の下に表示されます。
他にも、指定したIDの要素の右に配置したり、親要素の中心に配置したりといった指定方法も可能です。
|
[
"stackoverflow",
"0008878401.txt"
] |
Q:
Can't read international characters from files
I am trying to read portuguese characters from files, and keep getting into problems.
I have the following C# code (for testing purposes):
var streamReader = new StreamReader("file.txt");
while (streamReader.Peek() >= 0)
{
var buffer = new char[1];
streamReader.Read(buffer, 0, buffer.Length);
Console.Write(buffer[0]);
}
It reads each character in the file and then outputs it to the console.
The file contains the following: "cãsa".
The output in the console is: "c?sa".
What am I doing wrong?
A:
You need to read the file using the correct encoding - by default the file will be read as UTF-8, if that's not the right encoding, you will get such issues.
In this example, I am using an constructor overload that takes an encoding, in this case UnicodeEncoding, which is UTF-16:
using(var streamReader = new StreamReader("file.txt", Encoding.UnicodeEncoding))
{
while (streamReader.Peek() >= 0)
{
var buffer = new char[1];
streamReader.Read(buffer, 0, buffer.Length);
Console.Write(buffer[0]);
}
}
In this example, I am using codepage 860, corresponding to Portuguese:
using(var streamReader = new StreamReader("file.txt", Encoding.GetEncoding(860)))
{
while (streamReader.Peek() >= 0)
{
var buffer = new char[1];
streamReader.Read(buffer, 0, buffer.Length);
Console.Write(buffer[0]);
}
}
|
[
"stackoverflow",
"0013374322.txt"
] |
Q:
Possible hibernate exceptions when two threads update the same Object?
Could someone help me with the possible hibernate exceptions when two threads update the same Object?
ex: employee with name "a", age "30" and address "test"
thread1 tries to update "a" to "b" and thread2 tries to update "a" to "c"
Thanks in advance,
Kathir
A:
If your object is a Hibernate entity, then two threads shouldn't have a reference to the same object in the first place.
Each thread will have its own Hibernate session, and each session will have its own copy of the entity. If you have a field annotated with @Version in your entity, for optimistic locking, one of the thread will get an OptimisticLockException. Otherwise, everything will go fine, and the last thread to commit will win.
A:
Thanks for the answers and below are the comments after observation and analysis
We can also do a conditional update with where clause in the query and use executeUpdate() method. Ex: The Hibernate - Query - executeUpdate() method updates and return the number of entities updated. So if the executeUpdate() returns "zero" it means the row has been already updated by another thread. (No Exception)
Using @Version. (OptimisticLockException)
Using Row Level DB lock. (DB Exception)
Using Synchronization. (Java Synchronization Exception)
|
[
"stackoverflow",
"0003843152.txt"
] |
Q:
Serialize class's ToString() value as XmlElement
In C#, I'm trying to serialize ClassA into XML:
[Serializable]
public ClassA
{
[XmlElement]
public string PropertyA { get; set; } // works fine
[XmlElement]
public ClassB MyClassB { get; set; }
}
[Serializable]
public ClassB
{
private string _value;
public override string ToString()
{
return _value;
}
}
Unfortunately, the serialized result is:
<PropertyA>Value</PropertyA>
<ClassB />
Instead, I want it to be:
<PropertyA>Value</PropertyA>
<ClassB>Test</ClassB>
...assuming _value == "Test". How do I do this? Do I have to provide a public property in ClassB for _value? Thanks!
UPDATE:
By implementing the IXmlSerializable interface in ClassB (shown here #12), the following XML is generated:
<PropertyA>Value</PropertyA>
<ClassB>
<Value>Test</Value>
</ClassB>
This solution is almost acceptable, but it would be nice to get rid of the tags. Any ideas?
A:
As you indicated, the only way to do this is to implement the IXmlSerializable interface.
public class ClassB : IXmlSerializable
{
private string _value;
public string Value {
get { return _value; }
set { _value = value; }
}
public override string ToString()
{
return _value;
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
_value = reader.ReadString();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteString(_value);
}
#endregion
}
Serializing the following instance...
ClassB classB = new ClassB() { Value = "this class's value" };
will return the following xml :
<?xml version="1.0" encoding="utf-16"?><ClassB>this class's value</ClassB>
You might want to do some validations so that you encode xml tags etc.
A:
You've answered yourself.
if you derive from IXmlSerializable, you can change the method to do exactly (hopefully) what you wish:
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("ClassB",_value);
}
|
[
"stackoverflow",
"0020745514.txt"
] |
Q:
Cron expression to schedule a job every two years
I'm building a Quartz cron expression to schedule a job to run on a specific day every two years from today. I've tested quite a few but I think one of the following should do the work:
53 18 23 12 ? 2013/2 => starting on year 2013 and on every two years later on
53 18 23 12 ? */2
But both of them fail the Quartz cron expression validation test. What could be the right cron expression?
A:
Your Cron expression is incomplete. Quartz Cron expressions are made up of seven parts:
Seconds
Minutes
Hours
Day-of-Month
Month
Day-of-Week
Year (optional)
So if you wanted to set up a schedule to run at 11:59pm on Dec 24th every two years starting in 2013, the expression would be:
0 59 23 24 12 ? 2013/2
|
[
"serverfault",
"0000293277.txt"
] |
Q:
rsync on Windows - permissions in remote folder not set properly
I am having a slight problem. I use rsync (Cygwin) in Window and the files that are synced in my remote folder is not right.
rsync -r /cygdrive/c/xampp/htdocs/mysite/* [email protected]:/home/mysite/public_html/
Right now, I use rsync to upload the files BUT then I have go into my remote directory and manually change the file/folder permissions myself.
Does rsync have an option to CHMOD, etc.?
Thanks,
Wenbert
EDIT: I'd like the files to be 644, etc.
A:
Cygwin does not understand NTFS ACLs and cannot replicate them. You'll always end up with goofy permissions on the remote side using rsync.
The two methods I've either used or heard recommended to get around the problem are:
Periodically run a fixup script on the remote server, using cacls.exe or some variant thereof to correct the ACLs. The con of this technique is that your script needs to be kept up to date, otherwise permissions on the destination side won't match the source. This is difficult to maintain.
Follow your rsync run with a robocopy.exe run, but only use robocopy to replicate the NTFS ACLs from source to destination. This requires that you be able to connect to the destination server using an SMB share or similar technique, which means you're supporting both cygwin/rsync/ssh and also an SMB share.
A:
If you want to force the permissions at the destination, you'll need to use the --chmod option and/or the --perms option.
--chmod overrides the source permissions (ie rsync pretends that the source permissions are whatever you specify instead of what they actually are)
--perms (or -p) forces the source permissions onto the destination server
For example:
rsync --chmod=a=r,u+w,D+x -p -r /cygdrive/c/xampp/htdocs/mysite/* \
[email protected]:/home/mysite/public_html/
You didn't mention what cygwin considers the source permissions to be (ie an ls -l /cygdrive/c/xampp/htdocs/mysite/* in cygwin) or what the actual permissions wind up being on the destination side. If we knew that, it might be possible to construct something a bit simpler.
For a thorough illumination of the various options, consult the very-detailed rsync manpage.
Note that rsync does not yet support octal permissions (eg --chmod=644). According to this post, support for that will be available in rsync 3.1.0.
|
[
"stackoverflow",
"0020313136.txt"
] |
Q:
Jquery/CSS Disable button click animation after an Jquery animation
My question is when i click the button it dose a click animation but when it´s open and then i click it it should stay and dont do the click animation. Is this even possible?.
Here The JSFiddle.
A:
fiddle Demo
var a_red = $(".a_demo_threee,.a_demo_threee_open"),
content = $("#contentlogin");
content.hide(); //hides the content so its invisibil on the refresh/load of the website
a_red.click(function (e) { //opens the login
e.stopPropagation();
a_red.stop().animate({
"width": "300px",
"height": "200px",
}, 1000);
content.show();
if (content.is(':visible')) {
$(this).removeClass('a_demo_threee').addClass('a_demo_threee_open');
}
});
$(document).click(function () {
a_red.stop().animate({
"width": "42px",
"height": "39px",
}, 1000);
content.hide();
a_red.removeClass('a_demo_threee_open').addClass('a_demo_threee');
});
change class to a_demo_threee_open when element with id contentlogin visible and switch back to a_demo_threee when it hide .
|
[
"stackoverflow",
"0038725535.txt"
] |
Q:
How to edit specific version of file in fugitive
Some content has been moved from a .c file to a .h file in my repository and I want to compare them to ensure that the new header is correct. This is for a Gerrit review and I am assuming there's no simple way to do this using the Gerrit toolchain.
I am trying to edit the .h file in one window and the old version of the .c file. When I issue the Gedit FETCH_HEAD:path/from/root/to/file.c always gives the following error: E492: Not an editor command: Gedit FETCH_HEAD:path/from/root/to/file.c. I've also tried the command using the hash.
What am I missing?
A:
Fugitive commands are only available when the current buffer is controlled by git or when vim first starts up is in a git directory.
Just open any file in the git repository before issuing your :Gedit command.
:e path/from/root/to/file.c
:Gedit FETCH_HEAD:%
Note: Using % to represent the current file. See :h c_%
|
[
"webapps.stackexchange",
"0000017920.txt"
] |
Q:
How to subscribe only to a specific category of videos in a YouTube channel?
I find most of the Tobuscus YouTube videos boring. But I like the "Cute Win Fail" ones. Can I be notified only when he uploads such videos, instead of subscribing to them all?
A:
It's not possible anymore. It used to be, but they removed this functionality when they updated to the new playlist format/layout.
|
[
"stackoverflow",
"0058240796.txt"
] |
Q:
Pass username and client certificate from apache to tomcat using mod_jk
I want to authenticate web services either by ssl certificate (aimed at automatisms) or openid (aimed at people, I am using auth0 as a provider). The web services run in a tomcat container, which is behind an apache web server, using jk. The web server already authenticates the user using auth0 (an using mod_auth_openidc) for other paths, and only available through https. I also have a database which currently maps usernames provided by auth0 to roles (used for authorization in apache).
I would like to have the following functionality:
figure out username
if apache have already logged in the user, use the username
if a client certificate is used in the request use the DN as a username
if none of the above, then redirect so apache does the authentication
figure out the role
make a database lookup based on the username
I have figured out that I might have to write a Filter, and it seems from jk's proxy documentation that I can get the cert and username from the request. I have written the following code:
package com.kodekonveyor.realm;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class KKAuthorizationFilter implements Filter {
private ServletContext context;
@Override
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
this.context.log("KKAuthorizationFilter initialized");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String user = httpRequest.getRemoteUser();
Object cert = httpRequest.getAttribute("javax.servlet.request.X509Certificate");
this.context.log("user:"+user);
this.context.log("cert:"+cert);
chain.doFilter(request, response);
}
}
However when I try to reach a servlet with a user which is currently authenticated, or with client ssl authentication, both the user and cert is logged as null. I suspect I have to do some more apache configuration to make it work.
A test servlet is at /servlet/servlet in tomcat.
I have the following apache configuration (parts are omitted for brewity)
DocumentRoot /var/www/repo
#correct OIDC configuration omitted
<VirtualHost myhost.mydomain.com:443>
ServerName myhost.mydomain.com
DBDriver pgsql
#other DBD configurations are omitted
JkMount /servlet* worker1
<Directory /var/www/repo/servlet>
DirectoryIndex off
RewriteEngine Off
AuthType openid-connect
AllowOverride None
AuthzDBDQuery "a correct database query"
Require dbd-group allrepo
LogLevel debug
</Directory>
<Directory /var/www/repo>
DirectoryIndex off
RewriteEngine Off
AllowOverride None
</Directory>
#correct letsencrypt configuration omitted
</VirtualHost>
A:
The cause is found to be the fact that if you have a JkMount in a Location (or perhaps also a Directory) directive, all other autorization and authorization (or even all other?) directives are ineffective.
An example working configuration for the servlet located at /servlet:
<Location "/servlet*">
JkMount worker1
</Location>
<LocationMatch /servlet.*>
DirectoryIndex off
RewriteEngine Off
AuthType openid-connect
AllowOverride None
LogLevel debug
Require valid-user
SSLOptions +StdEnvVars
SSLOptions +ExportCertData
SSLVerifyClient require
</LocationMatch>
another possible solution:
<LocationMatch /servlet.*>
SetHandler jakarta-servlet
SetEnv JK_WORKER_NAME worker1
DirectoryIndex off
RewriteEngine Off
AuthType openid-connect
AllowOverride None
Require valid-user
LogLevel debug
SSLOptions +StdEnvVars
SSLOptions +ExportCertData
SSLVerifyClient require
</LocationMatch>
See https://tomcat.markmail.org/thread/iax6picwsjlhbohd for discussion
|
[
"codereview.meta.stackexchange",
"0000006027.txt"
] |
Q:
An answer feed in The 2nd Monitor
Currently in The 2nd Monitor, there is a "recent questions" feed that is displayed by our very own Captain Obvious.
Would it be a good idea to have a "recent answers" feed, too?
A:
No
I think The Mission is about bringing down the zombie count. That's a much smaller subset than all the answers. I think all the answers would be too much. On days when users pimp several answers, that already feels too much sometimes.
Keep in mind that the main purpose of the 2nd monitor is to discuss site business. All the answers would be surely too much noise and annoying.
A:
No
Users who are regulars here are going to know other users who are regulars, and may feel strongly obliged to vote on another regular's answer if they seed it come up in the feed. This leads to falsely-earned reputation.
|
[
"stackoverflow",
"0063571873.txt"
] |
Q:
Firebase emulator always returns Error: 2 UNKNOWN after trying out the firestore background trigger functions?
** This is that my firestore (emulator) looks like**
I am trying to practice learning about cloud functions with firebase emulator however, I am running into this probably more often than I expected. I hope it is my end's problem.
I am trying to write a function where when the user made the https request to create an order, the background trigger function will return out the total (quantity * price) to the user. The later part is still WIP at the moment; I am currently just trying to understand and learn more about cloud functions.
This is the https request code I have to add the item, price, and quantity to my firestore. It works well and as intended.
exports.addCurrentOrder = functions.https.onRequest(async (req, res) => {
const useruid = req.query.uid;
const itemName = req.query.itemName;
const itemPrice = req.query.itemPrice;
const itemQuantity = req.query.itemQuantity;
console.log('This is in useruid: ', useruid);
const data = { [useruid] : {
'Item Name': itemName,
'Item Price': itemPrice,
'Item Quantity': itemQuantity,
}};
const writeResult = await admin.firestore().collection('Current Orders').add(data);
res.json({result: data});
});
This is the part that's giving me all sorts of errors:
exports.getTotal = functions.firestore.document('Current Orders/{documentId}').onCreate((snap, context) => {
const data = snap.data();
for(const i in data){
console.log('This is in i: ', i);
}
return snap.ref.set({'testing': 'testing'}, {merge: true});
});
Whenever I have this, the console will always give me:
functions: Error: 2 UNKNOWN:
at Object.callErrorFromStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call.js:30:26)
at Object.onReceiveStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/client.js:175:52)
at Object.onReceiveStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:341:141)
at Object.onReceiveStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:304:181)
at Http2CallStream.outputStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:116:74)
at Http2CallStream.maybeOutputStatus (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:155:22)
at Http2CallStream.endCall (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:141:18)
at Http2CallStream.handleTrailers (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:273:14)
at ClientHttp2Stream.<anonymous> (/Users/user/firecast/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:322:26)
at ClientHttp2Stream.emit (events.js:210:5)
Caused by: Error
at WriteBatch.commit (/Users/user/firecast/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js:415:23)
at DocumentReference.create (/Users/user/firecast/functions/node_modules/@google-cloud/firestore/build/src/reference.js:283:14)
at CollectionReference.add (/Users/user/firecast/functions/node_modules/@google-cloud/firestore/build/src/reference.js:2011:28)
**at /Users/user/firecast/functions/index.js:43:76**
at /usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:593:20
at /usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:568:19
at Generator.next (<anonymous>)
at /usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:8:71
at new Promise (<anonymous>)
at __awaiter (/usr/local/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:4:12)
⚠ Your function was killed because it raised an unhandled error.
Even if I comment out the function that I think is giving me the error, I will still run into this problem (and when I run the sample function found on the official cloud function guide too!)
I know there is definitely something that I am doing horribly wrong on the background trigger (and would love to have someone be kind enough to show me how to write such function/get me startted)
What am I doing wrong here? Or is this some sort of the emulator bug?
A:
I think I found it. Although I think there is better solution possible.
On completely new system+firebase I have used this firebase emulators tutorial to create first onCreate trigger called makeUppercase and it worked. Than I added your getTotal and it was not working and as well it spoiled the makeUppercase trigger as well!
I started to test some changes. Tried many times and, finally, I have removed "space" character from collection name like this:
exports.getTotal = functions.firestore.document('CurrentOrders/{documentId}')...etc.
Both triggers started working as well (used fresh VM with Windows+node12). It's possible that it will be working on real Firestore instance. So it seems the "space" in collection name is generating some errors in whole index.js.
|
[
"stackoverflow",
"0058167433.txt"
] |
Q:
Clear Blood Vessel Segmentation in 3D image using VTK
I am using vtk for segmenting blood vessels.
I have two dicom image sets,one has normal CT images and the other has CT with MIP(Maximum Intensity Projection).
So i subtracted the two series and gave that result to the input of vtkMarchingCubes.But my segmented image is showing only less details.I have attached what i got in the picture.
https://i.stack.imgur.com/V66nN.png
I tried using filters but no use
I need to get even the thin vessels.How is it possible using only VTK?
If not How is it possible in ITK.
If my question is not clear kindly inform
A:
In ITK, you could use vesselness filter to enhance the vessels. That should make them easier to extract.
|
[
"stackoverflow",
"0059613066.txt"
] |
Q:
Need guidance for prometheus memory utilization query
I am using the prometheus query '100 - ((node_memory_MemAvailable_bytes{job="jobname"} * 100) / node_memory_MemTotal_bytes{job="jobname"})' to get the memory utilization and it is working fine.
The above query is giving the result for current memory utilization.
I need to reconstruct the query to get the memory utilization for last 1 hour.For example, if the memory utilization reaches more than 10 MB at 9.15 am and the current memory utilization is 2 MB at 10 am, now i need to check whether the memory utilization is more than 9 MB between 9 am to 10 am
kindly guide me how to construct the prometheus query for it, i think it is something like,
'(100 - ((node_memory_MemAvailable_bytes{job="jobname"} * 100) / node_memory_MemTotal_bytes{job="jobname"}))>9[1H]'
A:
Probably you need SLI value answering the question: how much time the jobname used more than 90% of memory over the last hour? Then the following PromQL query should answer the question:
avg_over_time(
((1 - node_memory_MemAvailable_bytes{job="jobname"} /
node_memory_MemTotal_bytes{job="jobname"}) >bool 0.9)[1h:1m]
)
The returned value will be in the range [0..1], where 0 means 0% (i.e. memory usage didn't exceed 90% during the last hour), while 1 means 100% (i.e. memory usage was higher than 90% all the time during the last hour).
The query uses the following PromQL features:
subquery
bool modifier for comparison operator
avg_over_time function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.