text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Compare date and hour together I am using Amazon Redshift . In my tables I have two columns (Date and Hour) ,along with other columns with values like
requestdate requesthour
2016-10-10 1
2016-10-10 2
... ...
Now I want to compare two dates with hours (day between 2016-10-1005 && 2016-11-1109) . Generally comparing with qyery like
Where date>=xxxx && date<=yyyy && hour>=hhhh && hour<hhhh
will give incomplete results . Can I do something which can be useful here , I tried certain things after searching the web like concat , to_timestamp but could not come up with proper query .
Can anyone help here?
A: Here is one explicit way:
where (date > xxxx or (date = xxxx and hour >= hhhh)) and
(date < yyyy or (date = yyyy and hour < hhhh))
Another method would use date arithmetic:
where date + hour * interval '1 hour' >= xxxx + hhhh * interval '1 hour' and
date + hour * interval '1 hour' < yyyy + hhhh * interval '1 hour'
A: You can cast your date + hour to timestamp and let database to compare them
select (requestdate ||' '|| requesthour ||':00:00')::timestamp between ('2016-10-10 05:00:00')::timestamp and ('2016-08-01 04:00:00')::timestamp from bbt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39225296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Outer margins in pairs() function I have too much whitespace around the outside of my pairs() plot. How can one control the outer margins in a pairs() plot?
Changing oma for example does nothing (i.e. par(oma=c(0,0,0,0)) makes no difference).
A: tl;dr use oma as an argument within your pairs() call.
As usual, it's all in the documentation, albeit somewhat obscurely. ?pairs states:
Also, graphical parameters can be given as can arguments to
‘plot’ such as ‘main’. ‘par("oma")’ will be set
appropriately unless specified.
This means that pairs() tries to do some clever stuff internally to set the outer margins (based on whether a main title is requested); it will ignore external par("oma") settings, only paying attention to internal settings. The "offending" line within the code of stats:::pairs.default is:
if (is.null(oma))
oma <- c(4, 4, if (!is.null(main)) 6 else 4, 4)
Thus setting oma within the call does work:
par(bg="lightblue") ## so we can see the plot region ...
z <- matrix(rnorm(300),ncol=3)
pairs(z,oma=c(0,0,0,0))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33895907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make a multi-user file server system with PHP? I'm just looking a big picture idea here; I can google specifics once provided with guidelines.
I want to make a relatively simple file hosting website such as dropbox or skydrive for mainly pedagogical reasons.
Making a multi-user login and registration system with PHP and MySQL is pretty straight forward, but how would I go about managing file directories and permissions for each user?
A: There are probably hundreds of ways to do this, but this is what I would do:
*
*They should never have a direct download path as it can be abused.
*All files could be stored in the same place.
*File names should be changed to unique ids to avoid dupilcates.
*Store the file name, unique id, and user id in a database.
*When they visit the page for the unique id, you can do your checks and display the file info.
*You will then pass the file to them rather than having them download it directly.
*Their user page would show file names and links to those pages, etc.
I hope that is a good jumping off point.
A: At its simplest: Store files somewhere in any hierarchy you want in a location that's not simply publicly accessible through the web server. Store meta information about each file in a database. In said database, store who the owner of the file is. Write a script that allows people to download those files (see readfile), require that users are logged in and that only owners of files can them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10038752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the correct way of waiting for detached threads to finish? Look at this sample code:
void OutputElement(int e, int delay)
{
this_thread::sleep_for(chrono::milliseconds(100 * delay));
cout << e << '\n';
}
void SleepSort(int v[], uint n)
{
for (uint i = 0 ; i < n ; ++i)
{
thread t(OutputElement, v[i], v[i]);
t.detach();
}
}
It starts n new threads and each one sleeps for some time before outputting a value and finishing. What's the correct/best/recommended way of waiting for all threads to finish in this case? I know how to work around this but I want to know what's the recommended multithreading tool/design that I should use in this situation (e.g. condition_variable, mutex etc...)?
A: Don't detach, but instead join:
std::vector<std::thread> ts;
for (unsigned int i = 0; i != n; ++i)
ts.emplace_back(OutputElement, v[i], v[i]);
for (auto & t : threads)
t.join();
A: And now for the slightly dissenting answer. And I do mean slightly because I mostly agree with the other answer and the comments that say "don't detach, instead join."
First imagine that there is no join(). And that you have to communicate among your threads with a mutex and condition_variable. This really isn't that hard nor complicated. And it allows an arbitrarily rich communication, which can be anything you want, as long as it is only communicated while the mutex is locked.
Now a very common idiom for such communication would simply be a state that says "I'm done". Child threads would set it, and the parent thread would wait on the condition_variable until the child said "I'm done." This idiom would in fact be so common as to deserve a convenience function that encapsulated the mutex, condition_variable and state.
join() is precisely this convenience function.
But imho one has to be careful. When one says: "Never detach, always join," that could be interpreted as: Never make your thread communication more complicated than "I'm done."
For a more complex interaction between parent thread and child thread, consider the case where a parent thread launches several child threads to go out and independently search for the solution to a problem. When the problem is first found by any thread, that gets communicated to the parent, and the parent can then take that solution, and tell all the other threads that they don't need to search any more.
For example:
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <thread>
#include <vector>
void OneSearch(int id, std::shared_ptr<std::mutex> mut,
std::shared_ptr<std::condition_variable> cv,
int& state, int& solution)
{
std::random_device seed;
// std::mt19937_64 eng{seed()};
std::mt19937_64 eng{static_cast<unsigned>(id)};
std::uniform_int_distribution<> dist(0, 100000000);
int test = 0;
while (true)
{
for (int i = 0; i < 100000000; ++i)
{
++test;
if (dist(eng) == 999)
{
std::unique_lock<std::mutex> lk(*mut);
if (state == -1)
{
state = id;
solution = test;
cv->notify_one();
}
return;
}
}
std::unique_lock<std::mutex> lk(*mut);
if (state != -1)
return;
}
}
auto findSolution(int n)
{
std::vector<std::thread> threads;
auto mut = std::make_shared<std::mutex>();
auto cv = std::make_shared<std::condition_variable>();
int state = -1;
int solution = -1;
std::unique_lock<std::mutex> lk(*mut);
for (uint i = 0 ; i < n ; ++i)
threads.push_back(std::thread(OneSearch, i, mut, cv,
std::ref(state), std::ref(solution)));
while (state == -1)
cv->wait(lk);
lk.unlock();
for (auto& t : threads)
t.join();
return std::make_pair(state, solution);
}
int
main()
{
auto p = findSolution(5);
std::cout << '{' << p.first << ", " << p.second << "}\n";
}
Above I've created a "dummy problem" where a thread searches for how many times it needs to query a URNG until it comes up with the number 999. The parent thread puts 5 child threads to work on it. The child threads work for awhile, and then every once in a while, look up and see if any other thread has found the solution yet. If so, they quit, else they keep working. The main thread waits until solution is found, and then joins with all the child threads.
For me, using the bash time facility, this outputs:
$ time a.out
{3, 30235588}
real 0m4.884s
user 0m16.792s
sys 0m0.017s
But what if instead of joining with all the threads, it detached those threads that had not yet found a solution. This might look like:
for (unsigned i = 0; i < n; ++i)
{
if (i == state)
threads[i].join();
else
threads[i].detach();
}
(in place of the t.join() loop from above). For me this now runs in 1.8 seconds, instead of the 4.9 seconds above. I.e. the child threads are not checking with each other that often, and so main just detaches the working threads and lets the OS bring them down. This is safe for this example because the child threads own everything they are touching. Nothing gets destructed out from under them.
One final iteration can be realized by noticing that even the thread that finds the solution doesn't need to be joined with. All of the threads could be detached. The code is actually much simpler:
auto findSolution(int n)
{
auto mut = std::make_shared<std::mutex>();
auto cv = std::make_shared<std::condition_variable>();
int state = -1;
int solution = -1;
std::unique_lock<std::mutex> lk(*mut);
for (uint i = 0 ; i < n ; ++i)
std::thread(OneSearch, i, mut, cv,
std::ref(state), std::ref(solution)).detach();
while (state == -1)
cv->wait(lk);
return std::make_pair(state, solution);
}
And the performance remains at about 1.8 seconds.
There is still (sort of) an effective join with the solution-finding thread here. But it is accomplished with the condition_variable::wait instead of with join.
thread::join() is a convenience function for the very common idiom that your parent/child thread communication protocol is simply "I'm done." Prefer thread::join() in this common case as it is easier to read, and easier to write.
However don't unnecessarily constrain yourself to such a simple parent/child communication protocol. And don't be afraid to build your own richer protocol when the task at hand needs it. And in this case, thread::detach() will often make more sense. thread::detach() doesn't necessarily imply a fire-and-forget thread. It can simply mean that your communication protocol is more complex than "I'm done."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26444647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: sas difference between sum and +? data whatever;
infile '';
input price cost;
<statement>;
run;
In <statement>, what's the difference between using total = sum(total,cost) and total = total + cost ?
A: You'd probably have trouble with either of those if you actually including it after the input statement.
The information that ProgramFOX posted is correct, but if you're asking about the difference between these three statements, there's a little more to it:
total = sum(total,cost);
total + cost;
The second of these implies a retain total; statement and will also treat nulls as zero. You run into the null problem when you're using this type of expression:
total = total + cost;
A: The differnce can be seen below:
If you want to calculate cumulative total , you should use sum statement.
total = sum(total,cost) /* its a sum function */
total+cost /* its a sum statement,the form is variable+expression */
Here :
"total" specifies the name of the accumulator variable, which contains a numeric value.
1) The variable(total in this case) is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement.
2) To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value.
and
"Cost" is an expression
1) The expression is evaluated and the result added to the accumulator variable.
2) SAS treats an expression that produces a missing value as zero.
A sum statement is differ from a sum function in a way that a sum statement retains the value which it has calculated earlier.
However,
The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
retain total 0;
total=sum(total,cost);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19254475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Install node and npm using ant build.xml Could someone help to download node and ant from a URL and install them using ant build.xml?
I tried different ways. but it requires sudo privilege. but, it may/may not be available on the server. so, I need common support with normal user privilege.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71382106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Divs in template are pushing page out of alignment I have, with advice from members here, attempted to create divs rather than a table for article layout template. I had reasonable success - the content displayed, but not correctly and it also scrambled the page - I had the comments module, which should sit below the article, pushed up on the right and the article content pushed left and down. I'm posting the table code along with the divs in the hope that someone can assist (One issue, I think, is that there is a single column spanning 8 rows, 4 of which span 2 columns and 4 contain 2 columns, then below this is a further row which spans all 3 columns. I'm confused. For now I've retained the table, but I would really like to learn how to do this correctly. Any help would be appreciated.
Thanks,
Jude
Table:
<table id='display' width=648 border=0 summary="">
<tr>
<td rowspan=7 width=228><?php echo $item->fields_by_id[3]->result; ?></td>
<td width=200><b>Author:</b></td>
<td width=220><?php echo $item->fields_by_id[1]->result; ?></td>
</tr>
<tr>
<td width=200><b>Publisher:</b></td>
<td width=220><?php echo $item->fields_by_id[2]->result; ?></td>
</tr>
<tr>
<td width=200><b>Genre:</b></td>
<td width=220><?php echo $item->fields_by_id[9]->result; ?></td>
</tr>
<tr>
<td width=200><b>CRR Heat Rating:</b></td>
<td width=220 width=420><?php echo $item->fields_by_id[11]->result; ?></td>
</tr>
<tr>
<td colspan=2 width=420><?php echo $item->fields_by_id[12]->result; ?>
</td>
</tr>
<tr>
<td colspan=2 width=420><?php echo $item->fields_by_id[10]->result; ?>
</td>
</tr>
<tr>
<td colspan=2 width=420><?php echo $item->fields_by_id[13]->result; ?>
</td>
</tr>
<tr>
<td colspan=3 width=648><?php echo $item->fields_by_id[4]->result; ?></td>
</tr>
<tr>
<td colspan=3 width=648><?php echo $item->fields_by_id[5]->result; ?></td>
</tr>
</table>
Divs:
<div id="container">
<div id="article">
<div>
<div style="float:left;">
<div><?php echo $item->fields_by_id[3]->result; ?></div>
</div>
</div>
<div>
<div style="float:left;">
<div><b>Author:</b></div>
<div><b>Publisher:</b></div>
<div><b>Genre:</b></div>
<div><b>CRR Heat Rating:</b></div>
<div><?php echo $item->fields_by_id[12]->result; ?></div>
<div><?php echo $item->fields_by_id[10]->result; ?></div>
<div><?php echo $item->fields_by_id[13]->result; ?></div>
<div><?php echo $item->fields_by_id[5]->result; ?></div>
</div>
</div>
<div>
<div style="float:left;">
<div><?php echo $item->fields_by_id[1]->result; ?></div>
<div><?php echo $item->fields_by_id[2]->result; ?></div>
<div><?php echo $item->fields_by_id[9]->result; ?></div>
<div><?php echo $item->fields_by_id[11]->result; ?></div>
</div>
</div>
</div>
<div id="blurb">
<div>
<div style="float:left;">
<div><?php echo $item->fields_by_id[4]->result; ?></div>
</div>
</div>
</div>
</div>
A: float makes that the element has no height anymore, which causes all kinds of 'funny' stuff. I think you are searching for display: table and display: table-cell. Otherwise you can use clear: left; or clear: both on the element that should be displayed under the left-floating elements.
To get the display: table and display: table-cell working, you'll have to remove one div-wrapper around each column.
<div id="article">
<div>
<div><?php echo $item->fields_by_id[3]->result; ?></div>
</div>
<div>
<div><b>Author:</b></div>
<div><b>Publisher:</b></div>
<div><b>Genre:</b></div>
<!-- etc -->
</div>
</div>
Then use the following CSS:
#article {
display: table;
}
#article > div {
display: table-cell;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19079106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to call versioned graph API services in Facebook .NET SDK? It seems that Facebook now wants us to call versioned endpoints of the Graph API. E.g., https://graph.facebook.com/v2.0/me...
Does the Facebook SDK for .NET make versioned calls? Do I/can I do something to specify the version?
A: Sanjeev got it, there is a parameter you can add to specify version:
FacebookClient fbClient = new FacebookClient();
fbClient.Version = "v2.2";
fbClient.Post("me/feed", new
{
message = string.Format("Hello version 2.2! - Try #2"),
access_token = "youraccesstokenhere"
});
If you are not specifying a version, it'll default to the oldest supported version:
https://developers.facebook.com/docs/apps/versions#unversioned_calls
Facebook will warn you that you are nearing end of support for that version.
Don't take any chances that the auto-upgrade to newer version will work, better to develop, test and deliver with the latest version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28458334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Application on spark using java langage I'm new on a spark , and I want to run an application on this framework using java language. I tried the following code :
public class Alert_Arret {
private static final SparkSession sparkSession = SparkSession.builder().master("local[*]").appName("Stateful Streaming Example").config("spark.sql.warehouse.dir", "file:////C:/Users/sgulati/spark-warehouse").getOrCreate();
public static Properties Connection_db () {
Properties connectionProperties = new Properties();
connectionProperties.put("user", "xxxxx");
connectionProperties.put("password", "xxxxx");
connectionProperties.put("driver","com.mysql.jdbc.Driver");
connectionProperties.put("url","xxxxxxxxxxxxxxxxx");
return connectionProperties;
}
public static void GetData() {
boolean checked = true;
String dtable = "alerte_prog";
String dtable2 = "last_tracking_tdays";
Dataset<Row> df_a_prog = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable, Connection_db());
// df_a_prog.printSchema();
Dataset<Row> track = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable2, Connection_db());
if (df_a_prog.select("heureDebut") != null && df_a_prog.select("heureFin") != null ) {
track.withColumn("tracking_hour/minute", from_unixtime(unix_timestamp(col("tracking_time")), "HH:mm")).show() }
}
public static void main(String[] args) {
Connection_db();
GetData();
}
}
when I run this code nothing is displayed and I get this:
0/05/11 14:00:31 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
# A fatal error has been detected by the Java Runtime Environment:
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006c40022a,pid=3376, tid=0x0000000000002e84
I use IntelliJ IDEA and version of spark: 3.0.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61733047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating an inner stroke of semi transparency on coloured squares? I am drawing different colored squares on canvas with a fixed size of 50px x 50px.
I have successfully added a transparent inner stroke of 5px to these colored squares but it seems like massive overkill the way I am doing it.
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = this.color;
ctx.fillRect(this.x + 5, this.y + 5, engine.cellSize - 10, engine.cellSize - 10);
Is there a better way than drawing 3 separate rectangles to achieve what I am after?
A: Yes!
You can use both a fill color inside your rectangle and a stroke color around your rectangle.
Here is code an a Fiddle: http://jsfiddle.net/m1erickson/myGky/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "red";
ctx.fillRect(100,100,50,50);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(100,100,50,50);
ctx.fillStyle = this.color;
ctx.fillRect(105, 105, 40, 40);
ctx.fill();
ctx.beginPath();
ctx.rect(160,102.5,45,45);
ctx.fillStyle = 'rgb(163,0,0)';
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgb(204,0,0)';
ctx.stroke();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=600 height=400></canvas>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15059174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Regex help: My regex pattern will match invalid Dictionary I hope you guys can help me out.
I'm using C# .Net 4.0
I want validate file structure like
const string dataFileScr = @"
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple */
}
PZ 11
{
IA_return()
}
GDC 7
{
Message = 6
Message = 7
Message = 8
Message = 8
RepeatCount = 2
ErrorMessage = 10
ErrorMessage = 11
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
";
So far I managed to build this regex pattern
const string patternFileScr = @"
^
((?:\[|\s)*
(?<Section>[^\]\r\n]*)
(?:\])*
(?:[\r\n]{0,}|\Z))
(
(?:\{) ### !! improve for .ini file, dont take {
(?:[\r\n]{0,}|\Z)
( # Begin capture groups (Key Value Pairs)
(?!\}|\[) # Stop capture groups if a } is found; new section
(?:\s)* # Line with space
(?<Key>[^=]*?) # Any text before the =, matched few as possible
(?:[\s]*=[\s]*) # Get the = now
(?<Value>[^\r\n]*) # Get everything that is not an Line Changes
(?:[\r\n]{0,})
)* # End Capture groups
(?:[\r\n]{0,})
(?:\})?
(?:[\r\n\s]{0,}|\Z)
)*
";
and c#
Dictionary <string, Dictionary<string, string>> DictDataFileScr
= (from Match m in Regex.Matches(dataFileScr,
patternFileScr,
RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
select new
{
Section = m.Groups["Section"].Value,
kvps = (from cpKey in m.Groups["Key"].Captures.Cast().Select((a, i) => new { a.Value, i })
join cpValue in m.Groups["Value"].Captures.Cast().Select((b, i) => new { b.Value, i }) on cpKey.i equals cpValue.i
select new KeyValuePair(cpKey.Value, cpValue.Value)).OrderBy(_ => _.Key)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
}).ToDictionary(itm => itm.Section, itm => itm.kvps);
It works for
const string dataFileScr = @"
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple */
}
GDC 7
{
Message = 6
RepeatCount = 2
ErrorMessage = 10
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
";
in other words
Section1
{
key1=value1
key2=value2
}
Section2
{
key1=value1
key2=value2
}
, but
*1. not for multiple keyname, i want group by key and output
DictDataFileScr["GDC 7"]["Message"] = "6|7|8|8"
DictDataFileScr["GDC 7"]["ErrorMessage"] = "10|11"
*2. not work for .ini file like
....
[Section1]
key1 = value1
key2 = value2
[Section2]
key1 = value1
key2 = value2
...
*3. dont see next section after
....
PZ 11
{
IA_return()
}
.....
A: Do yourself and your sanity a favor and learn how to use GPLex and GPPG. They are the closest thing that C# has to Lex and Yacc (or Flex and Bison, if you prefer) which are the proper tools for this job.
Regular expressions are great tools for performing robust string matching, but when you want to match structures of strings that's when you need a "grammar". This is what a parser is for. GPLex takes a bunch of regular expressions and generates a super-fast lexer. GPPG takes the grammar you write and generates a super-fast parser.
Trust me, learn how to use these tools ... or any other tools like them. You'll be glad you did.
A: Here is a complete rework of the regex in C#.
Assumptions : (tell me if one of them is false or all are false)
*
*An INI file section can only have key/value pair lines in its body
*In an non INI file section, function calls can't have any parameters
Regex flags :
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.Singleline
Input test:
const string dataFileScr = @"
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple */
}
PZ 11
{
IA_return()
}
GDC 7
{
Message = 6
Message = 7
Message = 8
Message = 8
RepeatCount = 2
ErrorMessage = 10
ErrorMessage = 11
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
[Section1]
key1 = value1
key2 = value2
[Section2]
key1 = value1
key2 = value2
";
Reworked regex:
const string patternFileScr = @"
(?<Section> (?# Start of a non ini file section)
(?<SectionName>[\w ]+)\s* (?# Capture section name)
{ (?# Match but don't capture beginning of section)
(?<SectionBody> (?# Capture section body. Section body can be empty)
(?<SectionLine>\s* (?# Capture zero or more line(s) in the section body)
(?: (?# A line can be either a key/value pair, a comment or a function call)
(?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]*)) (?# Capture key/value pair. Key and value are sub-captured separately)
|
(?<Comment>/\*.+?\*/) (?# Capture comment)
|
(?<FunctionCall>[\w]+\(\)) (?# Capture function call. A function can't have parameters though)
)\s* (?# Match but don't capture white characters)
)* (?# Zero or more line(s), previously mentionned in comments)
)
} (?# Match but don't capture beginning of section)
)
|
(?<Section> (?# Start of an ini file section)
\[(?<SectionName>[\w ]+)\] (?# Capture section name)
(?<SectionBody> (?# Capture section body. Section body can be empty)
(?<SectionLine> (?# Capture zero or more line(s) in the section body. Only key/value pair allowed.)
\s*(?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]+))\s* (?# Capture key/value pair. Key and value are sub-captured separately)
)* (?# Zero or more line(s), previously mentionned in comments)
)
)
";
Discussion
The regex is build to match either non INI file sections (1) or INI file section (2).
(1) Non-INI file sections These sections are composed by a section name followed by a body enclosed by { and }.
The section name con contain either letters, digits or spaces.
The section body is composed by zero or more lines. A line can be either a key/value pair (key = value), a comment (/* Here is a comment */) or a function call with no parameters (my_function()).
(2) INI file sections
These sections are composed by a section name enclosed by [ and ] followed by zero or more key/value pairs. Each pair is on one line.
A: # 2. not work for .ini file like
Won't work because as stated by your regular expression, an { is required after [Section].
Your regex will match if you have something like this :
[Section]
{
key = value
}
A: Here is a sample in Perl. Perl doesen't have named capture arrays. Probably because of backtracking.
Maybe you can pick something out of the regex though. This assumes there is no nesting of {} bracktes.
Edit Never content to leave well enough alone, a revised version is below.
use strict;
use warnings;
my $str = '
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple
*/
}
asdfasdf
PZ 11
{
IA_return()
}
[ section 5 ]
this = that
[ section 6 ]
this_ = _that{hello() hhh = bbb}
TOC{}
GDC 7
{
Message = 6
Message = 7
Message = 8
Message = 8
RepeatCount = 2
ErrorMessage = 10
ErrorMessage = 11
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
';
use re 'eval';
my $rx = qr/
\s*
( \[ [^\S\n]* )? # Grp 1 optional ini section delimeter '['
(?<Section> \w+ (?:[^\S\n]+ \w+)* ) # Grp 2 'Section'
(?(1) [^\S\n]* \] |) # Condition, if we matched '[' then look for ']'
\s*
(?<Body> # Grp 3 'Body' (for display only)
(?(1)| \{ ) # Condition, if we're not a ini section then look for '{'
(?{ print "Section: '$+{Section}'\n" }) # SECTION debug print, remove in production
(?: # _grp_
\s* # whitespace
(?: # _grp_
\/\* .*? \*\/ # some comments
| # OR ..
# Grp 4 'Key' (tested with print, Perl doesen't have named capture arrays)
(?<Key> \w[\w\[\]]* (?:[^\S\n]+ [\w\[\]]+)* )
[^\S\n]* = [^\S\n]* # =
(?<Value> [^\n]* ) # Grp 5 'Value' (tested with print)
(?{ print " k\/v: '$+{Key}' = '$+{Value}'\n" }) # KEY,VALUE debug print, remove in production
| # OR ..
(?(1)| [^{}\n]* ) # any chars except newline and [{}] on the condition we're not a ini section
) # _grpend_
\s* # whitespace
)* # _grpend_ do 0 or more times
(?(1)| \} ) # Condition, if we're not a ini section then look for '}'
)
/x;
while ($str =~ /$rx/xsg)
{
print "\n";
print "Body:\n'$+{Body}'\n";
print "=========================================\n";
}
__END__
Output
Section: 'Start 0'
k/v: 'Next' = '1'
k/v: 'Author' = 'rk'
k/v: 'Date' = '2011-03-10'
Body:
'{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple
*/
}'
=========================================
Section: 'PZ 11'
Body:
'{
IA_return()
}'
=========================================
Section: 'section 5'
k/v: 'this' = 'that'
Body:
'this = that
'
=========================================
Section: 'section 6'
k/v: 'this_' = '_that{hello() hhh = bbb}'
Body:
'this_ = _that{hello() hhh = bbb}
'
=========================================
Section: 'TOC'
Body:
'{}'
=========================================
Section: 'GDC 7'
k/v: 'Message' = '6'
k/v: 'Message' = '7'
k/v: 'Message' = '8'
k/v: 'Message' = '8'
k/v: 'RepeatCount' = '2'
k/v: 'ErrorMessage' = '10'
k/v: 'ErrorMessage' = '11'
k/v: 'onKey[5]' = '6'
k/v: 'onKey[6]' = '4'
k/v: 'onKey[9]' = '11'
Body:
'{
Message = 6
Message = 7
Message = 8
Message = 8
RepeatCount = 2
ErrorMessage = 10
ErrorMessage = 11
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}'
=========================================
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5514195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to update element at the arraylist on Android I had used arraylist to recycleview like this :
product.add(new InfoProduct(R.drawable.cloth, Product_title, "0", Product_data2, lunch));
I want to overwrite R.drawable.cloth when I click it , how can I do ?!
A: productList.get(0).setDrawableId(R.drawable.new_cloth_id); Type any position what you want instead of '0'. And then notify adapter.
A: Please make model(get/set) class of InfoProduct and in onClick of item you'll get the position. On that position you can set drawable to different drawable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42413237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I'm simply trying to create a file in python3, but the standard answers are not working Simple task with answers all over the web. I just can't get any of them to work. When I run the code below on macOS, I get the following error messages:
open error: [Errno 1] Operation not permitted: 'test_60'
Path error: [Errno 1] Operation not permitted: 'test_60'
mknod error: [Errno 1] Operation not permitted
The complete test program follows. What stupid thing am I doing wrong?
#!/usr/local/bin/python3
from pathlib import Path
import os
db_file = "test_60"
#
try:
open(db_file, 'a').close()
except OSError as e:
print('open error:', e)
try:
Path(db_file).touch()
except OSError as e1:
print('Path error:', e1)
try:
os.mknod(db_file)
except OSError as e2:
print('mknod error:', e2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60791991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ngInfiniteScroll handler not firing with specific CSS & div structure I've purchased an Angular template to build a web app and I'm struggling to get the scroll event handler to fire using ngInfiniteScroll v1.2.0 (NOTE: the handler does fire once if I set infinte-scoll-immediate-check to true) . I've reproduced the issue by building the same div structure and CSS that came with the template using jsFiddle:
jsFiddle link
This is the structure that I have to work within because of the template:
<div ng-app='myApp' ng-controller='DemoController'>
<div class="app-content">
<div class="box">
<div class="box-row">
<div class="box-cell">
<div class="box-inner padding">
<div infinite-scroll=" loadMore() " infinite-scroll-distance="2 ">
<img ng-repeat='image in images' ng-src='http://placehold.it/225x250&text={{image}}'>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the CSS that is being used by each of the divs:
.padding {
padding: 32px 32px;
}
.box .box-inner {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.box .box-row .box-cell {
position: relative;
width: 100%;
height: 100%;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.box .box-row {
display: table-row;
height: 100%;
}
.box {
display: table;
width: 100%;
height: 100%;
border-spacing: 0;
table-layout: fixed;
}
.app-content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 100%;
overflow-y: auto;
}
If I comment out the five surrounding divs, everything works fine. I'm not a CSS guy so this "table structure" that is being used is causing me some problems. Any help would be appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32273447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make a DIV cover entire page, but WITHOUT using CSS position I want to make a div with a background-color of red to cover my entire page, but I do not want to use CSS position: absolute. Here is my example with CSS position:
<div style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;"></div>
CSS position works for the most part, but then I am unable to create more than one of these divs (they overlap or cancel each other out because of top: 0 and left: 0). When you scroll down, I want you to see additional divs.
It would really help if there was a pure CSS solution, but JavaScript and HTML are open to me as well. JUST NO JQUERY.
A: What about using viewport height and viewport width?
I've created an example in this JSFiddle.
body, html {
margin: 0;
padding: 0;
}
div {
width: 100vw;
height: 100vh;
}
.one {
background-color: blue;
}
.two {
background-color: green;
}
.three {
background-color: yellow;
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
A: If you want to make div to occupy entire space use vw and vh
because making div alone height:100% and width:100% would not do it
without using viewport units
check this snippet
div{
width: 100%;
height:100%;
background:red;
}
html,body{
height:100%;
width:100%;
}
<div ></div>
but making html and body to have height and width is a bad idea
so to skip it use view port units
check this with viewport unist
div {
width: 100vw;
height: 100vh;
background: red;
}
<div></div>
Hope it helps
A: Older browsers such as IE7 and 8 could be supported without using visual height and width units by using a single absolutely positioned container with inner divs inheriting height and width property values.
CSS
body {
margin: 0px; /* optional */
}
#box {
position:absolute;
height: 100%;
min-width: 100%;
}
.page {
padding: 5px; /* optional */
height: inherit;
}
HTML
<body>
<div id="box">
<div class="page" style="background-color: red">
<div style="width:25em; background-color: gray">25em</div>
</div>
<div class="page" style="background-color: green">2</div>
<div class="page" style="background-color: white">3</div>
</div>
</body>
Update: the width property of the container has been replaced by a min-width property, introduced in IE7, to fix an ugly horizontal scrolling issue. Supplying width for inner div elements was removed as being unnecessary.
A: Simply change the top: value for each one. The first one would be 0, the second 100%, the third 200%, and so on. Here's a working example:
<div style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;background:red;"></div>
<div style="width: 100%; height: 100%; position: absolute; top: 100%; left: 0; background:blue;"></div>
<div style="width: 100%; height: 100%; position: absolute; top: 200%; left: 0; background:green;"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40597692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error: error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found I have both VS 2012 and 2013 installed in my computer and for some projects need 2012 version. using msbulid in shell command I have the following error:
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Platform.targets(44,5): error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found
Would you please let me know how could I change msbuild option to use VS 2013?
Please Do not ask me to uninstall the VS 2012 version, because it is crucial for some other projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31781625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Workaround for piping to an if-statement in powershell? I wanted to pipe an object to a PowerShell if-statement, but it doesn't work:
for($i = 1; $i -le 70; $i++) {
Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | if ($_.ProvisioningState -eq 'Succeeded') {
Remove-AzureRmRedisCache $_ -Force
}}
"The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program". So what should I do instead?
A: you need to do something like this:
Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | where { $_.ProvisioningState -eq 'Succeeded' } |
Remove-AzureRmRedisCache -Force
You filter with Where-Object.
Alternatively you can do:
$cache = Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101"
if ( $cache.ProvisioningState -eq 'Succeeded' ) { do stuff }
or this (UGLY):
if ( (Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101").ProvisioningState -eq 'Succeeded' ) { do stuff }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52561839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jest: How to test get descriptor of Object I'm trying to test object and return his descriptors using jest. In my case the object contains get function. I believe my syntax is wrong here:
get: function number() {
return this.x;
},
Any ideas how to fix it?
Here the example:
let obj = {
x: 10,
get number() {
return this.x;
},
};
test('Return property descriptors of obj', () => {
expect(Object.getOwnPropertyDescriptors(obj)).toMatchObject({
x: {
value: 10,
writable: true,
enumerable: true,
configurable: true
},
number: {
get: function number() {
return this.x;
},
set: undefined,
enumerable: true,
configurable: true
}
});
});
And result:
A: The assertion fails because get: function number() {...} isn't the same function as in the descriptor, function number() {} !== function number() {}.
It should be asserted to be any function with:
...
number: {
get: expect.any(Function),
set: undefined,
enumerable: true,
configurable: true
}
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64688656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Undefined class OneSignal I use Laravel 5.2 and want to use berkayk/laravel-onesignal package, and I installed this package step by step according to Guide on github.
But when I want to use this package I get "Undefined class OneSignal", also I run this artisan command in the terminal:
php artisan config:clear
php artisan config:cache
I try this code in controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use OneSignal;
use App\Http\Requests;
class SignalController extends Controller
{
public function index()
{
OneSignal::sendNotificationToAll("Some Message");
}
}
I get this error
A: You should use full namespace for the facade:
\OneSignal::sendNotificationToAll("Some Message");
Or add this to the top of your class:
use OneSignal;
A: You should write use OneSignal top of the class underneath the namespace.
Hope this work for you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41607649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Not receiving emails, but Mailgun shows 100% delivery rate I'm using a CMS to send emails when a form is submitted. Its configured to use smtp.mailgun.org:587 with the username [email protected]. I'm using Google Apps for my email, so in this case the email account I'm receiving emails at is [email protected]. Customers fill out a form and enter their email address is used as the "from" address and the "to" address is [email protected]. I don't see anything in my Junk folder in Gmail. Mailgun is getting all the emails and marking them as sent/received, but I simply am not getting the emails in Gmail, thus not getting support emails from my customers. What gives?
A: Issue was I had mxa.mailgun.org and mxb.mailgun.org added in my MX Records on my host (Linode). Removing those records fixed the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36878572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I read another program's STDOUT from a Ruby program line by line? I have a small test Ruby program called "count", which counts 1..50.
#!/usr/bin/ruby
#count
for i in 1..50 do
STDOUT.puts i
sleep 1
end
I want to call it from another program, and read the outputted numbers line by line, and output them from the other program, line by line.
However my construction doesn't work:
IO.popen("count","r+") {|f| puts f.readline}
What should I do to make it work? Maybe some modification in the test program "count"?
A: If you have some patience (about 50s worth), you'll see that you do get one line of output and that line will be "1\n". You have two problems:
*
*count is using buffered output. This means that nothing will show up in your stdin until count's output buffer is full; given the small number of bytes that you're printing, the buffer won't be flushed until count finishes.
*Your popen block is only looking for one line.
You can solve the first one by using STDOUT.sync = true to turn off the output buffering in count:
STDOUT.sync = true
for i in 1..50 do
STDOUT.puts i
sleep 1
end
Then in your popen, you can iterate over the lines using each:
IO.popen("count","r+") { |fp| fp.each { |line| puts line } }
Then you should one line of output showing up each second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24499244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to modify selectWithKeyChar()'s function in JComboBox.java? I have a combo box that contains items that start with special characters (ie. À).
Currently, when using the combo box, if you press a key (ie. "a"), it selects an item that starts with the same first letter - but it wouldn't select the one that starts with the special character..
Is there a way to modify the method selectWithKeyChar() in JComboBox.java to ignore the special characters and and treat it like a regular character?
Solutions I have thought of but don't know how to implement:
1) Passing in a temporary combo box model to selectWithKeyChar() that doesn't include the accents. If this is possible, how do you pass in the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run instead of the one that already exists in JComboBox.java?
Here is a minimal example of my setup:
*
*create a new project
*create a new file that has a JPanel form file type
*add a combo box with the following items: "Àpplebee", "Test", "Able"
*call the JPanel in the main:
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new B());
frame.pack();
frame.setVisible(true);
}
});
A:
1) Passing in a temporary combo box model to selectWithKeyChar() that
doesn't include the accents. If this is possible, how do you pass in
the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run
instead of the one that already exists in JComboBox.java?
All of this are possible, You can create a temp ComoBoxModel and you extends JComboBox to override selectWithKeyCharacter on your CustomComboBox. Here is the sample of a code:
CustomComboBox.java
public class CustomComboBox extends JComboBox<String>{
private static final long serialVersionUID = 1L;
public CustomComboBox(String[] items) {
super(items);
}
@Override
public boolean selectWithKeyChar(char keyChar) {
int index;
ComboBoxModel<String> tempModel = getModel(); // Put the model on temp variable for saving it for later use.
String[] itemsArr = new String[getModel().getSize()];
for(int i = 0; i < getModel().getSize(); i++) {
// This will normalizes the Strings
String normalize = Normalizer.normalize(getModel().getElementAt(i), Normalizer.Form.NFD);
normalize = normalize.replaceAll("\\p{M}", "");
itemsArr[i] = normalize;
}
if ( keySelectionManager == null )
keySelectionManager = createDefaultKeySelectionManager();
setModel(new DefaultComboBoxModel<String>(itemsArr)); // Set the Temporary items to be checked.
index = keySelectionManager.selectionForKey(keyChar,getModel());
setModel(tempModel); // Set back the original items.
System.out.println(index);
if ( index != -1 ) {
setSelectedIndex(index);
return true;
}
else
return false;
}
}
If you will test it, even if you enter a normal char 'a', it will select the element in JComboBox with accent or with non-accent.
TestMain.java
public class TestMain {
public static void main(String[] args) {
String[] lists = {"ápa","Zabra","Prime"};
CustomComboBox combo = new CustomComboBox(lists);
System.out.println(combo.selectWithKeyChar('A'));
JFrame frame = new JFrame("Sample");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
combo.setSize(70, 30);
combo.setLocation(100, 100);
frame.add(combo);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46064995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Ruby gem mechanize throwing an error : undefined method `<=>' I am using the Ruby gem mechanize to scrape some html... When I load my page and display the necessary results, the page laods fine. After a reload, I get this error when doing "search_results = @agent.submit(search_form)":
undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem
Before I post any code, just does this ring any bells?
Thanks.
Code:
start = Time.now
# initial set up
@agent = Mechanize.new
Mechanize.html_parser = Hpricot
page = @agent.get("http://www.google.com/")
search_form = page.forms.first
# conduct initial search
@search_term = search_form.q = params[:search].to_s
search_results = @agent.submit(search_form)
# helper variables
search_qs = ""; @page_number = 1; i = 0; @flag = false;
# get the query string structure
search_results.links.each { |li| search_qs = li.href if li.href.match(/.*search\?q=.*start=.*/) }
# search through all paginated pages
while (i < 500)
search_qs = search_qs.gsub(/start=\d+/,"start=#{i}")
@search_url = "http://google.com#{search_qs}"
search_results = @agent.get(@search_url)
search_results.links.each { |li| @flag = true if li.text.match("All Bout Texas Tailgating") }
break if @flag
i+=10; @page_number+=1
end
@execution_time = Time.now-start
render :layout => false
VIEW:
<h2>Query results for "<%= @search_term %>" on Google</h2>
<% if @flag %>
<p>What page is this keyword found: <b><%= @page_number %></b></p>
<p><%= link_to "Click to see page", "#{@search_url}", {:target => "_blank"} %></p>
<p>How long did this query take to run?: <%= @execution_time %> seconds</p>
<% else %>
<p>Keyword not found in Google search reults</p>
<% end %>
STACK TRACE:
NoMethodError (undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem):
mechanize (1.0.0) lib/mechanize/form/field.rb:30:in `<=>'
mechanize (1.0.0) lib/mechanize/form.rb:171:in `sort'
mechanize (1.0.0) lib/mechanize/form.rb:171:in `build_query'
mechanize (1.0.0) lib/mechanize.rb:373:in `submit'
app/controllers/admin/importer_controller.rb:24:in `check_page_rank'
/opt/local/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/opt/local/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/opt/local/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start'
/opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/opt/local/lib/ruby/1.8/webrick/server.rb:95:in `start'
/opt/local/lib/ruby/1.8/webrick/server.rb:92:in `each'
/opt/local/lib/ruby/1.8/webrick/server.rb:92:in `start'
/opt/local/lib/ruby/1.8/webrick/server.rb:23:in `start'
/opt/local/lib/ruby/1.8/webrick/server.rb:82:in `start'
Rendered rescues/_trace (98.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (internal_server_error)
A: So if you look through the source for mechanize in form.rb - form submitting is calling a function called build_query which sorts the fields on the form. Since sort uses the <=> operator, and it's undefined on Hpricot elements, you are getting an exception.
It seems as if mechanize was built to use Nokogiri - it may have unfixed bugs with other parsing implementations. I did not get too deep into mechanize's source and don't want to blame anyone, but you may want to try switching to Nokogiri for this project (if possible). It doesn't seem from this snippet as if you're relying heavily on Hpricot. It seems strange to me that mechanize is throwing an exception on a hidden form field from Hpricot, but the stack trace is pretty clear in this regard.
Your other major option is to hop into the mechanize source and see if you can fix it yourself (or file a bug on the mechanize github and hope somebody gets to it).
Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4073410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I assign 2 different variable to the return values from a function that return 2 values? Sorry for the very messy title. What I have is a function that returns 2 different values:
def func(name):
return value1, value2
Now I would like to assign these 2 values to variables in one line. This is what I have tried:
x,y = func(name)[0] , [1]
The x variable is assigned correctly, but the y variable is assigned just assigned as [1].
If it relevant: The [0] is an array and the [1] is a DataFrame form a .csv file.
A: You are close. It's even simpler than you think, you can extract without reference to indices:
def func(name):
# do something
return value1, value2
x, y = func(var)
func returns a tuple (note parentheses are not required). You can then unpack via sequence unpacking. I would advise you choose variable names that are informative.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50874493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling a URL in jQuery I would like to call a URL. Currently I am using a hidden iFrame to call this URL:
var data = {File: file,NAME: 'file.txt'};
<iframe src="requestFile?'+ $.param(data) + '" style="display: none;" ></iframe>
Now I would like to use AJAX to call the file. The file just has to be called.
I tried it with a GET request:
$.ajax({
'url' : 'requestFile?'+ decodeURIComponent($.param(data)),
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
Unfortunately this does not work. May there be a problem with the length of the URL? The file string is quite long. I do not get an error message.
A: Rather than use the decodeURIComponent($.param(data)), simply use the encode method .param as $.param(data),
decodeURIComponent does just what it says, decodes it and you want to use the encoded which $.param should do for you: http://api.jquery.com/jquery.param/
NOTE: on that page they use the decodeURIComponent in an example so you can see the original decoded value/put it in a variable.
Reworked code (my assumption is that you DO return "success" string and not the actual file here?):
var myparam = var data = {File: file,NAME: 'file.txt'};
$.ajax({
url: 'requestFile?' + $.param(myparam),
type: 'GET'
}).done(function (data) {
if (data == "success") {
alert('request sent!');
}
});
NOTE: You did not show how file was defined so I can only make the assumption that it is a JavaScript object somewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32156050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't build apk with the last android studio when the sdk version is changed to 4.4 I am creating a project that can run on android 4.4.
When pressing 'F4' ( open module setting ), I see that the 'Compile sdk version is on API 23: Android 6.0 (Marshmallow)
But my cellPhone is with version 4.4.2, so I move the version back as I define when I create the project => to API 19: Android 4.4 (KitKat)
Now, nothing works ... the IDE can't find the 'R' anywhere ... and I can't compile it.
I try to clear and rebuild the project
I try to click on the 'sync'
when i leave compile SDK at 23 and set your TARGET SDK to 19 .. the debug is not run on my cellphone.
but nothing .. not working.
Any help please ...
10x
A: Leave your compile SDK at 23, set your TARGET SDK to 19.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33189485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Auto It Script Debugging I have a simple script that works on my PC but not on three others. I am running the script directly from SciTE on all the machines, including my own. Anyway, is there something I can turn on to see what's happening?
Script:
While True
WinSetOnTop("[TITLE:Production Floor Display]","", 1)
Sleep(20000)
WinSetOnTop("[TITLE:Production Floor Display]","", 0)
WinSetOnTop("[TITLE:Preview Image]","", 1)
Sleep(5000)
WinSetOnTop("[TITLE:Preview Image]","", 0)
Wend
A: No, at least not natively.
What are you trying to achieve?
Try compiling the program before doing anything else.
If that is what it looks like (something to do with an industrial camera feed), then you're better off just using Javascript, PHP, NGINX and HTML. That would also be uncomparable to your approach in terms of reliability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68930774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Knockout foreach binding inside a binding (array within an array) i have two classes; users and readings. this relates to healthcare to each user has an array of readings:
/*
* Reading class
* containts health readings
*/
function Reading(date,weight,glucose)
{
var self = this;
self.date=ko.observable(date);
self.weight=ko.observable(weight);
self.glucose=ko.observable(glucose);
self.formattedWeight = ko.computed(function(){
var formatted = self.weight();
return formatted+" lb"
});
}
/*
* User class
* contains a user name, date, and an array or readings
*/
function User(name,date,readings) {
var self = this;
self.name = name;
self.date = date;
self.readingsArray = ko.observableArray([
new Reading(99,99)
]);
}
i know how to use a foreach binding to display the information for a reading or a user. but im not sure how to show the readings inside of a user?
is there a way to use a nested foreach binding or a with binding? here is my html:
<h2>Users (<span data-bind="text: users().length"></span>)</h2>
<table>
<thead><tr>
<th>User name</th><th>Date</th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: users">
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: date" /></td>
<td data-bind="text: readingsArray"></td>
<td><a href="#" data-bind="click: $root.removeUser">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addUser">Add User</button>
<h2>Readings (<span data-bind="text: readings().length"></span>)</h2>
<table>
<thead><tr>
<th>Date</th><th>Weight</th><th>Glucose</th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: readings">
<tr>
<td strong data-bind="text: date"></td>
<td strong data-bind="text: formattedWeight"></td>
<td strong data-bind="text: glucose"></td>
</tr>
</tbody>
</table>
and here is my model if anyone is interested. any help would be greatly appreciated! Thanks in advance!
// Overall viewmodel for this screen, along with initial state
function userHealthModel() {
var self = this;
self.inputWeight = ko.observable();
self.inputDate = ko.observable();
self.inputId = ko.observable();
self.inputGlucose = ko.observable();
// Operations
self.addUser = function(){
self.users.push(new User("",0,0,(new Reading(0,0))));
}
//adds a readings to the edittable array of readings (not yet the reading array in a user)
self.addReading = function(){
var date = self.inputDate();
var weight = self.inputWeight();
var glucose = self.inputGlucose();
if((weight&&date)||(glucose&&date))
{
self.readings.push(new Reading(date,weight,glucose));
}
else{
alert("Please complete the form!")
}
}
self.removeUser = function(userName){self.users.remove(userName)}
//editable data
self.readings = ko.observableArray([
new Reading(12,99,3),new Reading(22,33,2),
new Reading(44,55,3)
]);
self.users = ko.observableArray([
new User("George",2012),
new User("Bindu",2012)
]);
}
ko.applyBindings(new userHealthModel());
A: I'm not sure how you want the Readings rendered, but here is an example:
http://jsfiddle.net/jearles/aZnzg/
You can simply use another foreach to start a new binding context, and then render the properties as you wish.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9900603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How To Enter Words Into This Program? He told me to put any words into this program and I can see one transform to the other, but I have no idea where to insert the words I want. I downloaded CodeBlocks because it looked like the best C++ runner according to Google but when I click run it just says I need two strings. Guessing that means words.
Can anyone look at this and tell me how to insert 2 words?
The Program:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
#define MIN(X,Y) ((X <= Y) ? X:Y)
#define MIN3(A,B,C) ((A <= MIN(B,C)) ? A : MIN(B,C))
class EDIST {
private:
string _s1, _s2;
int _edit_distance;
enum backtrace_pointer { L, D, U };
// L==left, D==diagonal, U==up.
vector<vector<int> > dp_table;
vector<vector<int> > backtrace;
public:
EDIST(const char *a, const char *b) {
_s1 = a;
_s2 = b;
_edit_distance = 0;
}
void run();
private:
int edit_distance() const { return _edit_distance; }
void dp_edit_distance();
void print_dp_tables();
void init_dp_tables();
void print_solution();
};
void EDIST :: print_dp_tables()
{
cout << "\nPrinting dynamic programming table\n";
cout << "\t_";
for ( int i=0; i < _s2.size(); i++ )
cout << "\t" << _s2[i];
cout << endl;
for ( int i=0; i <= _s1.size(); i++ ) {
if ( i ) cout << _s1[i-1];
else cout << "_";
for ( int j=0; j <= _s2.size(); j++ )
cout << "\t" << dp_table[i][j];
cout << endl;
}
cout << "\nPrinting backtrace table\n";
cout << "\t_";
for ( int i=0; i < _s2.size(); i++ )
cout << "\t" << _s2[i];
cout << endl;
for ( int i=0; i <= _s1.size(); i++ ) {
if ( i ) cout << _s1[i-1];
else cout << "_";
for ( int j=0; j <= _s2.size(); j++ ) {
cout << "\t";
if ( backtrace[i][j] == L ) cout << "L";
else if ( backtrace[i][j] == D ) cout << "D";
else cout << "U";
}
cout << endl;
}
}
void EDIST :: init_dp_tables()
{
for ( int i=0; i <= _s1.size(); i++ ) {
vector <int> v;
vector<int> b;
for ( int j=0; j <= _s2.size(); j++ ) {
int n=0, op=0;;
if ( !i ) { n=j; op=L; }
else if ( !j ) { n=i; op=U; }
else { n=0; op=D; }
v.push_back(n);
b.push_back(op);
}
dp_table.push_back(v);
backtrace.push_back(b);
}
for ( int i=0; i <= _s1.size(); i++ )
dp_table[i][0] = i;
for ( int j=0; j <= _s2.size(); j++ )
dp_table[0][j] = j;
}
void EDIST :: dp_edit_distance()
{
for ( int j=1; j <= _s2.size(); j++ ) {
for ( int i=1; i <= _s1.size(); i++ ) {
int a = dp_table[i-1][j]+1;
int b = dp_table[i-1][j-1];
int c = dp_table[i][j-1]+1;
if ( _s1[i-1] != _s2[j-1] )
b++;
dp_table[i][j] = MIN3(a,b,c);
if ( a == dp_table[i][j] ) backtrace[i][j] = U;
else if ( b == dp_table[i][j] ) backtrace[i][j] = D;
else backtrace[i][j] = L;
}
}
}
void EDIST :: print_solution()
{
vector<string> string_sequence;
string_sequence.push_back(_s2);
int i = _s1.size();
int j = _s2.size();
while ( i || j ) {
string s = string_sequence[string_sequence.size()-1];
bool add_string=true;
int new_i=i, new_j=j;
if ( backtrace[i][j] == L ) {//LEFT :: insert
new_j--;
s.erase(j-1,1);
}
else if ( backtrace[i][j] == U ) {//UP : delete
new_i--;
string sub1 = (j >= 1 ? s.substr(0,j) : "");
string sub2 = (j < s.size() ? s.substr(j) : "");
s = sub1 + _s1[i-1] + sub2;
}
else {//DIAGONAL : replace OR no-operation
new_i--;
new_j--;
if ( i && j && dp_table[i][j] != dp_table[new_i][new_j] )
s.replace(j-1,1,_s1.substr(i-1,1));
else
add_string = false;
}
if ( add_string ) {
string_sequence.push_back(s);
_edit_distance++;
}
i = new_i;
j = new_j;
}
cout << "\nEdit distance : " << edit_distance() << endl;
if ( string_sequence.size() )
cout << "\nPrinting mutations : \n";
for ( int i=string_sequence.size()-1; i >= 0; i-- )
cout << "\t" << string_sequence[i] << endl;
}
void EDIST :: run()
{
cout << "\nFinding edit-distance between strings `";
cout << _s1 << "' and `" << _s2 << "'" << endl;
init_dp_tables();
dp_edit_distance();
print_dp_tables();
print_solution();
}
int main(int argc, char *argv[])
{
if ( argc != 3 ) {
cerr << "Need 2 strings as input!\n" << endl;
exit(1);
}
EDIST e(argv[1], argv[2]);
e.run();
return 0;
}
A: When you downloaded the program you probably got a .exe file, you need to execute this program with two command line arguments like so:
programname.exe word1 word2
If your friend didn't give you a executable file you need to compile the source into an executable. CodeBlocks provides this functionality and automatically runs the compiled result. Unfortunately it doesn't pass any arguments to the result which is why the program is telling you that it needs two words. (CodeBlocks is just executing programname.exe)
One solution to this problem is to configure code blocks to provide the arguments. As danben pointed out you can use the "Set program arguments" option in the "Project" menu to configure it to provide arguments. If you set your program arguments as word1 word2 then CodeBlocks will execute programname.exe word1 word2 which is what you want.
If you want to run this program elsewhere you need to compile it. Luckily whenever you click "run" in CodeBlocks it actually does compile an executable somewhere, typically in the project folder under bin\debug or bin\release you'll find a exectuable file. You can use this file as outlined above.
A: This is a question about CodeBlocks rather than about C++, but a quick Google search reveals that you need to select the "Set program arguments" option under the "Project" menu.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14372026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EC2 Instance not available in ECS I have created an EC2 instance via Terraform with the following configuration:
*
*EC2 instance is using the latest Amazon ECS-Optimized Amazon Linux 2 AMI.
*Instance is sitting in a private subnet, with a route to a NAT GW. Tested internet connectivity fine.
*SG rules are configured correctly.
*EC2 Instance profile is using AmazonEC2ContainerServiceforEC2Role
*EC2 user-data is configured (with my cluster name) with:
echo ECS_CLUSTER=my-cluster-name >> /etc/ecs/ecs.config
When I go to my ecs-cluster, no instances show in the EC2 Instance section of the console.
Is there anything else I'm missing as to why this cluster can't register with the EC2 instance?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71253531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simfony2-Twig: Render only a single part of a template I have a homepage wich dynamically loads a bunch of "posts" (similar to facebook wall).
There is the option to follow a post, but when someone clicks on the follow button, which has a counter on following people, I need to reload all the homepage to update this value. How can I update just the part corresponding to the post? Actually the post is in an extern hmtl.twig file which I render from the homepage code:
<div class="row">
<div class="col-md-6">
{% for sueno in suenos %}
{% if loop.index0 is even %}
{{ render(controller('SuenoBundle:Default:suenoFrontend', { 'sueno': sueno } )) }}
{% endif %}
{% endfor %}
</div><!--/col-md-6-->
This is the controller:
public function suenoFrontendAction($sueno)
{
return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
'sueno' => $sueno));
}
This the post html file:
<h4 class="text-center nombre-usuario">{{ sueno.usuario.nombre ~ ' ' ~ sueno.usuario.apellido }}</h4>
{% if sueno.necesitaAyuda == 1 %}
<p class="text-center texto-sueno"><img src="{{ asset('bundles/estructura/images/SOS.png') }}" width="25" height="25" alt="SOS" /></p>
{% endif %}
{% if sueno.rol == 'foto' %}
<a href="#" data-toggle="modal" data-target="#imageModal" data-image="{{ asset('upload/images/' ~ sueno.fotoLink) }}" onclick="verFoto(this.getAttribute('data-image'))"><img src="{{ asset('upload/images/' ~ sueno.fotoLink) }}" class="img-responsive img-thumbnail" alt="Responsive image"></a>
{% elseif sueno.rol == 'video' %}
<div class="video-container"><iframe src="{{ sueno.linkVideo }}" frameborder="0" allowfullscreen=""></iframe></div>
{% endif %}
<h4 class="text-center titulo-sueno">{{ sueno.titulo }}</h4>
<h4 class="text-center quepido-sueno">{{ sueno.quePido }}</h4>
<p class="text-center texto-sueno info">{{ sueno.texto }}</p>
<br>
<div>
{% set size = sueno.usuariosColaboradores | length %}
{% set size2 = sueno.usuariosSeguidores | length %}
<p class="text-center opciones-sueno">
<img src="{{ asset('bundles/estructura/images/colaboradores.png') }}" width="20" height="20" alt="Colaboradores" /> {{ size }}
<img src="{{ asset('bundles/estructura/images/punto.png') }}" width="5" height="5" alt="punto" />
<a href="{{ path('seguir', { 'suenoid': sueno.id }) }}"><img src="{{ asset('bundles/estructura/images/seguidores.png') }}" width="20" height="20" alt="Seguidores" /></a> {{ size2 }}
<img src="{{ asset('bundles/estructura/images/punto.png') }}" width="5" height="5" alt="punto" />
<img src="{{ asset('bundles/estructura/images/compartir.png') }}" width="20" height="20" alt="Compartir" />
</p>
</div>
<hr>
Here you can see the action correpsonding to follow a post(its in the previous code, I remark the line):
<a href="{{ path('seguir', { 'suenoid': sueno.id }) }}"><img src="{{ asset('bundles/estructura/images/seguidores.png') }}" width="20" height="20" alt="Seguidores" /></a> {{ size2 }}
size2 value is the one to update. the controller called when clicking here is this(and where I suppose the failure is):
public function seguirAction($suenoid)
{
$em = $this->getDoctrine()->getManager();
$usuario = $this->getUser();
$sueno = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array('id' => $suenoid));
$usuario->getSuenosSigue()->add($sueno);
$em->persist($usuario);
$em->flush();
// $suenos = $em->getRepository('SuenoBundle:Sueno')->findBy(array('usuario' => $usuario->getId()));
//esto hay que cambiarlo entero para conseguir los sueños apropiados
//return $this->render('EstructuraBundle:Home:home.html.twig', array('suenos'=> $suenos , 'usuario' => $usuario));
return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
'sueno' => $sueno));
}
The thing is that when this render happens, the post fills the full page.
What I want is just to re-render this post in the homepage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20447282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to validate the Content-MD5 header (from the actual content) in a RequestInterceptor (WCF REST Starter Kit) - REST web service I'm implementing REST web services by means of the WCF REST Starter Kit.
I get the request in a System.ServiceModel.Channels.RequestContext.
Specifically: the interceptor starts this way: Public Overrides Sub ProcessRequest(ByRef requestContext As RequestContext)
If the request includes the Content-MD5 header, I must validate the provided hash against the actual content body, right? Because this does not happen 'automatically'. Nobody (IIS, or whoever) is verifying this for me, as I first thought it would happen.
I thought doing this content verification would be easy. I just have to get the request body as a string and compare the result of my GenerateChecksumForContent() with the hash included in the header.
How to compute the MD5 from the content:
Public Shared Function GenerateChecksumForContent(ByVal content As String) As String
' Convert the input string to a byte array and compute the hash.
Dim hashed As Byte() = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(content))
' Convert the hash to a Base64 Encoded string and return it
Return Convert.ToBase64String(hashed)
End Function
How to get the Content-MD5 request Header value:
Dim message As Message = requestContext.RequestMessage
Dim reqProp As HttpRequestMessageProperty = DirectCast(message.Properties(HttpRequestMessageProperty.Name), HttpRequestMessageProperty)
Dim contentMD5HeaderValue As String = reqProp.Headers("Content-MD5")
My problem is that I don't know how to do something so apparently simple as compute the Content-MD5 of the request's body.
I could not find any built-in property telling me this information (the content's MD5 current hash value).
I've tried this, but it does not work:
Dim content As String = requestContext.RequestMessage.GetBody(Of String)()
Dim computedMD5 As String = GenerateChecksumForContent(content)
In addition, what would happen after the RequestInterceptor run and the 'real' method process the content? The content would be lost because it was already read?
Should I in addition do something like ".CreateBufferedCopy()" to keep the request body available for the post-RequestInterceptor processing?
I cannot understand why this is so complicated! It should be something trivial, but as you can see, I'm completely lost.
Please someone, help me...
Many thanks,
Horacio.-
A: Here are two MSDN pages that give an answer to your question:
*
*http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
*http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx
Hopefully one of them will be sufficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3162094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In a json embedded YAML file - replace only json values using Python I have a YAML file as follows:
api: v1
hostname: abc
metadata:
name: test
annotations: {
"ip" : "1.1.1.1",
"login" : "fad-login",
"vip" : "1.1.1.1",
"interface" : "port1",
"port" : "443"
}
I am trying to read this data from a file, only replace the values of ip and vip and write it back to the file.
What I tried is:
open ("test.yaml", w) as f:
yaml.dump(object, f) #this does not help me since it converts the entire file to YAML
also json.dump() does not work too as it converts entire file to JSON. It needs to be the same format but the values need to be updated. How can I do so?
A: What you have is not YAML with embedded JSON, it is YAML with some the value for annotations being
in YAML flow style (which is a superset of JSON and thus closely resembles it).
This would be
YAML with embedded JSON:
api: v1
hostname: abc
metadata:
name: test
annotations: |
{
"ip" : "1.1.1.1",
"login" : "fad-login",
"vip" : "1.1.1.1",
"interface" : "port1",
"port" : "443"
}
Here the value for annotations is a string that you can hand to a JSON parser.
You can just load the file, modify it and dump. This will change the layout
of the flow-style part, but that will not influence any following parsers:
import sys
import ruamel.yaml
file_in = Path('input.yaml')
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 1024
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout)
which gives:
api: v1
hostname: abc
metadata:
name: test
annotations: {"ip": "4.3.2.1", "login": "fad-login", "vip": "1.2.3.4", "interface": "port1", "port": "443"}
The type(annotations['vip'])() establishes that the replacement string in the output has the same
quotes as the original.
ruamel.yaml currently doesn't preserve newlines in a flow style mapping/sequence.
If this has to go back into some repository with minimal chances, you can do:
import sys
import ruamel.yaml
file_in = Path('input.yaml')
def rewrite_closing_curly_brace(s):
res = []
for line in s.splitlines():
if line and line[-1] == '}':
res.append(line[:-1])
idx = 0
while line[idx] == ' ':
idx += 1
res.append(' ' * (idx - 2) + '}')
continue
res.append(line)
return '\n'.join(res) + '\n'
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 15
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout, transform=rewrite_closing_curly_brace)
which gives:
api: v1
hostname: abc
metadata:
name: test
annotations: {
"ip": "4.3.2.1",
"login": "fad-login",
"vip": "1.2.3.4",
"interface": "port1",
"port": "443"
}
Here the 15 for width is of course highly dependent on your file and might influence other lines if they
were longer. In that case you could leave that out, and make the wrapping
that rewrite_closing_curly_brace() does split and indent the whole flow style part.
Please note that your original, and the transformed output are, invalid YAML,
that is accepted by ruamel.yaml for backward compatibility. According to the YAML
specification the closing curly brace should be indented more than the start of annotation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72144081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: issue with fx scene builder Hey I got this error when trying to start my fx application. I'm using icons which I believe are part of an external jar (com.gluonhq.charm.glisten.control). So I downloaded the jar and put it in referenced libraries, nothing happened. Then added it as an external annotation to the fx library. Didn't solve the problem. Any idea's?
javafx.fxml.LoadException: /C:/Users/Gebruiker/eclipse-workspace/Pyxus/bin/application/Layout.fxml
at
javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
at
javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2863)
at
javafx.fxml/javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2707)
at
javafx.fxml/javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2676)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2542)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435) at
application.Main.start(Main.java:18) at
javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
at java.base/java.security.AccessController.doPrivileged(Native
Method) at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
at
javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at
javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
Method) at
javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
at java.base/java.lang.Thread.run(Thread.java:844) Caused by:
java.lang.ClassNotFoundException:
com.gluonhq.charm.glisten.control.Icon at
java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at
java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at
javafx.fxml/javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2931)
at javafx.fxml/javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2920)
at
javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2861)
... 15 more
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52470435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Force couchdb to reference attachments instead of duplicate in new revision I have a problem with attachments in couchdb.
Let's say I have a document with a big attachment (100 MB). It means that each time you're modifying the document (not the attachment, just one field of the document), it will duplicate the 100 MB attachment.
Is it possible to force couchdb to create references of attachments when they are not modified (couchdb can easily verify if the attachment has been modified with the MD5)?
Edit:
According to this it should be able to do it but how? Mine (personal install) doesn't do it by default!
A: Normally, what you expect to find is the default behaviour of CouchDB. I think it could depend on how the API is used however. For example, following sample scenario works fine (on CouchDB 1.5)
All commands are given in bash syntax, so you can reproduce easily (just make sure to use correct document id and revision numbers).
Create 10M sample file for upload
dd if=/dev/urandom of=attach.dat bs=1024 count=10240
Create test DB
curl -X PUT http://127.0.0.1:5984/attachtest
Database expected data_size is about few bytes at this point. You can query it as follows, and look for data_size attribute.
curl -X GET http://127.0.0.1:5984/attachtest
which gives in my test:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":2,"purge_seq":0,"compact_running":false,"disk_size":8287,"data_size":407,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":2}
Create sample document
curl -X POST -d '{"hello": "world"}' -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest
This command gives an output with document id and revision, which are then should be used hereafter
Now, attach sample file to the document; command should use id and revision as logged in the output of the previous one:
curl -X PUT --data-binary @attach.dat -H "Content-Type: application/octet-stream" http://127.0.0.1:5984/attachtest/DOCUMENT-ID/attachment\?rev\=DOCUMENT-REVISION-1
Last command output denotes that revision 2 have been created, so the document was updated indeed. One can check the database size now, which should be around 10000000 (10M). Again, looking for data_size in the following command's output:
curl -X GET http://127.0.0.1:5984/attachtest
Now, geting the document back from DB. It will be used then to update it. Important to have in it:
*
*the _rev in the document, to be able to update it
*attachment stub, to denote that attachment should not be deleted, but kept intact
curl -o document.json -X GET http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Update document content, not changing the attachment itself (keeping the stub there). Here this will simply change one attribute value.
sed -i 's/world/there/' document.json
and update document in the DB
curl -X PUT -d @document.json -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Last command output denotes that revision 3 have been created, so we now that the document is updated indeed.
Finally, now we can verify the database size! Expected data_size is still around 10000000 (10M), not 20M:
curl -X GET http://127.0.0.1:5984/attachtest
And this should work fine. For example, on my machine it gives:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":8,"purge_seq":0,"compact_running":false,"disk_size":10535013,"data_size":10493008,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":8}
So, still 10M.
A:
It means that each time you're modifying the document (not the
attachment, just one field of the document), it will duplicate the 100
MB attachment.
In my testing I found the opposite - the same attachment is linked through multiple revisions of the same document with no loss of space.
Please can you retest to be certain of this behaviour?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25859323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Copying Conditional Formatting without adding to the data set I have an inventory and ordering management Sheet where I use color coding via Sheets Conditional Formatting to make some cells quickly visible as having outstanding orders. In my particular case, I am using conditional formatting based on a neighboring cell.
The sheet I built utilizes several columns for ordering cycles with our suppliers. When I am ready to move on to the next ordering cycle, I copy and paste a set of columns to create the new cycle.
The problem that I encounter is this: the new column's Conditional Formatting gets added to the old, both in terms of adding a new column to format, but also referencing the cell from which the copied columns use to decide whether to format.
Original Order Block
In this second image, I have pasted a new order block from Columns AD-AL to Columns AM -AU.
Pasted Order Block
There are two things that I am trying to solve:
*
*I would expect the custom formula to update to =$AR5<>"", but it holds on to the Original Order Block's formula, thus applying the formatting from cells that are in the Original Order Block.
*I would expect the range to update to only the new range of AQ5:AQ397, rather than add the additional range to the original order block range.
Each order block needs the conditional formatting to be independent from the one which it was copied.
Thanks in advance.
A: In this case, you can just remove the "$" from your custom formula and it will move just fine
Your ranges are going to be together as you shown, but will look at the cell at its right
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74726035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Binary Search Tree with key and value I need to implement a Binary Search Tree class as homework but I struggle making the insert function. I have looked through Google a lot to find some solutions or possibilities on how to do it but none of them has used a key and value (mostly just value) or if they used a key aswell, they had tons of seperate functions which I am not allowed to do I think.
So the pre-built is simply that:
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def insert(self, key, value):
pass
def remove(self, key):
pass
def find(self, key):
pass
Now the thing is, if I want to check for example whether the value is smaller or bigger than a current Node to put it either right or left, I get Errors such as "root is not defined" or "root.right" has no such attribute etc...
And I guess that makes sense because self.root is declared as None.
But how do I actually fix it now to make the insert function work?
I am a little confused by this task as it uses key + value, so I need to insert the value bound to the specific key and in case the key already existed, overwrite its value.
A: its 5 in the morning so this might be all wrong, but here goes:
the key is what we are sorting by, the values aren't interesting
your insert function should probably look something like this:
def insert(self, key, value):
if self.root = None:
self.root = Node(key,value)
return
#regular binary tree traversal (comparing the key) to find where to insert, lets assume we need to insert on the left
parent.left = Node(key,value)
can you figure it out from here or would you like more direction
A: You didn't specify, but I'm guessing the point of the keys is to determine if a particular key is already in the tree, and if so, replace the related node's value in O(1) runtime complexity.
So when you're inserting a node, you will first check the dictionary for the key (you will initialize an empty dictionary yourself in __init__). If it already is there, then you simply just need to replace the value of the node for that particular key. Otherwise, you add the new node the same way that you would in any BST, and also remember to update your dictionary to map the key to it's node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44184951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Three.js wrong texture on ShaderMaterial I'm trying to use a shaderMaterial to adjust the brightness and contrast on one object (the sphere for VR video)
Here is how I implement the ShaderMaterial
var geometry = new THREE.SphereGeometry( 500, 60, 40 );
var panoTexture = new THREE.VideoTexture( video );
panoTexture.minFilter = THREE.LinearFilter;
panoTexture.magFilter = THREE.LinearFilter;
panoTexture.format = THREE.RGBFormat;
// var material = new THREE.MeshLambertMaterial( { map : texture } );
var shader = THREE.BrightnessContrastShader;
shader.uniforms[ "contrast" ].value = 0.0;
shader.uniforms[ "brightness" ].value = 0.0;
shader.uniforms[ "texture" ].texture = panoTexture;
var panoMaterial = new THREE.ShaderMaterial(shader);
panoVideoMesh = new THREE.Mesh( geometry, panoMaterial );
And here is the code I'm using for the shader
THREE.BrightnessContrastShader = {
uniforms: {
"tDiffuse": { type: "t", value: null },
"brightness": { type: "f", value: 0 },
"contrast": { type: "f", value: 0 },
"texture": { type: "t", value: 0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform sampler2D tDiffuse;",
"uniform float brightness;",
"uniform float contrast;",
"varying vec2 vUv;",
"void main() {",
"gl_FragColor = texture2D( tDiffuse, vUv );",
"gl_FragColor.rgb += brightness;",
"if (contrast > 0.0) {",
"gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;",
"} else {",
"gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;",
"}",
"}"
].join("\n")
};
When the sphere is rendered it's using another more recently generated texture that is for another part of the scene.
How do I keep the video texture on the panoTexture, is this possible and and am I going about this the right way?
A: This worked
shader.uniforms[ "tDiffuse" ].value = panoTexture;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40715234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What if any, programming fundamentals are better learned in C as opposed to C++? As a person who wanted to increase his fundamental programming skills, I chose to learn C++ instead of C. Which leads me to ask: Is there any fundamental skills that I leave in C that might not be obtained by learning C++?
Related question: Should I learn C before learning C++?
A: I don't think there are any skills that you can learn in C but not C++, but I would definitely suggest learning C first still. Nobody can fit C++ in their head; it may be the most complex non-esoteric language ever created. C, on the other hand, is quite simple. It is relatively easy to fit C in your head. C will definitely help you get used to things like pointers and manual memory management much quicker than C++. C++ will help you understand OO.
Also, when I say learn C, it's okay to use a C++ compiler and possibly use things like iostreams if you want, just try to restrict yourself to mostly C features at first. If you go all out and learn all the weird C++ features like templates, RAII, exceptions, references, etc., you will be thoroughly confused.
A: Compare the following code examples (apologies, my C++ is a little rusty).
C++:
int x;
std::cin >> x;
C:
int x;
scanf("%d", &x);
So, what do you see above? In C++, a value is plugged into a variable. That's cool, but what does it teach us? In C, we notice a few things. The x has a funny & in front of it, which means it's address is being passed. That must mean that the scanf function actually needs to know where in memory x is. Not only that, but it needs a format string, so it must not really hvae any idea of what address you're giving it and what format it's getting information in?
C lets you discover all these wonderful things about how the Computer and the Operating System actually work, if you will put effort towards it. I think that's pretty cool.
A: There is certainly one thing: memory management. Take following code for example:
struct foo {
int bar;
char **box;
};
struct foo * fooTab = (struct foo *) malloc( sizeof(foo) * 100 );
for(int i = 0; i<100; i++) {
fooTab[i].bar = i;
fooTab[i].box = (char **) malloc( sizeof(char *) * 10 );
for(int j = 0; j<10; j++) {
fooTab[i].box[j] = (char *) malloc( sizeof(char) * 10 );
memset(fooTab[i].box[j], 'x', 10);
}
}
Using C++ you simply do not deal with memory allocation in such way. As a result, such skills may be left untrained. This will certainly result in e.g. lower debugging skills. Another drawback may be: lower optimizing skills.
C++ code would look like:
struct foo {
int bar;
static int idx;
vector< vector<char> > box;
foo() : bar(idx), box(10) {
idx++;
for ( auto it = box.begin(); it != box.end(); it++) {
it->resize(10,'x');
}
}
};
int foo::idx = 0;
foo fooTab[100];
As you can see there is simply no way to learn raw memory management with C++-style code.
EDIT: by "C++-style code" I mean: RAII constructors/destructors, STL containers. Anyway I had probably exaggerated, it would be better to say: It is far more difficult to learn raw memory management with C++-style code.
A: I find it's better to learn memory management in C before attempting to dive into C++.
In C, you just have malloc() and free(). You can typecast things around as pointers. It's pretty straightfoward: multiply the sizeof() by the # items needed, typecast appropriately, and use pointer arithmetic to jump all over the place.
In C++, you have your various reinterpret_cast<> (vs. dynamic_cast, etc) kind of things, which are important, but only make sense when you're realizing that the various castings are meant to trap pitfalls in multiple inheritance and other such lovely C++-isms. It's kind of a pain to understand (learn) why you need to put the word "virtual" on a destructor on objects that do memory management, etc.
That reason alone is why you should learn C. I also think it's easier to (at first) understand printf() vs. the potentially overloaded "<<" operator, etc, but to me the main reason is memory management.
A: I wouldn't say you missed anything fundamental. Check out Compatibility of C and C++ for a few non-fundamental examples, though.
Several additions of C99 are not supported in C++ or conflict with C++ features, such as variadic macros, compound literals, variable-length arrays, and native complex-number types. The long long int datatype and restrict qualifier defined in C99 are not included in the current C++ standard, but some compilers such as the GNU Compiler Collection[3] provide them as an extension. The long long datatype along with variadic templates, with which some functionality of variadic macros can be achieved, will be in the next C++ standard, C++0x. On the other hand, C99 has reduced some other incompatibilities by incorporating C++ features such as // comments and mixed declarations and code.
A: The simplicity of C focuses the mind wonderfully.
With fewer things to learn in C, there is a reasonable chance that the student will learn those things better. If one starts with C++ there is the danger of coming out the other end knowing nothing about everything.
A: If all you've ever used is object-oriented programming languages like C++ then it would be worthwhile to practice a little C. I find that many OO programmers tend to use objects like a crutch and don't know what to do once you take them away. C will give you the clarity to understand why OO programming emerged in the first place and help you to understand when its useful versus when its just overkill.
In the same vein, you'll learn what it's like to not rely on libraries to do things for you. By noting what features C++ developers turned into libraries, you get a better sense of how to abstract your own code when the time comes. It would be bad to just feel like you need to abstract everything in every situation.
That said, you don't have to learn C. If you know C++ you can drag yourself through most projects. However, by looking at the lower-level languages, you will improve your programming style, even in the higher-level ones.
A: It really depends on which subset of C++ you learned. For example, you could get by in C++ using only the iostreams libraries; that would leave you without experience in the C stdio library. I'm not sure I would call stdio a fundamental skill, but it's certainly an area of experience one should be familiar with.
Or perhaps manually dealing with C-style null-terminated strings and the str*() set of functions might be considered a fundamental skill. Practice avoiding buffer overflows in the face of dangerous API functions is definitely worth something.
A: This is just a shot in the dark, but perhaps you use function pointers more in C than in C++, and perhaps utilizing function pointers as a skill might be boosted by starting to learn C. Of course all of these goodies are in C++ as well, but once you get your hands on classes it might be easy to just keep focusing on them and miss out on other basic stuff.
You could for example construct your own inheritance and polymorphism "system" in pure C, by using simple structs and function pointers. This needs a more inventive thinking and I think builds up a greater understanding of what is happening "in the box".
If you start with C++ there is a chance that you miss out on these little details that are there in C++ but you never see them, since the compiler does it for you.
Just a few thoughts.
A: Depends on how you approach C++. I would normally recommend starting at a high level, with STL containers and smart pointers, and that won't make you learn the low-level details. If you want to learn those, you probably should just jump into C.
A: Playing devil's advocate, because I think C is a good starting point...
Personally, I started learning with C, algorithms, data structures, memory allocation, file manipulation, graphics routines... I would call these the elementary particles of programming.
I next learned C++. To over-simplify, C++ adds the layer of object-oriented programming - you have the same objectives as you do regardless of language, but the approach and constructs you build to achieve them are different: classes, overloading, polymorphism, encapsulation, etc...
It wasn't any educated decision on my part, this is simply how my programming course was structured, and it worked out to be a good curriculum.
Another simplification... C is basically a subset of C++. You can "do C" with C++, by avoiding to use the language features of C++. From the perspective of language features. Libraries are different matter. I don't think you will get past more than just programming 101 without beginning to use and build libraries, and there is enough out there to keep you busy for a lifetime.
If your goal is to learn C++ ultimately, then beginning with "C" could be a logical start, the language is "smaller" - but there is so much in "C" that you would probably want to narrow your focus. You are tackling a bigger beast, but if you get guidance, I see no compelling reason not to, despite the path I took.
A: Most C code can be compiled as C++ code with a few minimal changes. For examples of a very few things that can't be changed see Why artificially limit your code to C?. I don't think any of these could be classed as fundamental though.
A: C is essentially a subset of C++. There are differences as highligted by some of the other answers, but essentially most C compiles as C++ with only a little modification.
The benefits of learning C is that it's a much more compact language and learning it is therefore quicker. C also requires you to work on a relatively low abstraction level which is good for understanding how the computer actually works. I personally grew up with assembly and moved to C from there, which I now see as a definitive advantage in understanding how compilers actually map high abstraction level contstructs to actual machine code.
In C++ you can find yourself quickly entrenched in higher levels of abstraction. It's good for productivity but not necessarily so for understanding.
So my advice is: study C++ if you have the motivation, but first concentrate on the core low level constructs that are common with C. Only then move to the higher level things such as object orientation, templates, extensive class libraries and so on.
A: optimization theory
primarily because the asm output of a C compiler is generally mush more predictable and usually well correlated to the C. This lets you teach/learn why its better to structure code a certain way by showing the actual instructions generated.
A: You should learn data structures in C. First, it will force you to really understand pointers, which will help you to deal with leaky abstractions in higher level languages. Second it will make obvious the benefits of OO.
A: Coding Sytle
By coding style I don't mean {} and whitespace, I mean how you organizing data, classes, files, etc.
I started off learning c++, which usually favors creating classes and organizing things a certain way. I could write c code just fine when needed, but it was never like the c style code that others wrote who started off with c.
One of my OS classes required us to write a file system in C. My partner was originally a C guy and I was amazed at the difference in the code we wrote. Mine was obviously trying to use c++ style coding in c.
It's kindof like when you first learn perl or ruby or something and you are just trying to write the same c# code except translated into that new language rather than using that languages features.
While C is a subset of C++, C programs and C++ programs are so different as to not really be comparable.
A: Yes, simple structured programming.
With OOP everywhere, it is easy to forget that you can build sound system just by using modules and functions. C's module system is pretty weak, but still...
This is also one of the advantages of functional programming, in my book. Many functional programming languages have a strong module system. When you need more genericity than simple functions can offer, there are always higher order functions.
A: if you want to learn new skills and you have good fundamentals of structured programing(SP) you should go for C++. learn to think a given problem in an object oriented(OOP) way (define objects, methods, Inheritance, etc) its sometimes the most difficult part. I was in the same situation as you a few years ago, and i choose C++, because learning a new paradigm, a new way of thinking and design software, sometimes its more difficult that the code itself, and if you don't like C++ or OOP you can go back to C and SP, but at least you will have some OOP skills.
A: I would choose C to learn low-level primitives of programming.
For OOP, there are so many other languages to learn before C++ that are much easier to learn. This isn't 1990 when the only OOP languages were Smalltalk and C++, and only C++ was used outside of academia. Almost every new programming language invented since has objects, and almost all are less complex than C++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/946855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Magento 2 wrong product price in cart after removal of category discount In Magento 2 I have created a custom module category discount. When active its working fine for product list, details and cart view page.
But when I remove this discount it shows the original price for list and details page which is correct but mini cart view shows me the discounted price which shouldn't be the case. However if I update the quantity then it's fine.
I don't want to click the update button in the mini cart view for the original price. I want to do this using an observer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38827988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best practice for handling state change during screen rotation I've got a very simple program with a spinner and toggleButton.
When the button is toggled on I disable the spinner, and enable when I toggle off.
I've come across an issue that means the spinner is re-enabled during screen rotation.
I understand this is due to the activity state changing and onCreate being called again, but I haven't come across a definitive answer on best practice for view states in instances like this.
NOTE: The most relevant SO questions relating to this that I've found are below. All 3 have discussions on how to handle state changes (onPause/OnResume versus overriding onSaveInstanceState), but none seem to clarify which is preferred option for something as simple as this.
Losing data when rotate screen
Saving Android Activity state using Save Instance State
Android CheckBox -- Restoring State After Screen Rotation
A: The accepted answer at Saving Android Activity state using Save Instance State is the way to go.
Use onSaveInstanceState to save a boolean flag indicating whether the spinner is disabled, then read the flag in onCreate (or onRestoreInstanceState) and disable the spinner as necessary.
If you give your views an android:id in the XML layout and don't explicitly set android:saveEnabled to false, their "state" will be saved and restored automatically. For example, for text views, this includes the text currently in the view and the position of the cursor. It appears the enabled/disabled status is not part of this "state", however.
A: How does System retains ListView scroll posion automatically?
You may have noticed that some data does not get affected during rotation even if you have not handled it onSaveInstanceState method. For example
*
*Scrollposition Text in EditText
*Text in EditText etc.
What happens when the screen rotates?
When the screen rotates System kills the instance of the activity and recreates a new instance. System does so that most suitable resource is provided to activity for different configuration. Same thing happens when a full activity goes in multipane Screen.
How does system recreates a new Instance?
System creates a new instance using old state of the Activity instance called as "instance state". Instance State is a collection of key-value pair stored in Bundle Object.
By default System saves the View objects in the Bundle for example.
eg Scroll position EditText etc.
So if you want to save additional data which should survive orientation change you should override onSaveInstanceState(Bundle saveInstanceState) method.
Be careful while overriding onSaveInstance method!!!
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Always call the super.onSaveInstanceState(savedInstanceState) ekse the default behavior will not work. ie EditText value will not persist during orientation. Dont beleive me ? Go and check this code.
Which method to use while restoring data?
*
*onCreate(Bundle savedInstanceState)
OR
*
*onRestoreInstanceState(Bundle savedInstanceState)
Both methods get same Bundle object so it does not really matter where you write your restoring logic. The only difference is that in onCreate(Bundle savedInstanceState) method you will have to give a null check while it is not needed in the latter case.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
}
OR
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
Always call super.onRestoreInstanceState(savedInstanceState) so that
System restore the View hierarchy by default.
A: <activity
android:name="com.rax.photox.searchx.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
It worked for me perfectly
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16533506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: change and initialise variables in a function I was wondering if it's possible to change and initialize variables in a function without passing arguments to the function. Here is what I want to achieve:
$foo = 'Lorem';
$array = array();
foobar($foo);
function foobar(){
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
fubar();
function fubar(){
if (empty($fouten))
echo $bar;
}
A: $foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();
function foobar(){
global $foo, $array, $bar;
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects
A: Functions in php can be given arguments that have default values. The code you posted as written will give you notices for undefined variables. Instead, you could write:
function foobar($foo = null) {
if($foo) { // a value was passed in for $foo
}
else { // foo is null, no value provided
}
}
Using this function, neither of the below lines will produce a notice
foobar();
foobar('test');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10738878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: data exchange between boost::generic_image_library and external class I know how external class data can be transformed into generic image library class, such as the following codes show:
unsigned char *dst_pixels;
dst_pixels = new unsigned char [200*500];
for(int i=0; i<500; i++)
{
for(int j=0; j<200; j++)
dst_pixels[i*200+j]= j;
}
gray8c_view_t my_view = interleaved_view(200,500,(const gray8_pixel_t*)dst_pixels,src_row_bytes);
However, I cannot find a easy way to obtain the image data pointer in the image view class of generic image library, which can be used to communicate with external classes as the following codes show:
unsigend char *p_memory;
p_memory = my_view.get_pointers_to_the_image_data;
functin_work_on_p_memory;
Any ideas will be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17613570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get app version from UWP (Windows 10) app A simple question : How to get app version from C# code?
I want to send email from my UWP app and add into it app version to know which version user is using.
App version is stored on Package.appxmanifest, but i didn't want to make a xml reader to get it and i hope there is an esay way to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33043838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: remove text where regex pattern has trailing backslash doublequote at end of string I have a string from which I need to remove some characters that end in backslash doublequote. There are multiple matches. I have it to where it ALMOST works, except I can't get rid of the last backslash double quote (\") in each place that the namespace occurs.
I went to regexpal.com and came up with this regex string that does what I want.
xmlns=*.+be/\\"
But when I put it in C# the two backslashes make it grab way too much. This code repeats my issue and shows my progress:
var str = "<Request> <sender xmlns=\"http://stuff.otherstuff.be/\"> <name>Sender name</name> </sender> <addressee xmlns=\"http://some.stuff.be/\"> </addressee> <networkType xmlns=\"http://yet.more.stuff.be/\">11</networkType></Request>";
str = Regex.Replace(str, @"xmlns=.*?\.be/", "", RegexOptions.IgnoreCase);
I wind up with a string that looks like this. I need to modify the regex a bit to also catch the backslash and double quote
<Request>
<sender \">
<name>Sender name</name>
</sender>
<addressee \">
</addressee>
<networkType \">11</networkType>
</Request>
I've tried various combinations of multiple backslashes and multiple double quotes but am not getting it.
I have looked at a lot of answers here and elsewhere, and haven't figured it out, so a "has duplicate" isn't really going to help me.
EDIT: At this point in the code all I have is a string that came from a serialized class. I don't really want to load the string into and XMLDocument and do recursive calls like in the possible answer shown. A quick regex replace should get me what I need in 1 statement.
EDIT: The answer with adding two doublequotes does not help me because it ignores the final backslash that I'm trying to get rid of.
A: You need to add the trailing quote like this (if using the @ syntax you must use "" to match a one quote):
str = Regex.Replace(str, @"xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);
Add a space at the beginning if you want <sender> instead of <sender >:
str = Regex.Replace(str, @" xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);
A: Note that to remove XML namespaces, you can use regular C# code described at How to remove all namespaces from XML with C#?, but since you say that does not help, here is a solution for your special case.
In order to remove any slashes you may use a character class [/\\] - just in case you have both \ and /. Note that a literal backslash must be doubled in a verbatim string literal.
The regex will look like
\s*xmlns=[^<]*?\.be[/\\]"
Here is a regex demo
And in C#:
var rx = new Regex(@"\s*xmlns=[^<]*?\.be[/\\]""");
The \s* will "trim" the whitespace in the resulted replacement.
Results after replacing with string.Empty:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32640845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SiteMinder SSO not protecting ASP.NET MVC 5 site This problem may be related to the UrlRoutingModule handling all the routing and bypassing SiteMinder. Any ideas on how may I be able to make SiteMinder's webagent handle the HTTP request before MVC's default request handler?
<system.webServer>
<!-- SM Server Config -->
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="wa-handler" path="*" verb="*" type="" modules="IsapiModule" scriptProcessor="%NETE_WA_PATH%\ISAPI6WebAgent.dll"
resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />
</handlers>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
A: Issue Resolved: Apparently, for SiteMinder to protect ASP.NET MVC Apps, it must be upgraded to version R12.5 / WebAgent 7 or higher. Just update SiteMinder on your IIS server and it should start working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45221757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP gzipping JSON, saving to memcache... Node.js serving - proper headers? In PHP I am doing something like:
$gzdata = gzencode(json_encode($data), 9);
$mc->set("latest", $gzdata);
So I pull my associative array from the DB, I turn it to JSON, Gzip it and store to memcache
In my Node.js I read the memcached entry and serve it (where client is memcache client)
client.get('latest', function(err, response) {
if (err) { console.log("GET", err.type ); }
else{
result.writeHead(200,{
"Content-Type": "application/json",
"content-encoding":"gzip"
});
result.end(response['latest']);
}
});
I am getting
Content Encoding Error
on the page
The page you are trying to view cannot be shown because it uses an
invalid or unsupported form of compression.
I cannot even check the headers in FB... any ideas what am I doing wrong?
A: Did you know that the Memcache client can already do compression for you?
$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);
This would compress values when larger than 20k with a minimum compression of 20%.
See also: Memcache::setCompressThreshold
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13485794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to change color of a container border using radio buttons using JS? I have an issue, I need to create a settings dropdown menu when you can select different themes. The themes have to change the background color and border color, I have the background color working, however I'm struggling to make the border change color.
function changeTheme() {
if (document.getElementById("theme1").checked = true) {
document.container.style.backgroundColor = "lightgray";
document.container.style.borderColor = "red";
}
}
function bgcolor(color, border) {
document.body.style.background = color;
document.body.style.borderColor = border;
}
<div class="dropdown">
<input type="radio" id="theme1" name="theme" value="1" onclick="bgcolor('lightgray', 'red');" onchange="showFeedback('You changed the theme!')">Light<br><br>
</div>
So the container is a square in the middle of the page with a border. When I select one of the themes the background color of the whole page should change and the border color of the container in the middle should change as well.
I tried onclick="changeTheme()but it doesn't work
A: To set a border, you must specify the thickness and style.
Also, don't use inline styles or inline event handlers. Just set a pre-existing class upon the event. And instead of checking to see if the radio button is selected, just use the click event of the button. If you've clicked it, it's selected.
Lastly, if you are using a form field, but only as a UI element and not to actually submit data anywhere, you don't need the name attribute.
document.getElementById("theme1").addEventListener("click", function() {
document.body.classList.add("lightTheme");
});
.lightTheme { border:1px solid red; background-color:lightgrey; }
<div class="dropdown">
<input type="radio" id="theme1" value="1">Light<br><br>
</div>
A: As @Tyblitz remarked: your "border" needs to be set properly:
function changeTheme() {
if (document.getElementById("theme1").checked = true) {
document.container.style.backgroundColor = "lightgray";
document.container.style.borderColor = "red";
}
}
function bgcolor(color, border) {
document.body.style.background = color;
document.body.style.border = border;
}
<div class="dropdown">
<input type="radio" id="theme1"
name="theme" value="1"
onclick="bgcolor('lightgray', '6px solid red');"
onchange="console.log('You changed the theme!')">Light<br><br>
</div>
A: 2nd Edit :
(Thanks to Scott Marcus answer and Mike 'Pomax' Kamermans comment)
Here is a pen for it.
I create classes for each theme with the naming pattern : prefix "colorTheme" followed by the input value attribute's value.
function themeChange() {
/* theme class naming pattern : prefix "colorTheme"
followed by the input "value attribute" 's value */
var themeCheckedClassValue = "colorTheme" + this.value;
/* don't do anything if we click on the same input/label */
if (themeCheckedClassValue != document.body.dataset.currentThemeClass) {
document.body.classList.remove(document.body.dataset.currentThemeClass);
document.body.classList.add(themeCheckedClassValue);
/* new current theme value stored in data-current-theme-class custom
attribut of body */
document.body.dataset.currentThemeClass = themeCheckedClassValue;
}
}
document.addEventListener('DOMContentLoaded', function () {
/* querySelector and if statement only needed at DOMContentLoaded
So I did a seperate function for this event */
var themeChecked = document.querySelector('input[id^="theme"]:checked');
if (themeChecked) {
var themeCheckedClassValue = "colorTheme" + themeChecked.value;
document.body.classList.add(themeCheckedClassValue);
document.body.dataset.currentThemeClass = themeCheckedClassValue;
}
else {
/* if there is no input with the attribute "checked"
the custom attribut data-current-theme-class takes the value "null" */
document.body.dataset.currentThemeClass = null;
}
});
/* input[id^="theme] mean every input with an id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');
for (let i = 0; i < themeInputs.length; i++) {
themeInputs[i].addEventListener("click", themeChange);
}
This way you can simply add new themes by following the same naming pattern.
function themeChange() {
/* theme class naming pattern : prefix "colorTheme"
followed by the input "value attribute" 's value */
var themeCheckedClassValue = "colorTheme" + this.value;
/* don't do anything if we click on the same input/label */
if (themeCheckedClassValue != document.body.dataset.currentThemeClass) {
document.body.classList.remove(document.body.dataset.currentThemeClass);
document.body.classList.add(themeCheckedClassValue);
/* new current theme value stored in data-current-theme-class custom
attribut of body */
document.body.dataset.currentThemeClass = themeCheckedClassValue;
}
}
document.addEventListener('DOMContentLoaded', function() {
/* querySelector and if statement only needed at DOMContentLoaded
So I did a seperate function for this event */
var themeChecked = document.querySelector('input[id^="theme"]:checked');
if (themeChecked) {
var themeCheckedClassValue = "colorTheme" + themeChecked.value;
document.body.classList.add(themeCheckedClassValue);
document.body.dataset.currentThemeClass = themeCheckedClassValue;
} else {
/* if there is no input with the attribute checked
the custom attribut data-current-theme-class takes the value "null" */
document.body.dataset.currentThemeClass = null;
}
});
/* input[id^="theme] mean every input with an id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');
for (let i = 0; i < themeInputs.length; i++) {
themeInputs[i].addEventListener("click", themeChange);
}
html {
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-size: 16px;
}
*,
*::after,
*::before {
-webkit-box-sizing: inherit;
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
min-height: 100vh;
width: 100vw;
border: 10px solid;
border-color: transparent;
-webkit-transition: all .4s;
transition: all .4s;
}
ul {
list-style: none;
margin: 0;
padding: 10px;
font-size: 20px;
}
li {
padding: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
input,
label {
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
outline: none;
}
.colorTheme1 {
color: rgb(36, 36, 33);
font-weight: 400;
background-color: rgb(248, 236, 220);
border-color: rgb(60, 75, 124);
}
.colorTheme2 {
background-color: rgb(39, 34, 28);
border-color: rgb(102, 102, 153);
color: rgb(248, 236, 220);
font-weight: 700;
}
.colorTheme3 {
background-color: rgb(255, 0, 0);
border-color: rgb(0, 255, 255);
color: rgb(255, 255, 0);
font-weight: 700;
}
<body>
<ul>
<li><input type="radio" id="theme1" name="theme" value="1" checked><label for="theme1">Light</label></li>
<li>
<input type="radio" id="theme2" name="theme" value="2"><label for="theme2">Dark</label></li>
<li>
<input type="radio" id="theme3" name="theme" value="3"><label for="theme3">Flashy</label></li>
</ul>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57540103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javafx treeview cell factory with gridpane I have a TreeView<GridPane> and the GridPane contains multiple Nodes like Buttons and Labels. The amount of nodes inside the GridPane varies.
I need the cell factory to get the MouseEntered event but when I use the code below then no content gets displayed.
My current code looks like that:
treeView.setCellFactory(tv -> {
TreeCell<GridPane> cell = new TreeCell<GridPane>() {
@Override
protected void updateItem(GridPane item, boolean empty) {
super.updateItem(item, empty);
}
};
cell.setOnMouseEntered(e -> {
//TODO
});
return cell ;
});
I know that the updateItem method needs to be modified but I dont know how because the number of nodes inside the GridPane varies.
EDIT
Here are the classes.
TreeController.java:
public class TreeController {
private TreeItem<GridPane> rootItem;
private int hgap = 5;
@FXML private TreeView<GridPane> treeView;
@FXML
private void initialize() {
GridPane gp = new GridPane();
gp.add(new Label("Label1"), 0, 0);
gp.getColumnConstraints().add(0, new ColumnConstraints());
gp.getColumnConstraints().get(0).setHgrow(Priority.NEVER);
Button cond = new Button("button");
gp.add(cond, 1, 0);
gp.getColumnConstraints().add(1, new ColumnConstraints());
gp.getColumnConstraints().get(1).setHgrow(Priority.NEVER);
gp.add(new Label("Label2"), 2, 0);
gp.getColumnConstraints().add(2, new ColumnConstraints());
gp.getColumnConstraints().get(2).setHgrow(Priority.ALWAYS);
Button btnAdd = new Button("Add");
gp.add(btnAdd, 3, 0);
gp.setHgap(hgap);
rootItem = new TreeItem<GridPane>(gp);
rootItem.setExpanded(true);
treeView.setRoot(rootItem);
rootItem.getChildren().add(new TreeItem<GridPane>(createGridRow("Age", false)));
rootItem.getChildren().add(new TreeItem<GridPane>(createGridRow("Person", true)));
/*
treeView.setCellFactory(tv -> {
TreeCell<GridPane> cell = new TreeCell<GridPane>() {
@Override
protected void updateItem(GridPane item, boolean empty) {
super.updateItem(item, empty);
}
};
cell.setOnMouseEntered(e -> {
System.out.println("changed cell");
});
return cell ;
});
*/
}
private GridPane createGridRow(String selectedCol, Boolean showAddButton) {
int index = 0;
GridPane gp = new GridPane();
Button columnName = new Button(selectedCol);
gp.add(columnName, index, 0);
gp.getColumnConstraints().add(index, new ColumnConstraints());
gp.getColumnConstraints().get(index).setHgrow(Priority.NEVER);
index++;
Button condition = new Button("greater than");
gp.add(condition, index, 0);
gp.getColumnConstraints().add(index, new ColumnConstraints());
gp.getColumnConstraints().get(index).setHgrow(Priority.NEVER);
index++;
Button value = new Button("[enter value]");
gp.add(value, index, 0);
gp.getColumnConstraints().add(index, new ColumnConstraints());
gp.getColumnConstraints().get(index).setHgrow(Priority.ALWAYS);
index++;
if (showAddButton) {
Button btnAdd = new Button("Add");
gp.add(btnAdd, index, 0);
gp.getColumnConstraints().add(index, new ColumnConstraints());
gp.getColumnConstraints().get(index).setHgrow(Priority.NEVER);
index++;
}
gp.setHgap(hgap);
return gp;
}
}
MainClass.java:
public class MainClass extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Parent root;
try {
TreeController controller = new TreeController();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("TreeController.fxml"));
fxmlLoader.setController(controller);
root = fxmlLoader.load();
Scene scene = new Scene(root, 600, 500);
stage.setMinHeight(400);
stage.setMinWidth(500);
stage.setTitle("TreeController");
stage.setScene(scene);
stage.setResizable(true);
stage.show();
} catch (IOException e) {
e.printStackTrace();
};
}
@Override
public void stop() {
System.exit(0);
}
}
TreeController.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.TreeView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.161" xmlns:fx="http://javafx.com/fxml/1">
<children>
<ScrollPane fitToHeight="true" fitToWidth="true" layoutX="155.0" layoutY="111.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="20.0" AnchorPane.rightAnchor="20.0" AnchorPane.topAnchor="20.0">
<content>
<TreeView fx:id="treeView" prefHeight="200.0" prefWidth="200.0" />
</content>
</ScrollPane>
</children>
</AnchorPane>
A: This is rather simple but comprehensive example. After analysing it you should be able to implement your solution.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TreeViewCellApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
TreeItem<Employee> leaf1Item = new TreeItem<Employee>(new Employee("Anne Burnes", "Employee"));
TreeItem<Employee> leaf2Item = new TreeItem<Employee>(new Employee("Ronan Jackson", "Employee"));
TreeItem<Employee> rootItem = new TreeItem<Employee>(new Employee("Jack Shields", "Head"));
rootItem.getChildren().add(leaf1Item);
rootItem.getChildren().add(leaf2Item);
Label label = new Label();
TreeView<Employee> treeView = new TreeView<>(rootItem);
treeView.setCellFactory(param -> new TreeCell<Employee>() {
@Override
protected void updateItem(Employee employee, boolean empty) {
super.updateItem(employee, empty);
if (employee == null || empty) {
setGraphic(null);
} else {
EmployeeControl employeeControl = new EmployeeControl(employee);
employeeControl.setOnMouseClicked(mouseEvent -> label.setText(employee.getName()));
setGraphic(employeeControl);
}
}
});
VBox vBox = new VBox(label, treeView);
stage.setScene(new Scene(vBox));
stage.show();
}
}
class Employee {
private final String name;
private final String capacity;
public Employee(String name, String capacity) {
this.name = name;
this.capacity = capacity;
}
public String getName() {
return name;
}
public String getCapacity() {
return capacity;
}
}
class EmployeeControl extends HBox {
private final Label nameLabel = new Label();
private final Label capacityLabel = new Label();
{
getChildren().addAll(nameLabel, capacityLabel);
}
public EmployeeControl(Employee employee) {
nameLabel.setText(employee.getName());
capacityLabel.setText(employee.getCapacity());
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55141657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: what's the best practice in creating a service request reference number? I'll be creating a ticketing system wherein a user can post a request and then the system is suppose to return a ticket number or reference number of the request to track its status. My question is it safe to use an auto number generated from sql server table to use as the reference number returned to the user? Guessing reference numbers will not be an issue because anyone should be able to check the status of the request since no sensitive data is involved. Could there be any best practice for this or any better approach? Thank you.
A: Sure - using an INT IDENTITY is probably the easiest and safest bet.
SQL Server handles all everything for you - you just get a nice, clean number and be done with it.
If you want to, you can also combine a consecutive number (your ID) with e.g. a project or product prefix to create "case numbers" like PROJ-000005, OTHR-000006 and so forth. This can be very easily done by using a computed column in your table - something like this:
ALTER TABLE dbo.YourTable
ADD PrefixedNumber AS Prefix + '-' + RIGHT('000000' + CAST(ID AS VARCHAR(10)), 6) PERSISTED
Then your table would have an identity column ID with auto-generated numbers, some kind of a customer or project or product determined Prefix, and your computed column PrefixedNumber would contain those fancy prefixed case numbers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12120071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Encrypt passwords on Sql Server 2008 using SHA1 I have designed a Log In System using C# where the username and password is checked in SQL server 2008 before loading the main page. I wish to encrypt the stored password on the database. Is it possible to do it using C# and SHA1 algorithm?
Following is my stored procedure:
ALTER procedure [dbo].[proc_UserLogin]
@userid varchar(20),
@password nvarchar(50)
As
declare
@ReturnVal varchar(500)
SET NOCOUNT ON
if exists(select userid,password from LoginManager where userid=@userid and password=@password)
set @ReturnVal='0|Logged in Successfully'
else
set @ReturnVal='1|Login Failed/Username does not exist'
select @ReturnVal
C# Code
public void button1_Click(object sender, EventArgs e)
{
mainform = new Form1();
string[] v;
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string query = "EXEC dbo.proc_UserLogin'" + username.Text+ "', '" + password.Text+"'";
OleDbCommand cmd = new OleDbCommand(query, conn);
string s = Convert.ToString(cmd.ExecuteScalar());
v= s.Split('|');
if (v[0]=="0")
{
mainform.Show();
this.Hide();
}
else
{
MessageBox.Show("Please enter correct user credentials and try again");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
I have gone through similar questions asked by other users here, but they were not working for me. Can anyone suggest changes to the code, so that password encryption can be accomplished?
Thanks
A: Hash and salt passwords in C#
https://crackstation.net/hashing-security.htm
https://www.bentasker.co.uk/blog/security/201-why-you-should-be-asking-how-your-passwords-are-stored
As I stated in my comments, hashing passwords is something that you probably shouldn't be doing yourself.
A few things to note:
*
*SHA1 is not recommended for passwords
*Passwords should be salted
*You should use a verified userstore framework rather than attempting to create your own, as you will likely "do it wrong"
*I'm sure there are many more
That being said, to accomplish your specific question, you would want something like this:
Users
----
userId
passwordHashed
passwordHashed stores a hashed version of the user's password (the plain text password is never stored anywhere in persistence.)
for checking for valid password something like this is done:
ALTER procedure [dbo].[proc_UserLogin]
@userid varchar(20),
@password nvarchar(50)
As
declare
@ReturnVal varchar(500)
SET NOCOUNT ON
if exists(select userid,password from LoginManager where userid=@userid and password=HASHBYTES('SHA1', @password))
set @ReturnVal='0|Logged in Successfully'
else
set @ReturnVal='1|Login Failed/Username does not exist'
select @ReturnVal
For inserting/updating user passwords, you need to make sure to store the hashed password not the plain text password, as such;
INSERT INTO users(userId, passwordHashed)
VALUES (@userId, HASHBYTES('SHA1', @rawPassword)
or
UPDATE users
SET passwordHased = HASHBYTES('SHA1', @rawPassword)
WHERE userId = @userId
EDIT:
just realized you're asking how to accomplish the hash in C#, not SQL. You could perform the following (taken from Hashing with SHA1 Algorithm in C#):
public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(temp);
return Convert.ToBase64String(hash);
}
}
Your code snip could be:
conn.Open();
string query = "EXEC dbo.proc_UserLogin'" + username.Text+ "', '" + this.Hash(System.Text.Encoding.UTF8.GetBytes(password.Text))+"'";
OleDbCommand cmd = new OleDbCommand(query, conn);
You should also note that you should parameterize your parameters to your stored procedure rather than passing them in the manner you are - which it looks like you already have a separate question in regarding that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26256351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python true global variables (python 3.7.0) I know you can use the global keyword. But that's not...global. It's just a way to reference another variable outside of this function. If you have one variable that you want to reference it's no big deal I guess (although still troublesome). But what if you have lots of variables that you want to move around functions? Do I have to declare those 2 or 3 or 10 variables each and every time in each function that are of global scope? Isn't there a way to declare[1] a variable (someplace or somehow) so as to be truly global?
Ideally I would like to have one file main.py with my main code and one file common.py with all my global variables (declared/initialized[1]) and with a from common import * I would be able to use every variable declared in common.py.
I apologize if it's a duplicate. I did search around but I can't seem to find something. Maybe you could do it with classes(?), but I'm trying to avoid using them for this particular program (but if there's no other way I'll take it)
EDIT: Adding code to show the example of two files not working:
file main.py
from common import *
def func1():
x=2
print('func1', x)
def func2():
print('fuc2',x)
print('a',x)
func1()
func2()
file common.py
x=3
this prints:
a 3
func1 2
fuc2 3
but it should print:
a 3
func1 2
fuc2 2
because func2 even though it's called after func1 (where x is assigned a value) sees x as 3. Meaning that fuc1 didn't actually use the "global" variable x but a local variable x different from the "global" one. Correct me If I'm wrong
[1] I know that in python you don't really declare variables, you just initialize them but you get my point
A: Technically, every module-level variable is global, and you can mess with them from anywhere. A simple example you might not have realized is sys:
import sys
myfile = open('path/to/file.txt', 'w')
sys.stdout = myfile
sys.stdout is a global variable. Many things in various parts of the program - including parts you don't have direct access to - use it, and you'll notice that changing it here will change the behavior of the entire program. If anything, anywhere, uses print(), it will output to your file instead of standard output.
You can co-opt this behavior by simply making a common sourcefile that's accessible to your entire project:
common.py
var1 = 3
var2 = "Hello, World!"
sourcefile1.py
from . import common
print(common.var2)
# "Hello, World!"
common.newVar = [3, 6, 8]
fldr/sourcefile2.py
from .. import common
print(common.var2)
# "Hello, World!"
print(common.newVar)
# [3, 6, 8]
As you can see, you can even assign new properties that weren't there in the first place (common.newVar).
It might be better practice, however, to simply place a dict in common and store your various global values in that - pushing a new key to a dict is an easier-to-maintain operation than adding a new attribute to a module.
If you use this method, you're going to want to be wary of doing from .common import *. This locks you out of ever changing your global variables, because of namespaces - when you assign a new value, you're modifying only your local namespace.
In general, you shouldn't be doing import * for this reason, but this is particular symptom of that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60284797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to measure data stored by 1 client in a SaaS database I have a multi tenant database for my SaaS web application. I want to set a limit of 10GB data storage per Client. How do I enforce this limit in SQL Azure. I see a lot of SaaS companies putting such limits, but how to measure how much storage 1 client has consumed in the database?
Tx
A: One option to isolate the data is to have a separate schema per tenant. And you can measure the size of the schema using below script.
SET NOCOUNT ON
declare @SourceDB sysname
DECLARE @sql nvarchar (4000)
IF @SourceDB IS NULL BEGIN
SET @SourceDB = DB_NAME () -- The current DB
END
CREATE TABLE #Tables ( [schema] sysname
, TabName sysname )
SELECT @sql = 'insert #tables ([schema], [TabName])
select TABLE_SCHEMA, TABLE_NAME
from ['+ @SourceDB +'].INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = ''BASE TABLE'''
EXEC (@sql)
---------------------------------------------------------------
-- #TabSpaceTxt Holds the results of sp_spaceused.
-- It Doesn't have Schema Info!
CREATE TABLE #TabSpaceTxt (
TabName sysname
, [Rows] varchar (11)
, Reserved varchar (18)
, Data varchar (18)
, Index_Size varchar ( 18 )
, Unused varchar ( 18 )
)
---------------------------------------------------------------
-- The result table, with numeric results and Schema name.
CREATE TABLE #TabSpace ( [Schema] sysname
, TabName sysname
, [Rows] bigint
, ReservedMB numeric(18,3)
, DataMB numeric(18,3)
, Index_SizeMB numeric(18,3)
, UnusedMB numeric(18,3)
)
DECLARE @Tab sysname -- table name
, @Sch sysname -- owner,schema
DECLARE TableCursor CURSOR FOR
SELECT [SCHEMA], TabNAME
FROM #tables
OPEN TableCursor;
FETCH TableCursor into @Sch, @Tab;
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @sql = 'exec [' + @SourceDB
+ ']..sp_executesql N''insert #TabSpaceTxt exec sp_spaceused '
+ '''''[' + @Sch + '].[' + @Tab + ']' + '''''''';
Delete from #TabSpaceTxt; -- Stores 1 result at a time
EXEC (@sql);
INSERT INTO #TabSpace
SELECT @Sch
, [TabName]
, convert(bigint, rows)
, convert(numeric(18,3), convert(numeric(18,3),
left(reserved, len(reserved)-3)) / 1024.0)
ReservedMB
, convert(numeric(18,3), convert(numeric(18,3),
left(data, len(data)-3)) / 1024.0) DataMB
, convert(numeric(18,3), convert(numeric(18,3),
left(index_size, len(index_size)-3)) / 1024.0)
Index_SizeMB
, convert(numeric(18,3), convert(numeric(18,3),
left(unused, len([Unused])-3)) / 1024.0)
[UnusedMB]
FROM #TabSpaceTxt;
FETCH TableCursor into @Sch, @Tab;
END;
CLOSE TableCursor;
DEALLOCATE TableCursor;
select [SCHEMA],SUM(ReservedMB)SizeInMB from #TabSpace
group by [SCHEMA]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47206555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Php checkboxes - what's missing ? i try to update ban and remove of user.
<tr>
<td>{$user4.username}</td>
<td>{$user4.email}</td>
<td>{$user4.name} {$user4.surname}</td>
{if $user4.banned}
<td><center><input type="checkbox" name="banCheckNoBan" checked value="{$user4.id}"</center></td>
{else}
<td><center><input type="checkbox" name="banCheckBan" value={$user4.id}</center></td>
{/if}
{if $user4.status}
<td><center><input type="checkbox" name="removeCheck"</center></td>
{else}
<td><center><input type="checkbox" name="removeCheck" checked></center></td>
{/if}
</tr>
As you see above, if user is banned, checkbox is checked, remove is same.
however,
This is in my php side,
I do this, but it does not update why
if(isset($_POST['updateBanRemove'])){
if(isset($_POST['banCheckBan']))
NCore::db('USER')->updateAsArray(array('BANNED' => 1))->eq('ID', $_POST['banCheckNoBan'])->execute();
elseif(isset($_POST['banCheckNoBan']))
NCore::db('USER')->updateAsArray(array('BANNED' => 0))->eq('ID', $_POST['banCheckNoBan'])->execute();
}
A: if(isset($_POST['banCheckBan']))
NCore::db('USER')->updateAsArray(array('BANNED' => 1))->eq('ID', $_POST['banCheckNoBan'])->execute();
You are using $_POST['banCheckNoBan'] instead of $_POST['banCheckBan'] in your query.
A: I see two problems:
*
*you have a syntax errors - you dont close the <input> tag with >!
*you should add value="something" attribute to the <input type="checkbox"> tag.
A: This bit:
{if $user4.banned}
<td><center><input type="checkbox" name="banCheckNoBan" checked value="{$user4.id}"</center></td>
{else}
<td><center><input type="checkbox" name="banCheckBan" value={$user4.id}</center></td>
{/if}
Should be:
{if $user4.banned}
<td><center><input type="checkbox" name="banCheckNoBan" checked value="{$user4.id}" /></center></td>
{else}
<td><center><input type="checkbox" name="banCheckBan" value="{$user4.id}" /></center></td>
{/if}
Notice that the input tag needs to close: />. You just went straight into </center>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9954583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Finding the input Tensors of a Tensorflow Operation I am trying to generate some kind of textual representation for the TensorFlow Computational Graph. I know that Tensorboard can provide me with the visualization. However, I need some kind of representation (adjacency matrix or adjacency list) from where I can parse information associated with graphs.
So far, I have tried the following:
import tensorflow as tf
a = tf.constant(1.3, name = const_a)
b = tf.constant(3.1, name = const_b)
c = tf.add(a,b, name = 'addition')
d = tf.multiply(c,a, name = 'multiplication')
e = tf.add(d,c, name = 'addition_1')
with tf.Session() as sess:
print(sess.run([c,d,e]))
After this, I decided to keep the graph object in a separate variable and tried to parse information from there:
graph = tf.get_default_graph()
I found out how to get the list of all operations from this documentation.
for op in graph.get_operations():
print(op.values())
This part actually provides me with the information of the nodes of the computation graph.
(<tf.Tensor 'const_a:0' shape=() dtype=float32>,)
(<tf.Tensor 'const_b:0' shape=() dtype=float32>,)
(<tf.Tensor 'addition:0' shape=() dtype=float32>,)
(<tf.Tensor 'multiplication:0' shape=() dtype=float32>,)
(<tf.Tensor 'addition_1:0' shape=() dtype=float32>,)
However, I cannot seem to find any method that can provide me with information regarding the edges of the computation graph. I cannot find any method that can give me the input tensors associated with each operation. I would like to know that the operation named addition_1 has input tensors produced by the operations addition and multiplication; or something that can be used to derive this information. From the documentation, it seems that the Operation object has a property named inputs which may be the thing I am looking for. Nonetheless, I don't see a method that can be called to return this property.
A: From your code I think you are using tensorflow v<2. So, not sure if this will solve your problem but I can create adj.list and adj.mat format using v2.2.0
split is used to parse name, following this answer
Adjacency matrix generation,
# adjacency matrix
# if operation input is node1 and output is node2, then mat[node1][node2] = 1
graph_adj_mat = []
# name to number mapping to set 1/0 from the node name tensorflow gives
graph_node_name_to_num_map = {}
# node number to name map will be needed later to understand matrix
# as tensorflow identify node using name
graph_node_num_to_name_map = {}
# usage of compat module to use Session in v2.2.0
# if v < 2 use tf.Session() as sess
with tf.compat.v1.Session() as sess:
# initiating the matrix and necessary map
for op in sess.graph.get_operations():
graph_node_num_to_name_map[len(graph_adj_mat)] = op.name
graph_node_name_to_num_map[op.name] = len(graph_adj_mat)
graph_adj_mat.append([0]*len(sess.graph.get_operations()))
# parsing the name and setting adj. mat
# edge direction input tensor to output tensor
for op in sess.graph.get_operations():
dst_node_name = op.name.split(':')[0]
for in_tensor in op.inputs:
src_node_name = in_tensor.name.split(':')[0]
graph_adj_mat[graph_node_name_to_num_map[src_node_name]][graph_node_name_to_num_map[dst_node_name]] = 1
print(graph_adj_mat)
print(graph_node_num_to_name_map)
Adjacency list generation (using dict),
# adjacency list is dictionary of tensor name,
# each input tensor name key holds output tensor name containing list
graph_adj_list = {}
with tf.compat.v1.Session() as sess:
for op in sess.graph.get_operations():
graph_adj_list[op.name] = []
for op in sess.graph.get_operations():
dst_node_name = op.name.split(':')[0]
for in_tensor in op.inputs:
src_node_name = in_tensor.name.split(':')[0]
graph_adj_list[src_node_name].append(dst_node_name)
# graph_adj_list[in_tensor_name] contains list containing tensor names which are produced using in_tensor_name
print(graph_adj_list)
Output tested with modified version of given code,
import tensorflow as tf
print(tf.__version__)
tf.compat.v1.disable_eager_execution()
tf.compat.v1.reset_default_graph()
a = tf.constant(1.3, name = 'const_a')
b = tf.constant(3.1, name = 'const_b')
c = tf.add(a,b, name = 'addition')
d = tf.multiply(c,a, name = 'multiplication')
e = tf.add(d,c, name = 'addition_1')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58527671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to deal with sharing deep-linked sites URLs? I made a site which can be browsed both as non-deep linked version for non-javascript users (somesite.com?state) and a deep-link version for javascript-enabled users (somesite.com#state). Note: both of these versions give the same content except in one version, the content is populated by PHP, and in other by javascript.
It works perfectly however when a javascript-enabled user browses the site and wants to share a link on Facebook such as (somesite.com#someotherstate), the Facebook can't parse the proper content of the page since it can't deal with hash parameters for deep-linking.
So, other then putting a separate "Share" button on the page which will give explicitly a non-deep linked version of the URL (somesite.com?someotherstate) for the user to copy and share on Facebook, how does the industry go about with this issue?
UPDATE
I noticed that Facebook implemented Google Ajax methodology. Can't find official statement though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4845417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server - create timeout exception in function I have a table-valued function.
Now, I need to do a test when this function (SELECT query) returns Timeout exception.
When I'm doing the test the functions works fine for me, so I was wondering if I can force Timeout exception in order to do a test.
If it can't be done within a function, can it be done at all?
A: Try this. You can pass whatever value you want and it'll loop through until it reaches 0. Too high of a number throws an arithmetic error.
Function:
CREATE FUNCTION dbo.timeoutFunction(@P1 int)
RETURNS @table TABLE
(
Id int
)
AS
BEGIN
WHILE @P1 > 0
BEGIN
SET @P1 -= 1
INSERT INTO @table
SELECT @P1
END
RETURN
END
Call:
SELECT * FROM timeoutfunction(1000000)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50008425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add Multiple Databases in VB.NET Is it possible to connect multiple databases to a program?
I added a database, but it was always through the "Data Source Config Wizard". My application deals with one main database, but I need to load information from other databases and add it to the main one (the user will select which database through the OpenFileDialog).
Public Class Form1
Private Sub TblTestBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblTestBindingNavigatorSaveItem.Click
Me.Validate()
Me.TblTestBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TestdbDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestdbDataSet.tblTest' table. You can move, or remove it, as needed.
Me.TblTestTableAdapter.Fill(Me.TestdbDataSet.tblTest)
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim DBConnection As New OleDb.OleDbConnection
'''' Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;"
'Dim dbSource As String = opnFile.ShowDialog()
opnFile.ShowDialog()
Dim ex As String = opnFile.FileName
MessageBox.Show(ex)
Dim dbSource As String = "DataSource=" & ex
MessageBox.Show(dbSource, "Data Source String", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Dim DBDataSet As New DataSet
'''' Dim ds As New DataSet
Dim DBDataAdapter As OleDb.OleDbDataAdapter
'''' Dim da As OleDb.OleDbDataAdapter
DBConnection.ConnectionString = dbProvider & dbSource
'DBDataAdapter = (sql, DBConnection)
End Sub
End Class
Also, can someone explain to me the link in DataAdapter, DataConnection, and the DataSet? From what I see, the DataConnection is just the link that will connect the application to the database. The DataSet is your actual data from the database. So what is the DataAdapter for?
Thanks for any help!
A: You can add several databases using the Database wizard. You will be missing the binding navigator but you can get this easily by creating a temporary form in your project add the database to this then just copy over the binding navigator before deleting the temp form.
A: See this thread Display data from access using dataset The use the following.
Try something like this after you load your table into a Dataset
For Each row1 In (From dr As DataRow In yourDataSet.Tables(0).Rows Select dr Where dr("Column_Name").ToString.StartsWith(yourstring)
somestring = row1("Column_Name").ToString
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30508455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you set up .vimrc How do you set up a .vimrc file on Ubuntu?
This is not helping: http://vim.wikia.com/wiki/Open_vimrc_file
*
*Where do you create it?
*Whats the format inside?
I know the stuff I want to put in it, just don't know how.
A: .vimrc should be in your home directory. .vimrc is there to make more interactive according to your need. Here is an example of .vimrc
filetype indent on
set ai
set mouse=a
set incsearch
set confirm
set number
set ignorecase
set smartcase
set wildmenu
set wildmode=list:longest,full
A: Where:
On UN*X systems your .vimrc belongs in your home directory. At a terminal, type:
cd $HOME
vim .vimrc
This will change to your home directory and open .vimrc using vim. In vim, add the commands that you know you want to put in, then type :wq to save the file.
Now open vim again. Once in vim you can just type: :scriptnames to print a list of scripts that have been sourced. The full path to your .vimrc should be in that list. As an additional check that your commands have been executed, you can:
*
*add an echo "MY VIMRC LOADED" command to the .vimrc, and when you run vim again, you should see MY VIMRC LOADED printed in the terminal. Remove the echo command once you've verified that your.vimrc is loading.
*set a variable in your .vimrc that you can echo once vim is loaded. In the .vimrc add a line like let myvar="MY VIMRC LOADED". Then once you've opened vim type echo myvar in the command line. You should see your message.
The Format:
The format of your .vimrc is that it contains Ex commands: anything that you might type in the vim command-line following :, but in your .vimrc, leave off the :.
You've mentioned :set ruler: a .vimrc with only this command looks like:
set ruler
Search for example vimrc and look over the results. This link is a good starting point.
A: The ".vimrc"(vim resource configuration) file provides initialization settings that configure Vim every time it starts. This file can be found in "$HOME/.vimrc" for linux/OSX and "$HOME/_vimrc" for Window users. Inside Vim, type ":echo $HOME" to see the value of $HOME for your system
For example, we can do following settings in your .vimrc file.
set hlsearch: Enable search highlighting
set ignorecase: Ignore case when searching
set incsearch: Incremental search that shows partial matches.
A: Open vim ~/.vimrc using vim ~/.vimrc, put this in it:
set paste
set nonumber
set hlsearch
Save the file and quit using :wq. Changes in this .vimrc will be used when reopening your Vim editor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11567176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Can't install pgadmin4 repository does not have file I was use command
sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
But I was got this
Err:2 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/n/a pgadmin4 Release
404 Not Found [IP: 87.238.57.227 443]
Hit:3 https://community-packages.deepin.com/printer eagle InRelease
Hit:4 https://home-store-img.uniontech.com/appstore deepin InRelease
Reading package lists... Done
E: The repository 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/n/a pgadmin4 Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
So I can't install pgadmin
Use Deepin linux 20.2.3
A: # apt-get install curl ca-certificates gnupg
# curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
#vim /etc/apt/sources.list.d/pgdg.list
####### ADD
#deb http://apt.postgresql.org/pub/repos/apt/ buster-pgdg main
# apt-get update
# apt-get install pgadmin4 pgadmin4-apache2
It should now be successfully installed.
A: The problem is that lsb_release -cs is not returning the codename for Deepin linux, instead is returning n/a.
Try with that dpkg --status tzdata|grep Provides|cut -f2 -d'-' to retrive the codename.
If you want a oneliner like the one you posted, here you have:
sudo sh -c 'curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add && echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(dpkg --status tzdata|grep Provides|cut -f2 -d'-') pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
A: I am using Linux mint, issue has been fixed using the below command.
$ sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add
$ sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/focal pgadmin4 main" \
> /etc/apt/sources.list.d/pgadmin4.list && apt update'
$ sudo apt update
And then, if you want desktop
$ sudo apt install pgadmin4-desktop
OR the web version:
$ sudo apt install pgadmin4-web
$ sudo /usr/pgadmin4/bin/setup-web.sh
A: For Ubuntu 22.10 and other versions that complain about apt-key being deprecated, use this:
curl -fsS https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo gpg --dearmor -o /usr/share/keyrings/packages-pgadmin-org.gpg
sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/jammy pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
Note that "jammy" is being used here in the ftp link. You may browse through the other versions and pick the one that matches your Ubuntu installation's version
sudo apt install pgadmin4
This installs both web and desktop versions.
A: I experienced this error trying to upgrade my pgadmin4 to version 6. There was a problem with the certificates on my system I think, the solution was updating ca-certificates, if it's not installed you should probably install it, but that may be very unlikely that it's not installed though as it should already be there, but either way just run the command:
sudo apt install ca-certificates
A: I had the same problem with Debian 11, however exploring options I found this answer enter link description here and fixed the problem by installing lsb-release
A: I am facing those errors after running this command. sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' What I have to do now?
Ign:14 http://apt.postgresql.org/pub/repos/apt vera-pgdg InRelease
Err:16 http://apt.postgresql.org/pub/repos/apt vera-pgdg Release
404 Not Found [IP: 217.196.149.55 80]
Ign:17 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 InRelease
Get:18 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Err:19 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 Release
404 Not Found [IP: 87.238.57.227 443]
Get:20 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [107 kB]
Hit:15 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Reading package lists... Done
W: https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/Release.gpg: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
E: The repository 'http://apt.postgresql.org/pub/repos/apt vera-pgdg Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: https://packagecloud.io/slacktechnologies/slack/debian/dists/jessie/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69185413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Unable to read .txt file which stored on local storage I am trying to read file.txt file which stored on my SD Card but am unable read it on my app. I provided
"android.permission.READ_EXTERNAL_STORAGE"
permissions on manifest. Not sure where it went wrong. Please see my code below what i tried.
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44692166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RoR: How to show a due day instead of due date? My application contains mobile views with Gmail style divs. Each div has a subject, name and due date.
The Due date column is a normal datetime value.
What I am looking to do is to have the first entries in the view show up as days for the last 6 days and then the rest show as datetime.
For example:
Mon
Tues
Wed
Wed
Thurs
Fri
2016/11/04
2016/11/03
.....
etc.
How can this be best achieved? I don't think I need to post code for this question but I will if required.
Thanks!
EDIT
Not working...
In view...
<font size="1"><strong>Due:</strong> <%= homework.formatted_date(due) %></font>  
In ApplicationController...(not sure if I have syntax correct...)
helper_method :formatted_date
def formatted_date(due)
if (Date.today - due).abs < 6
due.strftime('%A')
else
due.strftime('%Y/%m/%d')
end
end
The view loads but the dates show same as before...
A: make a helper for your view... put it in ApplicationController
helper_method :formatted_date
def formatted_date(item_date)
if (Date.today - item_date).abs < 6
item_date.strftime('%A')
else
item_date.strftime('%Y/%m/%d')
end
end
Then in your view, instead of showing the object_date field show formatted_date(object_date)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40427690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: authorization error azure container services I'm new to DevOps. Any help on this error is highly appreciated.
When I try to create and deploy DevOps project on Azure I'm receiving the following error.
I'm following steps in this link.
https://learn.microsoft.com/en-us/azure/devops-project/azure-devops-project-aks
{
"code": "DeploymentFailed",
"message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.",
"details": [
{
"code": "Conflict",
"message": {
"status": "Failed",
"error": {
"code": "ResourceDeploymentFailure",
"message": "The resource operation completed with terminal provisioning state 'Failed'.",
"details": [
{
"code": "DeploymentFailed",
"message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.",
"details": [
{
"code": "BadRequest",
"message": {
"code": "InvalidRequestValue",
"message": "Failed to create the project 'xxxxxxx'. More details: 'Configuration failed at step: 'Configuring release pipeline'. More details: Failed to acquire authorization token. Details: [AADSTS70002: Error validating credentials. AADSTS50012: Invalid client secret is provided.Trace ID: 5cebc087-cb41-4b95-bc72-3c55cf250400 Correlation ID: 2a51cf8c-c8b1-420d-84a2-e50ca8193044 Timestamp: 2018-08-01 09:07:39Z]. ResponseCode: Unauthorized.'.",
"target": "ProcessCompletedJob"
}
}
]
}
]
}
}
}
]
}
A: As the error message says, AADSTS50012 indicates that an invalid client secret was provided. Check if your current key is expired in the Azure Portal and try generating a new one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51630354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do I need to make an entirely new site if I want to use jquery mobile? I would like to make a mobile version of my website and I came across jquery mobile. I was looking at examples online, I have only seen these websites make a copy of the website and put it on a subdomain or a in a /mobile/ directory on the server. I would like to keep only one form of my site so that I do not need to maintain two different sites. I have a mobile detecting script from http://www.detectmobilebrowsers.com which can detect the mobile site, but I just want to avoid making two sites. Is that possible to only have one site that can double as a mobile and desktop site? Thanks, I appreciate the help!
A: Use Bootstrap 3 which can do exactly what you wish using its css media queries.
Alternatively you can simpy write your own CSS to be responsive using media queries.
A: As mccainz mentioned, you have several options. All of those examples are under an umberalla term called "responsive design".
According to Wikipedia, "Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from mobile phones to desktop computer monitors)".
Now, there are many options when it comes to responsive design. Either use ready-made libraries or create it yourself.
Check the links below and see when resizing the browser how the layout changes so that you get an optimal view experience.
*
*Bootstrap
*Skeleton
*Foundation
*HTML Kickstart
All of them share the same idea: Use the great and holy CSS to decouple the layout from the real code, so that people like you who want to have the same codebase and different view experience do not have to re-write the code. Beauty of the CSS lies here.
Also, if you think above libraries do not do what you want write your own responsive CSS. For that, I highly recommend to check the following two books:
*
*HTML & CSS by John ducket
*The Modern Web: Multi-Device Web Development with HTML5, CSS3, and JavaScript by Peter Gasston
UPDATE: Since you commented that you want to avoid Responsive Layouts, There are a few people who think that responsive layout does not work and then use adaptive approaches.Check this out Why responsive layout does not worth it. The author explains a few minimal optimziation points and believes that Responsive layouts are overkill in many circumstances. He offers techniques such as lazy loading (under section 4).
Other resource: Alternatives to responsive design: part 1 (mobile) discusses the issues again with responsive layout.
With adaptive approaches, it is you who decide what is a good experience on devices and you sort of do some part of optimziation with pre-coded layouts for each case, but generally there are no rule of thumbs for that. Just the books comes to my mind.
Also try liquid layouts as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20401547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Datatable data binding using knockoutjs I want to render data into table using datatable knockoutjs binding.
I am using the below link and code for rendering data into table. http://datatables.net/dev/knockout/
The only change I did in above example is while rendering age data I have added input box in age col for ever record and Updatebutton at the bottom of table, so that user can change his age and click of update button data should be updated automatically and in next page it should reflect in table.
The issue am facing is that i am unable to update local js "people" model and hence unable to bind updated data using knockoutjs.
ko.observableArray.fn.subscribeArrayChanged = function(addCallback, deleteCallback) {
var previousValue = undefined;
this.subscribe(function(_previousValue) {
previousValue = _previousValue.slice(0);
}, undefined, 'beforeChange');
this.subscribe(function(latestValue) {
var editScript = ko.utils.compareArrays(previousValue, latestValue);
for (var i = 0, j = editScript.length; i < j; i++) {
switch (editScript[i].status) {
case "retained":
break;
case "deleted":
if (deleteCallback)
deleteCallback(editScript[i].value);
break;
case "added":
if (addCallback)
addCallback(editScript[i].value);
break;
}
}
previousValue = undefined;
});
};`
`var data = [
{ id: 0, first: "Allan", last: "Jardine", age: 86 },
{ id: 1, first: "Bob", last: "Smith", age: 54 },
{ id: 2, first: "Jimmy", last: "Jones", age: 32 }
]; `
`var Person = function(data, dt) {
this.id = data.id;
this.first = ko.observable(data.first);
this.last = ko.observable(data.last);
this.age = ko.observable(data.age);
// Subscribe a listener to the observable properties for the table
// and invalidate the DataTables row when they change so it will redraw
var that = this;
$.each( [ 'first', 'last', 'age' ], function (i, prop) {
that[ prop ].subscribe( function (val) {
// Find the row in the DataTable and invalidate it, which will
// cause DataTables to re-read the data
var rowIdx = dt.column( 0 ).data().indexOf( that.id );
dt.row( rowIdx ).invalidate();
} );
} );
};
$(document).ready(function() {
var people = ko.mapping.fromJS( [] );
//loadData();
var dt = $('#example').DataTable( {
"bPaginate": false,
"bInfo" : false,
"bAutoWidth" : false,
"sDom" : 't',
"columns": [
{ "data": 'id' },
{ "data": 'first' },
{ "data": 'age',
"mRender": function (data, type, row ) {
var html = '<div style="display:inline-flex">' +
'<input type="text" class="headerStyle h5Style" id="ageId" value="'+data()+'"/>' +
'</div>';
return html;
}
}
]
} );
// Update the table when the `people` array has items added or removed
people.subscribeArrayChanged(
function ( addedItem ) {
dt.row.add( addedItem ).draw();
},
function ( deletedItem ) {
var rowIdx = dt.column( 0 ).data().indexOf( deletedItem.id );
dt.row( rowIdx ).remove().draw();
}
);
// Convert the data set into observable objects, and will also add the
// initial data to the table
ko.mapping.fromJS(
data,
{
key: function(data) {
var d = data;
return ko.utils.unwrapObservable(d.id);
},
create: function(options) {
return new Person(options.data, dt);
}
},
people
);
} );
A: This is the way to do it... I have made a jsfiddle showing this:
Edit: Recently worked out a way to get this binding using vanilla knockout. I've tested this out on the latest version of knockout (3.4) Just use this binding and knockout datatables works!
ko.bindingHandlers.dataTablesForEach = {
page: 0,
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
valueAccessor().data.subscribe(function (changes) {
var table = $(element).closest('table').DataTable();
ko.bindingHandlers.dataTablesForEach.page = table.page();
table.destroy();
}, null, 'arrayChange');
var nodes = Array.prototype.slice.call(element.childNodes, 0);
ko.utils.arrayForEach(nodes, function (node) {
if (node && node.nodeType !== 1) {
node.parentNode.removeChild(node);
}
});
return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = ko.unwrap(valueAccessor()),
key = 'DataTablesForEach_Initialized';
ko.unwrap(options.data); // !!!!! Need to set dependency
ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
(function() {
console.log(options);
var table = $(element).closest('table').DataTable(options.dataTableOptions);
if (options.dataTableOptions.paging) {
if (table.page.info().pages - ko.bindingHandlers.dataTablesForEach.page == 0)
table.page(--ko.bindingHandlers.dataTablesForEach.page).draw(false);
else
table.page(ko.bindingHandlers.dataTablesForEach.page).draw(false);
}
})();
if (!ko.utils.domData.get(element, key) && (options.data || options.length))
ko.utils.domData.set(element, key, true);
return { controlsDescendantBindings: true };
}
};
JSFiddle
A: I made a fiddle with a solution
http://jsfiddle.net/Jarga/hg45z9rL/
Clicking "Update" will display the current knockout model as text below the button.
What was missing was the linking the change of the textbox to the observable by adding a listener in the render function. Also each row's textbox was being given the same id, which is not a good idea either. (Note: the event aliases are just to prevent collision with other handlers)
Changing the render function to build useful ids and adding the following should work:
$('#' + id).off('change.grid')
$('#' + id).on('change.grid', function() {
row.age($(this).val());
});
Ideally Knockout would handle this for you but since you are not calling applyBindings nor creating the data-bind attributes for the html elements all that knockout really gives you here is the observable pattern.
Edit: Additional Solution
Looking into it a little bit more you can let Knockout handle the rendering by adding the data-bindattribute into the template and binding your knockout model to the table element.
var html = '<div style="display:inline-flex">' +
'<input type="text" class="headerStyle h5Style" id="' + id + '" data-bind="value: $data[' + cell.row + '].age"/>'
And
ko.applyBindings(people, document.getElementById("example"));
This removes the whole custom subscription call when constructing the Personobject as well.
Here is another fiddle with the 2nd solution:
http://jsfiddle.net/Jarga/a1gedjaa/
I feel like this simplifies the solution. However, i do not know how efficient it performs nor have i tested it with paging so additional work may need to be done. With this method the mRender function is never re-executed and the DOM manipulation for the input is done entirely with knockout.
A: Here is a simple workaround that re-binds the data in knockout and then destroys/recreates the datatable:
// Here's my data model
var ViewModel = function() {
this.rows = ko.observable(null);
this.datatableinstance = null;
this.initArray = function() {
var rowsource1 = [
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
];
this.redraw(rowsource1);
}
this.swapArray = function() {
var rowsource2 = [
{ "firstName" : "James",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Alice",
"lastName" : "Smith",
"age" : 32 },
{ "firstName" : "Doug",
"lastName" : "Murphy",
"age" : 40 }
];
this.redraw(rowsource2);
}
this.redraw = function(rowsource) {
this.rows(rowsource);
var options = { paging: false, "order": [[0, "desc"]], "searching":true };
var datatablescontainer = $('#datatablescontainer');
var html = $('#datatableshidden').html();
//Destroy datatable
if (this.datatableinstance) {
this.datatableinstance.destroy();
datatablescontainer.empty();
}
//Recreate datatable
datatablescontainer.html(html);
this.datatableinstance = datatablescontainer.find('table.datatable').DataTable(options);
}
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
https://jsfiddle.net/benjblack/xty5y9ng/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27707378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Test if value of double is less than maximum value of an int Assume that d is a double variable. Write an if statement that assigns d to the int variable i if the value in d is not larger than the maximum value for an int.
The method below is my attempt at this problem:
public static void assignInt(double d)
{
int i = 0;
if(d < Integer.MAX_VALUE)
i = (int)d;
System.out.print(i);
}
Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold? With this assumption in mind, I attempt to call assingDoubleToInt() three times:
public static void main(String[] args)
{
assignDoubleToInt(2147483646); //One less than the maximum value an int can hold
assignDoubleToInt(2147483647); //The maximum value an int can hold
assignDoubleToInt(2147483648);//One greater than the maximum value an int can hold. Causes error and does not run.
}
The first two calls output:
2147483646
0
And the third call, assignDoubleToInt(2147483648);, throws "The literal 2147483648 of type int is out of range." Isn't the comparison 2147483648 < 2147483647 here? Why is i being assigned the value if the comparison should evaluate to false?
Using the comparison d < Integer.MAX_VALUE is not the proper way to do this. How can I test whether a double variable can fit in an int variable?
A: The int range issue is because you have an int literal. Use a double literal by postfixing 'd':
public static void main(String[] args) {
assignDoubleToInt(2147483646); // One less than the maximum value an int can hold
assignDoubleToInt(2147483647); // The maximum value an int can hold
assignDoubleToInt(2147483648d);// One greater than the maximum value an int can hold. Causes error and does not
// run.
}
I believe your equality test should be <=, also: "if the value in d is not larger than the maximum value for an int" - so if it is EQUAL to the maximum value for an int, it's valid:
public static void assignDoubleToInt(double d) {
int i = 0;
if (d <= Integer.MAX_VALUE)
i = (int) d;
System.out.println(i);
}
A:
Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold?
Yes.
throws "The literal 2147483648 of type int is out of range."
You can't create an int literal representing a number outside of the int range, so 2147483647 is legal but 2147483648 is not. If you want a larger integer literal, use a long literal, with the letter L appended: 2147483648L, or a double literal with a decimal point (or D appended): 2147483648.0 (or 2147483648D).
is not the proper way to do this.
The comparison d < Integer.MAX_VALUE is legal and correct, because Integer.MAX_VALUE will be widened to a double for the comparison, and a double can be (much) larger in value than Integer.MAX_VALUE. You just need to make sure you can pass the proper value in as detailed above.
(As noted in a comment above, it should be d <= Integer.MAX_VALUE, with <=.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55347233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: randomBytes vs pseudoRandomBytes In what situations is it acceptable (from a security standpoint) to use node's crypto.pseudoRandomBytes instead of the cryptographically-strong crypto.randomBytes?
I assume pseudoRandomBytes performs better at the expense of being more predictable (incorrect), but the docs don't really have much to say about how less-strong it is.
Specifically, I'm wondering if I'm ok using pseudoRandomBytes to generate a CSRF token.
A: As it turns out, with the default OpenSSL (which is bundled with node, but if you've built your own, it is possible to configure different engines), the algorithm to generate random data is exactly the same for both randomBytes (RAND_bytes) and pseudoRandomBytes (RAND_pseudo_bytes).
The one and only difference between the two calls depends on the version of node you're using:
*
*In node v0.12 and prior, randomBytes returns an error if the entropy pool has not yet been seeded with enough data. pseudoRandomBytes will always return bytes, even if the entropy pool has not been properly seeded.
*In node v4 and later, randomBytes does not return until the entropy pool has enough data. This should take only a few milliseconds (unless the system has just booted).
Once the the entropy pool has been seeded with enough data, it will never "run out," so there is absolutely no effective difference between randomBytes and pseudoRandomBytes once the entropy pool is full.
Because the exact same algorithm is used to generate randrom data, there is no difference in performance between the two calls (one-time entropy pool seeding notwithstanding).
A: Just a clarification, both have the same performance:
var crypto = require ("crypto")
var speedy = require ("speedy");
speedy.run ({
randomBytes: function (cb){
crypto.randomBytes (256, cb);
},
pseudoRandomBytes: function (cb){
crypto.pseudoRandomBytes (256, cb);
}
});
/*
File: t.js
Node v0.10.25
V8 v3.14.5.9
Speedy v0.1.1
Tests: 2
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per test: ~3000ms (3s 0ms)
Total time: ~6000ms (6s 0ms)
Higher is better (ops/sec)
randomBytes
58,836 ± 0.4%
pseudoRandomBytes
58,533 ± 0.8%
Elapsed time: 6318ms (6s 318ms)
*/
A: If it's anything like the standard PRNG implementations in other languages, it is probably either not seeded by default or it is seeded by a simple value, like a timestamp. Regardless, the seed is possibly very easily guessable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18130254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: browser waiting for server indefinitely I have an issue with a long-running page. ASP.NET page takes about 20 minutes to get generated and served to the browser.
Server successfully completes the response (according to logs and ASP.NET web trace) and I assume sends it to the browser. However, browser never recieves the page. It (IE8 & Firefox 3 both) keeps spinning and spinning (I've let it run for several hours, nothing happens).
This issue only appears on the shared host server. When I run the same app on dev machine or internal server, everything works fine.
I've tried fiddler and packet sniffing and it looks like server doesn't send anything back. It doesn't even send keep-alive packets. Yet both browsers I've tried don't time out after pre-defined timeout period (1 hour in IE I believe, not sure what it is in Firefox).
The last packet server sends back is ACK to the POST from the browser.
I've tried this from different client machines, to ensure it's not a broken configuration on my machine.
How can I futher diagnose this problem? Why doesn't browser time-out, even though there're no keep-alive packets?
p.s. server is Windows 2003, so IIS6. It used to work fine on shared hosting, but they've changed something (when they moved to new location) and it broke. Trying to figure out what.
p.p.s. I know I can change page design to avoid page taking this long to get served. I will do this, but I would also like to find the cause of this problem. I'd like to stay focused on this issue and avoid possible alternative designs for the page (using AJAX or whatever else).
A: Check the server's connection timeout (on the Web Site properties page).
A better approach would be to send the request, start the calculation on the server, and serve a page with a Javascript timer that keeps sending requests to itself. Upon post-back, this page checks whether the server process has completed. While the process is still running, it responds with another timer. Once it has completed, it redirects to the results.
A: Would you clarify how you fixed this problem? It seems I have the same one. I'm getting .docx report and both browsers (IE10 and Fx37) indefinitely wait for a response (keep on spinning).
But it works great in VS2012's IIS Express and on my localhost IIS7.
Although server has IIS6.1
And when it works on localhost, it's just several minutes to get a report.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/671393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to concatenate columns without null value in sql This question is asked many time here but i am not getting the proper output as i am expecting:
I have a table in which i need to concatenate columns but i don't want NULL value in it. I want it in sql server 2008 concate function does not work in 2008.
Example:
OrderTable
Customer_Number order1 order2 order3 order4
1 NULL X Y NULL
2 NULL A B NULL
3 V NULL H NULL
Now want i want is the data in concatenated manner for order only like this:
Customer_Number Order
1 X,Y
2 A,B
3 V,H
This is the code i used
Select Customer_number, ISNULL(NULLIF(order1,' ')+',','')+
ISNULL(NULLIF(order2,' ')+',','')+
ISNULL(NULLIF(order3,' ')+',','')+
ISNULL(NULLIF(order4,' ')+',','')
as Order from Ordertable
I got the below output
Customer_Number Order
1 NULL,X,Y,NULL
2 NULL,A,B,NULL
3 V,NULL,H,NULL
I already try Coalesce, Stuff, ISNULL, NULLIF but all have same result
Thanks in advance !!!
A: Another variation, for fun and profit, demonstrating the FOR XML trick to concatenate values pre-SQL Server 2012.
SELECT Customer_Number, STUFF(
(SELECT ',' + order1, ',' + order2, ',' + order3, ',' + order4 FOR XML PATH('')),
1, 1, ''
)
This is slight overkill for a constant number of columns (and not particularly efficient), but an easy to remember pattern for concatenation. Also, it shows off STUFF, a function any SQL developer should learn to love.
A: Example
Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into @YourTable Values
(1,NULL,'X','Y',NULL)
,(2,NULL,'A','B',NULL)
,(3,'V',NULL,'H',NULL)
Select Customer_Number
,[Order] = IsNull(stuff(
IsNull(','+order1,'')
+IsNull(','+order2,'')
+IsNull(','+order3,'')
+IsNull(','+order4,'')
,1,1,''),'')
From @YourTable
Returns
Customer_Number Order
1 X,Y
2 A,B
3 V,H
EDIT - IF the "NULL" are strings and NOT NULL Values
Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into @YourTable Values
(1,'NULL','X','Y','NULL')
,(2,'NULL','A','B','NULL')
,(3,'V','NULL','H','NULL')
Select Customer_Number
,[Order] = IsNull(stuff(
IsNull(','+nullif(order1,'NULL'),'')
+IsNull(','+nullif(order2,'NULL'),'')
+IsNull(','+nullif(order3,'NULL'),'')
+IsNull(','+nullif(order4,'NULL'),'')
,1,1,''),'')
From @YourTable
A: This is a bit unpleasant, it needs to be in a subquery to remove the trailing comma efficiently (though you could use a CTE):
SELECT
Customer_number,
SUBSTRING([Order], 0, LEN([Order])) AS [Order]
FROM(
SELECT
Customer_number,
COALESCE(order1+',', '') +
COALESCE(order2+',', '') +
COALESCE(order3+',', '') +
COALESCE(order4+',', '') AS [Order]
FROM
OrderTable) AS SubQuery
A: You were on the right track with the Coalesce, or IsNull. Instead of trying to track the length and use substring, left or stuff, I just used a replace to remove the trailing comma that would show up from the coalesce.
Select Customer_number,
Replace(
Coalesce(Order1 + ',','')+
Coalesce(Order2 + ',','')+
Coalesce(Order3 + ',','')+
Coalesce(Order4 + ',','')
+',',',,','') --Hack to remove the Last Comma
as [Order] from Ordertable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45086384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Oculus SDK: Unable to run Oculus Tiny Room using OpenGL I am getting started with Oculus SDK. As a first step, I decided to try out the "OculusRoomTiny (GL)" example from the provided samples. The project compiles all right on Visual Studio 2017. However, when I run the binary, I get the following error
OpenGL supports only the default graphics adapter.
I am using a Windows 10 desktop with Intel(R) Core(TM) i7-6700k CPU @ 4.00GHz and a dedicated NVIDIA GeForce GTX 980 Ti GPU.
Things I have tried so far:
*
*Update NVIDIA drivers
*Go to Nvidia Control Panel --> Manage 3D settings --> OpenGL Rendering GPU and change that from "Auto" to "GeForce GTX 980 Ti"
*Change BIOS to set the dedicated GPU as the primary GPU
*Disable multi-monitor support in BIOS
None of have provided any positive results.
I have already looked at all the online posts I could find and haven't been able to find a solution in a couple of days. So any help is much appreciated!
A: I finally figured it out. The error was caused because the Oculus was plugged into the dedicated GPU and the monitor for the desktop was plugged into the on-chip Intel GPU. It was resolved when I plugged both of them into the NVIDIA GPU.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46682366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: npm install bootstrap vs download source code I'm trying to use Bootstrap's build tools but I'm having trouble using them when I use npm install bootstrap. When I download the files from their site, I have no problems.
When I install Bootstrap via npm (npm install bootstrap) and then run npm install inside the bootstrap folder, it looks like it installs, but then none of the commands (like npm run dist) work.
When I download the files from the site and then run npm install on the folder, I have no problem running the commands.
I noticed that the npm installation includes far fewer files:
Compared to the downloaded version:
What am I missing? Was I supposed to install other things separately?
I'm in a mac, with node 8.11.2 and npm 6.1.0
A: When installing Bootstrap from their GitHub repository, you get a large amount of files that are only required for debugging, testing, compiling from source, etc. It includes many operations that are only needed if you are trying to contribute to Bootstrap.
The NPM version is just a packaged, production-ready version of Bootstrap. Even after running npm install, you don't get all of the GitHub files, as they are unnecessary for a production environment. You cannot therefore build the NPM version, except by adding basically everything from the GitHub version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50684454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to control display in UIPickerView using selected state of button hi i have used UIButton and also UIpickerview,when i select value(select team) ,the value is changed(india).but
when i hold the button(india) ,the value is changed to initial value(select team).if i release the button from pressing ,the value is changed(india).but i want to do when i hold , the button must show (india) ...i want to use selected state configuration...anyhelp?
A: What is value here? UIPicker's value? or it's some other control in your view?
Check out Highlighted state for UIButton in Interface Builder... hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1529339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: maven compilation fails because unavailable dependency I'm trying to run java program with maven but when i compiled using the command mvn -U compile
he shows me the following error
[root@onePK-EFT1 tutorials]# mvn -U compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building onePK Java Tutorials 0.6.0.5
[INFO] ------------------------------------------------------------------------
Downloading: http://repo.maven.apache.org/maven2/com/cisco/onep/libonep-core-rel
/0.6.0.5/libonep-core-rel-0.6.0.5.pom
[WARNING] The POM for com.cisco.onep:libonep-core-rel:jar:0.6.0.5 is missing, no
dependency information available
Downloading: http://repo.maven.apache.org/maven2/com/cisco/onep/libonep-
core-rel/0.6.0.5/libonep-core-rel-0.6.0.5.jar
[INFO] ------------------------------------------------------------------------
INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.517s
[INFO] Finished at: Tue Jul 09 07:28:28 PDT 2013
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project java-tutorials: Could not resolve
dependencies for project com.cisco.onep:java-tutorials:jar:0.6.0.5: Could not find
artifact com.cisco.onep:libonep-core-rel:jar:0.6.0.5 in central
(http://repo.maven.apache.org/maven2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read
the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN
/DependencyResolutionException
and this is my pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org
/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cisco.onep</groupId>
<artifactId>hello-network-app</artifactId>
<version>0.1-SNAPSHOT</version>
<name>The onePK Hello Network Example Application</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<forkMode>always</forkMode>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.8</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.cisco.onep</groupId>
<artifactId>libonep-core-rel</artifactId>
<version>0.6.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.6.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<developers>
<developer>
<name>onePK Team</name>
<email>[email protected]</email>
<organization>Cisco.com</organization>
</developer>
</developers>
I think it's because he can't find libonep-core-rel.jar which i have it included
please any help
A: The simple solution is to use the appropriate maven repository for the artifacts com.cisco.onep* which are not located in Maven central.
A: As an immediate solution, but not a recommendation, you can use system dependencies to resolve artifacts on your local filesystem.
As @khmarbaise implied, try to publish those corporate artifacts to your corporate Maven repository (Nexus, Artifactory, Archiva, etc.), even an FTP/HTTP server would do...
Once you publish those corporate artifacts to your "corporate" repository(hopefully it's already in place), you just need a new repository declaration in your Maven POM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17551405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read notification while app is in background? I'm using swift 3 and trying to read notifications in didReceiveRemoteNotification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print(userInfo)
}
It's working while app is running but not printing anything while app is background (inactive). How can I read notifications while app is in background (inactive).
A: After taking appropriate permissions for the background notifications in your app and adopting UNUserNotificationCenterDelegate in the appropriate viewController. You can implement this method to trigger notifications in the background and take actions to perform any action from the notification. To perform any action from the notification you need to adopt the function userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void).
func startNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
// to include any action in the notification otherwise ignore it.
let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])
let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [], options: [])
notificationCenter.setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = "Your Title"
content.body = "Message you want to give"
content.sound = UNNotificationSound.default
// To trigger the notifications timely and repeating it or not
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)
content.categoryIdentifier = "CategoryName"
print("Notifications Started")
let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { (error) in
if error != nil {
print("Error in notification : \(error)")
}
})
}
Disclaimer: do apply the solution according to your need and ask if anything wrong happens. This code is for triggering background notifications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53259270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Can I SignUp new User with AWS cognito with Postman without using hosted UI Basically I want the below flow in the application .
I have created one user pool in the cognito and configure it.
I want to integrate cognito authentication and authorization with below flow.
*
*Register new user with by using cognito signUp api via postman (I dont want to use hosted UI) .
once user is successfully registered in cognito.
*User will call the cognito login api via postman - On successful login cognito will return access_token.
*I will use that access token in all subsequent requests to make sure the user is authenticated and authorized .
The main thing here is I do not want to use that hosted UI given by cognito .I want to achieve this via api calls .
I am not sure for achieving this what I need to . You can tell me if any more steps needed before the first step I wrote like authorize my app or anything like that.
I understood I need to authorize my app before it uses the signup api but I am not sure about exact flow and process or in which manner I need to perform the steps .
Please guide..
A: There are aws sdks available for different platform. You need to implement one of them according to your backend technology and expose your api and test it out in the post man. Please go through this link docs.aws.amazon.com/cognito-user-identity-pools/latest/… There are sdks links at the bottom.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66220566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Expanding UIView -Iphone I'm working on an i-phone app that when you press a button a UITableView drops down. I want to push/animate the objects that are underneath the button so that they are underneath the tableview.
For each label/textfield that needs to be moved down would I need something like:
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration:0.3f];
self.view.frame = CGRectOffset(self.view.frame, 0, 70);
Any examples would be helpful.
A: In iPhone OS 4.0 and later, block-based animation methods are recommended by Apple such as
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
for eg.
[UIView animateWithDuration:0.3
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:(void (^)(void)) ^{
self.view.frame = CGRectOffset(self.view.frame, 0, 70); }
completion:^(BOOL finished){
}];
A: So, there will be a UITableView that come from above to self.view and you wanted to move down all the elements in self.view, except the UITableView.
How about putting all the elements in self.view to a container view what have the same size as self.view? And then you can animate all the UI elements with one move
A: Yes, you missed commitAnimations for the view.
A: try this,
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelay:0.3];
self.view.frame = CGRectOffset(self.view.frame, 0, 70);
[UIView commitAnimations];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18015289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating a module for raising class-specific errors In my rails projects, I often use this sort of behavior in my classes and models:
class Whatever
class WhateverError < StandardError; end
def initialize(params={})
raise WhateverError.new("Bad params: #{params}") if condition
# actual class code to follow
end
end
The trouble is, this is both hugely repetitive and fairly verbose. I'd love it if I could just do this whenever I need to raise a class-specific error:
class ErrorRaiser
include ClassErrors
def initialize(params={})
error("Bad params: #{params}") if condition
error if other_condition # has default message
# actual class code to follow
end
def self.class_method
error if third_condition # class method, behaves identically
end
end
I'm having major trouble creating such a module. My sad early attempts have tended to look something like the below, but I'm pretty confused about what's available within the scope of the module, how to dynamically create classes (within methods?) or whether I have straightforward access to the "calling" class at all.
My basic requirements are that error be both a class method and an instance method, that it be "namespaced" to the class calling it, and that it have a default message. Any thoughts/help? Is this even possible?
module ClassErrorable
# This and the "extend" bit (theoretically) allow error to be a class method as well
module ClassMethods
def self.error(string=nil)
ClassErrorable.new(string).error
end
end
def self.included(base)
set_error_class(base)
base.extend ClassMethods
end
def self.set_error_class(base)
# I'm shaky on the scoping. Do I refer to this with @ in a class method
# but @@ in an instance method? Should I define it here with @ then?
@@error_class = "##{base.class}Error".constantize
end
def self.actual_error
# This obviously doesn't work, and in fact,
# it raises a syntax error. How can I make my
# constant a class inheriting from StandardError?
@@actual_error = @@error_class < StandardError; end
end
def initialize(string)
@string = string || "There's been an error!"
end
def error(string=nil)
raise @@actual_error.new(string)
end
end
A: How about something like this (written in pure Ruby; it could be refactored to use some Rails-specific features like .constantize):
module ClassErrorable
module ClassMethods
def error(message = nil)
klass = Object::const_get(exception_class_name)
raise klass.new(message || "There's been an error!")
end
def exception_class_name
name + 'Error'
end
end
def self.included(base)
base.extend ClassMethods
Object::const_set(base.exception_class_name, Class.new(Exception))
end
def error(message = nil)
self.class.error(message)
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20674714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hide content in listbox item depending on a binding property in Silverlight I have xaml that lookes like this
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<StackPanel Orientation="Vertical" x:Name="contentPanel" >
Content goes here...
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
The listbox binds to an object with a bool property called ShowContent.
How do I get silverlight to hide the contentPanel if the object with ShowContent is false?
A: Write a BoolToVisibility IValueConveter and use it to bind to the Visibility property of your contentPanel
<StackPanel Visibility="{Binding YourBoolProperty, Converter={StaticResource boolToVisibilityResourceRef ..../>
You can find a BoolToVisibility pretty easy anywhere.
Check IValueConveter if you are new to that. http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
A: I would recommend setting the ListBoxItem visibility at the ListBoxItem level or you will end up with tiny empty listbox items due to the default padding and border values e.g.
<ListBox>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Visibility" Value="{Binding MyItem.IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" />
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<CheckBox Content="{Binding MyItemName}" IsChecked="{Binding IsVisible, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This hides the entire ListBoxItem not just the contents of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/679575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Im trying to combine date times and string in the same column of a list I have a list of names like this:
['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover',....]
And a list of date-times:
[datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17),.....]
now I'm trying to add them together in between of each other like this in a new list:
[('Albert Einstein', datetime.date(1879, 3, 14)),...
Nothing I tried seem to work. It also doesn't seem possible to me with append or extend, hope someone can help me.
A: Use zip(a, b) for the two lists, e.g.
a = [1, 2, 3]
b = ["a", "b", "c"]
print(list(zip(a, b)))
[(1, "a"), (2, "b"), (3, "c")]
A: As mentioned in the comments you can simply use zip which can take lists as parameters and returns an iterator, with tuples of i-th position of the lists passed as arguments, therefore if we try to print it, we'll get a zip object at ... that's why we need to use list() so we can access the values in a list format:
import datetime
people = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]
output = list(zip(people,dates))
For example:
[('Albert Einstein', datetime.date(1642, 12, 25)),
('Benjamin Franklin', datetime.date(1879, 3, 14)),
('J. Edgar Hoover', datetime.date(1706, 1, 17))]
A: Try this:
names = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]
print(list(zip(names, dates)))
Output:
[('Albert Einstein', datetime.date(1642, 12, 25)), ('Benjamin Franklin', datetime.date(1879, 3, 14)), ('J. Edgar Hoover', datetime.date(1706, 1, 17))]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60623018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQLAlchemy Datetime Differences In SQLAlchemy, you can do a query similar to:
self.session.query(JobsRunning).filter((datetime.datetime.utcnow() - JR.start_time) > datetime.timedelta(hours=3)).all()
This fails because I'm assuming that datetime.datetime.utcnow() returns a double after being subtracted with JR.start_time. Is there a way around this without pulling the datetime.datetime.utcnow() outside of the query itself?
For some, this may make the query look cleaner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30538230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I change this code to show a hidden form with a menu drop down instead of a checkbox? This code is working great, but I'd like to change it so it uses a drop-down menu choice instead of a checkbox. For example, the Dropdown menu choices for "More?" would be "yes" or "no". If "yes" is selected in the menu, I then want the hidden div to show just like it does when one checks the checkbox in the current code.
The javascript:
<script language="JavaScript">
function showhidefield()
{
if (document.frm.chkbox.checked)
{
document.getElementById("hideablearea").style.display = "block";
}
else
{
document.getElementById("hideablearea").style.display = "none";
}
}
</script>
And this is the HTML:
<form name='frm' action='nextpage.asp'>
<input type="checkbox" name="chkbox" onclick="showhidefield()">
Check/uncheck here to show/hide the other form fields
<br>
<div id='hideablearea' style='visibility:hidden;'>
<input type='text'><br>
<input type='submit'>
</div>
This is a text line below the hideable form fields.<br>
</form>
Thank you.
A: Replace your checkbox with
<select name="more" onchange="showhidefield()">
<option value="yes">Yes</option>
<option value="yes">Yes</option>
</select>
And replace the
if (document.frm.chkbox.checked)
in your showhidefield() function with
if (document.frm.more.value == 'yes')
A: <form name='frm' action='nextpage.asp'>
<select name="chkbox" onChange="showhidefield(this)">
<option value="0" selected="true">-Select-</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
Check/uncheck here to show/hide the other form fields
<br>
<div id='hideablearea' style='display:none;'>
<input type='text'><br>
<input type='submit'>
</div>
This is a text line below the hideable form fields.<br>
</form>
And javascript code is:
<script language="JavaScript">
function showhidefield(that)
{
if (that.value == 1)
{
document.getElementById("hideablearea").style.display = "block";
}
else
{
document.getElementById("hideablearea").style.display = "none";
}
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8642058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ^ and $ expressed in fundamental operations in regular expressions I've read a book where it states that all fundamental operations in regular expressions are concatatenation, or(|), closure(*) and parenthesis to override default precedence. Every other operation is just a shortcut for one or more fundamental operations.
For example, (AB)+ shortcut is expanded to (AB)(AB)* and (AB)? to (ε | AB) where ε is empty string. First of all, I looked up ASCII table and I am not sure which charcode is designated to empty string. Is it ASCII 0?
I'd like to figure out how to express the shortcuts ^ and $ as in ^AB or AB$ expression in the fundamental operations, but I am not sure how to do this. Can you help me out how this is expressed in fundamentals?
A: Regular expressions, the way they are defined in mathematics, are actually string generators, not search patterns. They are used as a convenient notation for a certain class of sets of strings. (Those sets can contain an infinite number of strings, so enumerating all elements is not practical.)
In a programming context, regexes are usually used as flexible search patterns. In mathematical terms we're saying, "find a substring of the target string S that is an element of the set generated by regex R". This substring search is not part of the regex proper; it's like there's a loop around the actual regex engine that tries to match every possible substring against the regex (and stops when it finds a match).
In fundamental regex terms, it's like there's an implicit .* added before and after your pattern. When you look at it this way, ^ and $ simply prevent .* from being added at the beginning/end of the regex.
As an aside, regexes (as commonly used in programming) are not actually "regular" in the mathematical sense; i.e. there are many constructs that cannot be translated to the fundamental operations listed above. These include backreferences (\1, \2, ...), word boundaries (\b, \<, \>), look-ahead/look-behind assertions ((?= ), (?! ), (?<= ), (?<! )), and others.
As for ε: It has no character code because the empty string is a string, not a character. Specifically, a string is a sequence of characters, and the empty string contains no characters.
A: ^AB can be expressed as (εAB) ie an empty string followed by AB and AB$ can be expressed as (ABε) that's AB followed by an empty string.
The empty string is actually defined as '', that's a string of 0 length, so has no value in the ASCII table. However the C programming language terminates all strings with the ASCII NULL character, although this is not counted in the length of the string it still must be accounted for when allocating memory.
EDIT
As @melpomene pointed out in their comment εAB is equivalent to AB which makes the above invalid. Having talked to a work college I'm no longer sure how to do this or even if it's possible. Hopefully someone can come up with an answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56390657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to create JSONObject from ArrayList to make post request? I am trying to post data into server using JSONObject as request. And I dont know how to create JSONObject from ArrayList with following type of data.
{"AnswersList":[
{
"questionID": 1,
"question": "What is yout name?",
"questionType": "STRI",
"questionOrder": 1,
"answer":"Avishek",
"choiceList": []
},
{
"questionID": 2,
"question": "Sports?",
"questionType": "MULT",
"questionOrder": 2,
"answer":"1,2",
"choiceList": [
{
"choiceID": 1,
"choiceName": "Football",
"choiceOrder": 1
},
{
"choiceID": 2,
"choiceName": "Basketball",
"choiceOrder": 2
}
]
}]}
Can anyone please help me to solve this problem.
I have create two model classes for handling the JSON. First one is Question.java for second is Choice.java
Model classes are:
Question.java
public class Question {
@SerializedName("questionID")
public String questionID;
@SerializedName("question")
public String question;
@SerializedName("questionType")
public String questionType;
@SerializedName("questionOrder")
public String questionOrder;
@SerializedName("answer")
public String answer;
@SerializedName("choiceList")
public ArrayList<Choice> choices = new ArrayList<>();
@SerializedName("isRequired")
public boolean isRequired;
//getter and setter methods
}
Choice.java
public class Choice {
@SerializedName("choiceID")
private String choiceID;
@SerializedName("choiceName")
private String choiceName;
@SerializedName("choiceOrder")
private String choiceOrder;
//getter and setter method
}
I've tried this code but did not work
DatabaseHelper databaseHelper = new DatabaseHelper(mContext);
ArrayList<Question> questionsAnswer = new ArrayList<>();
questionsAnswer.addAll(databaseHelper.getQuestionList());
Log.v(TAG, "size of question answer list : " + questionsAnswer.size());
Map<String, Object> jsonParams = new ArrayMap<>();
//put something inside the map, could be null
JSONArray jsArray = new JSONArray(questionsAnswer);
jsonParams.put("AnswersList", jsArray);
A: First of all, I'll suggest to use Retrofit library for requests (https://square.github.io/retrofit/)
For creating a json String from your object you can use Gson library
Gson gson = new Gson();
String jsonInString = gson.toJson(obj);
Update
don't forget to add Gson dependency on your gradle file
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
A: Parsing JSON Objects & Arrays on Java we should use GSON Library
Add gradle File:
implementation 'com.google.code.gson:gson:2.8.2'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63936352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Marshalling LPWSTR * from a C function I have a sample function from a native code
HRESULT getSampleFunctionValue(_Out_ LPWSTR * argument)
This function outputs the value in argument. I need to call it from the Managed code
[DllImport("MyDLL.dll", EntryPoint = "getSampleFunctionValue", CharSet = CharSet.Unicode)]
static extern uint getSampleFunctionValue([MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder argument);
This returns garbage value. AFAIK the original C function does not create string using CoTaskMemAlloc. What is the correct call?
Any help will be appreciated.
A: You need the C# code to receive a pointer. Like this:
[DllImport("MyDLL.dll")]
static extern uint getSampleFunctionValue(out IntPtr argument);
Call it like this:
IntPtr argument;
uint retval = getSampleFunctionValue(out argument);
// add a check of retval here
string argstr = Marshal.PtrToStringUni(argument);
And you'll also presumably need to then call the native function that deallocates the memory that it allocated. You can do that immediately after the call to Marshal.PtrToStringUni because at that point you no longer need the pointer. Or perhaps the string that is returned is statically allocated, I can't be sure. In any case, the docs for the native library will explain what's needed.
You may also need to specify a calling convention. As written, the native function looks like it would use __cdecl. However, perhaps you didn't include the specification of __stdcall in the question. Again, consult the native header file to be sure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18118978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Assign var as a selector I have a var named as sliceText which contains a text which is collected whenever user hover over the section of a visualforce chart. I'm trying to increase the size of this text with a value which gets calculated at run time and newSize var hold the same. But using jquery following syntax is not working and I'm not able change the font size.
var sliceText = j$(this).text();
j$(sliceText).css('font-size', newSize);
How can I assign a var as a selector using jquery? I want following solution work for me but its NOT when I tried to!! https://docs.acquia.com/articles/increase-text-size-jquery
A: You need to apply css to the DOM object containing the text no the text
j$('path, tspan').mouseover(function(e) {
j$(this).children().css('font-size', 15);//reset to default size font
j$(e.target).css('font-size', newSize);
});
A: You didn't mentioned whether the dom is an id or a class
var sliceText = j$(this).text();
j$("#"+sliceText).css('font-size', newSize); --- if the dom element is an id
j$("."+sliceText).css('font-size', newSize); --- if the dom element is a class
A:
var newSize = '30px';
var originalSize = '14px';
$("span").hover(function(){
$(this).css('font-size', newSize);
}, function(){
$(this).css('font-size', originalSize);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span> Jan </span><br/>
<span>Feb</span><br/>
<span>March</span>
A: As i understand you want to change the font size of hover element
so try this one
function funtest()
{
var oldSize = parseFloat(j$('text').css('font-size'));
var newSize = oldSize * 2;
j$('path, tspan').mouseover(function () {
j$(this).css('font-size', newSize);
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35884127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Large react-redux form app I've been working on rewriting one of the modules in my company using react, the module is a single page composable of 4-5 different forms, selections made in each form are then determine the appeareance of the next form step.
There are a lot of "static" input fields which not affecting the visual ui state of the app, but are required to send to the server, other inputs are changing the ui state.
I'm looking for the right approach for this type of apps, since it seems attaching onChange event to every single input (there are more than 100 inputs total in the whole page). I've used react-redux-forms plugin, but it is too much of a blockbox for me, since I need to have direct access to the state and make decision based on it. I would preferer hacing more control over the state.
Is the right solution to bind onChange event for every input? Or is there a better approach.
A: We do this with redux-form quite easily. Because everything's maintained in the fields prop, you could do something like this:
const Form = ({
fields,
handleSubmit,
saveForm
}) => (
<form onSubmit={handleSubmit(saveForm)}>
<fieldset>
<input type="text" {...fields.hasAlternativeDelivery} />
</fieldset>
{fields.hasAlternativeDelivery.value === true &&
<fieldset>
{/* more fields go here */}
</fieldset>
}
</form>
);
We then conditionally validate certain fieldsets like this.
So, to answer your question: you shouldn't rely on change events to hide / show certain fields, this goes against the very nature of React (React is declarative, what you're describing is an imperative way of doing things). Instead, figure out what state (/props) should lead to which UI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38240033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery effect continues to iterate I have a div within a parent div, that is normally hidden. When you hover over the parent div the child is then visible. I am using JQuery .toggle() to get this effect. The problem is that if you MouseIn and MouseOut really fast, repeatedly over the parent, the child div is toggled that many times. Is there a way to prevent this from happening, it is slowing down my page?
JSFIDDLE: http://jsfiddle.net/vY59g/1/
My JQuery:
$(document).ready(function() {
$(".result").hover(function() {
$(this).find(".result-user-facts").toggle("slow");
});
});
A: It is because the queuing nature of animations, every mouser enter and mouse leave operation queues a toggle operation. So if there are quick movement of mouse triggering the enter and leave events then even after the events are over the animations will keep happening.
The solution is to stop and clear previous animations before the toggle is called using .stop()
$(document).ready(function() {
$(".result").hover(function() {
$(this).find(".result-user-facts").stop(true, true).toggle("slow");
});
});
Demo: Fiddle
A: If you want to make things better, just put div:.result-user-facts into an Variable if there only has one. Like this:
$(function (){
var container = $(".result");
var item = container.find(".result-user-facts").eq(0);
$(".result").hover(function (){
item.stop().toggle("slow");
});
});
A: Use .stop(true,true)
Stop the currently-running animation on the matched elements.
Fiddle DEMO
$(document).ready(function() {
$(".result").hover(function() {
$(this).find(".result-user-facts").stop(true,true).toggle("slow");
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19944194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what port tomcat7 use? how do I set AWS Security group? I run a tomcat7 in ubuntu in aws. not use apache.
and my site use default tomcat port 8080.
I don't want to open port except 8080 so I'm setting in aws security group.
inbound
8080 TCP anywhere
and outbound allTraffic.
but I try to rest call to
http://my_aws_ip:8080/test.do
but it doesn't work.
What should I open the port?
Does tomcat7 use a some port?
A: Tomcat uses whatever port or ports and protocols you configure it to use. By default it listens for HTTP requests on tcp/8080, AJP requests on tcp/8009, and service management requests on tcp/8005.
This is configured in Connector elements in $CATALINA_HOME/conf/server.xml:
https://tomcat.apache.org/tomcat-7.0-doc/config/http.html
You should reconfigure Tomcat to listen on standard ports like tcp/80 for HTTP and tcp/443 for HTTPS. Non-standard ports are a ready indication of a novice deployment.
The AWS Security Group should be configured to allow HTTP, HTTPS, pr both depending on your need. I highly recommend using HTTPS unless the information being transferred is public domain or has no value.
You can check what ports Tomcat is using on your EC2 instance with netstat -anpt. It will show all active and listen ports and the programs that have bound them (including java or tomcat for your Tomcat ports).
Unless you really need root access to the OS, you might want to consider using Amazon Elastic Beanstalk as it manages all that cruft for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31208834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting size of inner region of Java SWT shell window In a Java SWT shell window, how do I set its inner size than its whole window frame size?
For instance, if I use shell.setSize(300, 250) this would make the whole window appearing as exactly 300x250. This 300x250 includes the size of the window frame.
How can I set the inner size, that is the content display region of the shell window to 300x250 instead? That's this 300x250 excludes the width of the window frame.
I tried to minus some offset values but the thing is different Operating Systems have different window frame sizes. So having a constant offset would not be accurate.
Thanks.
A: From your question what I understood is that you want to set the dimension of the Client Area. And in SWT lingo it is defined as a rectangle which describes the area of the receiver which is capable of displaying data (that is, not covered by the "trimmings").
You cannot directly set the dimension of Client Area because there is no API for it. Although you can achieve this by a little hack. In the below sample code I want my client area to be 300 by 250. To achieve this I have used the shell.addShellListener() event listener. When the shell is completely active (see the public void shellActivated(ShellEvent e)) then I calculate the different margins and again set the size of my shell. The calculation and resetting of the shell size gives me the desired shell size.
>>Code:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
public class MenuTest {
public static void main (String [] args)
{
Display display = new Display ();
final Shell shell = new Shell (display);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
layout.numColumns = 1;
shell.setLayout(layout);
shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,true));
final Menu bar = new Menu (shell, SWT.BAR);
shell.setMenuBar (bar);
shell.addShellListener(new ShellListener() {
public void shellIconified(ShellEvent e) {
}
public void shellDeiconified(ShellEvent e) {
}
public void shellDeactivated(ShellEvent e) {
}
public void shellClosed(ShellEvent e) {
System.out.println("Client Area: " + shell.getClientArea());
}
public void shellActivated(ShellEvent e) {
int frameX = shell.getSize().x - shell.getClientArea().width;
int frameY = shell.getSize().y - shell.getClientArea().height;
shell.setSize(300 + frameX, 250 + frameY);
}
});
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
A: If I get you right you should set the size of the inner component to the needed size and use the method pack() (of the frame).
A: import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
public class SWTClientAreaTest
{
Display display;
Shell shell;
final int DESIRED_CLIENT_AREA_WIDTH = 300;
final int DESIRED_CLIENT_AREA_HEIGHT = 200;
void render()
{
display = Display.getDefault();
shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);
Point shell_size = shell.getSize();
Rectangle client_area = shell.getClientArea();
shell.setSize
(
DESIRED_CLIENT_AREA_WIDTH + shell_size.x - client_area.width,
DESIRED_CLIENT_AREA_HEIGHT + shell_size.y - client_area.height
);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args)
{
SWTClientAreaTest appl = new SWTClientAreaTest();
appl.render();
}
}
A: Use computeTrim to calculate the bounds that are necessary to display a given client area. The method returns a rectangle that describes the bounds that are needed to provide room for the client area specified in the arguments.
In this example the size of the shell is set so that it is capable to display a client area of 100 x 200 (width x height):
Rectangle bounds = shell.computeTrim(0, 0, 100, 200);
shell.setSize(bounds.width, bounds.height);
This article describes the terms used by SWT for widget dimensions:
https://www.eclipse.org/articles/Article-Understanding-Layouts/Understanding-Layouts.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6004134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android custom Drawable vs custom View I wanted to know what's the difference between creating a custom Drawable like in the Shelves project: http://code.google.com/p/shelves/ to creating a custom View?
A: Drawble only response for the draw operations, while view response for the draw and user interface like touch events and turning off screen and more.
View can contain many Drawbles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12445045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android Timer is firing twice I am trying to update TextView content every second using Timer Class. Given below is my code. The problem is that the value is increasing by 2 not by 1. Please tell me what the problem is.
public class MainActivity extends ActionBarActivity {
public void onButtonClick (View view) {
// calendar
OnDateSetListener datelistener = new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int Year, int monthOfYear, int dayOfMonth) {
....
reScheduleTimer(); // starting the timer
}
};
}
public void reScheduleTimer(){
timer = new Timer();
timerTask = new myTimerTask();
timer.schedule(timerTask, 1000, 1000);
}
public class myTimerTask extends TimerTask{
@Override
public void run() {
elapsed = elapsed + 1;
runOnUiThread(new Runnable(){
public void run() {
TextView seconds = (TextView) findViewById(R.id.seconds);
seconds.setText("seconds so far "+elapsed);
}
});
}
}
}
A: Wouldn't hurt to check if timerTask is null at the beginning of reScheduleTimer and cancel it if it is not null.
At the beginning of reScheduleTimer:
if(timerTask != null) {
timerTask.cancel();
}
A: I still don't know how the variable is increasing by more than 1, but I solved the problem by reading the system clock on every invocation of the function and displaying it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24159850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to auto-start a WCF for only specific projects? I have a WCF project which several other projects depend on, but others, like unit testing projects and other support utilities which don't need the service. It contains the following XML in the .csproj file:
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{3D9AD99F-2412-4246-B90B-4EAA41C64699}">
<WcfProjectProperties>
<AutoStart>True</AutoStart>
</WcfProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
Is there a way to get the "auto-start service with project" functionality to only apply to specific projects in the solution? Or is it all or nothing? Is there anything I could add to the other projects to tell them they depend on this service to make it auto-start in the debugging session? Or add some condition to the service's .csproj that depends on which project is the current startup project?
I tried experimenting with Condition="'$(Configuration)' == 'Debug'" in various places, but I couldn't get it to behave an different based on that Configuration variable.
A: To make the client applications debugable, create a new tiny project and set both the service and the client application as dependencies. The only file it should contain is Program.cs, and its only function should look like this:
[STAThread]
static void Main(string[] args)
{
new System.ServiceModel.ServiceHost(typeof(MyServiceClass)).Open();
MyClientApplication.Program.Main(args);
}
And then merge the app.config for both into a single app.config for this tiny application. But now the service is hosted inside the same process as the client, and they can both be debugged interchangeably.
This allows removing the AutoStart feature from the service, but still run the client application together with the service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66925140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rails how to display data or retrieve values after find I did a find on some model and got the following
>> @addy
=> [#<Address id: 3, street: "Some Street", houseNumber: nil, created_at: "2010-01-20 06:09:52", updated_at: "2010-01-20 06:09:52", address_id: 16>]
Now how do I retrieve the values? what if i want the street?
@addy.street does not work netiher does @addy[:street]
what if i had a list of @addy's and wanted to loop through them to show street for each?
A: @addy.first.street should work, as it is list of Adress classes containing only one member.
For displaying each street for more adresses in list:
@addy.each do |address|
puts address.street
end
or
list_of_streets = @addy.map { |address| address.street }
Edit:
When you have problem identifying what class you have, always check object.class. When you just use object in IRB, then you see output from object.inspect, which doesn't have to show class name or even can spoof some informations. You can also call object.methods, object.public_methods.
And remember that in Ruby some class is also an instance (of Class class). You can call @addr.methods to get instance methods and @addr.class.methods to get class methods.
Edit2:
In Rails #find can take as first parameter symbol, and if you pass :first of :last, then you'll get only one object. Same if you pass one integer (id of retrieved object). In other cases you get list as result, even if it contains only one object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2099479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the current size of the heap memory of a process in Linux using C/C++ system calls? I am working on a software library, which can constantly keep track of the size of the heap memory of programs written in C/C++.
What I would like to do is as follows.
void check_memory(){
heap_size = get_process_heap_size(.....);
if(heap_size>=upper_bound){
//do something to reduce the heap size
heap_size = get_process_heap_size(.....);
}
}
Is there any system call in C/C++ that is equivalent to get_process_heap_size() in the code above?
A: I dont know if there is any direct system call that gives you memory details, but if you are on linux you can read and parse /proc/(pid of your process)/status file to get the needed memory usage counts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47806853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JAVA HOME PATH correctly set in Environment but wrong when compiling via Node.js I received this isue: com.sun.tools.javac.Main is not on the classpath. Oerhaps JAVA_HOME does not point to the JDK. It is currently set to "C:\Program Files\Java\jre7"
However, my JAVA HOME is set as follows:
C:\Program Files\Java\jdk1.7.0_51
With PATH
C:\Program Files\Java\jdk1.7.0_51
Any recommendations?
A: When node.js spawns a forked environment, it doesn't copy over your user's environment variables. You will need to do that manually.
You will need to get JAVA_HOME from process.env and set it in your exec() call.
Something like this should work:
var config = {
env: process.env
};
exec('javacmd', config,
function() {
console.log(arguments);
});
Or if you wanted to be more explicit, you could extract only the variables you needed (JAVA_HOME, etc) from process.env
See here for more details:
How to exec in NodeJS using the user's environment?
A: Just uninstall node js and re install node js. Its solve my problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21842807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: forcing overflow-x using percentage and float I have a small structure of <li> inside a container and what i'm trying to make is to force the overflow-x appear instead of overflow-y, but i can't achieve this, i presume it is beacuse of properties float and the percentage that i'm using.
is there i way where i can reach this result ? show only the horizontal overflow ?
here is the code:
html
<div id="CockpitCenter">
<ul class="CockpitContainerResult">
<li><div class="box">Box 1</div></li>
<li><div class="box">Box 2</div></li>
<li><div class="box">Box 3</div></li>
<li style="height: 400px;">
<div class="box" style="height: 370px;">Box 4</div>
</li>
<li><div class="box">Box 5</div></li>
<li><div class="box">Box 6</div></li>
<li><div class="box">Box 7</div></li>
</ul>
</div>
and css
#CockpitCenter {
height: 500px; /* set only here in jsFiddle */
position: fixed;
left: 0;
border: solid 2px #ccc;
border-bottom: none;
overflow: auto;
}
div#CockpitCenter ul.CockpitContainerResult {
float: left;
width: 100%;
}
ul.CockpitContainerResult li {
margin: 5px 0;
height: 150px;
width: 50%;
float: left;
}
ul.CockpitContainerResult li:nth-child(even) {
float: right;
}
ul.CockpitContainerResult li div.box {
border: solid 1px #ccc;
margin: 15px;
border-radius: 20px;
height: 150px;
text-align: center;
}
here is a demo
A: Sounds like you are trying to make a carousel, which there are many handy jquery plugins for. Regardless, you cannot do this using percentages for widths, you have to give your main container a fixed width, then give the inner one (your ul) whatever larger width you want. You must force a width on the UL otherwise the LI elements will just wrap. Once thats done just add an 'overflow-x: auto' to the main container and you should be on your way.
Quick example, http://jsfiddle.net/ybJ6C/8/
I'm using my ipad right now, and didn't see the scroll bar but it does indeed scroll. You'll notice that the scroll continues well past the end, you can adjust that with the width if you know what you want. If its dynamic then you would need js to adjust the width for you based on the elements within. I also don't have the height correct, but its enough to get the idea. (again doing this from my ipad, coding ain't the greatest)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11566896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: remove all styles based on browser version I would like to know how i can remove all css styles based on checking if the browser is less than IE8.
So if it detects IE7 then remove all styles? I wonder if this is possible via some jquery?
Will this fix most IE7 issues:
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script>
<![endif]-->
A: I don't know why you want to remove all styles for a browser version. I suppose that you have some CSS problems with IE7, and often a good way of fixing it, rather than deleting all your CSS, is to use ie7.js: http://code.google.com/p/ie7-js/.
Here is a demo of what it can do.
Also, this script has a version for IE8 and IE9.
A: <!--[if lt IE 8]>
<body class='oldIE'>
<![endif]-->
<!--[if gte IE 8]>
<body class='ok'>
<![endif]-->
<!--[if !IE]>
<body class='ok'>
<![endif]-->
here you would need to prefix all the styles you don't IE7 to apply with .ok
another method would be
<!--[if lt IE 8]>
//include an old IE specific stylesheet or none at all
<![endif]-->
<!--[if gte IE 8]>
//include your stylesheets
<![endif]-->
<!--[if !IE]>
//include your stylesheets
<![endif]-->
A: The best solution is to remove a specific class name rather than wiping the entire CSS for an element:
// Identity browser and browser version
if($.browser.msie && parseInt($.browser.version) == 7) {
// Remove class name
$('.class').removeClass('class');
// Or unset each CSS selectively
$('.class').css({
'background-color': '',
'font-weight': ''
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10043031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is a foreach data binding not creating a $parent context? In the following code, why is the remove handler accessible without $parent?
If I use data-bind="click: $parent.remove" I get an error saying that property remove of undefined doesn't exists, but being inside a foreach loop, shouldn't I get a $parent context?
Template:
<ul data-bind="foreach:list">
<li><!-- ko text: $data --><!-- /ko --> <button data-bind="click: remove">x</button></li>
</ul>
ViewModel:
function ViewModel() {
var self = this;
this.list = ko.observableArray(['asd', 'lol', 'rofl']);
this.remove = function(index){
console.log('Clicked ' + index);
self.list.splice(index, 1);
};
};
ko.applyBindings(ViewModel);
https://jsfiddle.net/3d7nfbr3/3/
A: You are missing the new, when creating your viewmodel.
Your code should look like this:
ko.applyBindings(new ViewModel());
Without the new the this refers to the global window object so your remove function is declared globally, that is why the $parent is not working.
Demo JsFiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31056430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Want to update my old html css ,js site with React , $('some').owlCarousel, throws an error Type error , owlCarousel is not a function Want to update my old HTML, CSS ,js site with React.
I make the components for HTML and integrate js also, but when I am trying to import and run owl carousel in jquery, like $('some').owlCarousel, throws an error Type error,
owlCarousel is not a function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50856035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How count objects with element value? I need your help.
I have for example such array:
var array = [{
"name": "Tony",
"year": "2010"
}, {
"name": "Helen",
"year": "2010"
}, {
"name": "Jack",
"year": "2005"
}, {
"name": "Tony",
"year": "2008"
}, {
"name": "Max",
"year": "2005"
}];
How i can count them by year and get something like this:
2010 = 2 times;
2005 = 2 times;
2008 = 1 time;
Thank you
A: check this fiddle
var countObj = {};
for( var counter = 0; counter < array.length; counter++ )
{
var yearValue = array [ counter ].year;
if ( !countObj[ yearValue ] )
{
countObj[ yearValue ] = 0;
}
countObj[ yearValue ] ++;
}
console.log( countObj );
A: Try this:
var array = [{
"name": "Tony",
"year": "2010"
}, {
"name": "Helen",
"year": "2010"
}, {
"name": "Jack",
"year": "2005"
}, {
"name": "Tony",
"year": "2008"
}, {
"name": "Max",
"year": "2005"
}];
var map={}
for (var i = 0; i<array.length;i++){
if ( !map[ array [ i ].year ] ){
map[ array [ i ].year ] = 0;
}
map[ array [ i ].year] ++;
}
console.log( map );
Fiddle
A: Here arrange uses reduce to build an object using the years as keys. It accepts a prop argument so that you can build the object as you see fit.
function arrange(arr, prop) {
return arr.reduce(function(p, c) {
var key = c[prop];
p[key] = p[key] || 0;
p[key]++;
return p;
}, {});
}
You can then iterate over the key/values of that object and print out the results for year:
var obj = arrange(array, 'year');
for (var p in obj) {
console.log(p + ' = ' + obj[p] + ' times');
}
Or even by name:
var obj = arrange(array, 'name');
DEMO
A: You are trying to re-invent the wheel.
This and many more methods are exposed by a third-party JS library, called "lodash"; old name was "underscore". All its methods or most of them are exposed like
_.methodName(listName, iteratorFunction)
You can download it at: https://lodash.com/
Once you download and include lodash your script in your html, go to your function and do:
_.groupBy(yourArrayVariable, function(item){
return item.year;
});
WARNING
This method will not return an array. It will return a JSON, in which the keys are represented by the "item.year" through the whole original array, and the values will be an array for each year listed. Every such array is a list of objects having the same "year" value:
{
"2010" : [
{ "name" : "Tony", "year" : "2010" },
{ "name" : "Helen", "year" : "2010" }
],
"2011" : [ ..... ]
}
Lodash has lots of useful methods anyway.
A:
var array = [{
"name": "Tony",
"year": "2010"
}, {
"name": "Helen",
"year": "2010"
}, {
"name": "Jack",
"year": "2005"
}, {
"name": "Tony",
"year": "2008"
}, {
"name": "Max",
"year": "2005"
}];
var result = {};
array.forEach(function(data) {
console.log(data.year);
result[data.year] = result[data.year] ? ++result[data.year] : 1;
});
document.write(JSON.stringify(result));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34352799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.