qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
44,472,209 |
My production site just provides the old ICU version 4.2.1. Since Yii2 requires Version 49.1 or higher I need to make workarounds in PHP.
How do I get the nersion number of ICU (libicu) which is used by PHP during runtime. Since I have frequent production updates I need to get the version number dynamically in PHP code, e.g. by
```
$libIcuVersion = ...
```
The version number is shown in `phpinfo.php` but the output cannot be used in my code.
|
2017/06/10
|
[
"https://Stackoverflow.com/questions/44472209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3286903/"
] |
This is how [Symfony/Intl](https://github.com/symfony/intl) does it in `Symfony\Component\Intl::getIcuVersion()`.
```php
try {
$reflector = new \ReflectionExtension('intl');
ob_start();
$reflector->info();
$output = strip_tags(ob_get_clean());
preg_match('/^ICU version (?:=>)?(.*)$/m', $output, $matches);
$icuVersion = trim($matches[1]);
} catch (\ReflectionException $e) {
$icuVersion = null;
}
```
|
20,092 |
I'm trying to understand Joseph's approach to Pilate. Mark and Matthew appear to be describing his approach in different ways. Did he ask boldly or did he beg for Jesus' body?
>
> Mark 15:43 Joseph of Arimathaea, an honourable counsellor, which also waited for the kingdom of God, came, and went in boldly unto Pilate, and craved the body of Jesus. (KJV)
>
>
> Mark 15:43 Joseph of Arimathea, a respected member of the council, who was also himself looking for the kingdom of God, took courage and went to Pilate and asked for the body of Jesus. (ESV)
>
>
> Matt. 27:58 He went to Pilate, and begged the body of Jesus. Then Pilate commanded the body to be delivered. (KJV)
>
>
>
|
2015/09/28
|
[
"https://hermeneutics.stackexchange.com/questions/20092",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/6661/"
] |
Both of those passages use the same Greek word αἰτέω (KJV: "crave", "beg", ESV: "asked for"), so any variance in the translation of it is due to the quirks of English, not Greek. Liddell-Scott says:
>
> ask, beg, mostly with accusative: ask for, demand
>
>
>
Whether the asking is bold or not is not inherent in that word. The most we can say is that the ESV is more modern English.
---
Instead, we infer boldness from τολμήσας (KJV: "went in boldly", ESV: "took courage"), which is only in Mark (but is not contradicted in Matthew). [Liddell-Scott](http://logeion.uchicago.edu/index.html#%CF%84%CE%BF%CE%BB%CE%BC%CE%AC%CF%89) says:
>
> undertake, take heart either to do or bear anything terrible or difficult ... mostly abs., dare, endure, submit
>
>
>
...or, with another infinitive (which we don't have here but helps color the meaning):
>
> to have the courage, hardihood, effrontery, cruelty, or the grace, patience, to do a thing in spite of any natural feeling, dare, or bring oneself, to do...
>
>
>
Again, we see some ambivalence, and must look to the context to guess the shades of meaning. The King James guessed that Joseph had a good dose of thumos and wrote "went in boldly", as if he had a bit of a swagger. The ESV guessed he was more humble and wrote "took courage" (although that would be a better reading if the Greek used θαρσέω instead). I would just render it "when he dared, he went in" rather than try to cement my guess for the reader. The emphasis is more on the riskiness of the action rather than the psychological state of the actor (which isn't surprising at all since that culture "thought in allocentric (social) terms; they did not, as we do, think in idiocentric (psychological) terms" ([Crook](https://books.google.com/books?id=pSEhAAAAQBAJ&pg=PA47), following Malina et al).
All of which is to say, "the text doesn't make it clear".
|
33,825,232 |
We have a running Graphhopper Server in our company for getting routes.
Is there a way to find out how far we are driving in each country? e.g if I'm driving from Munich to Vienna I would like to know how many km we are driving in Germany and how many in Austria.
|
2015/11/20
|
[
"https://Stackoverflow.com/questions/33825232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423855/"
] |
This is not yet possible out of the box. You'll have to create a feature request for this or implement this on your own: grab the country boundaries, identify the edges/nodes to mark in the graph and then create additional instructions or store the point indices to later calculate the distances/times for every path.
|
12,951,317 |
Actually the apache-tomcat 7 server running at The Eclipse.but in browser getting error "The requested resource is not available." .Any reasons Please..?
|
2012/10/18
|
[
"https://Stackoverflow.com/questions/12951317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127619/"
] |
There could be a number of reasons, have it as a checklist and go through it
Is your server running on 8080?I mean that is the default port but it could be configured to run on other.
Also there is a possibility that the default application is removed/uninstalled that is why it is giving "the requested resource is not available"
Also it could be a proxy issue. make sure you are not using any proxy in your browser.
|
23,945,311 |
I have a query that currently looks like:
```
SELECT [column a], [column b], [column c], [column d]
FROM [table]
WHERE FIND_IN_SET(2, column d)
ORDER BY [column a] DESC
```
Where [column d] is of type `varchar`, and holds a set of numbers (ex, `3, 2, 4, 6, 1, 9`). So basically I am trying to return all records where `2` is in its set of numbers. However, when I execute an `EXPLAIN` on the above query, this is my output:
```
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE [table] ALL NULL NULL NULL NULL 500000 Using where; Using filesort
```
This query does not seem to be using any indices during the execution of this query. `[column a]` is the primary key, so there is an index on that column already. Is there any way to utilize an index for this query to run faster? Or is there another way for me to improve the performance of this query?
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23945311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470257/"
] |
Alternative: properly normalize the schema.
FIND\_IN\_SET is *not* [Sargable](http://en.wikipedia.org/wiki/Sargable) and the index *cannot* be used.
|
4,086 |
I always use something like `\overfullrule=1mm` when I am writing Latex documents. I do read all warnings regarding overfull \hboxes, but I still prefer the visual output that very clearly shows exactly which boxes are overfull.
Can I somehow have something similar for *underfull* \hboxes? Some kind of simple visual highlighting that shows exactly where in the final document I have those problematic lines of text?
I am using pdflatex in case it matters.
|
2010/10/13
|
[
"https://tex.stackexchange.com/questions/4086",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/100/"
] |
It's not possible in the general case, but you can visualise when underfull boxes occur by taking apart a paragraph and measuring the badness of the individual lines of the paragraph. An example is shown here: <https://gist.github.com/0f42f19422d446490e0e> (update: I just edited the file a little to give better results).
It requires that you put markup around your paragraphs, unfortunately, but it's fun to play with. Perhaps the new everyhook package might be helpful to apply these sort of command to every text paragraph in a document, but I suspect that would require major surgery of LaTeX's section heading system.
|
54,725,650 |
I am trying to align text center using below code but its not working. My codepen [`link`](https://codepen.io/rama-krishna-the-selector/pen/omQqYK) and code:
```css
body {
padding: 0;
margin: 0;
}
.container {
width: 1200px;
overflow: auto;
margin: 240px auto;
background: transparent;
position: relative;
}
.container .box {
position: relative;
float: left;
width: calc(400px - 30px);
height: calc(300px - 30px);
background: yellow;
overflow: hidden;
margin: 15px;
border-radius: 10px;
box-sizing: border-box;
}
.container .box .icon {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
transition: 0.5s;
z-index: 1;
}
.container .box:hover .icon {
top: 20px;
left: calc(50% - 40px);
width: 80px;
height: 80px;
border-radius: 50%;
}
.container .box .icon .fa {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 80px;
color: #fff;
transition: 0.5s;
}
.container .box:hover .icon .fa {
font-size: 40px;
}
.container .box .content {
position: absolute;
top: 100px;
height: calc(100% - 100px);
padding: 20px;
box-sizing: border-box;
transition: 0.5s;
text-align: center;
}
```
```html
<div class="container">
<div class="box">
<div class="icon">
<i class="fa fa-search" aria-hidden="true"></i>
</div>
<div class="content">
<h3>Search</h3>
<p>sadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfen</p>
</div>
</div>
</div>
```
|
2019/02/16
|
[
"https://Stackoverflow.com/questions/54725650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5571461/"
] |
Add `width: 100%` to the `content` element to *fit* the *absolutely* positioned element in its container - see demo below:
```css
body {
padding: 0;
margin: 0;
}
.container {
width: 1200px;
overflow: auto;
margin: 240px auto;
background: transparent;
position: relative;
}
.container .box {
position: relative;
float: left;
width: calc(400px - 30px);
height: calc(300px - 30px);
background: yellow;
overflow: hidden;
margin: 15px;
border-radius: 10px;
box-sizing: border-box;
}
.container .box .icon {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
transition: 0.5s;
z-index: 1;
}
.container .box:hover .icon {
top: 20px;
left: calc(50% - 40px);
width: 80px;
height: 80px;
border-radius: 50%;
}
.container .box .icon .fa {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 80px;
color: #fff;
transition: 0.5s;
}
.container .box:hover .icon .fa {
font-size: 40px;
}
.container .box .content {
position: absolute;
top: 100px;
height: calc(100% - 100px);
padding: 20px;
box-sizing: border-box;
transition: 0.5s;
text-align: center;
width: 100%; /* ADDED */
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box">
<div class="icon">
<i class="fa fa-search" aria-hidden="true"></i>
</div>
<div class="content">
<h3>Search</h3>
<p>sadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfen</p>
</div>
</div>
</div>
```
You don't need *positioning* here actually - use `flexbox` and *align* it to the bottom.
1. Remove `height`, the *absolute* `position` and `top` from `content`.
2. Make your `box` a `flexbox` and add `align-items: flex-end` to push it to the bottom.
See demo below:
```css
body {
padding: 0;
margin: 0;
}
.container {
width: 1200px;
overflow: auto;
margin: 240px auto;
background: transparent;
position: relative;
}
.container .box {
position: relative;
float: left;
width: calc(400px - 30px);
height: calc(300px - 30px);
background: yellow;
overflow: hidden;
margin: 15px;
border-radius: 10px;
box-sizing: border-box;
display: flex; /* ADDED */
align-items: flex-end; /* ADDED */
}
.container .box .icon {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
transition: 0.5s;
z-index: 1;
}
.container .box:hover .icon {
top: 20px;
left: calc(50% - 40px);
width: 80px;
height: 80px;
border-radius: 50%;
}
.container .box .icon .fa {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 80px;
color: #fff;
transition: 0.5s;
}
.container .box:hover .icon .fa {
font-size: 40px;
}
.container .box .content {
/*position: absolute;
top: 100px;
height: calc(100% - 100px);*/
padding: 20px;
box-sizing: border-box;
transition: 0.5s;
text-align: center;
width: 100%; /* ADDED */
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box">
<div class="icon">
<i class="fa fa-search" aria-hidden="true"></i>
</div>
<div class="content">
<h3>Search</h3>
<p>sadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfensadfdfoiljwkjfen</p>
</div>
</div>
</div>
```
|
11,323,040 |
Long story short: I want to put an image in a column of a DataTable. To do this, I've gathered from various other sources that I need to convert the image to bytes, and then assign the bytes to the desired DataRow column.
So I've got pretty much exactly what I need, EXCEPT, all the guides I've found are for referencing files on the system. The image I need to convert is within the project.
Here's what I have, abbreviated:
```
DataColumn amountcol = new DataColumn();
amountcol.DataType = System.Type.GetType("System.Byte[]");
//...
newrow = dt.NewRow();
newrow[amountcol] = ReadImage("images/dashboard/myvacstatus-am.png", new string[] { ".png" });
```
---
```
private static byte[] ReadImage(string p_postedImageFileName, string[] p_fileType)
{
bool isValidFileType = false;
try
{
FileInfo file = new FileInfo(p_postedImageFileName);
foreach (string strExtensionType in p_fileType)
{
if (strExtensionType == file.Extension)
{
isValidFileType = true;
break;
}
}
if (isValidFileType)
{
FileStream fs = new FileStream(p_postedImageFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return image;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
```
---
**The problem: it looks for the file on the system, and not within the project.**
I get the following error:
Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\images\dashboard\myvacstatus-ampm.png'.
|
2012/07/04
|
[
"https://Stackoverflow.com/questions/11323040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044866/"
] |
Make sure that the path from which you are reading the image is valid.
**UPDATE**
Get the complete path using the following code.
```
string path = Server.MapPath("images/dashboard/myvacstatus-am.png")
```
|
28,698,883 |
Related with the [third answer from this question,](https://stackoverflow.com/questions/12297169/sublime-text-2-trim-trailing-white-space-on-demand) I would like to refactor this simple plugin so that it works with Sublime Text 3. Please, could you help me? I am new to python, and I don´t know anything about plugin development for sublime.
```
import sublime, sublime_plugin
def trim_trailing_white_space2(view):
trailing_white_space2 = view.find_all("[\t ]+$")
trailing_white_space2.reverse()
edit = view.begin_edit()
for r in trailing_white_space2:
view.erase(edit, r)
view.end_edit(edit)
class TrimTrailingWhiteSpace2Command(sublime_plugin.TextCommand):
def run(self, edit):
trim_trailing_white_space2(self.view)
```
I have searched and the problem is `begin_edit()` and `end_edit()`. I don´t want to install a plugin just for triggering trailing white space on demand. Thanks a lot, best regards.
|
2015/02/24
|
[
"https://Stackoverflow.com/questions/28698883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201840/"
] |
Working on ST3.
```
import sublime, sublime_plugin
class TrimTrailingWhiteSpace2Command(sublime_plugin.TextCommand):
def run(self, edit):
trailing_white_space = self.view.find_all("[\t ]+$")
trailing_white_space.reverse()
for r in trailing_white_space:
self.view.erase(edit, r)
class TrimTrailingWhiteSpace2(sublime_plugin.EventListener):
def run(self, view):
view.run_command("trim_trailing_white_space2")
```
|
59,525,272 |
I am replicating this webpage <https://www.modsy.com/project/furniture> and I wrote the code On every slide there will be changing of image and phrase like that there are three phrases and images now I want to store the image and phrase in the local storage what the user has finalized
My html code is:
```
<div class="image mt-3 mb-3" id="sliderImages">
<img src="../static/images/1.jpg" width="400" height="180">
<img src="../static/images/2.jpg" width="400" height="180">
<img src="../static/images/3.jpg" width="400" height="180">
</div><br>
<div class="rangeslider">
<input type="range" min="1" max="3" value="1" class="myslider" id="sliderRange">
<div id="sliderOutput">
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
</div>
<div class="row mb-3 mt-3">
<div class="col-4 mr-5">
<a href="/car" class="previous">« Home</a>
</div>
<div class="col-4 ml-5">
<a href="/car/project4" class="next" id="room_next">Next »</a> </div>
</div>
</div>
```
My CSS code is:
```
<style>
.rangeslider {
width: 50%;
margin: 0 auto;
position: absolute;
}
.myslider {
-webkit-appearance: none;
background: white;
width: 100%;
height: 20px;
opacity: 0.8;
margin-top: 180px;
}
.myslider::-webkit-slider-thumb {
-webkit-appearance: none;
cursor: pointer;
background: #000080;
width: 33%;
height: 20px;
}
.col-4 {
text-align: center;
}
.myslider:hover {
opacity: 1;
}
.image {
position: relative;
width: 400px;
margin: 0 auto;
}
.image>img {
position: absolute;
display: none;
}
.image>img.visible,
.image>img:first-child {
display: block;
}
#sliderOutput>div {
display: none;
}
#sliderOutput>div.visible,
#sliderOutput>div:first-child {
display: block;
}
#p1{
height: 10px;
}
</style>
```
My JS code is:
```
<script>
window.addEventListener('load', function() {
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("sliderOutput");
var images = document.getElementById("sliderImages");
rangeslider.addEventListener('input', function() {
for (var i = 0; i < output.children.length; i++) {
output.children[i].style.display = 'none';
images.children[i].style.display = 'none';
}
i = Number(this.value) - 1;
output.children[i].style.display = 'block';
images.children[i].style.display = 'block';
});
});
</script>
```
My main requirement if the slider is in the first that phrase and image should be stored in local storage like that if it is in second that details should store.
|
2019/12/30
|
[
"https://Stackoverflow.com/questions/59525272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12557362/"
] |
As suggested by @Deadpool (great name!):
```
import java.util.*;
class Playground {
public static void main(String[ ] args) {
Optional<String> startingOptional = Optional.ofNullable(null);
List<String> finishingValue =
startingOptional
.map(value -> Arrays.asList(value.split(",")))
.orElseGet(() -> {
System.out.println("value not found");
return new ArrayList<String>();
});
System.out.println("finishingValue: " + finishingValue);
}
}
```
|
1,708,917 |
How many five digit integers (base-10 numeral system)
a) start with a $9$?
b) contain a $9$?
c) do not contain a $9$?
For a) I think its $10000$; we already have the first number $9$ and we need to find the rest of $4$ numbers. Each number has $10$ ways so $10 \times 10 \times 10 \times 10 = 10000$.
Part b and c I don't understand. Please explain.
|
2016/03/22
|
[
"https://math.stackexchange.com/questions/1708917",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/324261/"
] |
A) start with 9: $1\times 10\times 10\times 10\times 10 = 10^4 = 10000$. (One choice for the first digit ten for all the others)
C) has no 9s: $8\times 9\times 9\times 9\times 9 = 8\times 9^4 = 52488$. (Nine choices for each of the digits except the first that can't be zero).
Z) how many five digits numbers total are there: $9\times 10\times 10\times 10\times 10 = 9\times 10^5 = 90000$. (9 for the first digit as we cant start with 0. Well... we *can* and we'd have 100000 and that'd be fine but then I'd have to deal with nitpickers and you *will* have questions where leading zeros will be excluded so we'll deal with those now)
B1) How many with at least 1 nine: Z - C = $90000 - 52488 = 37512$.
B2) How many with exactly 1 nine: Start with 9 + Second is 9 + .... + ends with 9 = $1\times 10\times 10\times 10\times 10 + 9\times 1\times 10\times 10\times 10 + ... 9\times 10\times 10\times 10\times 1 = 10000 + 4\times 9\times 10\times 10\times 10 = 36000$
|
33,658,829 |
I'm trying to create my own localized version of Date object. I know there's a method called `toLocaleDateString()` which has a locale parameter for example in order to display date with Arabic calendar we just need to set locale argument:
```
.toLocaleDateString('ar-EG')
```
Now my question is that How can I override this behavior to display my own calendar with its locale format?
|
2015/11/11
|
[
"https://Stackoverflow.com/questions/33658829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5220681/"
] |
It is considered very bad practice to override a native method like this, but since you asked:
```
Date.prototype.toLocaleDateString = function () {
// Your custom function
}
var foo = new Date();
foo.toLocaleDateString();
```
|
506,082 |
I am currently dual-booting Windows 8 and Ubuntu 14.04, and would like to get some familiarity with linux server admin. I plan to install CentOS and maybe host a small website or something. What will happen to grub after installing CentOS?
|
2014/08/03
|
[
"https://askubuntu.com/questions/506082",
"https://askubuntu.com",
"https://askubuntu.com/users/227490/"
] |
You'll need to reinstall/update grub. I had the same issue after installing CentOS 6.4 on top of my Ubuntu 14.04. Following this post fix my problem:
<http://muthusaravananmca.wordpress.com/2010/09/29/ubuntu-grub-recover-after-installing-centos-or-windows/>
(Just to clarify that in Step 4: use "--root-directory ...")
Hope it helps.
|
3,211,945 |
in regards to [how can i know if a student was in the campus? edit: using first order logic(logic)](https://math.stackexchange.com/questions/3208387/how-can-i-know-if-a-student-was-in-the-campus-edit-using-first-order-logiclog/3208475#3208475), which dealt with inferring, i am asking here assistance with formalizing the sentences with the following emphasis:
* closed world emphasis(What is not currently known to be true, is false)
* domain closure(There are no more domain elements than those
named by constant symbols)
did i do the following correctly?
1. every professor counsels at least one student
$\forall x,y(C(x,y) \land \forall x,y -> (x=p \land y=(\exists S(s)))$
2. Helen is a professor
$\exists x(P(x) \land x-> x='Helen')$
3. every student has a counselor, who is a professor
$\forall x,y(H(x,y) \land \forall x,y(x=s \land y=c) \land c -> p)$
4. counseling meeting occur at the campus
$\exists x,y(occurs(x,y) \land \forall x,y ((x=m \land i) \land y = u)$
5. Leno is a student
$\exists x(S(x) \land x -> x= s \land x='Leno')$
6. every counselor meets with all of his counselees(the ones he counsels)
new attempt: $\forall x,y((P(x) \land S(y) \land C(x,y) -> M(x,y))$
$\forall x,y(M(x,y) \land x=c \land M(x,y) -> y=h )$ (e counselor meets with all of his counselees, and if he meets someone it must be his counselee)
where:
S(x) - x is a student
P(x) - x is a professor
C(x,y) - x counsels y
M(x,y) - x meets with y
O(x,y) - x occurs at y
H(x,y) - x has y
p - a professor
s - a student
c - a counselor
m - a meeting
h - a counselee
i - a counseling
u - a campus
would appreciate your input and corrections. some where quite complicated for me.
thank you very much for helping
(note, as mentioned, those 2 questions are different in their subject. here the subject is converting the sentences into first order logic under the given assumptions(closed world and domain closure) whereas the other was about inferring)
|
2019/05/03
|
[
"https://math.stackexchange.com/questions/3211945",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/659796/"
] |
First of all some general comments:
1) You are erroneously conflating constant names with variables.
**Constant names** like $h$ or $l$ are used to refer to particular individuals (like Helen or Leno). Their meaning is fixed and given by the model's interpretation function, which is why they belong to the non-logical symbols (= the symbols that are specific to a particular predicate logic language and whose meaning needs to be defined) and you have to provide a translation key from them.
**Variables**, on the other hand, as used with quantifiers, usually named $x, y, z, ...$ belong to the logical symbols (= the symbols that are common to all predicate logic languages, and whose meaning is not determined by an interpretation function). Variables are called variables because other than constants, their meaning (= the object they refer to) is not fixed (as the meaning of the name $h$ or $l$ would be), but varies depending on what the chosen assignment function maps them to. The meaning of a variable is given by the local context, such as a universal or existential quantification; for these reasons, you do *not* provide a translation key for variables.
The only particular, specified, fixed individuals you need refer to in this assignment are Helen and Leno, hence $h$ and $l$ are the only constant sybmols you need to use, and the only ones you have to provide a translation key for. All other occurences of terms, such as the quantification over all professors or some students, are variables, which have no place in the translation key.
2) **The name of constant names or variables does not say anything about what they refer to.**
The naming of constant names is arbitrary: As a constant name for Helen you could choose $leno$ and as a constant name for Leno you could choose $helen$, or $cheesecake$ or whatever you want. The name does not say anything about its meaning. The only thing that determines what $helen$ or $leno$ refer to is the interpretation you specify in the translation key.
Likewise, the naming of variables is arbitrary: You could call a variable named $x$ $y$ instead or $u$ or $blah$ or whatever you want; their interpreation does not depend on the name given. The only thing that determines what a variable refers to is the assignment function.
If often make sense to choose mnemnoic names, to make it easier to see what your symbols refer to, e.g. to choose $h$ or $helen$ as a constant name for Helen, or (less commonly done) choose mnemonic names for variables, e.g. $p$ if with $p$ you quantify over the set of professors. But such a name choice alone does not have any consequences on their interpreation.
**This means that in a formula like $\forall p \exists s (C(p,s))$, the variables $p$ and $s$ are not restricted to any domain**: $p$ and $s$ are just variables that could stand for anything, so $\forall p \exists s (C(p,s))$ means "Everyone counsels someone". If you want a restriction, you need to make that explicit: "Every professor counsels some student" has to be formalize as $\forall p(P(p) \to \exists s (S(s) \land C(p,s))$, or equivalently $\forall x(P(x) \to \exists y (S(y) \land C(x,y))$, since the name of the variables doesn't matter.
---
This is the key for the non-logical symbols that I would choose:
Predicates (= properties of and relations between individuals):
* $P(x)$ = x is a professor
* $S(x)$ = x is a student
* $C(x,y)$ = x counsels y
* $M(x,y)$ = x meets with y
* $A(x)$ = x is at the campus
Constant symbols (= names that refer to particular individuals):
* $h$ = Helen
* $l$ = Leno
Function symbols: none
---
>
> 1. Every professor counsels at least one student
>
>
> $\forall x,y(C(x,y) \land \forall x,y -> (x=p \land y=(\exists S(s)))$
>
>
>
$\forall xy(C(x,y)) \land ...)$ means "Everyone counsels everyone." This is wrong because a) every profesor counsels only at least one student, not all of them and b) the domains are not restricted to the professors and students.
I don't know what you mean by the rest of your formula behind $\land$, it's not even syntactically correct, i.e. simply not a predicate logic formula at all.
$\forall x,y -> (...)$ is not syntactically correct: $\to$ expects a formula on its left-hand side, but there is not any formula $\forall x,y$ quantifies over.
$y=(\exists S(x)))$ is not syntactically correct either. $=$ expects a term to its right-hand side, but $\exists S(s)$ is not a term. It is not even a formula, because the variable behind the quantifier is mising.
Instead, the sentence is
>
> For every $x$ which is a professor, there exists some $y$ such that $y$ is a student and $x$ counsels $y$
>
>
>
which is translated as
>
> $\forall x(P(x) \to \exists y(S(y) \land C(x,y))$
>
>
>
---
>
> 2. Helen is a professor
>
>
> $\exists x(P(x) \land x-> x='Helen')$
>
>
>
Again, this is not a formula, because again, $\to$ expects a formula to its left-hand side, but $x$ is not a formula, but a term.
I suppose you wanted to say
>
> There is a professor, and this professor is Helen
>
>
> $\exists x(P(x) \land x = h)$
>
>
>
which could be abbreviated to just
>
> Helen is a professor
>
>
> $P(h)$
>
>
>
---
>
> 3. every student has a counselor, who is a professor
>
>
> $\forall x,y(H(x,y) \land \forall x,y(x=s \land y=c) \land c -> p)$
>
>
>
Your formula says "Everyone has everyone and everyone is identical to s (which you want to be some constant name that refers to some student?) and everyone is identical to c (again, a constant name that refers to some undspecified counselor)" and the rest behind the $\land$ is, again, not even a proper formula, because neither $c$ nor $p$ are formulas, so you can't $\to$ them. This formula doesn't make sense at all.
Hint: The sentence can be paraphrased as
>
> For every $x$ who is a student, there is a $y$ such that $y$ is a professor and counsels them.
>
>
>
This is very similar to 1. Try to correct your formula along the lines of this explanation.
---
>
> 4. counseling meeting occur at the campus
>
>
> $\exists x,y(occurs(x,y) \land \forall x,y ((x=m \land i) \land y = u)$
>
>
>
This one is a bit tricky, but let me first translate what your formula says:
"There are x and y such that x occurs at y, and all x are identical to m (a constant for a particular but in your translation key not further specified meeting), and i??? (not a formula) and all y are identical to u (a constant which refers to a particular but unspecified campus)." I don't even what you want to say with this.
Instead, one could paraphrase "All meetings occur at the campus" as
>
> For all pairs of x and y where x has a meeting with y, x is at the campus and y is at the campus
>
>
>
which, according to the translation key above, would be formalized as
>
> $\forall x,y(M(x,y) \to A(x) \land A(y))$
>
>
>
---
>
> 5. Leno is a student
>
>
> $\exists x(S(x) \land x -> x= s \land x='Leno')$
>
>
>
This statement is nowhere needed to derive the desired inference, but the problems are the same as before and the correct solution completely analogous to 2. Try correcting this one according to the previous explanations.
---
>
> 6. every counselor meets with all of his counselees(the ones he counsels)
>
>
> $\forall x,y(M(x,y) \land x=c \land M(x,y) -> y=h )$ (e counselor
> meets with all of his counselees, and if he meets someone it must be
> his counselee)
>
>
>
No, this is not what your formula says. Your formula says "Everyone meets with everyone (you didn't restrict the x to the counselors and the y to the students they counsel) and all x are identical to a particular counselor c and if x meets y, then y is identical to Helen."
Instead, your formlua should be
>
> For all $x$ and $y$, if $x$ is a professor and $y$ is a student and $x$ counsels $y$, then $x$ meets $y$.
>
>
>
Try to find the formalization for this one, and feel free to update your post with your revised version for feedback.
|
9,167,083 |
I have a dictionary collection of more than 100 fields and values. Is there a way to populate a gigantic class with a 100 fields using this collection?
The key in this dictionary corresponds to the property name of my class and the value would be the Value of the Property for the class.
```
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("MyProperty1", "Hello World");
myDictionary.Add("MyProperty2", DateTime.Now);
myDictionary.Add("MyProperty3", true);
```
Populates the properties of the following class.
```
public class MyClass
{
public string MyProperty1 {get;set;}
public DateTime MyProperty2 {get;set;}
public bool MyProperty3 {get;set;}
}
```
|
2012/02/06
|
[
"https://Stackoverflow.com/questions/9167083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56509/"
] |
You can use [`GetProperties`](http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx) to get a list of properties for a given type and use [`SetValue`](http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx) to set a specific value for a given property:
```
MyClass myObj = new MyClass();
...
foreach (var pi in typeof(MyClass).GetProperties())
{
object value;
if (myDictionary.TryGetValue(pi.Name, out value)
{
pi.SetValue(myObj, value);
}
}
```
|
188,090 |
Given directed graph $G=(V,E)$, two vertices and a weights function $w: E \to R$. In addition we know that there aren't negative cycles in $G$. I need to find a linear algorithm that finds among the shortest paths by edges from $s$ to $t$ the shortest path by weight.
I can find the graph of all shortest paths from $s$ to $t$ by two BFS (for $s$ and from $t$ on $G^T$- a version of BFS which does not get rid of edges of subsequent levels), but then how do I find in linear time the shortest path by weight? I need to use Bellman-Ford for that, no?
Thanks a lot.
|
2012/08/28
|
[
"https://math.stackexchange.com/questions/188090",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14829/"
] |
All the shortest paths by edges have the same length, so if you add $w$ to every edge it won't change the shortest path by weight. Choose a large enough $w$ so that every edge is positive, and then run Dijkstra's algorithm. (But this would still not quite be linear, since Dijkstra's algorithm runs in $O(\lvert E\rvert + \lvert V\rvert\ {\rm log}\ \lvert V\rvert)$).
|
9,744,264 |
This may be a basic PHP syntax question, but I could not get any results from search. So, in warning or error messages, what does actually "parameter 1" mean? Like in this example:
```
Warning: imagecopyresized() expects parameter 1 to be resource, integer given in ...
```
It is not to solve this special warning, but my question is, to what parameter 1 refers to. Is it imagecopyresized(parameter1,parameter2,...)? Or are these called arguments? I could not really understand the wikipedia article about parameters ([http://en.wikipedia.org/wiki/Parameter\_(computer\_programming)](http://en.wikipedia.org/wiki/Parameter_%28computer_programming%29))
|
2012/03/16
|
[
"https://Stackoverflow.com/questions/9744264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1201551/"
] |
The terms *arguments* and *parameters* are used interchangeably. Take a look at [this](http://php.net/manual/en/functions.arguments.php) php page which talks about them and you will notice they use both terms.
|
26,445,012 |
I am having problems increasing the prices of my hp products by 10%.
Here is what I've tried -->>
```
UPDATE products SET price = price*1.1;
from products
where prod_name like 'HP%'
```
Here is a picture of the products table:

|
2014/10/18
|
[
"https://Stackoverflow.com/questions/26445012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4034715/"
] |
This is your query:
```
UPDATE products SET price = price*1.1;
from products
where prod_name like 'HP%'
```
It has one issue with the semicolon in the second row. Also, it is not standard SQL (although this will work in some databases). The standard way of expressing this is:
```
update products
set price = price * 1.1
where prod_name like 'HP%';
```
The `from` clause is not necessary in this case.
|
29,816,396 |
In my android application I'm receiving a JSONArray and I'm parsing it and storing it in a arraylist and appending that to listview but I'm facing an error entire list is showing in a single list item.but I'm receiving 4 items.This is all what I did.
```
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("topicsJSON",composeJSON());
client.post("http://www.example.com/load_topics.php",params,newAsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
Gson gson = new GsonBuilder().create();
try
{
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Throwable error,String content)
{
if (statusCode == 404)
{
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
else if (statusCode == 500)
{
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
private String composeJSON() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> check_in_List;
check_in_List = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("subject_code",received_subject_code);
check_in_List.add(map);
Gson gson = new GsonBuilder().create();
return gson.toJson(check_in_List);
}
public void load_data()
{
ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
l1.setAdapter(phy);
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String pos = (String) l1.getItemAtPosition(position);
});
}
```
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29816396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4659323/"
] |
>
> I'm facing an error entire list is showing in a single list item.but
> I'm receiving 4 items
>
>
>
Because calling `load_data();` inside `for-loop` which is used for getting data from `JSONArray` in `ArrayList`
Move `load_data();` outside `for-loop` to show each item in separate row in ListView
|
15,989,577 |
On the SQL below it finds "bad rows" in my excel sheet and copies them into another table.
This works perfect. However under each OR satement below i want to make the column "rejectionreason" = some error text.
So for example if the eventID was = 0 then move the row to the table but also update the column "rejectionreason" to the text "Error the eventID was equals to 0".
I also need to do similar for all the other OR statements below.
How can i do this
**SQL**
```
REPLACE INTO InvalidBaseDataTable SELECT * FROM BaseDataTable where dateTime = '0000-00-00 00:00:00'
OR eventId = 0
OR ueType = 0
OR eventId NOT IN (SELECT DISTINCT(eventId) FROM EventCauseTable)
OR causeCode < (SELECT MIN(causeCode) FROM EventCauseTable)
OR causeCode > (SELECT MAX(causeCode) FROM EventCauseTable)
OR ueType NOT IN (SELECT DISTINCT(tac) FROM UeTable)
OR
(eventId NOT IN (SELECT DISTINCT(eventId) FROM EventCauseTable)
AND
causeCode NOT IN (SELECT DISTINCT(causeCode) FROM EventCauseTable))
```
|
2013/04/13
|
[
"https://Stackoverflow.com/questions/15989577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438082/"
] |
You could try something like:
```
REPLACE INTO InvalidBaseDataTable
SELECT *, CASE
WHEN dateTime = '0000-00-00 00:00:00' THEN 'datetime equal to 0'
WHEN eventId = 0 THEN 'eventId equal to 0'
WHEN ueType = 0 THEN 'ueType equal to 0'
ELSE 'All good'
END AS rejectionreason
FROM BaseDataTable WHERE dateTime = '0000-00-00 00:00:00'
OR eventId = 0
OR ueType = 0
OR eventId NOT IN (SELECT DISTINCT(eventId) FROM EventCauseTable)
OR causeCode < (SELECT MIN(causeCode) FROM EventCauseTable)
OR causeCode > (SELECT MAX(causeCode) FROM EventCauseTable)
OR ueType NOT IN (SELECT DISTINCT(tac) FROM UeTable)
OR (eventId NOT IN (SELECT DISTINCT(eventId) FROM EventCauseTable)
AND
causeCode NOT IN (SELECT DISTINCT(causeCode) FROM EventCauseTable))
```
|
11,355,393 |
I'm trying to find the lat/long of the Sydney Opera House using either the Google maps API or the Google Places API. But neither return anything like it, despite the fact that Google Maps from the browser instantly finds the correct result.
I'm using these URL's:
<http://maps.googleapis.com/maps/api/geocode/json?sensor=false&bounds=-28.729,153.984|-36.102,142.470&address=OPERA%20HOUSE>
and
<https://maps.googleapis.com/maps/api/place/search/json?location=-33.9179,151.2333&radius=5000&sensor=false&name=opera%20house&key=>{secret}
Google Maps API returns 3 places in China & USA, and Google Places API returns "ZERO\_RESULTS". You'll excuse me for not including my Google Places key. The lat/long are for central Sydney.
Am I doing something wrong, or does Google Maps use a private database which is more complete than the database the API's use?
|
2012/07/06
|
[
"https://Stackoverflow.com/questions/11355393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10592/"
] |
You are right to be skeptical of his solution.
Doubly-Linked list is the easy one. DLLs enforce the invariants:
1. Except for null nodes, a node's left node's right node is itself.
2. Except for null nodes, a node's right node's left node is itself.
3. Noncyclic DLLs will eventually reach a null as you keep following left.
4. Noncyclic DLLs will eventually reach a null as you keep following right.
5. Cyclic DLLs will eventually reach the starting node as you keep following left.
The preceeding is easy to check with only an extra temporary variable, and walking over the DLL.
(Note: checking 3 and 4, or 5 may take a long time.)
Binary Tree is the hard one. BTs enforce the invariants:
1. "No Loops" can be shown by any of the following:
* Demonstrate no two nodes point to the same node and no nodes point to the root.
* Demonstrate that all paths from the root eventually end at a leaf.
* Demonstrate that all referenced nodes are distinct.
2. "No Merges" can be shown by any of the following:
* Demonstrate that no two nodes point to the same node.
* Demonstrate that all referenced nodes are distinct.
As you suggested, these may be determined by traversing the tree and marking each node visited to ensure that no node gets visited twice, or alternatively storing a list of each node visited (such as in a hash-set or other structure) to quickly look-up if the node is distinct.
You could probably validate that there are no loops in the tree without another data structure, by simply traversing the tree and keeping a value of your current depth in the tree, if you got deeper in the tree than there is memory in the computer (or visited more nodes), you would be sure to have an infinite loop.
However, that doesn't help us distinguish Binary "Directed Acyclic Graphs" (DAGs) from Binary Trees.
If, however, we knew the count of elements in the tree, as this is usually the case for Library implementations of binary trees. You could detect an infinite loop by counting the number of edges compared to the previously known number of nodes, like the interviewer suggested.
Without knowing that number ahead of time, it is difficult to know the difference between an infinitely large tree and a large finite tree. (Unless you know the memory size of the computer, or other information like how long it took to make the tree, etc.)
This still does not help us detect the "No Merges" invariant.
I can't think of any useful way to determine that No Merges exist, without showing that no node is referenced twice by either storing visited nodes in an external data structure, or marking each node as visited when you visit it.
As a final resort, you could do the following:
1. Show there are "No Loops" based on the tree depth (or number of visited nodes) compared to computer memory. (or as below, in the edit)
2. Demonstrate "No Merges" through this method.
* Start at root's left child, i.e. depth 1 of the tree.
* Visit every node at depth 1 and depth 0 and verify that only the direct parent references the selected node.
* Do the same for the root's right child.
* Continue this process for each node in the tree:
1. select a node, keeping a reference to its direct parent,
2. visit every node higher in the tree and at the same depth as the selected node,
3. verify that out of the visited nodes, only the direct parent references the selected child.
* Once this is done, traverse the tree again to verify that the left and right pointers from every node do not both point to the same node.
This process would only take a few extra variables, but would take a lot of time, since you individually compare each node to every node higher or at the same depth in the tree.
My intuition tells me that the above procedure would a v-squared algorithm, instead of just being order v.
Add a comment if any of you think of another way to approach this.
---
Edit: you may be able to verify the "No Loops" here by simply extending the search to not just every node at same depth and higher, but comparing with every node in the tree. You would need to do this in a progressive algorithm, compare each node with every node above it in the tree and its own depth, then check against all nodes in the tree from 1 to 5 nodes deeper than it, then from 6-10 generations lower, and so forth. If you check in a non-progressive way, you could get stuck searching infinitely.
|
59,642,410 |
I have two blocks. First one is wizard and second is manual in Oracle Forms 11g with relational.
I execute the data into first block and I want to press in foreign key in first table and the second table appear data which is link together by the same number foreign key?
Which trigger should I use please? And which code should I put into trigger?

|
2020/01/08
|
[
"https://Stackoverflow.com/questions/59642410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12673705/"
] |
You can use `WHEN-NEW-RECORD-INSTANCE` trigger at block level of `Block1` with code :
```
declare
v_skulist table1.skulist%type;
begin
v_skulist := :Block1.f_skulist; --> represents left uppermost field
go_block('Block2');
execute_query;
go_block('Block1'); --> go back to the upper block again, if don't want to come back, then starting from this line upto `end;`(exclusive) should be removed.
while v_skulist != :Block1.f_skulist
loop
next_record;
end loop;
end;
```
where
* `Query Data Source Name` property is set to `table1` for `Block1`
and
* `Query Data Source Name` property is set to `myuser1.table2` with
`WHERE Clause` set to
`skulist = :Block1.skulist` for `Block2`
assuming the second table is on the other user at least
with granted `select` privilege to your current user as mentioned in your comment.
This way, whatever record touched in the first block, the counterpart foreign key column is brought in the second block.
|
163,066 |
I have a [Multilingual Drupal 7 site](http://landberg.at) using [i18](https://www.drupal.org/project/i18n).
But how do I get my homepage meta Title and description translated?
|
2015/06/24
|
[
"https://drupal.stackexchange.com/questions/163066",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/39848/"
] |
I tried almost every possible scenarios,
The best thing for me was use of [Oauth2 server](https://www.drupal.org/project/oauth2_server) module for master site to act as authentication server and [OpenID Connect](https://www.drupal.org/project/openid_connect) module for other sites which use out-of-box authentication.
This solution can be done without needing to merge databases, or host sites on same server, or periodic synchronization. the only challenge I have is that authentication server must use **https**, and I'm going to buy certificate for my host.
|
1,959 |
In the inline math mode (`$...$`), if the formula is too long, LaTeX will try to break it on operators, e.g.
```
very long text followed by a very long equation like $a+b+c+d+e+f+g+h+i+j+k+l$ etc
```
may be rendered as
```
very long text followed
by a very long equation
like a+b+c+d+e+f+g+h+i+
j+k+l etc
```
However, the break won't happen if they are separated by commas, e.g.
```
very long text followed by a very long equation like $a,b,c,d,e,f,g,h,i,j,k,l$ etc
```
will overflow the page like
```
very long text followed
by a very long equation
like a,b,c,d,e,f,g,h,i,j,k,l
etc
```
How to make LaTeX able to insert line breaks after a comma too?
|
2010/08/18
|
[
"https://tex.stackexchange.com/questions/1959",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/82/"
] |
If the expression contains many commas then consider to break it into several math expressions, separated by commas. It reads like a list of math expressions. This way TeX can break the line.
To achieve line breaks after a comma, you could insert `\allowbreak` after the comma and before the next math symbol. If necessary, leave a blank after `\allowbreak`.
If you would like to have a document wide solution, you could redefine the comma. One solution, following the tip [here](http://users.ugent.be/~gdschrij/LaTeX/textricks.html#mathcommabreak) would be:
```
\makeatletter
\def\old@comma{,}
\catcode`\,=13
\def,{%
\ifmmode%
\old@comma\discretionary{}{}{}%
\else%
\old@comma%
\fi%
}
\makeatother
```
|
15,231,165 |
I'm extremely unfamiliar with VB6 so please excuse the rookie question:
I'm attempting to turn a long into it's component bytes. In C it is simple because of the automatic truncation and the bitshift operators. For the life of me I cannot figure out how to do this in VB6.
Attempts so far have all generally looked something like this
```
sys1 = CByte(((sys & &HFF000000) / 16777216)) ' >> 24
sys2 = CByte(((sys & &HFF0000) / 65536)) ' >> 16
```
sys1 and sys2 are declared as `Byte` and sys is declared as `Long`
I'm getting a type mismatch exception when I try to do this. Anybody know how to convert a `Long` into 4 `Byte`s ??
Thanks
|
2013/03/05
|
[
"https://Stackoverflow.com/questions/15231165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378087/"
] |
You divide correctly, but you forgot to mask out only the least significant bits.
Supply the word you want to divide into bytes, and the index (0 is least significant, 1 is next, etc.)
```
Private Function getByte(word As Long, index As Integer) As Byte
Dim lTemp As Long
' shift the desired bits to the 8 least significant
lTemp = word / (2 ^ (index * 8))
' perform a bit-mask to keep only the 8 least significant
lTemp = lTemp And 255
getByte = lTemp
End Function
```
|
26,948,723 |
I am trying to read a number character with character, but I don't know if the stdin buffer is empty or not.
My first solution whas to look for `\n` character in stdin buffer, but this is no good if I what to enter multiple numbers separated by `" "`.
How can I know if in stdin buffer I have characters or not?
I need to do it in C and to be portable.
|
2014/11/15
|
[
"https://Stackoverflow.com/questions/26948723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3281352/"
] |
There are several soutions:
[poll](http://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html) or [select](http://pubs.opengroup.org/onlinepubs/9699919799/functions/select.html) with timeout of 0 - these would return immediately and result is either -1 with errno `EAGAIN` if no data available or number of descriptors with data (one, since you're checking only stdin).
[ioctl](http://pubs.opengroup.org/onlinepubs/9699919799/functions/ioctl.html) is a swiss army knife of using descriptors. The request you need is `I_NREAD`:
```
if (ioctl(0, I_NREAD, &n) == 0 && n > 0)
// we have exactly n bytes to read
```
However the correct solution is to read everything you got (using `scanf`) as a line, then process the result - and this works good enough with `sscanf`:
```
char buf[80]; // large enough
scanf("%79s", buf); // read everything we have in stdin
if (sscanf(buf, "%d", &number) == 1)
// we have a number
```
... as long as you properly handle re-reading, strings that are longer than your buffer, and other real-life complications.
|
2,765,073 |
I'm writing an ant script to rebuild our database i.e. dropping everything and rebuilding from scratch. The problem our DBA adds a Y/N prompt before executing the rest of the script, and therefore we can't call this from an automated build process.
Does anyone have any suggestions to circumvent the Y/N prompt? Obviously we could create separate scripts, one for the DBA's and one for the automated build - but this requires maintaining both. We're running on Windows so it's not as easy as using sed to strip out the prompt...but I'm thinking something along those lines.
Not sure if that's clear enough but hope you can help.
Cheers.
|
2010/05/04
|
[
"https://Stackoverflow.com/questions/2765073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150199/"
] |
Maybe Expect would help?
<http://en.wikipedia.org/wiki/Expect>
|
10,420 |
For favors that I am making for an upcoming party, I'm looking to do some old-fashioned homemade gum drops. I have found [a recipe](http://www.grouprecipes.com/48760/homemade-gum-drops.html) that looks do-able. It calls for candy flavoring. I've also found other recipes that call for using [juice](http://homecooking.about.com/od/candyrecipes/r/bldes53.htm), which rather limits the flavors to the flavor of juice that I purchase.
In looking at my local stores, I cannot find anything in their online product lists indicating that they have candy flavoring, even those that carry Wilton products. I like the idea of candy flavoring for the variety, but am unsure about finding it.
**Are there pros and cons to using candy flavoring for gummy candy that I should be aware of** in making the decision of juice versus specific flavoring? **Are their alternate ways of flavoring** that I should be considering besides what I've seen in recipes so far?
|
2010/12/22
|
[
"https://cooking.stackexchange.com/questions/10420",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/1816/"
] |
I would go for the juice if you are going for a fruit flavor. A pure ingredient like a fruit juice will always give a better flavor than pre-made flavorings. That said, when you do need a more difficult flavoring, I would recommend using oils, as has been suggested. You can find oil-based flavors in an almost infinite number of flavors:
<https://www.lorannoils.com/c-6-super-strength-flavors-candy-oils.aspx>
(I haven't tried these, but they have been recommended to me for use in chocolate.)
|
1,423,777 |
I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?
|
2009/09/14
|
[
"https://Stackoverflow.com/questions/1423777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161562/"
] |
Let's pretend you have HTML like this
```
<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />
```
For client-side validation, here's some Javascript to check which one is selected:
```
if(document.getElementById('gender_Male').checked) {
//Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
//Female radio button is checked
}
```
The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.
---
If you're just looking to see if **any** radio button is selected **anywhere** on the page, [PrototypeJS](http://www.prototypejs.org/) makes it very easy.
Here's a function that will return true if at least one radio button is selected somewhere on the page. Again, this might need to be tweaked depending on your specific HTML.
```
function atLeastOneRadio() {
return ($('input[type=radio]:checked').size() > 0);
}
```
---
For server-side validation *(remember, you can't depend entirely on Javascript for validation!)*, it would depend on your language of choice, but you'd but checking the `gender` value of the request string.
|
30,327,878 |
I'm implementing a page where we want to use srcset. The problem is that i want the image to render with default size, without setting its width.
It seems this is not possible on Chrome/FF. Surprisingly IE11 is showing this as I thought it should..
Take a look at this example:
```
<img src="http://www.komplett.no/img/p/200/F359034.jpg" srcset="http://www.komplett.no/img/p/200/F359034.jpg 200w,
http://www.komplett.no/img/p/200/F359034.jpg 200w ">
```
<http://jsfiddle.net/goa3xu5f/>
Here you see that the image will take as much width as possible, even though the image is much smaller.
If you don't set srcset it load with its initial size:
```
<img src="http://www.komplett.no/img/p/200/F359034.jpg">
```
<http://jsfiddle.net/g7j6fgd2/>
I dont know if this is a bug or not, but does anyone know how I can use srcset and still show the image as it's original size and not with the browser scaling it up?
|
2015/05/19
|
[
"https://Stackoverflow.com/questions/30327878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037338/"
] |
You should name your "new" field 'birth\_date' or 'dob' or anything other than 'birthday' just to avoid changing existing field data type. In next step you can copy values from current 'birthday' field to new one (through postgresql).
|
32,570,144 |
I think i have been looking at this to long.. I have 2 gridviews with data. I want to loop through them and send each item to a stored procedure. That stored procedure checks for duplicates and sends back 1 if they exists and 0 if they don't. Well when I do the for each loop.. I get stuck. I have tried moving things around with no luck.. Here is my code:
```
public int IsExists()
{
foreach (GridViewRow row in gvSerials.Rows)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("usp_InsertReceiptSerials", con))
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.Add("@ITEMNMBR", SqlDbType.Char).Value = OpenDescription.SelectedRow.Cells[5].Text.Trim();
cmd.Parameters.Add("@RecLineID", SqlDbType.Int).Value = int.Parse(OpenDescription.SelectedRow.Cells[1].Text.Trim());
cmd.Parameters.Add("@RCPTLNNM", SqlDbType.Int).Value = int.Parse(OpenDescription.SelectedRow.Cells[8].Text.Trim());
cmd.Parameters.Add("@POPRCTNM", SqlDbType.Char).Value = OpenDescription.SelectedRow.Cells[4].Text.Trim();
cmd.Parameters.Add("@SERLTNUM", SqlDbType.Char).Value = row.Cells[0].Text.Trim();
SqlParameter parm = new SqlParameter("@IsExists", SqlDbType.Int);
parm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
return IsExists();
if (IsExists() == 1) {
MessageBox.Show("Serials Already Exists!!");
Response.Redirect("Index.aspx"); }
else if (IsExists() == 0) {
MessageBox.Show("Serial Numbers have been updated.", "Important Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Response.Redirect("Index.aspx"); }
}
```
Here is the stored proc:
```
ALTER PROCEDURE [dbo].[usp_InsertReceiptSerials]
@POPRCTNM CHAR(17), @ITEMNMBR CHAR(31), @SERLTNUM CHAR(21), @RecLineID INT, @RCPTLNNM INT, @IsExists INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @RecCount INT
-- DECLARE @IsExists INT
IF EXISTS (SELECT * FROM dbo.vwSerialNumbers WHERE SERLNMBR = Right(@SERLTNUM,20) AND ITEMNMBR = @ITEMNMBR)
BEGIN
SET @IsExists = 1
END
ELSE
BEGIN
INSERT INTO dbo.usr_ReceiptSerials(POPRCTNM, ITEMNMBR, SERLTNUM, FullSerialNumber, EntryDate, RecLineID, RCPTLNNM)
VALUES (@POPRCTNM, @ITEMNMBR, Right(@SERLTNUM,20), @SERLTNUM, GetDate(), @RecLineID, @RCPTLNNM)
SET @RecCount = (SELECT COUNT(*) FROM dbo.usr_ReceiptSerials WHERE RecLineID = @RecLineID)
UPDATE dbo.usr_ReceiptLine SET QTYSHPPD = @RecCount
WHERE RecLineID = @RecLineID
SET @IsExists = 0
END
END
```
|
2015/09/14
|
[
"https://Stackoverflow.com/questions/32570144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5277308/"
] |
I can see a simple recursion problem which is causing the stackoverflow.
```
=> return IsExists();
```
In your returns staement you're calling the same function. Remove this line if this is not part of any business logic.
Also, rather checking `if (IsExists() == 1)`
use:
`int result = cmd.ExecuteNonQuery();`
Then do the evaluation on result:
```
if (result == 1) {
MessageBox.Show("Serials Already Exists!!");
Response.Redirect("Index.aspx"); }
else if (result == 0) {
MessageBox.Show("Serial Numbers have been updated.", "Important Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Response.Redirect("Index.aspx"); }
```
For build error you must return an integer value that method is expecting.
E.g. It could be `result` itself.
>
> Update:
>
>
>
In your case it seems you want to read the value of `Output` parameter. To read an output parameter value from Command object see [this answer](https://stackoverflow.com/a/290676/881798). Then `result` variable would be assigned by the `Output` parameter that you will read from SqlParameter after exeuction of Command.
|
3,975 |
Recently [toxicology](https://chemistry.stackexchange.com/questions/tagged/toxicology "show questions tagged 'toxicology'") has been created, which prompted this question. Originally I wanted to suggest renaming [phamacology](https://chemistry.stackexchange.com/questions/tagged/phamacology "show questions tagged 'phamacology'") into [phamacology-toxicology](https://chemistry.stackexchange.com/questions/tagged/phamacology-toxicology "show questions tagged 'phamacology-toxicology'") as the lines are especially blurry (in terms of chemistry).
>
> Definition of **pharmacology** (from [Merriam-Webster](https://www.merriam-webster.com/dictionary/pharmacology))
>
>
> 1. the science of drugs including their origin, composition, pharmacokinetics, therapeutic use, and toxicology
> 2. the properties and reactions of drugs especially with relation to their therapeutic value
>
>
>
>
> ---
>
>
> Definition of **toxicology** (from [Merriam-Webster](https://www.merriam-webster.com/dictionary/toxicology))
>
>
> 1. a science that deals with poisons and their effect and with the problems involved (such as clinical, industrial, or legal problems)
>
>
>
From the definition I understand, that toxicology is actually a part of pharmacology. Therefore (as the least intrusive action) I would propose merging the tags (or retagging) and create the synonym.
About three years ago, I asked a similar question:
[Merging 'drugs', 'pharmaceuticals', 'pharmacology', 'medicinal-chemistry'](https://chemistry.meta.stackexchange.com/q/454/4945)
At the time we decided to only merge drugs (main) with pharmaceuticals (synonym), but left out pharmacology and medicinal chemistry to revisit later.
As our site has matured quite a bit (we graduated in the meantime) I'd like to revisit this question. I am not en expert on the field and hence I am not sure what to do. Two options were presented at the time:
>
> Klaus-Dieter Warzecha:
>
> As far as the interaction of drugs with living organsims is concerned, medicinal-chemistry seems fully sufficient to cover various aspects, such as uses in folk medicine, metabolism, kinetics, etc. Consequently, pharmacology should be merged into it.
>
>
>
>
> ---
>
>
> Greg E.:
>
> In short, the semantic content and organizational utility of the tag [ref:
> pharmacology] in the context of this site is questionable, I think, but I'm also not sure that it exclusively overlaps strongly enough with any single other tag to make it a synonym.
>
>
>
To add another definition:
>
> Definition of **medicinal chemistry** (Segen's Medical Dictionary. Retrieved from [the free dictionary](https://medical-dictionary.thefreedictionary.com/medicinal+chemistry).)
>
> The discipline involved in discovering and developing new chemical compounds into useful medicines; the analysis, development, preparation, and manufacture of drugs.
>
> Medicinal chemistry begins after biologically validated targets have been screened against a diverse library of compounds and promising initial chemical structures (known as hits) have been identified; the hits are then optimised to improve their therapeutic index—potency vs. toxicity.
>
>
>
>
> ---
>
>
> Definition of **Medicinal chemistry** (from [nature.com](https://www.nature.com/subjects/medicinal-chemistry))
>
> Medicinal chemistry deals with the design, optimization and development of chemical compounds for use as drugs. It is inherently a multidisciplinary topic — beginning with the synthesis of potential drugs followed by studies investigating their interactions with biological targets to understand the medicinal effects of the drug, its metabolism and side-effects.
>
>
>
>
> ---
>
>
> Definition of **Pharmacology** (from [nature.com](https://www.nature.com/subjects/pharmacology))
> Pharmacology is a branch of biomedical science, encompassing clinical pharmacology, that is concerned with the effects of drugs/pharmaceuticals and other xenobiotics on living systems, as well as their development and chemical properties.
>
>
>
>
> ---
>
>
> Definition of **Toxicology** (from [nature.com](https://www.nature.com/subjects/toxicology))
>
> Toxicology is the scientific discipline concerned with the detection, evaluation and prevention of the toxic effects of substances that humans are exposed to. It has a key role in the development of new drugs, which are evaluated for potential toxic effects in preclinical studies, clinical trials and post-marketing studies with the aim of ensuring that their benefits outweigh their risks.
>
>
>
Pharmacology has now gathered 33 questions, medicinal-chemistry is clocking in on 62. Currently only 3 questions are overlapping. I didn't have time to go through all of them, but those I have read (about 20 score>3 questions) could (from my point of view) be reasonably tagged with either of the tags (if they were correctly tagged in the first place).
Given the above definitions and current uses, I suggest again:
**Merge [pharmacology](https://chemistry.stackexchange.com/questions/tagged/pharmacology "show questions tagged 'pharmacology'") and [toxicology](https://chemistry.stackexchange.com/questions/tagged/toxicology "show questions tagged 'toxicology'") into [medicinal-chemistry](https://chemistry.stackexchange.com/questions/tagged/medicinal-chemistry "show questions tagged 'medicinal-chemistry'"), keeping synonyms alive.**
>
> *Editorial Notice: As of 27th of November 2017 the proposal is declined.*
>
>
>
|
2017/11/06
|
[
"https://chemistry.meta.stackexchange.com/questions/3975",
"https://chemistry.meta.stackexchange.com",
"https://chemistry.meta.stackexchange.com/users/4945/"
] |
Medicinal chemistry definitely needs to be kept separate from the other two, which are slightly more related to biology. A lot of med chem is about the *route* towards designing a drug, which can include many things a pharmacologist would not really think about, such as traditional synthetic chemistry, correlation of molecular structure to bioactivity, molecular docking, etc.
Regarding toxicology and pharmacology, the two fields are different, and the definitions you quoted already indirectly demonstrate it. Pharmacology is essentially the study of drugs, but it is not limited to their toxicity. Toxicology is essentially the study of poisons, but it is not limited to drugs, because there are lots of poisons which are not drugs.
I agree that on Chemistry there is no reason to have separate tags for such niche fields. However, I also don't think that it is appropriate to merge tags which technically mean different things, even if they use similar concepts (physics and chemistry both use calculus, doesn't mean they're the same thing).
Looking at the [one question](https://chemistry.stackexchange.com/questions/84419/could-muscarine-be-an-antidote-to-atropine-poisoning) tagged with [toxicology](https://chemistry.stackexchange.com/questions/tagged/toxicology "show questions tagged 'toxicology'"), it doesn't actually seem to have any chemistry in it. I would therefore recommend:
1. migration to Biology, or
2. at the very least, retagging with [pharmacology](https://chemistry.stackexchange.com/questions/tagged/pharmacology "show questions tagged 'pharmacology'") (atropine is a drug, after all) and perhaps [biochemistry](https://chemistry.stackexchange.com/questions/tagged/biochemistry "show questions tagged 'biochemistry'"); and
3. removal of [toxicology](https://chemistry.stackexchange.com/questions/tagged/toxicology "show questions tagged 'toxicology'") (note that we already have [toxicity](https://chemistry.stackexchange.com/questions/tagged/toxicity "show questions tagged 'toxicity'") to deal with the harmful effects of chemicals on organisms!)
I don't think there's a need to change our tag structure based on one arguably off-topic question. Just my 2c, so please feel free to disagree - no offence will be taken.
|
14,071,272 |
I have REST api for accessing "parties" and the URL's look like this:
```
/parties
/parties/{partyId}
```
Using Spring controllers and @PathVariable I'm able to implement this interface. But to prevent users from accessing parties they don't have access to, I have to add checks to *every* method call which is kind of repeating myself and I might forget to add it everywhere:
```
@RequestMapping(value="/parties/{partyId}", method=RequestMethod.GET)
public @ResponseBody Party getParty(@PathVariable Integer partyId){
authorizeForParty(partyId);
...
```
Now what I would like to do is create a check that would be called every time that user enters url like this:
```
/parties/{partyId}/**
```
How would I do something like this? Do I have to create some servlet filter and parse the url myself? If I have to parse the url then is there atleast tools that would make it easy? I wish there was a way to add a method to controller that would be called before methods but could still use @PathVariables and such...
|
2012/12/28
|
[
"https://Stackoverflow.com/questions/14071272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325324/"
] |
What I ended up with is using the Spring MVC interceptors and parsing the path variables in the same way that Spring does. So I define an interceptor for the REST url:
```
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/parties/*/**" />
<bean class="PartyAuthorizationInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
```
The PartyAuthorizationInterceptor has to implement HandlerInterceptor in which we have to implement preHandle. It has HttpServletRequest as a parameter so we can get the request URL but we still have to parse the partyId from the url. After reading how Spring MVC does it, I found out they have a class named org.springframework.util.AntPathMatcher. It can read the path variables from the URL and place the values in a map. The method is called extractUriTemplateVariables.
So the result looks like this:
```
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String partyIdStr = new AntPathMatcher().extractUriTemplateVariables("/parties/{partyId}/**", request.getPathInfo()).get("partyId");
...
```
That makes the parsing almost as easy as using @PathVariable in MVC Controller methods. You still have to do conversions yourself(e.g. String -> Integer).
Now I can implement authorization logic on all urls that access a party in this interceptor and keep that logic out of the individual controller methods. Not as easy as I would have hoped but it gets the job done.
|
30,457,828 |
I am working on a Javascript function for calculating a coordinate with latitude and longitude on a "line" between two other coordinates. This coordinate that i need to calculate for example is 300 meters away from the first coordinate while the distance between the two coordinates is 1600 meters.
What i already have is the function for calculating the distance between the two coordinates that are known.
Gr.
|
2015/05/26
|
[
"https://Stackoverflow.com/questions/30457828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584292/"
] |
The VBA script
==============
Stick this in a Module in the current workbook:
```
Function SummaryMatch(Totals As Range, SummaryTotals As Range) As Variant()
Dim Sum As Double
Dim T As Long, S As Long, I As Long
Dim Result() As Variant
Result = SummaryTotals.Value
T = 1: S = 1
Do
If T > Totals.Rows.Count _
Or S > SummaryTotals.Rows.Count _
Then Exit Do
Sum = 0: I = T
Do
Sum = Sum + Totals(I)
I = I + 1
If Abs(Sum - SummaryTotals(S)) < 0.001 Then
Debug.Print SummaryTotals(S) & " T "
Result(S, 1) = True
T = I
S = S + 1
Exit Do
ElseIf Sum > SummaryTotals(S) + 0.001 Then
Debug.Print SummaryTotals(S) & " F "
Result(S, 1) = False
S = S + 1
Exit Do
End If
Loop While True
Loop While True
SummaryMatch = Result
End Function
```
How to use it
=============
If your totals are in A2:A14 and you summary totals are in C2:C10 then you would highlight E2:E10 and enter =SummaryMatch(A2:A14,C2:C10) into E2 and press Control-Shift-Enter because the function returns an array. The formula will display as {=SummaryMatch(A2:A14,C2:C10)} and will return a true/false value for each Summary Totals that indicates whether it has Totals that add up to that value or not.
```
A B C D E
1 Totals Summary Match
2 275 1090 TRUE
3 815 1655 TRUE
4 1655 9783.46 TRUE
5 9783.46 9571.26 TRUE
6 3393 2376.66 TRUE
7 4487.26 1997 TRUE
8 1691 100 TRUE
9 2376.66 620.3 FALSE
10 1997 5685.91 TRUE
11 100
12 6167.91
13 675
14 8843
```
How it works
============
The script keeps an pointer to the two lists (T for the Totals list and S for the Summary Totals list) as well as an index (I) that scans forward through the Totals list. Initially both T and S are set to start at the top (row 1 of each list) and then the loop is started.
The loop first checks whether we are at the bottom of one of the lists or not and then sets the current Sum to zero and starts scanning forward adding the current Total to the Sum and then comparing the Sum with the current Summary Total.
If the Sum matches the current Summary Total then we increment S to move to the next Summary Total and set the current Total to the current Index (so that we don't sum those values again) and then we start the main loop again.
If the Sum is more than the current Summary Total then the current Summary Total wasn't matched and we go on to the next one without changing the current Total to the current Indegx (so we start scanning at the current total again)
|
41,376 |
I have created simple site that create a new case.

Note :
* I have given the Site permissions Visualforce page,Controller ,Lead Object and Case Object.
* While execute the site Lead is created similarly I tried to create a new case it not happens.
* I have given the case Object create permission but why it is not created
Can someone please help me.
While executing the site it showing the error:
**Visualforce Page**
```
<apex:page controller="Controller" action="{!init}" showHeader="false" sidebar="false">
<center>
<apex:pageBlock title="Request Listener"></apex:pageBlock>
</center>
</apex:page>
```
**Controller :**
```
public with sharing class Controller
{
public PageReference init()
{
try
{
// Lead l1 = new Lead(FirstName='first name1',LastName = 'lead last name',phone ='9876543210');//testing
//insert l1; testing
Case c = new Case(Subject = 'Subject Test',Description ='Description Test');
insert c;
}
}
catch(exception e){}
RETURN null;
}
}
```
|
2014/06/24
|
[
"https://salesforce.stackexchange.com/questions/41376",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3989/"
] |
It is not related to permissions or profile if they are correct as you already checked. You are definitely getting an exception in code. There are some exception happening.
You should first try to run the same page by login into Salesforce organisation and check debug logs then.
|
57,668,557 |
I have a query which rounds the time to the nearest 15 minutes window:
```
Select Sysdate,
Trunc (Sysdate) + ( Round ( (Sysdate - Trunc (Sysdate))* 96)/ 96)
FROM dual;
```
However, I don't want the nearest but the lower 15 minutes window.
e.g. 1:
>
> Time 19:57:03
>
> Above query output 20:00:00
>
> Required output 19:45:00
>
>
>
e.g 2:
>
> Time 17:18:00
>
> Above query output 17:15:00
>
> required output 17:15:00
>
>
>
The second example is correct but the first one rounds to `20:00` as its nearer point. However I want query to output `19:45` for first example.
|
2019/08/27
|
[
"https://Stackoverflow.com/questions/57668557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10370655/"
] |
>
> There is any way to call Publish-AzWebApp based on only publish profile (no login by account)?
>
>
>
No, you can't. If you want to use the `Publish-AzWebApp` , you always need to login with `Connect-AzAccount`, whatever the parameters you use, examples [here](https://learn.microsoft.com/en-us/powershell/module/az.accounts/Connect-AzAccount?view=azps-2.5.0#examples).
If you want to use powershell to deploy the web app based on only publish profile, the workaround is to [use Kudu API via powershell](https://github.com/projectkudu/kudu/wiki/REST-API#sample-of-using-rest-api-with-powershell).
```
$username = "`$webappname"
$password = "xxxxxxx"
# Note that the $username here should look like `SomeUserName`, and **not** `SomeSite\SomeUserName`
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
$apiUrl = "https://joywebapp.scm.azurewebsites.net/api/zipdeploy"
$filePath = "C:\Users\joyw\Desktop\testdep.zip"
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST -InFile $filePath -ContentType "multipart/form-data"
```
|
14,158,772 |
```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Titanium" parent="android:Theme.NoTitleBar.Fullscreen">
<item name="android:windowBackground">@drawable/background</item>
</style>
</resources>
```
How can i customize my ActionBar component using theme.xml. I tried to generate these files and did place in my `platform/android/res folder`, but no luck
<http://jgilfelt.github.com/android-actionbarstylegenerator/#name=ActionBar&compat=holo&theme=light&actionbarstyle=solid&backColor=ffffff%2C100&secondaryColor=1f6e0d%2C100&tertiaryColor=F2F2F2%2C100&accentColor=fafffb%2C100>
|
2013/01/04
|
[
"https://Stackoverflow.com/questions/14158772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98514/"
] |
Two most important pieces of info for you to know are that you should use a client library to do the work for you, and you should use the "Installed application" flow/client type.
Use the tutorial here, which walks you through using an installed application:
<https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted>
You do have to use a web browser to get the credentials from the user, but once you do that, you should be able to re-use those credentials (refresh token) without re-prompting. The library makes moving these credentials from the browser to your app simple.
|
52,138,203 |
I know It might be already asked, but my question is something different. I've searched and I know java method `object.clone()` uses shallow copy which means copying references and not the actual objects. Let's say I have a dog Class
```
Class Dog{
public Dog(String name, DogTail tail, DogEar ear){
this.name = name;
this.tail = tail;
this.ear = ear;
}
}
DogTail t = new DogTail();
DogEar ear = new DogEar();
Dog dog1 = new Dog("good", t,ear);
```
let's say I want to get a copy of dog1.
>
> Dog dognew = dog1.clone();
>
>
>
If this `clone()` method uses shallow copy, it means copying references. So If I change t object created above or ear method, it's gonna change in the dognew object or vice versa. How is this cloning good? This question was born because someone said that creating an big huge object is worse than cloning, as you save performance while using `clone()` method.
|
2018/09/02
|
[
"https://Stackoverflow.com/questions/52138203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9780666/"
] |
It's pretty easy to test these, `artisan tinker` is an interactive console.
`mix()` suffixes a version id and will only work if you have a mix manifest (used for versioning front end assets). `asset()` prefixes your app url.
Both should be used for displaying an absolute url to a versioned asset:
**Tinker output:**
```
>>> (string) mix('js/app.js')
=> "/js/app.js?id=68390ee698d5dd6a7283"
>>> (string) asset('js/app.js')
=> "http://site.test/js/app.js"
>>> (string) asset(mix('js/app.js'))
=> "http://site.test/js/app.js?id=68390ee698d5dd6a7283
```
|
6,950,713 |
I have an app that lets the user trace lines on the screen. I am doing so by recording the points within a UIPanGestureRecognizer:
```
-(void)handlePanFrom:(UIPanGestureRecognizer *)recognizer
{
CGPoint pixelPos = [recognizer locationInView:rootViewController.glView];
NSLog(@"recorded point %f,%f",pixelPos.x,pixelPos.y);
}
```
That works fine. However, I'm very interested in the first point the user tapped before they began panning. But the code above only gives me the points that occurred *after* the gesture was recognized as a pan (vs. a tap.)
From the documentation, it appears there may be no easy way to determine the initially-tapped location within the UIPanGestureRecognizer API. Although within UIPanGestureRecognizer.h, I found this declaration:
```
CGPoint _firstScreenLocation;
```
...which appears to be private, so no luck. I'm considering going outside the UIGestureRecognizer system completely just to capture that initailly-tapped point, and later refer back to it once I know that the user has indeed begun a UIPanGesture. I Thought I would ask here, though, before going down that road.
|
2011/08/05
|
[
"https://Stackoverflow.com/questions/6950713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/365279/"
] |
Late to the party, but I notice that nothing above actually answers the question, and there is in fact a way to do this. You must subclass UIPanGestureRecognizer and include:
```
#import <UIKit/UIGestureRecognizerSubclass.h>
```
either in the Objective-C file in which you write the class or in your Swift bridging header. This will allow you to override the touchesBegan:withEvent method as follows:
```
class SomeCoolPanGestureRecognizer: UIPanGestureRecognizer {
private var initialTouchLocation: CGPoint!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
initialTouchLocation = touches.first!.locationInView(view)
}
}
```
Then your property initialTouchLocation will contain the information you seek. Of course in my example I make the assumption that the first touch in the set of touches is the one of interest, which makes sense if you have a maximumNumberOfTouches of 1. You may want to use more sophistication in finding the touch of interest.
**Edit:** Swift 5
```
import UIKit.UIGestureRecognizerSubclass
class InitialPanGestureRecognizer: UIPanGestureRecognizer {
private var initialTouchLocation: CGPoint!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
initialTouchLocation = touches.first!.location(in: view)
}
}
```
|
35,675,890 |
Why do we need to have two tables (master and transaction table) of any topic like `sales`,`purchase`,etc.. What should be the relationship between the two tables and what should be the difference between them. Why do we really need them.
|
2016/02/27
|
[
"https://Stackoverflow.com/questions/35675890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5955010/"
] |
Master and Transaction tables are needed in the database schema specially in the verticals of sales.
**Master Data**: Data which seldom changes.
For example, if a company has a list of 5 customer then they
will maintain a customer master table having the name and
address of the customers alongwith other data which will
remain permanent and is less likely to change.
**Transaction Data**: Data which frequently changes. For
example, the company is selling some materials to one of the
customer.So they will prepare a sales order for the
customer. When they will generate a sales order means they
are doing some sales transactions.Those transactional data
will be stored in Transactional table.
This is really required to maintain database normalization.
|
2,259,114 |
Let's say I have an interface like that:
```
interface IAwesome
{
T DoSomething<T>();
}
```
Is there any way to implement the DoSomething method with type constraint? Obviously, this won't work:
```
class IncrediblyAwesome<T> : IAwesome where T : PonyFactoryFactoryFacade
{
public T DoSomething()
{
throw new NotImplementedException();
}
}
```
This obviously won't work because this DoSomething() won't fully satisfy the contract of IAwesome - it only work for a subset of all possible values of the type parameter T. Is there any way to get this work short of some "casting black magic" (which is what I'm going to do as last resort if the answer is no)?
Honestly, I don't think it's possible but I wonder what you guys think.
**EDIT**: The interface in question is **[System.Linq.IQueryProvider](http://msdn.microsoft.com/en-us/library/system.linq.iqueryprovider.aspx)** so I can't modify the interface itself.
|
2010/02/13
|
[
"https://Stackoverflow.com/questions/2259114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954/"
] |
No, this cannot work by design, since it would mean that the contract for `IAwesome` would not be (fully) satisfied.
As long as `IncrediblyAwesome<T>` implements `IAwesome`, one is allowed to do this:
```
IAwesome x = new IncrediblyAwesome<Something>()
```
Obviously, with your additional constraint, this could not work, since the user of `IAwesome` cannot know of the restrictions put on it.
In your case, the only solution I can think of is this (doing runtime checking):
```
interface IAwesome { // assuming the same interface as in your sample
T DoSomething<T>();
}
class IncrediblyAwesome<TPony> : IAwesome where TPony : PonyFactoryFactoryFacade {
IAwesome.DoSomething<TAnything>() {
return (TAnything)((object)DoSomething()); // or another conversion, maybe using the Convert class
}
public TPony DoSomething() {
throw new NotImplementedException();
}
}
```
|
11,124 |
When I recently entered the field of game development, I actually assumed that “game engine” meant something with which you can make your game story script run in an environment where non-player characters have a state, and so you can test running your story as the bare bones of a game. A typical example of a tool for this is [Chat Mapper](http://www.chat-mapper.com/). This in my perspective is the core of your game, around which you build animations, sounds, etc. using say a 3D engine. A 3D engine can also be used for ends which have little to do with games. Let’s temporarily call what I mean a game-story engine.
But this does not seem the intended meaning – I guess it depends on the focus and stage of your game. Possible meanings of “game engine” seem to be:
* An environment which supports creating and running a complete game; this too is quite ambiguous definition, consider Unity, <http://unity3d.com/unity/engine/>, Vassal <http://www.vassalengine.org> .
* The term “game engine” is actually a shortcut for “game 2D engine” or “game 3D engine”
Now what I am asking is not to become uselessly precise with words, but just whether there is a better term used for “game-story engine” which experienced game developers use. Thanks.
*P.S. And no, I’m not heading towards (nor advising to) creating “game engines” before creating games. In my startup we actually created a very simple JavaScript “game-story engine” for our browser games (it was strictly necessary) which we would like to share and am now wondering how to present it.*
|
2011/04/14
|
[
"https://gamedev.stackexchange.com/questions/11124",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/3853/"
] |
The industry doesn't have these terms nailed down well yet, but I'd say your concept is pretty far from colloquial use.
"Game Engine" usually refers to a piece of software that is meant to be extended by a game developer with their own specific logic to make a unique game. The Game Engine would provide all or nearly all of the generic services a game might need; e.g. audio playback, asset management, a renderer, physics simulation, AI framework, special effects systems, etc.
Usually a good Game Engine will also have a heavy tool component, where the Game Engine will ship with one or more tools to facilitate creating assets for use with the Game Engine; e.g. a 3D model and texture converter, a level editor, a sound back editor, etc.
The general idea is that a game dev should only have to bring their own unique work to the project (their logic, their art, their flair for lack of a better term), avoiding reinventing the wheel by leaving the common stuff to the Game Engine.
The murky part usually is how much needs to come with a Game Engine to consider it complete. That's a shifting target, both by who's looking at the question and what's currently fashionable. It's not at all uncommon that a project will use only a portion of the Game Engine they're purportedly using, patching in other components they find desirable/necessary. These other components (usually referred to as libraries) are also often bought in rather than written in house.
To throw in one more related common term: both the individual systems (Libraries) and comprehensive collections of integrated systems and tools (Game Engines) are collectively referred to as Middleware.
Note: here we're talking about Game Engine, as in a specific case of engine. The term engine alone is commonly (at least in my experience) used synonymously with library, module, system and even manager, and in that context would refer to a logical unit of code that provides a service, as per the components of a Game Engine above. I guess you could say all these nouns serve to form the sentence "the X that does Y" for the form YX; e.g. "the engine that does games", "the library that does pathfinding", "the module that does dialogue trees".
|
42,270,578 |
I have been battling with this for ages. I am trying to upload an image to a server but keep getting a 500 error.
Here is the code I use to get the image, base64 encode it, and then add it to a dictionary.
```
if let imageDataToUpload = UIImageJPEGRepresentation(selectedImage, 1.0) {
let encodedImageData = imageDataToUpload.base64EncodedString(options: [])
let extras = "data:image/jpeg;base64,"
let postBody = [
"image": extras + encodedImageData,
"id": id,
"instruction": "1",
"ext": ""
]
let endPoint = UrlFor.uploadPhoto
ApiManager().apiPostImage(endPoint: endPoint, postBody: postBody, callBackFunc: handleResultOfUploadPhoto) }
```
And here is the code I use to perform the actual POST request. You'll notice I am trying to convert the post body to a JSON object.
```
func apiPostImage(endPoint: String, postBody: [String: Any]?, callBackFunc: @escaping (ResultOfApiCall) -> Void) {
// get the sessionKey
guard let sessionKey = KeyChainManager().getSessionKey() else {
print("error getting session key")
AppDelegate().signUserOut()
return
}
// create a url with above end point and check its a valid URL
guard let url = URL(string: endPoint) else {
print("Error: cannot create URL")
return
}
// set up the request
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
if let postBody = postBody {
do {
try urlRequest.httpBody = JSONSerialization.data(withJSONObject: postBody, options: [])
} catch {
print("problems creating json body")
}
}
// set up the header
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept": "application/json",
"apiKey": "0101010-0101010", // not the real apiKey
"usrKey": sessionKey,
"appInfo" : "appcode:1000|version:2.0.37",
"Content-Type": "application/json"
]
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest, completionHandler:
{ (data: Data?, response: URLResponse?, error: Error?) -> Void in
let (noProblem, ResultOfCall) = self.checkIfProblemsWith(data: data, response: response, error: error)
guard noProblem else {
callBackFunc(ResultOfCall)
return
}
let serializedData: [String:Any]
do {
// safe bc checked for nil already.
serializedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
} catch {
callBackFunc(ResultOfApiCall.errorWhileSerializingJSON)
return
}
// pass serialized data back using the callBackFunc
callBackFunc(ResultOfApiCall.success(serializedData))
})
task.resume()
}
```
The API is RESTful. I don't have access to the API error logs, but I am getting this error back from the API:
```
["codesc": GENERALERROR, "code": 5001, "msg": Conversion from string "Optional(1004007)" to type 'Double' is not valid.]
```
|
2017/02/16
|
[
"https://Stackoverflow.com/questions/42270578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133055/"
] |
Using [`pandas`](http://pandas.pydata.org/pandas-docs/stable/10min.html) you could do something like:
```
import pandas as pd
my_data = pd.read_csv('survey.csv')
# To summarize the dataframe for everything together:
print my_data.describe()
print my_data.sum()
# To group by gender, etc.
my_data.groupby('Gender').count()
```
|
30,008,574 |
I was just looking at the [Change Log for Haxe 3.2.0-rc.2](http://haxe.org/download/version/3.2.0-rc.2/) and found this at the end of *New features* list:
```
cpp : inititial implementation of cppia scripting
```
Can anyone can tell me what this means? I can tell that it has something to do with C++, but googling this gives nothing related to programming/scripting unless you count Haxe related results.
|
2015/05/02
|
[
"https://Stackoverflow.com/questions/30008574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1518408/"
] |
Cppia (pronounced "sepia") is a new part of the C++ target for Haxe. In the most basic sense it is a "scripting" language for hxcpp which can be compiled and run without the use of a C++ compiler. Some official documentation can be found here:
[Getting started with Haxe/Cppia](https://haxe.org/manual/target-cppia-getting-started.html)
In order to compile to cppia you need to modify your hxml build file. Add a `-D cppia` flag to your build and change the output to have a `.cppia` extension. Here is an example.
```
-cpp out.cppia # the cppia output file
-main Main # your Main.hx file
-D cppia # this enables cppia compilation
```
After you do that you compile the hxml file like normal with Haxe. It will give you a file named `out.cppia` which can then be run through hxcpp using the command `haxelib run hxcpp out.cppia`. One drawback to this method is there is no way to use native extensions without building your own cppia host. So if you need to run something using OpenFL or Kha you'll have to wait until they support cppia.
According to the information I've found it sounds like cppia runs as fast as Neko JIT. Considering the compile times are just as fast I can see this becoming a good alternative to the neko target in the future.
Additional information can be found in slides from a talk given by the creator, Hugh Sanderson, at WWX 2015.
<http://gamehaxe.com/wwx/wwx2015.swf>
|
640,219 |
I have a file containing numbers in many rows and 5 columns like this:
```
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
...
```
If I want to get sums of the numbers in the 1st row and 3rd row in this way: 1+11, 2+12, 3+13, 4+14, 5+15
which means what I want to see finally is `12 14 16 18 20`
What should I do?
|
2021/03/20
|
[
"https://unix.stackexchange.com/questions/640219",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/339837/"
] |
Solution 1
==========
```bsh
#!/bin/bash
{ read -ra line1; read _; read -ra line3; }
for i in "${!line1[@]}"; do
result+=("$(( ${line1[i]} + ${line3[i]} ))")
done
printf %s\\n "${result[*]}"
```
Example:
```bsh
$ bash script < yourfilename
12 14 16 18 20
$
```
**Script explanation**
`{ read -ra line1; read _; read -ra line3; }`
This part reads the first three lines of the file, keeping only the first two lines. It also splits them into arrays line1 and line3.
It assumes a stream of data from stdin. See the example on how to do that.
`for i in "${!line1[@]}"; do result+=("$(( ${line1[i]} + ${line3[i]} ))"); done`
This part loops over the elements of one of the two arrays, and sums the same elements from line1 and line2. The results are put into a new array called result
`printf %s\\n "${result[*]}"`
Prints the computed array elements space-separated.
---
Solution 2
==========
Another solution avoiding loops, assuming the input has 5 columns as requested:
```bsh
#!/bin/bash
{ read a b c d e; read _; read v w x y z; }
echo "$((a+v)) $((b+w)) $((c+x)) $((d+y)) $((e+z))"
```
Example:
```bsh
$ cat yourfilename
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
...
$ bash script < yourfilename
12 14 16 18 20
$
```
**Script explanation**
`{ read a b c d e; read _; read v w x y z; }`
Reads the numbers from line 1 (resp. line 3) into variables a to e (resp. v to z)
`echo "$((a+v)) $((b+w)) $((c+x)) $((d+y)) $((e+z))"`
Prints the sum of the variables space-separated as requested
|
60,764,709 |
I am learning rx/dart at the moment. But I am struggeling. Is there any way to make this property synchronized? The `await currentUser()` forces me to do make the property `async` that. But I need some kind of hack, because this part of an interface I can't change. And I don't want to use adapter pattern.
The property should return `Stream<User>`. Any way to achive this?
```
Future<Stream<User>> get onUserOrAuthStateChanged async {
return authentication.onAuthStateChanged
.asyncMap<User>((authenticationUser) async {
return await _retrieveUserFromAuthenticationUser(authenticationUser);
}).concatWith([
await currentUser() == null
? Stream.empty()
: userRepository.getStream((await currentUser()).id).skip(1)
]);
}
```
**Edit:** Also `authenticationUser` could be used instead of `await currentUser()`. Like this:
```
Stream<User> get onUserOrAuthStateChanged {
AuthenticationUser currentAuthenticationUser;
return authentication.onAuthStateChanged
.asyncMap<User>((authenticationUser) async {
currentAuthenticationUser = authenticationUser;
return await _retrieveUserFromAuthenticationUser(authenticationUser);
}).concatWith([
currentAuthenticationUser == null
? Stream.empty()
: userRepository.getStream(currentAuthenticationUser.uid).skip(1)
]);
}
```
With this approach, I get rid of the async, but currentAuthenticationUser is always `null` when the `concatWith` method get's executed, because the assignment happens not synchronized after the `concatWith` `currentAuthenticationUser = authenticationUser;`
|
2020/03/19
|
[
"https://Stackoverflow.com/questions/60764709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7558184/"
] |
This is the solution I came up with:
```
Stream<User> get onUserOrAuthStateChanged {
return authentication.onAuthStateChanged.switchMap((authenticationUser) =>
authenticationUser == null
? Stream.value(null)
: userRepository.getStream(authenticationUser.uid));
}
```
|
25,312,847 |
I'm having troubles getting related entities in a single query.I used both fetch=Eager and manual query with join.Here are my entities
```
----------------------Store.php--------------------------------------
/**
* @ORM\OneToMany(targetEntity="Mycomp\ProductBundle\Entity\Product", mappedBy="store_id", cascade={"all"},fetch="EXTRA_LAZY")
*
**/
protected $products;
--------------------Product.php---------------------------------------
/**
* @ORM\OneToMany(targetEntity="ProductOption", mappedBy="product", cascade={"all"},orphanRemoval=true,fetch="EAGER")
*
**/
protected $options;
/**
* @ORM\OneToMany(targetEntity="Like", mappedBy="product", cascade={"all"},orphanRemoval=true,indexBy="id",fetch="EAGER")
*
**/
protected $likes;
-------------------Like.php---------------------------------------------
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Product", inversedBy="likes")
*
**/
private $product;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Mycomp\UserBundle\Entity\User",inversedBy="likes")
*
**/
private $user;
-------------------Option.php---------------------------------------------
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="options")
*
**/
private $product;
```
And the query:
```
$qb = $em->createQueryBuilder('qb1');
$qb->add('select', 'a', 'p', 'po', 'pl','sl')
->add('from', 'MycompStoreBundle:Store a')
->add('where', 'a.id = :store')
->innerJoin('a.products','p')
->leftJoin('p.options','po') // ***
->leftJoin('p.likes','pl')
->leftJoin('a.followers','sl')// ***
->setParameter('store', $id);
$store = $qb->getQuery()->getResult();
```
And in twig
```
{% for product in store.0.products %}
{{ product.name }}
{% for option in product.options %}
{{ option }}
{% endfor %}
<div id="like-holder{{ product.id }}"> {{ like_module(product) }}</div>
{% endfor %}
```
For 4 products i get these queries:
```
+ SELECT t0.username AS [...] FROM apps_user t0 WHERE t0.id = ? LIMIT 1
Parameters: [2]
[Display runnable query]
Time: 1.52 ms [ + Explain query ]
+ SELECT s0_.id AS id0, [...] FROM store s0_ INNER JOIN [...] WHERE (s0_.id = ?) AND s0_.dtype [...]
Parameters: ['5']
[Display runnable query]
Time: 0.89 ms [ + Explain query ]
+ SELECT t0.id AS id1, t0.name AS [...] FROM product t0 WHERE t0.store_id_id = ? AND [...]
Parameters: [5]
[Display runnable query]
Time: 0.69 ms [ + Explain query ]
+ SELECT t0.id AS id1, t0.name AS [...] FROM product_option t0 WHERE t0.product_id = ? AND [...]
Parameters: [5]
[Display runnable query]
Time: 0.46 ms [ + Explain query ]
+ SELECT t0.createdAt AS createdAt1, [...] FROM product_like t0 WHERE t0.product_id = ? AND [...]
Parameters: [5]
[Display runnable query]
Time: 0.39 ms [ + Explain query ]
+ SELECT t0.id AS id1, t0.name AS [...] FROM product_option t0 WHERE t0.product_id = ? AND [...]
Parameters: [6]
[Display runnable query]
Time: 0.54 ms [ + Explain query ]
+ SELECT t0.createdAt AS createdAt1, [...] FROM product_like t0 WHERE t0.product_id = ? AND [...]
Parameters: [6]
[Display runnable query]
Time: 0.45 ms [ + Explain query ]
+ SELECT t0.id AS id1, t0.name AS [...] FROM product_option t0 WHERE t0.product_id = ? AND [...]
Parameters: [7]
[Display runnable query]
Time: 0.42 ms [ + Explain query ]
+ SELECT t0.createdAt AS createdAt1, [...] FROM product_like t0 WHERE t0.product_id = ? AND [...]
Parameters: [7]
[Display runnable query]
Time: 0.40 ms [ + Explain query ]
+ SELECT t0.id AS id1, t0.name AS [...] FROM product_option t0 WHERE t0.product_id = ? AND [...]
Parameters: [8]
[Display runnable query]
Time: 0.37 ms [ + Explain query ]
+ SELECT t0.createdAt AS createdAt1, [...] FROM product_like t0 WHERE t0.product_id = ? AND [...]
Parameters: [8]
[Display runnable query]
Time: 0.42 ms [ + Explain query ]
```
Why is that? As you can see i get addition 2 queries per product.For likes and options.
|
2014/08/14
|
[
"https://Stackoverflow.com/questions/25312847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3817718/"
] |
It is not possible to call that one specific method inside another method. However, you can call `[self.tableView reloadData]` inside any methods. This call all the UITableView delegate methods which includes `- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath`
|
315,633 |
I'm new at magento 2 and I'm trying to create a "SaveAndContinue" button.
I created the classes, but when i click the SaveAndContinue button on the form, it calls the "save" controller and not the "save and continue" controller. What could it be?
form.xml
```
<button name="save_and_continue" class="Hub\Api\Block\Adminhtml\Data\Edit\Buttons\SaveAndContinue" />
```
SaveAndContinue button:
```
class SaveAndContinue extends Generic implements ButtonProviderInterface
```
{
```
/**
* Get buttong attributes
*
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Save and Continue Edit'),
'class' => 'save',
'data_attribute' => [
'mage-init' => [
'button' => ['event' => 'saveAndContinueEdit'],
],
],
'sort_order' => 80,
];
}
```
}
|
2020/06/22
|
[
"https://magento.stackexchange.com/questions/315633",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/89247/"
] |
There is NO any "Print Shipment and Invoices" option in Vanilla Magento 1.x. It seems you might have any third party extension or customized code for it. So the solution would be
i) To get the M2 version of the extension you are using for your M1 site
ii) Or Migrate the customized code in M2
Add-On:
Rather there is a "Print All" option available in M1 & M2 which prints invoices & Packing slips unless you do not have a customized print layout, see if it helps you.
Thanks
|
20,666,786 |
I have in template this:
```
{% for item in items %}
{% ifchanged item.st2 %}
<div class="clear"></div>
<div class="item-title">{{ item.get_st2 }}</div>
{% endifchanged %}
<div class="cell {% cycle 'clear tco1' 'tco' 'tco' 'tco2' 'clear tce1' 'tce' 'tce' 'tce2' %}">{{ item.name }}</div>
{% endfor %}
```
and it shows things like this:
```
------------------ st2 name 1 -------------------
+-----------------------------------------------+
| grey item | grey item | grey item | grey item |
+-----------------------------------------------+
| dark item | dark item | dark item | dark item |
+-----------------------------------------------+
| grey item | grey item | grey item | grey item |
+-----------------------------------------------+
| dark item | dark item | dark item | dark item |
+-----------------------------------------------+
| grey item | grey item | grey item | grey item |
+-----------------------------------------------+
------------------ st2 name 2 -------------------
+-----------------------------------------------+
| grey item | grey item | grey item | grey item |
+-----------------------------------------------+
| dark item | dark item | dark item | dark item |
+-----------------------------------------------+
```
and its good.
But if items on st2 name is less than 4 in one line:
```
------------------ st2 name 1 -------------------
+-----------------------------------------------+
| grey item | grey item | grey item | grey item |
+-----------------------------------------------+
| dark item | dark item | dark item |
+-----------------------------------+
```
then next looks like this:
```
------------------ st2 name 1 -------------------
+-----------------------------------+
| grey item | grey item | grey item |
+-----------------------------------------------+
| dark item | dark item | dark item | dark item |
+-----------------------------------------------+
```
because cycle coutner is still on the fourth element.
How to reset cycle tag?
|
2013/12/18
|
[
"https://Stackoverflow.com/questions/20666786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/671391/"
] |
You can use `cycle` tag with `silent` keyword to declare the cycle but not produce the first value. By giving the cycle tag a name, using `"as"` you can insert the current value of the cycle wherever you’d like. Another `cycle` tag with name of the variable will move cycle to the next value independently. And `divisibleby` tag can be used to check for last in line item:
```
{% cycle 'clear tco1' 'tco' 'tco' 'tco2' 'clear tce1' 'tce' 'tce' 'tce2' as cellcls silent %}
{% for item in items %}
{% ifchanged item.st2 %}
<div class="clear"></div>
<div class="item-title">{{ item.get_st2 }}</div>
{% if not forloop.counter1|divisibleby:"4" %} {# im not tested it #}
{% cycle cellcls %}
{% endif %}
{% endifchanged %}
<div class="cell {{cellcls}}">{{ item.name }}</div>
{% cycle cellcls %}
{% endfor %}
```
|
816,582 |
This is the first time I ordered a dedicated server with 3 HDDs and I am quite confused. My limited knowledge tells me that
* `/dev/sda`
* `/dev/sdb`
* `/dev/sdc`
are the 3 drives that I actually have.
But, using the command `fdisk -l | grep '^Disk'` gives the following output:
```
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
Disk identifier: 0x5413d59f
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
Disk identifier: 0x541faf6a
Disk /dev/sdc: 1000.2 GB, 1000204886016 bytes
Disk identifier: 0x54145359
Disk /dev/md2: 995.2 GB, 995237888000 bytes
Disk identifier: 0x00000000
Disk /dev/md1: 4291 MB, 4291756032 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/sys1AP7-root: 990.9 GB, 990929485824 bytes
Disk identifier: 0x00000000
Disk /dev/md0: 536 MB, 536805376 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/sys1AP7-vartmp: 2147 MB, 2147483648 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/sys1AP7-tmp:
```
it appears I have more than 3 drives.
What exactly are the following?
* `/dev/md2`
* `/dev/md1`
* `/dev/mapper/sys1AP7-root`
* `/dev/md0`
* `/dev/mapper/sys1AP7-vartmp`
* `/dev/mapper/sys1AP7-tmp`
Edit: My config as I ordered it is suppose to be disk 1 and 2 in RAID1 setup, while disk 3 should be a standalone drive.
|
2014/09/25
|
[
"https://superuser.com/questions/816582",
"https://superuser.com",
"https://superuser.com/users/80762/"
] |
You have only 3 **physical** devices:
* /dev/sda
* /dev/sdb
* /dev/sdc
[It is simply as by convention, IDE drives will be given device names /dev/hda to /dev/hdd](http://www.tldp.org/HOWTO/Partition/devices.html).
Besides that you have **logical** RAID devices:
* /dev/md0
* /dev/md1
* /dev/md2
[RAID](http://en.wikipedia.org/wiki/RAID) (originally redundant array of inexpensive disks; now commonly redundant array of independent disks) is a data storage virtualization technology that combines multiple disk drive components into a logical unit for the purposes of data redundancy or performance improvement.
RAID needs a Linux kernel framework for mapping block devices onto higher-level virtual block devices, so-called **[device mapper](http://en.wikipedia.org/wiki/Device_mapper)**:
* /dev/mapper
|
19,642,311 |
Please could I request for your advise on the following problem:
I'd like to restrict access to a web folder through the Web URL (I understand that this could be done using .htaccess). However, my concern is that I'd also like the code files in this folder to be accessible to AJAX calls.
Reference question:
[deny direct access to a folder and file by htaccess](https://stackoverflow.com/questions/9282124/deny-direct-access-to-a-folder-and-file-by-htaccess)
Is it therefore correct to assume that any access allow/deny rule in .htaccess is automatically applicable to AJAX calls as well (since they're based on URLs)? And if so, what could be the best way to let the server access mechanism know that it's some "code" that is trying to communicate with it?
Please do let me know if I could provide any clarifications or additional details.
Thanks a lot!
|
2013/10/28
|
[
"https://Stackoverflow.com/questions/19642311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2298301/"
] |
You can do so based on `HTTP_REFERER`, put this code in your `DOCUMENT_ROOT/.htaccess` file::
```
RewriteEngine On
## disable direct access
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/ [NC]
RewriteRule ^somefolder - [F,NC]
```
Though I must add that `HTTP_REFERER` based check is not very strong and it can be easily spoofed.
|
46,502,264 |
I'm facing a scenario where I need to inject a service from asp.net core DI container to the constructor of an object created using automapper.
I don't know if this is the best practice but let me explain what I'm trying to accomplish.
I've an asp.net core mvc controller that receives a model parameter, just a POCO, that model needs to be converted into a ViewModel class that contains some business logic, data access etc, in that class object I want to get some info from the injected service, that is the part where I'm having problems, cant figure out how to inject the service from controller to the final ViewModel.
My code at this moment looks something like this.
**NewGameModel.cs**
```
namespace MyProject.Shared.Models
{
public class NewGameModel
{
public List<PlayerModel> Players { get; set; }
public bool IsValid => Players.Any();
public NewGameModel()
{
Players = new List<PlayerModel>();
}
}
}
```
**NewGameViewModel.cs**
```
namespace MyProject.Core.ViewModels
{
public class NewGameViewModel
{
private Guid Token = Guid.NewGuid();
private DateTime DateTimeStarted = DateTime.Now;
private readonly IConfiguration _configuration;
public List<PlayerModel> Players { get; set; }
public NewGameViewModel(IConfiguration config)
{
_configuration = config;
}
public string DoSomething()
{
//Do something using _configuration
//Business Logic, Data Access etc
}
}
}
```
**MapperProfile.cs**
```
namespace MyProject.Service
{
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<NewGameModel, NewGameViewModel>();
}
}
}
```
**ASP.NET Core project - Startup.cs**
```
namespace MyProject.Service
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(Configuration);
var autoMapperConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MapperProfile());
});
var mapper = autoMapperConfig.CreateMapper();
services.AddSingleton(mapper);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
```
**ASP.NET Core project - GameController.cs**
```
namespace MyProject.Service.Controllers
{
[Route("api/[controller]")]
public class GameController : Controller
{
private readonly IConfiguration _configuration;
private readonly IMapper _mapper;
public GameController(IConfiguration config, IMapper mapper)
{
_configuration = config;
_mapper = mapper;
}
[HttpPost]
public IActionResult CreateNewGame([FromBody]NewGameModel model)
{
if (!model.IsValid) return BadRequest();
//Throws error because no constructor parameter was passed
//How to pass the IConfiguration to the destination NewGameViewModel object?
var viewModel = _mapper.Map<NewGameModel, NewGameViewModel>(model);
var result = viewModel.DoSomething();
return CreatedAtRoute("GetGame", new { token = result.GameToken }, result);
}
}
}
```
I will appreciate your help
|
2017/09/30
|
[
"https://Stackoverflow.com/questions/46502264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4248768/"
] |
For those coming later, the method above is not preferred, as it has state inside profiles. Instead, use the `AutoMapper.Extensions.Microsoft.DependencyInjection` package and inside your startup:
```
services.AddAutoMapper();
```
Then in your profile, just tell AutoMapper that you want your destination object constructed with the container:
```
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<NewGameModel, NewGameViewModel>()
.ConstructUsingServiceLocator();
}
}
```
Your controller can then depend in `IMapper` and AutoMapper will use the DI container to construct the view model, and your configuration to ASP.NET Core will just be the one line to `services.AddAutoMapper();`
|
12,498,487 |
Would it have been bad if, instead of `synchronized` keyword we had `@Synchronized` annotation? Would an annotation be more natural in this case (because you can override a `synchronized` method with a non-synchronized method - thus `synchronized` says nothing about the method itself but rather specifies something in addition to the method (that the method is guarded in a certain way), so it's not really a keyword?)
|
2012/09/19
|
[
"https://Stackoverflow.com/questions/12498487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/721079/"
] |
Synchronized transforms practically directly into monitorenter/monitorexit on the byte code level. And you specify what to synchronized on, you can't do that with an annotation:
```
synchronized (myLock) {
}
```
So it makes perfect sense to me that it is a keyword.
|
24,746,046 |
I have expressions like the following:
```
{1000} AND ({1001} OR {1002} OR {1003})
```
Allowed operators are OR and AND, expressions can be nested using parenthesis.
I already managed to tokenize this string and to convert it to an abstract syntax tree (AST) using the Shunting Yard algorithm, implemented in PHP 5.3.
The above expression results in the following:
```
1000 1001 1002 | 1003 | &
&
/ \
1000 |
/ \
| 1003
/ \
1001 1002
```
When traversing this tree I want to output the final combinations of numbers a user can choose from. In the given representation this is not possible. What I need is actually the form, after the distributive law was applied:
```
(1000 & 1001) | (1000 & 1002) | (1000 & 1003)
1000 1001 & 1000 1002 & | 1000 1003 & |
_______________|_____________
/ \
_______|____ &
/ \ / \
& & 1000 1003
/ \ / \
1000 1001 1000 1002
```
I concluded, that the only nodes that are allowed to be &-operator nodes, are the last ones that carry the leafs. All others have to be |-operator nodes.
How to convert an arbitrary AST with the grammar explained above to one that represents all final permutations? Is it better to apply the distributive law on the tokens of the infix representation? Is it easier to work with the RPN representation instead of the tree?
Please also note, that there are more difficult examples possible like:
```
(1000 & 1008) & (1001 | 1002 | 1003)
1000 1008 & 1001 1002 | 1003 | &
______ & ___
/ \
& |
/ \ / \
1000 1008 | 1003
/ \
1001 1002
```
Which I'd like to result in:
```
(1000 & 1008 & 1001) | (1000 & 1008 & 1002) | (1000 & 1008 & 1003)
1000 1008 & 1001 & 1000 1008 & 1002 & | 1000 1008 & 1003 & |
__________________|_________
/ \
_____________|_________ &
/ \ / \
& & & 1003
/ \ / \ / \
& 1001 & 1002 1000 1008
/ \ / \
1000 1008 1000 1008
```
For another (more complicated) example just switch left sub tree and right sub tree or add another &-node in place of 1003 => 1003 1009 &
What I already tried: Googling a lot, traversing the tree pre and post order, trying to find an algorithm with no success.
I am grateful for any hints and pointers into the right direction.
|
2014/07/14
|
[
"https://Stackoverflow.com/questions/24746046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3838415/"
] |
What you seem to want to do is produce is [disjunctive normal form](http://en.wikipedia.org/wiki/Disjunctive_normal_form). This is
harder to do than it looks because there are lots of interesting cases to handle.
What you want to do is implement the following rewrite rule,
exhaustively, everywhere in your tree (actually, leaf upwards is probably good enough):
```
rule distribute_and_over_or(a: term, b: term, c: term): term->term
" \a and (\b or \c) " -> " \a and \b or \a and \c ";
```
In complex terms, you'll get redundant subterms, so you'll likely need these rules:
```
rule subsumption_identical_or_terms:(a: term): term->term
" \a or \a " -> \a";
rule subsumption_identical_and_terms:(a: term): term->term
" \a and \a " -> \a";
```
The way you expressed your problem, you didn't use "not" but it will likely show up, so you need the following additional rules:
```
rule cancel_nots:(term: x): term -> term
" not (not \x)) " --> "\x";
rule distribute_not_over_or(a: term, b: term): term->term
" not( \a or \b ) " -> " not \a and not \b ";
rule distribute_not_over_and(a: term, b: term): term->term
" not( \a and \b ) " -> " not \a or not \b ";
```
You may also encounter self-cancelling terms, so you need to handle those:
```
rule self_cancel_and(a: term): term->term
" \a and not \a " -> "false";
rule self_cancel_or(a: term): term->term
" \a or not \a " -> "true";
```
and ways to get rid of true and false:
```
rule and_true(a: term): term->term
" \a and true " -> " \a ";
rule and_false(a: term): term->term
" \a and false " -> " false ";
rule or_true(a: term): term->term
" \a or true " -> " true ";
rule and_false(a: term): term->term
" \a or false " -> " \a ";
rule not_false(a: term): term->term
" not false " -> " true ";
rule not_true(a: term): term->term
" not true " -> " false ";
```
(I've assumed expression precedence with "not" binding tighter than "and" binding tighter than "or").
The rules shown assume the various subtrees are at best "binary", but they may have many actual children, as you show in your examples. In effect, you have to worry about the associative law, too. You'll also have to take into account the commutative law if you want the the subsumption and cancellation laws to really work.
You'll probably discover some implicit "not" propagation if your sub-expressions contain relational operators, e.g.,
```
" not ( x > y ) " --> " x <= y "
```
You may also wish to normalize your relational compares:
```
" x < y " --> " not (x >= y )"
```
Since you've implemented your trees in PHP, you'll have to manually code the equivalent of these by climbing up and down the trees procedurally. This is possible but pretty inconvenient. (You can do this on both tokens-as-RPN and on ASTs, but I think you'll find it much easier on ASTs because you don't have to shuffle strings-of-tokens).
It is easier, when manipulating symbolic formulas, to apply an engine, typically a [program transformation system](http://en.wikipedia.org/wiki/Program_transformation), that will accept the rewrites directly and apply them for you. The notation I used here is taken from our DMS Software Reengineering Toolkit, which takes these rules directly and handles associativity and commutativity automatically. This is probably not a workable choice inside PHP.
One last issue: if your terms have any complexity, the final disjunctive normal form can get pretty big, pretty fast. We had a client that wanted exactly this, until we gave it to him on a big starting term, which happened to produce hundreds of leaf conjunctions. (So far, we've not found a pretty way to present arbitrary boolean terms.)
|
12,183,572 |
I am trying to fill out the fields on a form through JavaScript. The problem is I only know how to execute JavaScript on the current page so I cannot redirect to the form and execute code from there. I'm hesitant to use this term, but the only phrase that comes to mind is cross-site script. The code I am attempting to execute is below.
```
<script language="javascript">
window.location = "http://www.pagewithaform.com";
loaded();
//checks to see if page is loaded. if not, checks after timeout.
function loaded()
{
if(window.onLoad)
{
//never executes on new page. the problem
setTitle();
}
else
{
setTimeout("loaded()",1000);
alert("new alert");
}
}
//sets field's value
function setTitle()
{
var title = prompt("Field Info","Default Value");
var form = document.form[0];
form.elements["fieldName"].value = title;
}
</script>
```
I'm not truly sure if this is possible. I'm also open to other ideas, such as PHP. Thanks.
EDIT: The second page is a SharePoint form. I cannot edit any of the code on the form. The goal is to write a script that pre-fills most of the fields because 90% of them are static.
|
2012/08/29
|
[
"https://Stackoverflow.com/questions/12183572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096496/"
] |
You're trying to maintain state between pages. Conventionally there are two ways to maintain state:
* Store state in cookies
* Store state in the query string
Either way your first page has to persist state (to either cookies or the query string) and the other page has to - separately - restore the state. You can't use the same script across both pages.
Example: Using Cookies
======================
Using cookies, the first page would have to write all the form data you'll need on the next page to cookies:
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With Cookies</title>
</head>
<body>
<div>
Setting cookies and redirecting...
</div>
<script>
// document.cookie is not a real string
document.cookie = 'form/title=My Name is Richard; expires=Tue, 29 Aug 2017 12:00:01 UTC'
document.cookie = 'form/text=I am demoing how to use cookies in JavaScript; expires=Tue, 29 Aug 2017 12:00:01 UT';
setTimeout(function(){
window.location = "./form-cookies.html";
}, 1000);
</script>
</body>
</html>
```
... and the second page would then read those cookies and populate the form fields with them:
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With Cookies</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var COOKIES = {};
var cookieStr = document.cookie;
cookieStr.split(/; /).forEach(function(keyValuePair) { // not necessarily the best way to parse cookies
var cookieName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var cookieValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
COOKIES[cookieName] = cookieValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = COOKIES["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = COOKIES["form/text"];
</script>
</body>
</html>
```
Example: Using the Query String
===============================
In the case of using the Query String, the first page would just include the query string in the redirect URL, like so:
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Query String</title>
</head>
<body>
<div>
Redirecting...
</div>
<script>
setTimeout(function(){
window.location = "./form-querystring.html?form/title=My Name is Richard&form/text=I am demoing how to use the query string in JavaScript";
}, 1000);
</script>
</body>
</html>
```
...while the form would then parse the query string (available in JavaScript via `window.location.search` - prepended with a `?`):
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Query String</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var GET = {};
var queryString = window.location.search.replace(/^\?/, '');
queryString.split(/\&/).forEach(function(keyValuePair) {
var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
GET[paramName] = paramValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = GET["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = GET["form/text"];
</script>
</body>
</html>
```
Example: With a Fragment Identifier
===================================
There's one more option: since state is being maintained strictly on the client side (not on th server side) you could put the information in a fragment identifier (the "hash" part of a URL).
The first script is very similar to the Query String example above: the redirect URL just includes the fragment identifier. I'm going to re-use query string formatting for convenience, but notice the `#` in the place where a `?` used to be:
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Fragment Identifier</title>
</head>
<body>
<div>
Redirecting...
</div>
<script>
setTimeout(function(){
window.location = "./form-fragmentidentifier.html#form/title=My Name is Richard&form/text=I am demoing how to use the fragment identifier in JavaScript";
}, 1000);
</script>
</body>
</html>
```
... and then the form has to parse the fragment identifier etc:
```
<!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Fragment Identifier</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var HASH = {};
var hashString = window.location.hash.replace(/^#/, '');
hashString.split(/\&/).forEach(function(keyValuePair) {
var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
HASH[paramName] = paramValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = HASH["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = HASH["form/text"];
</script>
</body>
</html>
```
And if you can't edit the code for the form page
================================================
[Try a greasemonkey script.](http://userscripts.org/scripts/show/39313)
|
136,182 |
I want to load a lot of CSV files from a local disc in an already created postgres database. Which is the easiest way to do that? By using SQL or Java? I suppose that I need a loop for doing that, but how to implement loop in SQL?
|
2015/02/20
|
[
"https://gis.stackexchange.com/questions/136182",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/47840/"
] |
In Linux/Mac or on Windows using cygwin you can simply call the `psql` command in a loop, using Postgres's built in [COPY](http://www.postgresql.org/docs/9.4/static/sql-copy.html) command. You use the `-c` switch to psql to indicate that you are running the command inside the quotes. This works well because you can use the operating system to get the list of files very easily. For example,
```
for x in $(ls file_name*.csv);
do psql -c "copy table_name from '/path/todir/$x' csv" db_name; done
```
where you need to replace file\_name, table\_name and db\_name and the path with something appropriate to your system. file\_name\*.csv can be any regular expression that matches your file names, for example, the above would match file\_name1.csv, file\_name2.csv, etc.
If you want to do this within Postgres itself, you will need to use dynamic SQL inside a plpgsql function and loop through calling COPY multiple times with a file list that you will have to send to the function. This is considerably more painful, as you not only have to pass and parse the list within the function, but you also lose the ability to do expression searches on the filesystem as with the `ls file_name*.csv` example above.
If you are on Windows and don't have cygwin, I am sure there is any easy way using Power Shell or similar -- just don't ask me how :D. Java I would regard as overkill for this, though obviously you could do it.
|
31,891,630 |
I have installed the git and customized it, then I have tried to push repository. But it didn't do to push. Git say error: failed to push some refs to '<https://github.com/HeartOfProgrammer/PHP-CODES.git>'
What's the problem?
|
2015/08/08
|
[
"https://Stackoverflow.com/questions/31891630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5119153/"
] |
As a registered user, you can do the following:
Under [user preferences => appearance](https://en.wikipedia.org/w/index.php?title=Special:Preferences#mw-prefsection-rendering), switch on the "MathML with SVG or PNG fallback" mode. (The other two modes require a slightly different script but imho that mode is the best option right now.)
Next edit your user specific scripts page at `https://en.wikipedia.org/wiki/User:YOURHANDLE/common.js` [Don't forget to change user name!] and add the following custom script to it:
```
// add to User:YOURNAME/common.js to get smooth MathJax rendering
var mathTags = $('.mwe-math-mathml-a11y');
if (mathTags.length > 0){ //only do something when there's math on the page
window.MathJax = { //hook into MathJax's configuration
AuthorInit: function () {
MathJax.Hub.Register.StartupHook("End",function () { //when MathJax is done...
MathJax.Hub.Queue(
function(){
mathTags.removeClass('mwe-math-mathml-a11y'); // .. make the span around MathML (now MathJax output) visible
$('.mwe-math-fallback-image-inline').addClass('mwe-math-mathml-a11y'); //hide fallback images
}
);
});
}
};
mw.loader.load('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=MML_HTMLorMML-full');//load MathJax with a suitable combined config file
}
```
This script loads MathJax only when there's math in the page, renders it, and (when rendering its done) replaces the fallback images with the results.
This way, you have very little jitter. From a quick test this seems to work on Chrome 43, Firefox 39, IE8 and Edge, and WebKit 2.6.2 (so should work on Safari).
|
50,027,721 |
I would like to know, what does the '~' character mean in the following `Solr` query snippet:
```
... q="field:'value'~30^10 ...
```
|
2018/04/25
|
[
"https://Stackoverflow.com/questions/50027721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3190600/"
] |
`~` is used to do Fuzzy search in this case.
the fuzzy query is based on Levenshtein Distance algo. This algo identifies minumun number of edits required to covert one token to another.
this is the syntax that is used:
>
> q=field:term~N
>
>
>
where N is the edit distance. The value of N varies from 0 to 2.
If you do not specify anything for N, then a value of 2 is used as default.
N=2 -> This matches the highest number of edits.
N=0 -> This means no edit and would have same effect as term query.
You can give a fraction value between 0 and 1 but any fraction value greater then 1 will throw the following error.
```
org.apache.solr.search.SyntaxError: Fractional edit distances are not allowed!
```
Note: However giving a fraction values less then 1 also defaults to 2.
so `q=field:term~0.2` will have the same effect as `q=field:term~2`
Also any distance greater then 2 will also default to 2.
so in the following case
>
> q="field:value~30"
>
>
>
is same as (you can verify this by looking at debug query.)
>
> q="field:value~2"
>
>
>
which will match the highest no. of edits.
Note:
the tilde in the fuzzy query is different then the proximity query. In a proximity query the tilde is applied after the quotation mark.
e.g below query
>
> q=field:"foo bar"~30
>
>
>
So in your case when you are adding quotes around the field
```
q="field:'value'~30"
```
it is becoming proximity search, which really applies if you have two terms in the field. So it wont do much instead of just finding docs which have "value" set in "field".
|
26,270,631 |
I have a Heading tag of HTML which contains a message.Now as per my requirement i need to change the message on every 10 Seconds.I mean i have to change the content of the heading tag on specific interval so that the message that is displaying will get change..
Here is my HTML..
```
<h1 id="dynamicMessage">Responsive Page<br/><span>Message1</span></h1>
```
Please help me to get it by the help of jquery..
Thanks in advance..
|
2014/10/09
|
[
"https://Stackoverflow.com/questions/26270631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4104954/"
] |
There is no need for jQuery here, you can simply do that by using [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval) like,
```
setInterval(function(){
$("#dynamicMessage").html('here is your message');
}, 10000);
```
If you want to load some random data which are loaded dynamically, then the logic must be different according to the need.
|
33,414 |
On long-haul flights, there are extra pilots on board so that the flight crew gets a chance to rest. When the pilot in command gets relieved and goes to the rest area, who is legally in charge of the airplane? Is the PIC role transferred to one of the pilots in the cockpit, or is the person who was relieved still ultimately in command? (I'm especially interested in what happens if the relieved PIC feels that the crew is mishandling the aircraft and wants to come back and take control).
|
2016/11/25
|
[
"https://aviation.stackexchange.com/questions/33414",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/923/"
] |
The PIC is ultimately responsible for operation and safety, for everybody and everything on board, from pre-flight preparation till post-flight activities.
On long-haul flights there must be a sufficient number of relief crew members to substitute the nominal flight crew. This is regulated in national legislation and implemented in airline standard operation procedures (SOP). Details are apparently different from airline to airline.
The Captain is the highest ranking member of the flight crew, and will be designated as PIC. When the PIC takes a rest, there must be a qualified substitute available. That will be a Senior First Officer (SFO) in some airlines. In any case, the substitute will have gone through a dedicated training.
During the rest of the PIC, the substitute will *act* as PIC. The sleeping Captain remains PIC, and remains ultimately responsible. If there is an incident during his rest, it would have to be investigated if that incident was (partially) due to earlier decisions, actions or omissions, or if the problem was caused entirely by the relief crew.
|
64,057,131 |
I'm trying to navigate a website with Selenium
I searched Google and said that adding user-agent would solve it, but it didn't solve it.
<http://coupang.com/>
```
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time
options = Options()
options = webdriver.ChromeOptions()
# options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument('lang=ko_KR')
options.add_argument("--disable-gpu")
options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5")
options.add_argument("accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
options.add_argument("accept-charset=cp1254,ISO-8859-9,utf-8;q=0.7,*;q=0.3")
options.add_argument("accept-encoding=gzip,deflate,sdch")
options.add_argument("accept-language=tr,tr-TR,en-US,en;q=0.8")
driver = webdriver.Chrome('d:/temp/chromedriver.exe',options=options)
TEST_URL = 'https://login.coupang.com/login/login.pang?rtnUrl=https%3A%2F%2Fwww.coupang.com%2Fnp%2Fpost%2Flogin%3Fr%3Dhttps%253A%252F%252Fwww.coupang.com%252F'
driver.get(TEST_URL)
time.sleep(5)
driver.implicitly_wait(3)
elem_login = driver.find_element_by_id("login-email-input")
elem_login.clear()
elem_login.send_keys("id")
time.sleep(3)
elem_login = driver.find_element_by_id("login-password-input")
elem_login.clear()
elem_login.send_keys("pw")
time.sleep(3)
xpath = "/html/body/div[1]/div/div/form/div[5]/button"
driver.find_element_by_xpath(xpath).click()
driver.implicitly_wait(3)
print(driver.page_source)
```
|
2020/09/25
|
[
"https://Stackoverflow.com/questions/64057131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8044550/"
] |
Keep the state only in the parent, and pass it down as a prop, as well as another prop - a function which, when called, sets the age in the parent.
You also need to correct the shape of `onChange` - it accepts an argument of the *event*, not of the new value.
```
// in CreateGame
const setAge = i => (newAge) => {
setQuestions([
questions.slice(0, i),
{ ...questions[i], age: newAge },
questions.slice(i + 1),
]);
};
// ...
<Grid item lg={5}>
<SelectField age={questions.age} setAge={setAge(index)} />
</Grid>
```
```
export default function SelectField({ age, setAge }) {
// ...
<Select
value={age}
onChange={e => setAge(e.currentTarget.value)}
```
|
24,340,781 |
My controller is returning Json result of List
```
Public ActionResult Index([DataSourceRequest] DataSourceRequest request)
{
var list = new List<Product>();
Json(list.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
```
Below is the code of my Unit Test method,in which i am calling above method:
```
//Act
var actualResult = _Controller.Index(request) as JsonResult;
var data = actualResult.Data;
```
And now i want to covert this data object to its original type means List.
I tried like below :-
```
var result = ser.Deserialize<List<Product>>(ser.Serialize(actualResult.Data));
```
But i am not getting my original data by this.Can anyone help me out,how we can covert jsonresult.data output to its original type ?
|
2014/06/21
|
[
"https://Stackoverflow.com/questions/24340781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972569/"
] |
Your Index action is returning a DataSourceResult that contains your List, and not a simple List (Json(list.ToDataSourceResult(request)).
You first need to deserialize the result as a DataSourceResult, or as a JsonObject, and then select the List of Products.
In the DataSourceResult (KendoUI object) the list is in the Data Property:
```
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = ser.Deserialize<Kendo.Mvc.UI.DataSourceResult>(ser.Serialize(actualResult.Data));
var list = result.Data; //as an ArrayList
```
Using Javascript Object:
```
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = (Dictionary<string, object>)ser.DeserializeObject(ser.Serialize(actualResult.Data));
var list = ser.Deserialize<List<Product>>(ser.Serialize(result["Data"]));
```
Using Newtonsoft Json:
```
var result = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(JsonConvert.SerializeObject(actualResult.Data));
var list = JsonConvert.DeserializeObject<List<Product>>(result.SelectToken("Data").ToString());
```
|
7,676,005 |
Basically I'm trying to write a loop -
that on first iteration will have
```
srcT = Worksheets("I").Range("B1").Value
srcC = Worksheets("I").Range("B2").Value
trgT = Worksheets("I").Range("B3").Value
trgC = Worksheets("I").Range("B4").Value
```
then 2nd iteration
```
srcT = Worksheets("I").Range("B5").Value
srcC = Worksheets("I").Range("B6").Value
trgT = Worksheets("I").Range("B7").Value
trgC = Worksheets("I").Range("B8").Value
```
then 3rd iteration
```
srcT = Worksheets("I").Range("B9").Value
srcC = Worksheets("I").Range("B10").Value
trgT = Worksheets("I").Range("B11").Value
trgC = Worksheets("I").Range("B12").Value
```
and continue with this pattern until a blank cell is encountered in column B.
|
2011/10/06
|
[
"https://Stackoverflow.com/questions/7676005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688412/"
] |
Layouts are bound to the context of the Activity that holds it, so you do no want to save full `View` objects to files because the Activity that it's attached to is void.
The easiest method (depending on the amount and type of data you want to save) is using the [SharedPreferences](http://developer.android.com/guide/topics/data/data-storage.html#pref) library. It's a file I/O wrapper that makes saving and retrieving data pretty simple. You can save the specific layout data in the `onPause()` method, the rebuild the layout with the specifications in `onResume()`.
If the data you need is too complex for `SharedPreferences`, you'll have to save it to use other methods for saving (found in that link). The process for rebuilding the layouts will be the same.
|
29,316,437 |
I have 2 tables where one is a related table and the other is a base table. First one is class\_has\_student and the other is student. I need to return all related data of classes for a particular student in class\_has\_student and class information for classes where student not registered even. (student.id references class\_has\_student.student\_id)
```
class_has_student table student table
class_id | student_id id | name
---------|----------- --------|---------
1| 1001 1001| John
2| 1001 1002| Michael
1| 1002 1003| Anne
3| 1002
1| 1003
2| 1003
3| 1003
4| 1003
```
I need to get information from class\_has\_student when I pass a student.id and class\_has\_student.class\_id for related data and null for class\_has\_student.class\_id if the student not registered to that class. For example if I want to get class registration information for John for classes 1, 2 and 3. The result I expect is related class student data for classes 1 and 2 and only class information for class 3(class table is not showed here, so returning id is sufficient). So, the result must be,
```
class_id | student_id
---------|-----------
1| 1001
2| 1001
3| NULL
```
I tried to achieve this through following query and several variations but did not succeed. It's highly appreciated if somebody could help.
```
SELECT chs.class_id, s.id
FROM student s LEFT OUTER JOIN class_has_student chs ON s.id = chs.student_id AND s.id = 1001
WHERE chs.class_id IN(1,2,3);
```
The fiddle is here.
<http://sqlfiddle.com/#!9/839fe/4>
|
2015/03/28
|
[
"https://Stackoverflow.com/questions/29316437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/874000/"
] |
Based on [this blog post](http://www.ostricher.com/2015/01/python-subprocess-with-timeout/) code with a couple of changes you can use threading.Thread:
```
from threading import Thread
from subprocess import PIPE, Popen
def proc_timeout(secs, *args):
proc = Popen(args, stderr=PIPE, stdout=PIPE)
proc_thread = Thread(target=proc.wait)
proc_thread.start()
proc_thread.join(secs)
if proc_thread.is_alive():
try:
proc.kill()
except OSError:
return proc.returncode
print('Process #{} killed after {} seconds'.format(proc.pid, secs))
return proc
```
You should only catch specific exceptions in your try/except, don't try to catch them all.
|
5,527,779 |
i have this issue with app engine's datastore. In interactive console, I always get no entities when i ask if a url already exists in my db. When I execute the following code....
```
from google.appengine.ext import db
class shortURL(db.Model):
url = db.TextProperty()
date = db.DateTimeProperty(auto_now_add=True)
q = shortURL.all()
#q.filter("url =", "httphello")
print q.count()
for item in q:
print item.url
```
i get the this response, which is fine
```
6
httphello
www.boston.com
http://www.boston.com
httphello
www.boston.com
http://www.boston.com
```
But when I uncomment the line "q.filter("url =", "httphello")", i get no entities at all (a response of 0). I know its something ultra simple, but I just can't see it! help.
|
2011/04/03
|
[
"https://Stackoverflow.com/questions/5527779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689553/"
] |
[TextProperty](http://code.google.com/intl/it/appengine/docs/python/datastore/typesandpropertyclasses.html#TextProperty) values are not indexed, and cannot be used in filters or sort orders.
You might want to try with [StringProperty](http://code.google.com/intl/it/appengine/docs/python/datastore/typesandpropertyclasses.html#StringProperty) if you don't need more than 500 characters.
|
943,638 |
I am trying to integrate a password generator into my batch file so that it generates multiple passwords.
Unfortunately it give the following error:
```
\/?' was unexpected at this time.
```
The expected output is multiple (1000) lines of the form:
Random string is {password}
Where `{password}` consists of 32 random characters from the string `_Alphanumeric`.
Here is my batch file:
```
@echo off
set executecounter=0
setlocal
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set alfanum=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
:loop
(@Echo Off
Setlocal EnableDelayedExpansion
Set _RNDLength=32
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@()\/?'=-_+
Set _Str=%_Alphanumeric%987654321
:_LenLoop
IF NOT "%_Str:~18%"=="" SET _Str=%_Str:~9%& SET /A _Len+=9& GOTO :_LenLoop
SET _tmp=%_Str:~9,1%
SET /A _Len=_Len+_tmp
Set _count=0
SET _RndAlphaNum=
:_loop
Set /a _count+=1
SET _RND=%Random%
Set /A _RND=_RND%%%_Len%
SET _RndAlphaNum=!_RndAlphaNum!!_Alphanumeric:~%_RND%,1!
If !_count! lss %_RNDLength% goto _loop
Echo Random string is !_RndAlphaNum! >> D:\password2.txt
pause
)
set /a executecounter=%executecounter%+1
if "%executecounter%"=="1000" goto done
goto loop
:done
echo Complete!
endlocal
pause
```
How can I resolve this error?
|
2015/07/22
|
[
"https://superuser.com/questions/943638",
"https://superuser.com",
"https://superuser.com/users/471803/"
] |
### /?' was unexpected at this time error in batch file.
This is because you have used brackets `(` and `)` to group multiple commands.
Your code contains the following:
```
(
...
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZ ... @()\/?'=-_+
)
```
This means that the wrong `)` (the one in the `set`) is matching the first opening `(`, hence the error.
In fact you don't need to use brackets `(` and `)` to group multiple commands if a couple of other small changes are made, which is to re-initialise some variables because you have a new outer loop in order to generate multiple passwords.
---
### Fixed batch file:
```
@echo off
set executecounter=0
setlocal
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
:loop
Set _RNDLength=32
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@()\/?'=-_+
Set _Str=%_Alphanumeric%987654321
SET _RndAlphaNum=
set _RND=
set _len=
:_LenLoop
IF NOT "%_Str:~18%"=="" SET _Str=%_Str:~9%& SET /A _Len+=9& GOTO :_LenLoop
SET _tmp=%_Str:~9,1%
SET /A _Len=_Len+_tmp
Set _count=0
SET _RndAlphaNum=
:_loop
Set /a _count+=1
SET _RND=%Random%
Set /A _RND=_RND%%%_Len%
SET _RndAlphaNum=!_RndAlphaNum!!_Alphanumeric:~%_RND%,1!
If !_count! lss %_RNDLength% goto _loop
Echo Random string is !_RndAlphaNum!>> d:\password2.txt
set /a executecounter=%executecounter%+1
if "%executecounter%"=="1000" goto done
goto loop
:done
echo Complete!
endlocal
pause
```
---
### Further Reading
* [An A-Z Index of the Windows CMD command line](http://ss64.com/nt/) - An excellent reference for all things Windows cmd line related.
* [brackets](http://ss64.com/nt/syntax-brackets.html) - Using parenthesis/brackets to group expressions.
|
4,902,491 |
Background subtraction is an important primitive in computer vision. I'm looking at different methods that have been developed, and I've begun thinking about how to perform background subtraction in the face of random, salt and pepper noise.
In a system such as the Microsoft Kinect, the infrared camera will give off random noise pretty consistently. If you are trying to background subtract from the depth view, how can you avoid an issue with this random noise while reliably subtracting the background?
|
2011/02/04
|
[
"https://Stackoverflow.com/questions/4902491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/603760/"
] |
as you already said, noise and other unsteady parts of your background might give problems in segmentation, I mean lighting changes or other moving stuff in the background.
But if you're working on some indoor-project this shouldn't be too big of an issue, except of course the noise thing.
Besides substracing the background from an image to segment the objects in it you could also try to subtract two (or in some methods even three) following frames from each other. If the camera is steady this should leave the parts that have changed, so basically the objects that have moved. So this is an easy method for detecting moving objects.
But in most operations you might use you probably will have that noise you described. Easiest way to get rid of it is by using **Median Filter** or **Morpholocigal Operators (Opening)** on the segmented binary image. This should effectively remove small parts and leave the nice big blobs of the objects.
Hope that helps...
|
51,258,471 |
I'm using a SQL Server stored procedure but I'm getting a syntax error in SQL `Case`.
Here is my stored procedure code:
```
ALTER PROCEDURE [dbo].[spSelectServiceRequest]
AS
BEGIN
SELECT
[id],
[ServiceID],
[fullName],
[email], [mobile],
[address],
[serviceNeed],
[problem],
[serviceDate],
[createdOn],
[status] = CASE [status]
WHEN '1' THEN 'New Request'
WHEN '2' THEN 'Pending'
WHEN '3' THEN 'Accept By Provider'
ELSE 'Close'
END
FROM
[tblBookingDetail]
ORDER BY
[createdOn] DESC;
END;
```
Any kind of help will be appreciated.
|
2018/07/10
|
[
"https://Stackoverflow.com/questions/51258471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8861869/"
] |
Try this:
```
ALTER PROC [dbo].[spSelectServiceRequest]
AS
BEGIN
SELECT
[id]
, [ServiceID]
, [fullName]
, [email]
, [mobile]
, [address]
, [serviceNeed]
, [problem]
, [serviceDate]
, [createdOn]
, CASE [status]
WHEN '1'
THEN 'New Request'
WHEN '2'
THEN 'Pending'
WHEN '3'
THEN 'Accept By Provider'
ELSE 'Close'
END AS [status]
FROM [tblBookingDetail]
ORDER BY
[createdOn] DESC;
END;
```
|
56,326,248 |
I have created expandable recylerview following is my adapter code
```
public class FoodMenuRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<Object> objects;
FoodMenuParentListener foodMenuParentListener;
boolean isAddAllowed;
boolean isVegOnly;
static final int TYPE_FOOD = 0;
static final int TYPE_MENU_ITEM = 1;
public FoodMenuRecyclerAdapter(List<Object> objects, FoodMenuParentListener foodMenuParentListener, boolean isVegOnly, boolean isAddAllowed) {
this.foodMenuParentListener = foodMenuParentListener;
this.isVegOnly = isVegOnly;
this.isAddAllowed = isAddAllowed;
this.objects = objects;
}
@Override
public int getItemViewType(int position) {
Object object = objects.get(position);
if (object instanceof FoodMenuItem) {
return TYPE_FOOD;
} else if(this.objects.get(position) == null) {
throw new IllegalStateException("Null object added");
}else {
return TYPE_MENU_ITEM;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view;
switch (getItemViewType(i)) {
case TYPE_FOOD:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_parent, viewGroup, false);
return new MenuViewHolder(view);
case TYPE_MENU_ITEM:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_child, viewGroup, false);
return new ChildMenuHolder(view);
default:
throw new IllegalArgumentException("Invalid viewType");
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
Object object = objects.get(i);
Context context = viewHolder.itemView.getContext();
Log.d("myAdapter","position"+ i + ":"+ ((getItemViewType(i) == TYPE_MENU_ITEM) ? "TYPE_MENU_ITEM" : "TYPE_FOOD"));
if (getItemViewType(i) == TYPE_MENU_ITEM) {
ChildMenuHolder childMenuHolder = (ChildMenuHolder) viewHolder;
Item item = (Item) object;
childMenuHolder.tvTitle.setText(item.getTitle());
childMenuHolder.txtQty.setText(String.valueOf(item.getQuatity()));
childMenuHolder.txtCartInc.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
childMenuHolder.txtQty.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
childMenuHolder.txtCartDec.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
childMenuHolder.btnAdd.setVisibility(!item.isAddedToCart() ? View.VISIBLE : View.GONE);
childMenuHolder.btnAdd.setBackgroundResource(isAddAllowed ? R.drawable.rounded_bottom_edge_shape_food : R.drawable.rounded_bottom_edge_shape_disable);
childMenuHolder.btnAdd.setTextColor(isAddAllowed ? ContextCompat.getColor(context, R.color.button_green) : ContextCompat.getColor(context, R.color.gray_a1));
childMenuHolder.ivType.setColorFilter(item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG) ? ContextCompat.getColor(context, R.color.selected_green) : ContextCompat.getColor(context, R.color.app_red));
} else {
FoodMenuItem foodMenuItem = (FoodMenuItem) object;
MenuViewHolder menuViewHolder = (MenuViewHolder) viewHolder;
if (isVegOnly) {
List<Item> items = new ArrayList<>();
for (Item item : foodMenuItem.getItems()) {
if (item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG)) {
items.add(item);
}
}
menuViewHolder.tvNumItems.setText("(" + items.size() + " items)");
} else {
menuViewHolder.tvNumItems.setText("(" + foodMenuItem.getItems().size() + " items)");
}
menuViewHolder.ivArrow.setImageResource(foodMenuItem.isExpanded() ? R.drawable.chev_up : R.drawable.chev_down);
menuViewHolder.tvTitle.setText(foodMenuItem.getCategoryName());
}
}
@Override
public int getItemCount() {
return objects.size();
}
public class MenuViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvNumItems;
ImageView ivArrow;
// RecyclerView rvMenu;
View rlArrow;
public MenuViewHolder(@NonNull View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
tvNumItems = (TextView) itemView.findViewById(R.id.tvNumItems);
ivArrow = (ImageView) itemView.findViewById(R.id.ivArrow);
// rvMenu.setNestedScrollingEnabled(false);
rlArrow = itemView.findViewById(R.id.rlArrow);
rlArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (foodMenuParentListener != null) {
Object object = objects.get(getAdapterPosition());
if (object instanceof FoodMenuItem) {
FoodMenuItem foodMenuItem = (FoodMenuItem) object;
foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());
}
}
}
});
tvTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (foodMenuParentListener != null) {
Object object = objects.get(getAdapterPosition());
if (object instanceof FoodMenuItem) {
FoodMenuItem foodMenuItem = (FoodMenuItem) object;
foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());
}
}
}
});
}
}
public boolean isVegOnly() {
return isVegOnly;
}
public void setVegOnly(boolean vegOnly) {
isVegOnly = vegOnly;
}
public interface FoodMenuParentListener extends AddItemListener {
public void OnExpandClick(FoodMenuItem foodMenuItem, int position);
public void OnVegOnlyClicked();
}
public class ChildMenuHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView ivType;
TextView tvTitle;
TextView tvPrice;
TextView txtCartDec;
TextView txtQty;
TextView txtCartInc;
Button btnAdd;
public ChildMenuHolder(@NonNull View itemView) {
super(itemView);
ivType = (ImageView) itemView.findViewById(R.id.ivType);
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
txtCartDec = (TextView) itemView.findViewById(R.id.txtCartDec);
txtQty = (TextView) itemView.findViewById(R.id.txtQty);
txtCartInc = (TextView) itemView.findViewById(R.id.txtCartInc);
btnAdd = (Button) itemView.findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
txtCartInc.setOnClickListener(this);
txtCartDec.setOnClickListener(this);
}
@Override
public void onClick(View view) {
}
}
public void setExpandIndex(int expandIndex) {
}
public boolean isItemExpanded(int position) {
return true;
}
public class VegOnlyViewHolder extends RecyclerView.ViewHolder {
Switch wtVeg;
public VegOnlyViewHolder(@NonNull View itemView) {
super(itemView);
wtVeg = (Switch) itemView.findViewById(R.id.wtVeg);
wtVeg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (foodMenuParentListener != null) {
foodMenuParentListener.OnVegOnlyClicked();
}
}
});
}
}
public interface AddItemListener {
public void onAddClicked(Item item, int parentIndex);
public void increaseItemCount(Item item, int parentIndex);
public void decreaseItemCount(Item item, int parentIndex);
}
public void addAll(int position, List<Item> objectsToAdd) {
this.objects.addAll(position, objectsToAdd);
}
public void addItem(int position, Item object) {
this.objects.add(position, object);
}
public void removeItem(Object object) {
this.objects.remove(object);
}
public void removeAll(List<Item> objectsToRemove) {
objects.removeAll(objectsToRemove);
Log.d("myAdapter","item at first position after remove" + ":"+objects.get(0));
Log.d("myAdapter","item at second position after remove" + ":"+objects.get(1));
}
public Object isItemInList(Item item) {
for (Object object : objects) {
if (object instanceof Item && ((Item) object).getId().equals(item.getId())) {
return object;
}
}
return null;
}
}
```
Following is code in my Fragment to expand collapse RecyclerView
```
@Override
public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
recyclerViewMenu.getRecycledViewPool().clear();
FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
if (foodMenuItem.isExpanded()) {
foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());
} else {
foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
foodMenuRecyclerAdapter.notifyItemRangeRemoved(position + 1, foodMenuItem.getItems().size());
}
}
}
```
Following is listener code inside fragment to expand and collapse
```
public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
if (foodMenuItem.isExpanded()) {
foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());
} else {
foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
foodMenuRecyclerAdapter.notifyItemRangeRemoved(position +1 , foodMenuItem.getItems().size());
}
}
}
```
Above code is throwing exception following is exception stack trace
```
java.lang.ClassCastException: com.myapp.android.pojoentities.Item cannot be cast to com.myapp.android.pojoentities.FoodMenuItem
at com.myapp.android.food.menu.FoodMenuRecyclerAdapter.onBindViewHolder(FoodMenuRecyclerAdapter.java:104)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1183)
at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:870)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:889)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at com.myapp.android.custom.FitsSystemWindowsFrameLayout.onLayout(FitsSystemWindowsFrameLayout.java:247)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1231)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:
```
Update:
After collapsing first item I have checked log for type of first two items in list found that first two items are of type ParentItem which is FoodMenuItem but when I checked log for getItemViewType for same positions it is returning wrong value somehow
Following are logs
```
05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at first position after remove:com.myapp.android.pojoentities.FoodMenuItem@7fdf002
05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at second position after remove:com.myapp.android.pojoentities.FoodMenuItem@9cbfd13
05-28 00:13:47.664 32010-32010/com.myapp.android D/myAdapter: position1:TYPE_FOOD
05-28 00:13:47.678 32010-32010/com.myapp.android D/myAdapter: position2:TYPE_MENU_ITEM
```
[here is sample project for reference](http://here%20is%20sample%20project%20for%20reference%20github.com/amodkanthe/ExpandRecyclerView)
|
2019/05/27
|
[
"https://Stackoverflow.com/questions/56326248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153589/"
] |
Instead of manual iterating through the list, you can use built-in function [min](https://docs.python.org/3/library/functions.html?highlight=min#min) and [string slicing](https://docs.python.org/3/tutorial/introduction.html#strings):
```
temps = [7, 4, 1, -9, 18, 32, 10]
print(min(temps[1:]))
```
>
> `-9`
>
>
>
|
11,856,723 |
I have a NSMutableArray which is used inside the ASIHTTPRequest process. After the data loading is done, the NSMutableArray stores the info. When I add the data as
```
[MyArray addObject];
```
I dont have any errors. However when I insert the data as
```
[MyArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];
```
I have malloc error or index out of range exception issues. I assume this as a thread safety malfunctioning. Any solution for this?
EDITED:
in appdelegate.h
```
@interface{
NSMutableArray *imageArray;
}
```
in appdelegate.m
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
imageArray = [[NSMutableArray alloc] init];
return YES;
}
```
In the AsyncImageView.h
```
@interface{
AppDelegate *delegate
}
```
AsyncImageView.m
```
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.imageArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];
}
```
|
2012/08/08
|
[
"https://Stackoverflow.com/questions/11856723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189879/"
] |
It's hard to say without seeing your code, but I doubt this is a threading issue. When you call `insertObject:atIndex:` you have to be able to guarantee there are at least that many objects in the array already. Look at your code and see where you add objects, and make sure that every scenario leads to you adding enough objects that `insertObject:atIndex` won't fail.
Hopefully this next fact is obvious to you, but just in case, I'll point out that `initWithCapacity:` does **not** add any elements to the array. Many people assume it does, leading to the exact problem you described.
Based on your comment, the solution might be to pre-populate your array with a bunch of NSNull objects, or to use an NSDictionary instead of an array.
**EDIT**
Here's a quick NSDictionary example:
Upon further review, you'll actually need an NSMutableDictionary since you're dynamically updating its contents. You can't use an integer as the key, so you have to "wrap" the integer in an NSNumber object. (Note that you can use any object as a key, not just NSNumbers.)
Store an object like this:
```
[myDictionary setObject:[UIImage imageWithData:data] forKey:[NSNumber numberWithInt:buttonTag]];
```
Access it later like this:
```
myImage = [myDictionary objectForKey:[NSNumber numberWithInt:buttonTag]];
```
Of course, much more information is available in Apple's documentation or with a quick search for "NSDictionary example."
|
55,630,323 |
I have an ordinary library, presented in pypi. Inside it, there is a tricky way to resolve names in the modules that we import.
If I install it to Python folder, in a common way, PyCharm resolves it, builds a skeleton and I get the auto-completion for it.
But in our project, we are holding used libraries in a project folder and PyCHarm doesn't read and process the library. For this, I got the "unresolved references" inspection raising, and the red wave-line.
How can I make PyCharm resolve a library in a project folder?
Example:
```
MyProjectRoot
-- external_libs
--six.py
```
When I write:
```
from external_libs.six.moves import range
```
PyCharm marks "moved" with yellow and "range" with the red wave-line.
|
2019/04/11
|
[
"https://Stackoverflow.com/questions/55630323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/808740/"
] |
From the [documentation](https://pythonhosted.org/six/#module-six.moves) for the `six` package:
>
> **Note**: In order to make imports of the form:
>
>
> `from six.moves.cPickle import loads work`
>
>
> six places special proxy
> objects in in sys.modules. These proxies lazily load the underlying
> module when an attribute is fetched.
>
>
>
Because of that, the base path resolver in PyCharm is not able to easily find the actual path to the modules that are being imported for this package and other that use the same approach.
---
In order to overcome this problem, PyCharm uses [**Typeshed Stubs**](https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html#typeshed):
>
> Typeshed is a set of files with type annotations for the standard
> Python library and various packages. Typeshed stubs provide
> definitions for Python classes, functions, and modules defined with
> type hints. PyCharm uses this information for better code completion,
> inspections, and other code insight features.
>
>
>
The typeshed stubs which can be found in their [official repository](https://github.com/python/typeshed), serve as a lookup table. For example, if you are looking for the `range` function from `six.moves` which is just an alias for the built in `range` function, they will help PyCharm know how to resolve it by specifying that when you type `from six.moves import range` that should be resolved to something like `from builtins import range`.
---
You can override the bundled typeshed stubs by following the [PyCharm documentation](https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html#typeshed).
**Example:**
If you want to use the `six` package and you have a folder structure like this:
```
six_reproduce
|─── main.py
│
│
├───external_libs
│ |────six.py
```
Go to the original typeshed repository an download the stubs that you need.
For python 3 the stubs for the `six` library can be found **[here](https://github.com/python/typeshed/tree/master/third_party/3/six)**.
Download the folder and put it under `external_libs` so that your project structure becomes this:
```
six_reproduce
|─── main.py
│
│
├─── external_libs
│ |──── six
│ │ |──── moves
│ │ │
│ │ |──── __init__.pyi
│ │
│ |──── six.py
```
PyCharm should now be able to resolve your imports!
|
44,914,459 |
In Java, how do I test if an object's monitor is locked? In other words, given a object obj, does any thread own obj's monitor?
I do not care which thread owns the monitor. All I need to test is if ANY thread owns a given object's monitor. Since a thread other than the current thread could own the monitor, Thread.holdsLock( obj ) is not enough as it only checks the current thread.
I am trying to figure the simplest solution possible.
This is not a duplicate because:
1. I cannot use higher-level/newer concurrency/locking mechanisms. I cannot use Lock, etc. I must use low-level/old/traditional currency/locking mechanisms such as synchronized, wait(), etc.
2. I am not trying to find a time to execute code when has monitor has become unlocked. I am trying to execute code when a monitor is locked.
In fact, to give a little bit of background, this part of a unit test where I am trying to start run two threads which both need to lock the same object.
3. I cannot call internal private JVM dependent methods such as sun.\* .
As a result, in order to test for correct handling of concurrency. I need to
1. Create the two threads.
2. Start thread 1 .
3. As soon as thread 1 owns the monitor, suspend thread 1 .
4. Start thread 2 .
5. As soon as thread 2 is blocked by thread 1, suspend thread 2 .
6. Resume thread 1 .
7. Join thread 1 .
8. Run some assertions.
9. Resume thread 2 .
10. Join thread 2 .
11. Run some assertions.
What I am trying to figure out is the best way to do #3, primarily, determining when thread 1 owns the monitor.
|
2017/07/04
|
[
"https://Stackoverflow.com/questions/44914459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8249043/"
] |
If you really want to do this using thread suspension, you can have thread 1 set a thread safe flag when it has the monitor and observe the flag from your test thread.
However, I doubt that's the best way to put together your test. If you just want to test the business logic in your threads, you can run thread 1, join it, run your first set of assertions, then run thread 2, join it, and run your second set of assertions. Better yet, you could put the business logic in Runnables and test them in your test thread by invoking the run() method directly.
If there's an issue with thread synchronization that you are trying to get at, my experience is that using time delays is a better way to test those issues than interacting directly with the threads, as interacting directly with the threads may introduce or hide synchronization issues. For more on that, see my answer on the general question of testing threaded code here:
[How should I unit test threaded code?](https://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code/32532047#32532047)
|
3,476,563 |
i really need you guys your help. I have to do animation on a 3 X 3 grid of images.
My questions are :
1)
How do i construct the 3 X 3 grid with the images.?
This is what i did but is not working because because i get nullpointerException in this line : `rail[x][y] = new JLabel(icon);`
```
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ButtonGrid {
JFrame frame=new JFrame(); //creates frame
JButton[][] grid; //names the grid of buttons
JLabel[][] rail = null;
public ButtonGrid(int width, int length){ //constructor with 2 parameters
frame.setLayout(new GridLayout(width,length)); //set layout of frame
grid=new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
//grid[x][y]=new JButton("("+x+","+y+")");
//frame.add(grid[x][y]); //adds button to grid
ImageIcon icon = createImageIcon("images/crossingsHorizontal.JPG", "");
//JLabel lab = new JLabel(icon);
rail[x][y] = new JLabel(icon);
frame. add(rail[x][y]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static ImageIcon createImageIcon(String path,String description) {
java.net.URL imgURL = ButtonGrid.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
return null;
}
}
public static void main(String[] args) {
new ButtonGrid(3,3);//makes new ButtonGrid with 2 parameters
}
}
```
2)
How can i use this grid as a background for my animation?
3)
I have to rotate the the image in grid [2][2], how can i access this image alone and rotate it? I know how to do the rotation so tell me how to get the element [2][2] so that i can rotate it.
thanks for your help
|
2010/08/13
|
[
"https://Stackoverflow.com/questions/3476563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403328/"
] |
The code looks ok.
However you should make sure that `Flows` override `equals` and `hashCode`
|
48,796,574 |
I have a React Component with a toggle on it (on or off). The on / off state is handled by the components own state (this.state).
But I want that state to remain when the user goes from one page to the next. For instance they are on home.html and then when user clicks to another page like about.html.
Also this is not a single page app. Do I want Redux or Mobox or some other state management tool? Suggestions are welcomed.
|
2018/02/14
|
[
"https://Stackoverflow.com/questions/48796574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491565/"
] |
>
> But I want that state to remain when the user goes from one page to the next.
>
>
>
As has been said in comments probably the most straight-forward way is to just store the state to localstorage and retrieve it when the component mounts.
```
class Toggle extends Component {
componentDidMount() {
const storedValue = localStorage.getItem("my_value");
if (storedValue) {
this.setState({ value: storedValue });
}
}
handleChange = e => {
const value = e.target.value;
this.setState({ value });
localStorage.setItem("my_value", value);
}
render() {
return ...
}
}
```
>
> Also this is not a single page app. Do I want Redux or Mobox or some other state management tool? Suggestions are welcomed.
>
>
>
No, Redux and Mobx aren't necessary, they are state containers that have ways to persist to localstorage (for example [redux-localstorage](https://github.com/elgerlambert/redux-localstorage) and [mobx-localstorage](https://www.npmjs.com/package/mobx-localstorage)), but the key is just persisting to localstorage.
|
2,394,262 |
To Check whether the cardinality is same
I was solving cardinality of finite set.But couldn't find a way to mapp a bounded subset of $ \mathbb{ R } $ to $\mathbb{R}$
For example
How to prove that cardinality of [0,1] and $ \mathbb{R} $ are same
|
2017/08/15
|
[
"https://math.stackexchange.com/questions/2394262",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/450065/"
] |
$\star$ $[0,1]$ and $(0,1)$ are equivalent
To see this, let $A=[0,1] \setminus \{0,1,\frac{1}{2},\frac{1}{3},...\}$. Define $f:[0,1] \rightarrow (0,1)$ by
$$f(x)= \left\{ \begin{array}{lcc}
\frac{1}{2} & x=0 \\
\\ \frac{1}{n+2}, & x=\frac{1}{n} \\
\\ x & x\in A
\end{array}
\right.$$
Then $f$ is a bijection.
$\star$ $(0,1)$ and $(-\frac{\pi}{2},\frac{\pi}{2})$ are equivalent.
Consider $g:(0,1) \rightarrow (-\frac{\pi}{2},\frac{\pi}{2})$ defined by
$$g(x)=-\frac{\pi}{2}+\pi x$$
$\star$ $(-\frac{\pi}{2},\frac{\pi}{2})$ and $\Bbb{R}$ are equivalent.
Consider $h:(-\frac{\pi}{2},\frac{\pi}{2}) \rightarrow \Bbb{R}$ by
$$h(x)=\arctan x$$
Finally, we conclude $$[0,1] \sim (0,1) \sim (-\frac{\pi}{2},\frac{\pi}{2}) \sim \Bbb{R}$$
To explicitly find the map from $[0,1]$ to $\Bbb{R}$, take the composition of the above maps!
|
8,180,944 |
I've been struggling with this issue for a while now. Maybe you can help.
I have a table with a checkbox at the beginning of each row. I defined a function which reloads the table at regular intervals. It uses jQuery's load() function on a JSP which generates the new table.
The problem is that I need to preserve the checkbox values until the user makes up his mind on which items to select. Currently, their values are lost between updates.
The current code I use that tries to fix it is:
```
refreshId = setInterval(function()
{
var allTicks = new Array();
$('#myTable input:checked').each(function() {
allTicks.push($(this).attr('id'));
});
$('#myTable').load('/get-table.jsp', null,
function (responseText,textStatus, req ){
$('#my-table').tablesorter();
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ )
$("#my-table input#" + allTicks[i]).attr('checked', true);
});
}, $refreshInterval);
```
The id of each checkbox is the same as the table entry next to it.
My idea was to store all the checked checkboxes' ids into an array before the update and to change their values after the update is done, as most of the entries will be preserved, and the ones that are new won't really matter.
'#myTable' is the div in which the table is loaded and '#my-table' is the id of the table which is generated. The checkbox inputs are generated along with the new table and with the same ids as before.
The weird thing is that applying tablesorter to the newly generated table works, but getting the elements with the stored ids doesn't.
Any solutions?
P.S: I know that this approach to table generation isn't really the best, but my JS skills were limited back then. I'd like to keep this solution for now and fix the problem.
**EDIT:**
Applied the syntax suggested by Didier G. and added some extra test blocks that check the status before and after the checkbox ticking.
Looks like this now:
```
refreshId = setInterval(function()
{
var allTicks = []
var $myTable = $('#my-table');
allTicks = $myTable.find('input:checked').map(function() { return this.id; });
$('#myTable').load('/get-table.jsp', null,
function (responseText,textStatus, req ){
$myTable = $('#my-table');
$('#my-table').tablesorter();
var msg = 'Before: \n';
$myTable.find('input').each(function(){
msg = msg + this.id + " " + $(this).prop('checked') + '\n';
});
//alert(msg);
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ ){
$myTable.find('#' + allTicks[i]).prop('checked', true);
}
msg = 'After: '
$myTable.find('input').each(function(){
msg = msg + this.id + " " + $(this).prop('checked') + '\n';
});
//alert(msg);
});
}, $refreshInterval);
```
If I uncomment the alert lines, and check 2 checkboxes, on the next update I get (for 3 row table):
```
Before: host2 false
host3 false
host4 false
object [Object] length 2
After: host2 false
host3 false
host4 false
```
Also did a previous check on the contents of the array and it has all the correct entries.
Can the DOM change or working with an entirely new table instance be a cause of this?
**EDIT2:**
Here's a sample of the table generated by the JSP (edited for confidentiality purposes):
```
<table id="my-table" class="tablesorter">
<thead>
<tr>
<th>Full Name</th>
<th>IP Address</th>
<th>Role</th>
<th>Job Slots</th>
<th>Status</th>
<th>Management</th>
</tr>
</thead>
<tbody>
<tr>
<td>head</td>
<td>10.20.1.14</td>
<td>H</td>
<td>4</td>
<td>ON</td>
<td>Permanent</td>
</tr>
<tr>
<td>
<input type="checkbox" id="host2" name="host2"/>
host2
</td>
<td>10.20.1.7</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
<tr>
<td><input type="checkbox" id="host3" name="host3"/>
host3</td>
<td>10.20.1.9</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
<tr>
<td><input type="checkbox" id="host4" name="host4"/>
host4</td>
<td>10.20.1.11</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
</tbody>
</table>
```
Note that the id and name of the checkbox coincide with the host name. Also note that the first td does not have a checkbox. That's the expected behavior.
|
2011/11/18
|
[
"https://Stackoverflow.com/questions/8180944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053535/"
] |
Changing 'special' attributes like `disbaled` or `checked` should be done like this:
```
$(...).attr('checked','checked');
```
or this way if you are using jQuery 1.6 or later:
```
$(...).prop('checked', true); // more reliable
```
See jQUery doc about [.attr()](http://api.jquery.com/attr/) and [.prop()](http://api.jquery.com/prop/)
Here's your piece of code modified with a few optimizations (check the comments):
```
refreshId = setInterval(function()
{
var allTicks = [],
$myTable = $('#myTable'); // select once and re-use
// .map() returns an array which is what you are after
// also never do this: $(this).attr('id').
// 'id' is a property available in javascript and
// in .map() (and in .each()), 'this' is the current DOMElement so simply do:
// this.id
allTicks = $myTable.find('input:checked').map(function() { return this.id; });
$myTable.load('/get-table.jsp', null, function (responseText,textStatus, req ) {
$myTable.tablesorter();
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ )
// avoid prefixing with tagname if you have the ID: input#theId
// #xxx is unique and jquery will use javascript getElementById which is super fast ;-)
$myTable.find('#' + allTicks[i]).prop('checked', true);
});
}, $refreshInterval);
```
|
68,167,684 |
In my Angular 11 project I have an Observable what changes the view and take some times while it's rendering.
Something like this:
```js
export class MyComponent implements OnInit {
myObservable = of([1, 2, 3]);
constructor() { }
ngOnInit(): void {
this.myObservable.pipe(
// here is some functions
).subscribe();
}
}
```
After `ngOnInit` ran the observable still running and processing datas. After datas arrived the pipe change the template. But this change happening after `ngAfterViewInit` finished. So I need a soultion what run after pipe AND the rendering finished what is happening because pipe is finished.
How can I run codes (tooltip initialization) after my observable and the caused rendering is finished?
The `ngAfterViewChecked` not a good solution because it's always run when the view is changing, and my tooltip initialization will change the view too. So I want to run this initialization only once.
Is there any solution?
|
2021/06/28
|
[
"https://Stackoverflow.com/questions/68167684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972828/"
] |
We can create a grouping column with `cumsum`, `select` the columns of interest and use `group_split` to split the dataset into a `list` of datasets
```
library(dplyr)
library(tidyr)
TT %>%
mutate(grp = cumsum(replace_na(E, FALSE))) %>%
select(A:C, grp) %>%
group_split(grp, .keep = FALSE)
```
-ouptut
```
[[1]]
# A tibble: 5 x 3
A B C
<int> <int> <int>
1 1 21 1
2 2 22 2
3 3 23 3
4 4 24 4
5 5 25 5
[[2]]
# A tibble: 4 x 3
A B C
<int> <int> <int>
1 6 26 8
2 7 27 9
3 8 28 10
4 9 29 11
[[3]]
# A tibble: 3 x 3
A B C
<int> <int> <int>
1 10 30 18
2 11 31 19
3 12 32 20
[[4]]
# A tibble: 8 x 3
A B C
<int> <int> <int>
1 13 33 23
2 14 34 24
3 15 35 25
4 16 36 26
5 17 37 27
6 18 38 28
7 19 39 29
8 20 40 30
```
|
1,584,210 |
Have anyone ever thought of continuous analog Turing machine? The machine adopts continuous (from R) the input data from the tape,
It moves to a different state depending on the value on the tape.
On the output tape Turing machine writes real numbers according to its program. Is it possible to construct a computer on these principles?
|
2015/12/21
|
[
"https://math.stackexchange.com/questions/1584210",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/17354/"
] |
[Yes](http://www.mathpages.com/home/kmath135/kmath135.htm). Quote:
>
> Suppose, instead, we define a machine whose "state" at any time t is a real number s(t), and the "tape" is magnetized with intensity m(x) at location x (where x is the real-valued distance from the starting position). The machine is initially set to the state s(0) = 0 and placed at location x = 0 on the tape, which has been "programmed" with some initial profile of magnetic intensities over a finite range of the tape. (I'm treating m(x) as an ideal continuous function.)
>
About the question: "Is it possible to construct a computer on these principles?", [analog computers](https://en.wikipedia.org/wiki/Analog_computer) were invented before the digital ones. The problem is that infinite resolution isn't more possible than infinite tape.
|
118,833 |
We use SQL Server 2000 MSDE for an Point Of Sale system running on about 800 cash registers. Each box has its own copy, and only the local software accesses it.
This is a newly updated platform for the cash register vendor--who shall remain nameless.
Routinely we are seeing corruption of Master, MSDB, Model and the database used by the software.
I am looking for some piece of mind here more than anything and the confidence to utter that age old response: "It's not a software problem, it's a hardware problem".
My gut tells me that with this type of corruption a hardware problem is indicated. Can anyone suggest some alternatives to check out?
**Edit**: New information on problem
It has been a while since I first posted this problem. It turns out that aggressive use of CHKDSK in a preventative fashion seems to minimize the occurrences of the problem. Also it seems I failed to mention that the registers are running the WePOS version of Windows XP. Finally I have had cases where there were also corrupted files not part of the app which were fixed with CHKDSK.
Do any of these new facts strike a chord with anyone?
|
2008/09/23
|
[
"https://Stackoverflow.com/questions/118833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14547/"
] |
I have a rule of thumb that for every 100 problems 90 of them are user misunderstandings (like turning off the PC), 10 are caused by software and 1 is hardware.
With so many systems to update I would be looking for things like, systems that have not been fully patched. Users turning off PCs, and so on. Are the PCs locking up or crashing?
If the answers to all the above questions is no, then based on the rule of thumb I would be looking towards your software, as that would be the interface (presumably) to the SQL database.
There isn't enough information here to be more helpful.
Is this software you have written?
|
12,271,421 |
I am using sbt to build my Play 2.0 project. I managed to configure sbt to open a debugging port, attach an Eclipse remote debugger and enter a break point. I put the break point into one of my actions. But when the execution stops there, I cannot inspect any variable. I guess that sbt builds the Scala code without debugging information.
Does anybody know how to configure sbt to add debugging information? Or could it be a problem of my Scala IDE plugin for Eclipse or anything else?
Many thanks in advance!
|
2012/09/04
|
[
"https://Stackoverflow.com/questions/12271421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192208/"
] |
To start Play in debug mode via `sbt`, run:
```
sbt -jvm-debug 9999 run
```
|
7,328,513 |
I'm trying to import a pipe delimited file to sql server 2008. The last column is really long, so it should be varchar(max) or text.
I'm using the import wizard. I've set the source to Flat File, and the destination to Sql Native Client.
I've set 'column names in the first data row'.
The wizard correctly reads the column names, but it wants to make each column varchar(50). I found an advanced tab in the wizard where I can set the datatypes, but it only seems to set the type for the data flow and not the destination table? A few dialogs later I can "Edit Mappings", which lets me map source columns to destination columns, and set whether the destination columns are nullable, but it doesn't let me set the datatype of the destination columns.
Anyways, I'm confused. Is it possible to import data wider than 50 characters with the wizard? Because it doesn't seem to want to let me.
|
2011/09/07
|
[
"https://Stackoverflow.com/questions/7328513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197605/"
] |
What you have is actually OK I think.
But StevenzNPaul's suggestion not that bad, here's how you can use the `let` keyword to store the different projections, then select the results individually (for brevity, I did not project all the fields, but you get the point):
```
var query = from x in data
let result1 = new {title = x.GoalName, start = x.Start}
let result2 = new {title = string.Format("Start: {0:0.##}", x.StartValue), start = x.Start}
let result3 = new {title = "End", start = x.End}
let checkins = x.CheckIns.Select(checkin => new { title = "...", start = checkin.Start })
from result in new[] { result1, result2, result3 }.Concat(checkins)
select result;
```
Obviously, whether this is better is a matter of preference. Also, this will result in a different ordering, which may or may not be a problem for you.
|
21,735,200 |
I have a folder that should contain 10 files. Each file name will be different (name and extension), however, it will contain a pattern.
eg.
```
SomeThing.FILE0.DAT
SomeThing.FILE1.DAT
SomeThing.FILE2.DAT
and so on till
SomeThing.FILE9.DAT
```
My script currently does not have any checks. I manually run it ensuring that all files are present.
```
for ($i=0; $i -le 9; $i++)
{
$FileString = "*FILE"+$i+"*"
$MyFileName = Get-ChildItem e:\files -name -filter $($FileString)
}
```
However, I need to automate the process, so I want to add checks to make sure that:
```
a. Total of 10 files exist in that folder
$FC = ( Get-ChildItem c:\testing | Measure-Object ).Count;
if($FC -eq 10)
{
echo "File Count is correct"
}
else
{
echo "File Count is incorrect"
}
b. Each of the FILEX (X = 0-9) are present
c. Only one instance of each FILEX (X = 0-9) should be present. If multiple instances of FILEX are present, I need to display it on the screen saying that FILEX pattern is repeated multiple times.
```
How can I do these remaining checks? It looked simple, but is more complicated...
|
2014/02/12
|
[
"https://Stackoverflow.com/questions/21735200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3084626/"
] |
```
$> if ((compare (ls -name | %{ ([regex]'(?<=.*FILE).*(?=.DAT)').match($_).groups[0].value } | Sort-Object) (0..9 | %{$_.ToString()}) -SyncWindow 0).Length -eq 0) { Write-Host "ok" }
ok
```
---
Uh?
Rephrasing your question we have something like "check that directory contains only `*FILEX.DAT` files, where X should be every possible number between 0 and 9". In powershell it should look something like that:
```
$> if (allNumbersFromFileNames.IsEqualTo(0..9)) { Write-Info "ok" }
```
To get all numbers from filenames from the current directory:
```
$> ls -name | %{ ([regex]'(?<=.*FILE).*(?=.DAT)').match($_).groups[0].value }
0
1
2
3
5
6
7
8
9
4
```
We've constructed regex here with `([regex]'(?<=.*FILE).*(?=.DAT)')` and for every filename in current directory (`ls -name | %{ $_ }`) parse the magic number in it and get a first matched group's value.
Finally we need to have this `string[]` object, sort it and compare with array of strings of numbers. `compare` could be useful here.
I.e.
```
$> if ((compare 0..9 1..4).Length -eq 0) { Write-Host "equals" }
$> if ((compare 0..9 0..9).Length -eq 0) { Write-Host "equals" }
equals
```
Put it all together and you have an answer!
|
40,033,581 |
There are many good suggestions to how to fix gradle versions, but some of them are outdated or I just couldn't find the paths that were suggested. one solution did work for me is **project>project structure>project>gradle version**.
Here I can change it to the supported version, and successfully builds the project.
A small error in the the javascript code, so a change is made to it. `Ionic build android`, now something wrong occurrs here. `Minimum supprted Gradle version is 2.14.1. Current version is 2.13.`.
But in the **project/platforms/android/build.gradle**
`task wrapper(type: Wrapper){
gradleVersion = '2.14.1'
}`
and from this [link](https://docs.gradle.org/current/userguide/gradle_wrapper.html), it suggests that this is the way set your gradle wrapper.
So I am expecting in **project/platforms/android/gradle/wrapper/gradle-wrapper.properties** to have `distributionUrl=http\://services.gradle.org/distributions/gradle-2.14.1-all.zip`, instead this is what it has `distributionUrl=http\://services.gradle.org/distributions/gradle-2.13-all.zip`.
Can't make direct change to this file **project/platforms/android/gradle/wrapper/gradle-wrapper.properties**, because after each build it will revert back to `gradle-2.13-all.zip`.
What is going on here? can't find anything that explain why it keeps on changing the `distributionUrl=http\://services.gradle.org/distributions/gradle-2.13-all.zip`. Would anyone be kindly explain this please? Maybe something very stupid that I have missed. Thank you.
**Links that I have looked at**
["Gradle Version 2.10 is required." Error](https://stackoverflow.com/questions/34814368/gradle-version-2-10-is-required-error)
[How to update gradle in android studio](https://stackoverflow.com/questions/17727645/how-to-update-gradle-in-android-studio)
[ionic build android error when download gradle](https://stackoverflow.com/questions/29874564/ionic-build-android-error-when-download-gradle)
**gradle code**
```
apply plugin: 'com.android.application'
buildscript {
repositories {
mavenCentral()
jcenter()
}
// Switch the Android Gradle plugin version requirement depending on the
// installed version of Gradle. This dependency is documented at
// http://tools.android.com/tech-docs/new-build-system/version-compatibility
// and https://issues.apache.org/jira/browse/CB-8143
dependencies {
classpath 'com.android.tools.build:gradle:2.2.1'
}
}
// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
repositories {
mavenCentral();
jcenter();
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.14.1'
}
// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
apply from: 'CordovaLib/cordova.gradle'
// The value for android.compileSdkVersion.
if (!project.hasProperty('cdvCompileSdkVersion')) {
cdvCompileSdkVersion = null;
}
// The value for android.buildToolsVersion.
if (!project.hasProperty('cdvBuildToolsVersion')) {
cdvBuildToolsVersion = null;
}
// Sets the versionCode to the given value.
if (!project.hasProperty('cdvVersionCode')) {
cdvVersionCode = null
}
// Sets the minSdkVersion to the given value.
if (!project.hasProperty('cdvMinSdkVersion')) {
cdvMinSdkVersion = null
}
// Whether to build architecture-specific APKs.
if (!project.hasProperty('cdvBuildMultipleApks')) {
cdvBuildMultipleApks = null
}
// .properties files to use for release signing.
if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
cdvReleaseSigningPropertiesFile = null
}
// .properties files to use for debug signing.
if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
cdvDebugSigningPropertiesFile = null
}
// Set by build.js script.
if (!project.hasProperty('cdvBuildArch')) {
cdvBuildArch = null
}
// Plugin gradle extensions can append to this to have code run at the end.
cdvPluginPostBuildExtras = []
}
// PLUGIN GRADLE EXTENSIONS START
apply from: "cordova-plugin-badge/simplelogin777664-badge.gradle"
// PLUGIN GRADLE EXTENSIONS END
def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
apply from: 'build-extras.gradle'
}
// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}
// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)
def computeBuildTargetName(debugBuild) {
def ret = 'assemble'
if (cdvBuildMultipleApks && cdvBuildArch) {
def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
}
return ret + (debugBuild ? 'Debug' : 'Release')
}
// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
return computeBuildTargetName(true)
}
task cdvBuildRelease
cdvBuildRelease.dependsOn {
return computeBuildTargetName(false)
}
task cdvPrintProps << {
println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
println('cdvVersionCode=' + cdvVersionCode)
println('cdvMinSdkVersion=' + cdvMinSdkVersion)
println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
println('cdvBuildArch=' + cdvBuildArch)
println('computedVersionCode=' + android.defaultConfig.versionCode)
android.productFlavors.each { flavor ->
println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
}
}
android {
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
}
}
defaultConfig {
if (cdvMinSdkVersion != null) {
minSdkVersion cdvMinSdkVersion
}
minSdkVersion 16
targetSdkVersion 23
}
lintOptions {
abortOnError false;
}
compileSdkVersion 23
buildToolsVersion '21.1.2'
if (Boolean.valueOf(cdvBuildMultipleApks)) {
productFlavors {
armv7 {
versionCode defaultConfig.versionCode * 10 + 2
ndk {
abiFilters "armeabi-v7a", ""
}
}
x86 {
versionCode defaultConfig.versionCode * 10 + 4
ndk {
abiFilters "x86", ""
}
}
all {
ndk {
abiFilters "all", ""
}
}
}
}
/*
ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!
else if (!cdvVersionCode) {
def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
// Vary versionCode by the two most common API levels:
// 14 is ICS, which is the lowest API level for many apps.
// 20 is Lollipop, which is the lowest API level for the updatable system webview.
if (minSdkVersion >= 20) {
defaultConfig.versionCode += 9
} else if (minSdkVersion >= 14) {
defaultConfig.versionCode += 8
}
}
*/
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
if (cdvReleaseSigningPropertiesFile) {
signingConfigs {
release {
// These must be set or Gradle will complain (even if they are overridden).
keyAlias = ""
keyPassword = "__unset"
// And these must be set to non-empty in order to have the signing step added to the task graph.
storeFile = null
storePassword = "__unset"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
}
if (cdvDebugSigningPropertiesFile) {
addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
}
productFlavors {
}
}
dependencies {
compile fileTree(include: '*.jar', dir: 'libs')
// SUB-PROJECT DEPENDENCIES START
debugCompile project(path: "CordovaLib", configuration: "debug")
releaseCompile project(path: "CordovaLib", configuration: "release")
compile "com.android.support:support-v4:+"
// SUB-PROJECT DEPENDENCIES END
}
def promptForReleaseKeyPassword() {
if (!cdvReleaseSigningPropertiesFile) {
return;
}
if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
}
if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
}
}
gradle.taskGraph.whenReady { taskGraph ->
taskGraph.getAllTasks().each() { task ->
if (task.name == 'validateReleaseSigning') {
promptForReleaseKeyPassword()
}
}
}
def addSigningProps(propsFilePath, signingConfig) {
def propsFile = file(propsFilePath)
def props = new Properties()
propsFile.withReader { reader ->
props.load(reader)
}
def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
if (!storeFile.isAbsolute()) {
storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
}
if (!storeFile.exists()) {
throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
}
signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
signingConfig.storeFile = storeFile
signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
def storeType = props.get('storeType', props.get('key.store.type', ''))
if (!storeType) {
def filename = storeFile.getName().toLowerCase();
if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
storeType = 'pkcs12'
} else {
storeType = signingConfig.storeType // "jks"
}
}
signingConfig.storeType = storeType
}
for (def func : cdvPluginPostBuildExtras) {
func()
}
// This can be defined within build-extras.gradle as:
// ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
```
**Update**
'gradlew wrapper throws error, because certain wrapper doesn't exist under maven and the sub `build.gradle` uses it to download `2.14.1.prom` and `2.14.1.jar`. [This link will explain it.](https://stackoverflow.com/questions/39000831/android-studio-graddle-2-1-3-issue)
**Found problem**
The problem why it keeps on changing back to `2.13-all.zip` is because of this line, `var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.13-all.zip';` in the `[project name]/platforms/android/cordova/lib/builders/GradleBuilder.js` instead of `~/android/lib/GradleBuilder.js`. (Line 164)
|
2016/10/14
|
[
"https://Stackoverflow.com/questions/40033581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6563591/"
] |
**HERE IS A FIX :: Add this in Gradle File**
```
task wrapper(type: Wrapper){
gradleVersion = '7.2'
}
```
|
52,408,783 |
I am using FluentMigrator to migrate one database schema to another. I have a case in which I want to check if a foreign key exists before deleting it.
Previously, I just delete the foreign key by doing:
```
Delete.ForeignKey("FK_TableName_FieldName").OnTable("TableName");
```
How do I check that the foreign key exists first?
|
2018/09/19
|
[
"https://Stackoverflow.com/questions/52408783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487135/"
] |
This is how to delete a foreign key if it exists using FluentMigrator:
```
if (Schema.Table("TableName").Constraint("FK_TableName_FieldName").Exists())
{
Delete.ForeignKey("FK_TableName_FieldName").OnTable("TableName");
}
```
|
15,360,447 |
I have the following code in my Rails app:
```
link_to('???',{:controller => 'profile', :action => 'show', :id => id})
```
I want to get rid of '???' and it to show the dynamically generated URL. How do I this? It's kind of like what the [autolink gem](https://github.com/tenderlove/rails_autolink) does, but I want Rails to convert URL options into text, not vice versa.
|
2013/03/12
|
[
"https://Stackoverflow.com/questions/15360447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673206/"
] |
You can mock the instantiation of a new object with PowerMock using `expectNew()`
<http://code.google.com/p/powermock/wiki/MockConstructor>
```
SomeOtherClass someOtherMock = createMock(SomeOtherClass.class);
expectNew(SomeOtherClass.class).andReturn(someOtherMock);
expect(someOtherMock.do("blabla")).andReturn(...);
```
Edit: You can use with Mockito with the PowerMockito extensions
<http://code.google.com/p/powermock/wiki/MockitoUsage>
```
PowerMockito.whenNew(SomeOtherClass.class)...
```
|
1,905,271 |
I have a Image path(some thing like this "<http://ABC/XYZ/PQR.gif>").And I want to assign this image to checkbox in winforms using C#.winfroms checkbox does not have SRC,How can I assign this image to checkbox.?
|
2009/12/15
|
[
"https://Stackoverflow.com/questions/1905271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201478/"
] |
The *Background* of a check box can be *filled* with a provided image.
See
* [CheckBox Overview](http://msdn.microsoft.com/en-us/library/ms743611(VS.85).aspx)
* [CheckBox Members](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox_members.aspx)
* [Control.BackgroundImage Property](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.backgroundimage.aspx)
|
48,345,943 |
How can I refer the same temporary directory in two different function. I need to access the files that are decompressed in move\_source\_to\_dest as an input to the function df\_to\_csv in the pd.read\_csv statement. I've tried few changes but nothing is working out. Please help.
```
def move_source_to_dest(key, src_session):
with tempfile.TemporaryDirectory() as tempdir:
try:
print("downloading {}/{}".format(s3_src_bucket, key))
src_session.client('s3').download_file(Bucket=s3_src_bucket, Key=key,
Filename=os.path.join(tempdir, os.path.basename(key)))
#Command to decompress the files
command = "bzip2 -dk " + os.path.join(tempdir, os.path.basename(key))
subprocess.call(command,shell = True)
except Exception as e:
print("exception handling {}/{}".format(s3_src_bucket, key))
raise e
def df_to_csv(key, src_session):
with tempfile.TemporaryDirectory() as tempdir:
try:
#Reading all the columns names from the file "ambs_ambi_ColumnsNames.txt"
with open('./shakenbake_ds/ambs_ambi_ColumnsNames.txt') as f:
clist= f.read().splitlines()
#file = open('ambs_ambi_ColumnsNames.txt','r')
#clist=file.readlines()
Filename=os.path.join(tempdir, os.path.basename(key[:-4]))
Fileout=os.path.join(tempdir, os.path.basename(key[:-4])) + "-out.csv"
with open('./shakenbake_ds/ambs_ambi_OutColumnsNames.txt') as o:
outcols= o.read().splitlines()
#file = open('ambs_ambi_OutColumnsNames.txt','r')
#outcols=file.readlines()
#global Filename
c=0
for chunk in pd.read_csv(Filename, sep="\x01", names=clist ,iterator=True, chunksize=300000):
```
|
2018/01/19
|
[
"https://Stackoverflow.com/questions/48345943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9078220/"
] |
Pass the temporary directory as a parameter to both functions:
```
with tempfile.TemporaryDirectory() as tempdir:
move_source_to_dest(key, src_session, tempdir)
df_to_csv(key, src_session, tempdir)
```
|
13,308,029 |
I have buggy code and I don't know where or what is the fault.
I am writing an application for a customer. During the splash screen the app checks if Mysql is running to be able to connect to it later. If mysql is on, the app continues booting. If mysql is not running I start it and re-check again.
Initially, I was finding the mysql pid, but for some reason I can't get it without using unmanaged code.
So I found another way in xampp source code and I decided to use it.
Running the app under vstudio debugger stepping or stopping in a breakpoint works perfectly, but if run without stepping, the app boots mysql server but can´t detect it and eventually the application stop (I don't want the app continue loading if database fails).
This behavior has led me to think that one or more variables are disposed at runtime before I can use it again.
I don't know how solve this issue and need a hand.
**EDIT: The issue was mysql was not started yet running the app without interruption
As Jan & SWEKO said. Adding some delay works perfectly**
The splash screen Load code.
```
// App booting tasks
void Load()
{
// License validation ok
Boolean licensecheck = BootChecks.LicenseCheck();
if (! licensecheck)
{
MessageBox.Show("License Error Conta ct Technical Support","Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
Application.Exit();
}
bar.Width += 10; // feed progress bar ( it's a custom drawn label )
this.Refresh(); // update form to paint it
Application.DoEvents(); // process all pooled messages
// Mysql check
Boolean dbcheck = BootChecks.DbCheck();
// THE ISSUE IT'S HERE RUNNING WITHOUT STEPPING , ALWAYS FIRES THE ERROR
if ( ! dbcheck )
{
MessageBox.Show("Can't init Mysql. Contact Technical Support", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
bar.Width += 10;
this.Refresh();
Application.DoEvents();
// more stuff
}
```
Database check code
```
public static bool DbCheck()
{
Boolean norun = MysqlController.CheckMysqlIsRunning(Constants.dbpidfile);
// check if running
if ( norun ) return true;
// if not running, I start it
MysqlController.StartMysql(Constants.dbexe,Constants.dbopts);
Boolean rerun = MysqlController.CheckMysqlIsRunning(Constants.dbpidfile);
// if really running all it's ok
if ( rerun ) return true;
// really a fault
return false;
}
```
Real mysql check
comment: this way was found on xampp package. To know if mysql it's running find mysql pid file, and open a named event. if right definitively mysql it's running.
```
public static Boolean CheckMysqlIsRunning(String pathtopidfile)
{
try
{
Int32 pid;
using ( StreamReader sr = new StreamReader(pathtopidfile) )
{
pid = int.Parse(sr.ReadToEnd());
}
IntPtr chk = OpenEvent(SyncObjectAccess.EVENT_MODIFY_STATE, false,
String.Format("MySQLShutdown{0}", pid.ToString()));
if ( chk != null ) return true;
return false;
}
catch (Exception) { return false;}
}
public static void StartMysql(String path, String aargs)
{
// All ok. Simply spawn a process
}
```
|
2012/11/09
|
[
"https://Stackoverflow.com/questions/13308029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158405/"
] |
You have to code some kind of loop. You start the mysql process and when you check immediately after is, the process is still not there and you return false.
Try something like this:
```
// if not running, I start it
MysqlController.StartMysql(Constants.dbexe,Constants.dbopts);
// wait 10 seconds max.
int timeout = 10;
bool mySqlIsRunning = false;
while(!MysqlController.CheckMysqlIsRunning(Constants.dbpidfile)) {
// wait a while
Thread.Sleep(1000);
if (timeout-- == 0) {
// timeout error
// show message to user ...
}
}
// here mysql is running or your timeout is expired.
```
|
91,434 |
I have a web page where the users can sell their houses. They can also upload multiple images to make a carousel to show the house's images. The problem I'm facing is to decide whether or not to use responsive image or just resize and keep proportion.
For example, the carousel container is 400px height and 100% width, so I have 2 scenarios:
* Image fills the container, but crop some parts of it;
* Image keep propotion until reaches 100% of height or width;
See these 2 images for example:
This example will fill the entire container.
[](https://i.stack.imgur.com/XdtUX.jpg)
This example will fill a maximum height or width and center the image.
[](https://i.stack.imgur.com/RhJyT.jpg)
Because I'm not the one who control the image upload (I can only ask for a min/max image size) I'm kind of confused on what approach to use.
Filling the entire container has a better result on the design, but if the user upload a very vertical image, for example, it will zoom in too much and lose it's focus. In the other hand, if filling only a maximum height/width, will leave a lot of blank space on the sides of the image.
Both situations has it's pros/cons but what should I take in consideration in this case?
|
2016/03/15
|
[
"https://ux.stackexchange.com/questions/91434",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/76435/"
] |
**Let the user see their whole image**
As this is out of your control due to users uploading images, you will find people will be more frustrated with having their image cropped off than having some white space making your design feel messy.
I created a Gallery control at one point for a client and I used "overflow:hidden" to allow the image to fit in to MY space, cropping off the sides of the image where I needed to.
This created many issues as it was a responsive control, so on some resolutions and devices, more or less of the image would be cropped depending on the viewport of the user.
This was because people expected my gallery to crop their image, pick the focal point and make it sit perfect for them and pick the best possible way of displaying it, which was just not an option as every image is different.
To do that, I would have to have the user define the focal point of the image and position from there. But that was just so painful and people could not understand why I could not just show the whole image.
In the end going down your second route was the best option and no one has complained since.
This is an example of the finished gallery, I picked a nice subtle colour to fill the rest of the space
**Desktop**
[](https://i.stack.imgur.com/odxRp.jpg)
**Tablet**
[](https://i.stack.imgur.com/bksk0.jpg)
**Mobile**
[](https://i.stack.imgur.com/6FqbM.png)
|
23,164,861 |
The goal at this point is just to find out why this code isn't compiling. The class below creates a new instance of 'K12Student' according to certain conditions, that class being a super class which extends to three subclasses which define different types of students. Each subclass contains unique instance variables and their get and set methods. The class is currently as follows:
```
import java.util.*;
//Create New arraylist for client instances
public class StudentInput {
private InputHelper input;
private ArrayList students;
public void run() {
studentInfoEntry();
}
//Assign data to instances of client
public void studentInfoEntry() {
students = new ArrayList();
input = new InputHelper();
String studentIDString = "";
int studentID = 0;
String studentName = "";
String schoolName = "";
String gradeLevelString = "";
int gradeLevel = 0;
String validateAddNewStudent = "";
while (true) {
studentIDString = input.getUserInput("Enter student ID number.");
studentID = Integer.parseInt(studentIDString);
studentName = input.getUserInput("Enter student name.");
schoolName = input.getUserInput("Enter school name.");
gradeLevelString = input.getUserInput("Enter grade level.");
gradeLevel = Integer.parseInt(gradeLevelString);
if (gradeLevel >= 0 && gradeLevel <= 12) {
if (gradeLevel >= 0 && gradeLevel <= 4) {
String readingLevelString = "";
int readingLevel = 0;
String classSection = "";
readingLevelString = input.getUserInput("Enter reading level.");
readingLevel = Integer.parseInt(readingLevelString);
classSection = input.getUserInput("Enter class section.");
/*K12Student*/
PrimaryStudent newStudent = new PrimaryStudent();
newStudent.setStudentID(studentID);
newStudent.setStudentName(studentName);
newStudent.setSchoolName(schoolName);
newStudent.setReadingLevel(readingLevel);
newStudent.setClassSection(classSection);
}
if (gradeLevel >= 5 && gradeLevel <= 8) {
String lunchHourString = "";
int lunchHour = 0;
String homeroomTeacher = "";
lunchHourString = input.getUserInput("Enter lunch hour.");
lunchHour = Integer.parseInt(lunchHourString);
homeroomTeacher = input.getUserInput("Enter homeroom teacher.");
/*K12Student*/
MiddleStudent newStudent = new MiddleStudent();
newStudent.setStudentID(studentID);
newStudent.setStudentName(studentName);
newStudent.setSchoolName(schoolName);
newStudent.setLunchHour(lunchHour);
newStudent.setHomeroomTeacher(homeroomTeacher);
}
if (gradeLevel >= 9 && gradeLevel <= 12) {
String GPAString = "";
int GPA = 0;
String collegeChoice = "";
GPAString = input.getUserInput("Enter reading level.");
GPA = Integer.parseInt(GPAString);
collegeChoice = input.getUserInput("Enter class section.");
K12Student newStudent = new HighStudent();
newStudent.setStudentID(studentID);
newStudent.setStudentName(studentName);
newStudent.setSchoolName(schoolName);
newStudent.setReadingLevel(readingLevel);
newStudent.setClassSection(classSection);
}
students.add(newStudent);
validateAddNewStudent = input.getUserInput("Enter another student? (y/n)");
if (!validateAddNewStudent.equals("y")) {
break;
}
}else{
System.out.println("Grade level must be from 0-12.");
}
}
}
}
```
Also, the instantiation of each new middle school and elementary school student originally read like that of the high school student (`K12Student newStudent = new HighStudent`;), but I had more issues compiling with that format. The compiler errors are as follows:
javac K12StudentTestDrive.java
```
./StudentInput.java:97: error: cannot find symbol
newStudent.setReadingLevel(readingLevel);
^
symbol: variable readingLevel
location: class StudentInput
./StudentInput.java:98: error: cannot find symbol
newStudent.setClassSection(classSection);
^
symbol: variable classSection
location: class StudentInput
./StudentInput.java:100: error: cannot find symbol
students.add(newStudent);
^
symbol: variable newStudent
location: class StudentInput
3 errors
```
Thanks in advance for any feedback.
|
2014/04/19
|
[
"https://Stackoverflow.com/questions/23164861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3525241/"
] |
Variables only live in the scope they are declared in, scope being, for the most part, curly braces (there are other scope rules, but in your case, it's block scope). You define your variables inside the braces of an earlier `if` statement. They go out of scope as soon as the code leaves that `if` statement. They are not available later.
The significant parts of your code are:
```
if (...) {
int readingLevel = ...;
String classSection = ...;
...
} // <= readingLevel and classSection go out of scope here
if (...) {
K12Student newStudent = ...;
newStudent.setReadingLevel(readingLevel); // <= readingLevel isn't here
newStudent.setClassSection(classSection); // <= classSection isn't here
} // <= newStudent goes out of scope here
students.add(newStudent); // <= newStudent isn't here
```
Note that this is unrelated to abstract classes.
|
58,920,483 |
Let's take a look at the following function:
```
auto F(vector <int> *p) {
return [p](int y) -> int{ return y + (*p)[0]; };
}
```
It does a pretty simple thing: it receives a pointer at a vector of integers and returns a lambda which has another integer as an input and returns the result of adding this integer to the first element of the vector we have a pointer at.
If I want to implement a higher-order function which could accept such a lambda as input, I, obviously, cannot use the `auto` in the prototype. I tried fixing it like this:
```
typedef int *A (int);
A F(vector <int> *p) {
return [p](int y) -> int{ return y + (*p)[0]; };
}
```
But that implementation brings about a conflict as well: the lambda type cannot be converted to `A`.
How could this be implemented?
|
2019/11/18
|
[
"https://Stackoverflow.com/questions/58920483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11143763/"
] |
>
> I tried fixing it like this:
>
>
>
```
typedef int *A (int);
A F(vector <int> *p) {
return [p](int y) -> int{ return y + (*p)[0]; };
}
```
>
> ... the lambda type cannot be converted to `A`.
>
>
>
This would make sense in principle only for a completely stateless lambda. Your lambda has a capture, which means it has state that needs to be stored somewhere, which means it *must* be a callable object rather than a simple free function.
Your options are:
1. Implement the higher-order function as a template on the lower-order type:
```
template <typename Func>
int higherOrder(int x, Func&& f)
{
return f(x);
}
```
or
2. Wrap the lambda inside something with a well-known type, usually
```
int higherOrder(int x, std::function<int(int)> const &f)
{
return f(x);
}
```
|
3,481,476 |
I'm trying to add some simple user data into a database via a webpage written in PHP, but the following code (more specifically, line three) breaks the page. Am I using the wrong MySQL function? I'm pretty sure my query is formatted correctly.
```
mysql_query("CREATE TABLE stats ( userAgent CHAR(20) )");
$userAgent = $_SERVER["HTTP_USER_AGENT"];
mysql_query("INSERT INTO stats VALUES ("$userAgent"));
```
|
2010/08/14
|
[
"https://Stackoverflow.com/questions/3481476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379181/"
] |
The PHP error can be fixed like this (note the dot, it's used to "glue" the strings together):
```
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
```
Also, you should do some SQL Injection protection, the user-agent string is user-defined (there are tools to modify it), so it needs to be sanitized. Further, the user-agent is a string so you need to put it in between single quotes.
```
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')");
```
Another important thing would be error handling - echoing the error description is necessary to find bugs in your SQL syntax.
```
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')")
or die("MySQL Error: " . mysql_error());
```
|
734,137 |
How I can change font test phrase in Windows 8.1. I need to see if font have another characters set.

|
2014/03/27
|
[
"https://superuser.com/questions/734137",
"https://superuser.com",
"https://superuser.com/users/199206/"
] |
In older Windows versions it was as simple as hex editing FontView.exe.
In Windows 7 you can use Resource Hacker to edit a copy of `Windows\System32\en-US\fontview.exe.mui` (obviously replace en-US with your system's language code), compile script when you're done, save and replace the original:

This might work in Windows 8.x too. You may face a problem with Windows complaining about OS files being replaced however. As quadronom said it's best to use a third-party font viewer. There are tons of good free ones available.
---
Factoid: Apparently Windows ME and XP had alternate preview strings available for en-US besides "The quick brown fox jumps over the lazy dog" (for ME it was "Windows Millennium Edition" and for XP see below) which would show up based on locale settings and supported font code page tables, but Vista dropped them.

|
28,938,210 |
What I'm trying to achieve is a program that will use a Template of a letter. In the template there will be text like
>
> Hello Sir/Madam --NAME--
>
>
>
Is it somehow possible to replace the `"--NAME--"` with a `customer.getName()` method? I don't have any code yet but have been breaking my head over this problem.
|
2015/03/09
|
[
"https://Stackoverflow.com/questions/28938210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189582/"
] |
The problem is in your data.
If I understand correctly you want to know if there are such rows in Results which date is greater then Patients date. If no such row is found then it is OK.
If so your query looks correct. You can directly select incorrect data by:
```
SELECT *
FROM Patients p
CROSS APPLY ( SELECT MAX(ModifiedAt) AS ModifiedAt
FROM ResultsStored rs
WHERE p.RowId = rs.RowId
) a
WHERE a.ModifiedAt > p.ModifiedAt
```
|
2,908,412 |
I have a small .NET WinForms application, and couple of linux servers, DEV and CL1,CL2..CLN (DEV is development server and CL\* are servers which belons to our clients, they are in private networks and it's a kind of production servers)
I want an update mechanism so that
(1) i develop a new version and publish it to a DEV
(2) users of DEV-server install latest version from DEV
(3) users of CL2 (employees of client2) install stable version from CL-2 directly
(4) application checks for updates using server it was installed from (so, if it was installed from CL-2, it should check CL-2 for updates)
(5) i should be able to propogate the update to a selected CL-server (using just file copy & maybe sed; not republishing), if i want that (and if i don't, that CL-server will have an old version until manually i update it)
I tried to use clickonce, but looks like it meets only first two requirements.
What should i do?
|
2010/05/25
|
[
"https://Stackoverflow.com/questions/2908412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181866/"
] |
ClickOnce should handle 1-4 to be honest. All that would be needed is that for each site you want to deploy/update from, you'll need it to have its own publish, which after looking at your specifications is not incorrect to do.
What you could then do in order to make 5. applicable, is create an automated process to re-publish the file. This could perform a publish and then upload to the correct server.
Remember that ClickOnce needs a new manifest per version, and a new version requires a publish, so I'm not sure that you'll get around 5. with a simple file replacement.
|
13,374,963 |
This function seems not to be triggered until the cell is exited, as the value i'm getting is the post-change value. I need the pre-change value, but I only need it if in fact that particular column is edited.
Thank you
```
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
var r = s.getActiveCell();
var columnNum = r.getColumn();
var msg;
if (columnNum == 11) {
var dateCell = s.getRange(r.getRow(), 11);
var v=dateCell.getValue();
msg = 'Value= ' + v;
Browser.msgBox (msg);
//dateCell.setValue(v);
}
}
```
|
2012/11/14
|
[
"https://Stackoverflow.com/questions/13374963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807146/"
] |
This is a very old question, but in case anyone else needs the answer, it's quite easy to get both the old and new values of any edited cell with the event object:
```
function onEdit(e) {
let oldValue = e.oldValue;
let newValue = e.value;
console.log("The range's old value was: " + oldValue + ", and the updated value is: " + newValue);
}
```
Here are are the accessible properties of the [Google Sheets event objects](https://developers.google.com/apps-script/guides/triggers/events).
|
201,944 |
I search for a chain of clean references, which lead the fact of topological manifolds of dimension $n$ having the homotopy type of a CW of dimension $n$.
Milnor's [On spaces having the homotopy type of a CW-Complex](http://www.maths.ed.ac.uk/~aar/papers/milnorcw.pdf) proves that every topological manifold has the homotopy type of a countable CW-complex since it is an absolute neighborhood retract.
Theorem E of Wall's [Finiteness Conditions for CW-complexes](http://math.uchicago.edu/~shmuel/tom-readings/wall%20finiteness%201.pdf) then gives me the desired answer for dimensions at least 3, as long as I know that the universal covering $\tilde{M}$ of a topological manifold $M$ of dimension $n$ has vanishing homology up to dimension $n$ and it holds $H^{n+1}(M,\mathcal{B})=0$ for all abelian coefficient bundles $\mathcal{B}$.
Theorem 3.26 and Proposition 3.29 of Hatcher's book gives me the first claim about the homology since universal coverings of topological $n$ manifolds are again topological $n$ manifolds since the fundamental group of a topological manifold is countable (a clean reference for this is Theorem 7.21 in Lee's book 'Introduction to Topological Manifolds')
Since I am happy to forget about the low dimensional cases, it leaves me with the search for a solid reference to the claim
>
> Let $M$ be a topological manifold and $\mathcal{B}$ be an abelian coefficent bundle, then $H^{n+1}(M,\mathcal{B})=0$.
>
>
>
|
2015/04/04
|
[
"https://mathoverflow.net/questions/201944",
"https://mathoverflow.net",
"https://mathoverflow.net/users/69525/"
] |
Every topological manifold has a handlebody structure except in dimension 4, where a 4-manifold has a handlebody structure if and only if it is smoothable. This is a theorem on page 136 of Freedman and Quinn's book "Topology of 4-Manifolds", with a reference given to the Kirby-Siebenmann book for the higher-dimensional case. It is then an elementary fact that an $n$-manifold with a handlebody structure is homotopy equivalent to a CW complex with one $k$-cell for each $k$-handle, so in particular there are no cells of dimension greater than $n$. At least in the compact case a manifold with a handlebody structure is in fact homeomorphic to a CW complex with $k$-cells corresponding to $k$-handles; see page 107 of Kirby-Siebenmann. This probably holds in the noncompact case as well, though I don't know a reference.
|
35,509,789 |
I am building an app in codeigniter and my application folder hierarchy goes like this:
```
|-controller
|-admin
|-dashboard
```
I want to add dashboard to the `namespace admin`, so I did this:
```
defined('BASEPATH') OR exit('No direct script access allowed');
namespace admin;
class Dashboard extends MY_Controller {
//constructor and some methods
}
```
The problem is that whenever i try to access the dashboard class from uri `localhost/myapp/admin/dashboard`, I get error on the browser like this:
```
Server error
500
```
However if I comment out the line `namespace admin;` , it runs without any errors.
**Why is the namespace creating such internal server error?**
**How to prevent such error while using namespaces for controller class in codeigniter?**
|
2016/02/19
|
[
"https://Stackoverflow.com/questions/35509789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5350097/"
] |
"Broker" is a generic term for the type of messaging system that RabbitMQ is. It's a centralized messaging system, with a server that handles the routing and delivery of messages, etc.
This paper from ZeroMQ is good to understand the differences between brokered and brokerless: <http://zeromq.org/whitepapers:brokerless> (although this paper is fairly biased toward brokerless model, both are good and both have uses. i tend to prefer rabbitmq / brokered system, but not always)
From the other perspective, here is RabbitMQ's broker vs brokerless post: <https://www.rabbitmq.com/blog/2010/09/22/broker-vs-brokerless/>
For the most part, just substitute "rabbitmq server" in your mind, when you see the work "broker" and you'll be good to go.
The exchange, as you've noted, the thing through which you publish a message, in RabbitMQ. It handles the bindings and routing of the messages, depending on the exchange type.
|
59,215,369 |
I am using puppeteer to take screengrabs of content in an application I have built. The majority of my code is working but I have a couple of scenarios where the results are not as expected. I can successfully instruct puppeteer to take a screen grab of an element with a defined css height and width using getBoundingClientRect() on the element but in scenarios where there is not defined height/width, I was wondering if it was technically possible to get the height and width of an element based on the height and width of the inner elements.
For example (or the most likely case I am going to come across) I may have a piece of content where the body has no style parameters set but the inner content will have a height set. It might not be the first child element but it could even a child of the child element.
I have explored using get getBoundingClientRect() and offsetHeight but have had no success.
Is there a method that would allow me to get the calculated height / width of an element?
```js
var body = document.querySelector('body');
console.log(body.clientHeight);
console.log(body.style.height);
console.log(body.getClientRects());
console.log(body.getBoundingClientRect());
```
```css
#container {
height:200px;
width:200px;
background-color:blue;
border:1px solid black;
color: white;
text-align: center;
}
```
```html
<body>
<div id="container">
HELLO
</div>
</body>
```
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59215369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/656752/"
] |
In Puppeteer, this can be done with [boundingBox()](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#elementhandleboundingbox). Use the page or element selector to get the element, then call `elem.boundingBox()` to get the x, y, width, and height of the element. See the following code:
```
const elem = await page.$('.portal-body');
const boundingBox = await elem.boundingBox();
console.log('boundingBox', boundingBox)
```
For my example, the console logged the following:
```
2020-12-02 12:58 -08:00: boundingBox { x: 0, y: 0, width: 984, height: 1072 }
```
That width and height exactly matched the element, as you can see in the lower left of the screenshot:
[](https://i.stack.imgur.com/htry8.png)
|
8,545,783 |
In SBT .7, you could do
```
~jetty-run
```
in order to get your files to auto compile and reload the web app whenever something changes. In SBT .11, You can do
```
~container:start
```
which also re-compiles files, but does not seem to reload the web app, everytime something changes. Rather, I have to do a
```
container:stop
container:start
```
to see the changes. The problem with this is that it takes `~30s` for the it all to restart. Is there a better way of doing it? Digging through google and SBT has not found me any answers
EDIT:
doing a
```
container:start
container:reload
```
each time something changes, seems to work well. However, is it possible to make it happen automatically in that sequence? Something like:
```
~(container:start, container:reload)
```
which doesn't work, but i wish it did
|
2011/12/17
|
[
"https://Stackoverflow.com/questions/8545783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871202/"
] |
So it turns out the answer is that ~ can take a command list, as was mentioned in the link fmpwizard left. Hence you can do
```
~;container:start; container:reload /
```
does the correct thing: each time I save the files, it recompiles the necessary files and reloads the web app!
EDIT: should be container:reload, as mentioned. Thanks!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.