qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
16,097,031 | Alright, let's say my MySQL table is set up with entries similar to:
```
id code sold
1 JKDA983J1KZMN49 0
2 JZMA093KANZB481 1
3 KZLMMA98309Z874 0
```
I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it.
Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going. | 2013/04/19 | [
"https://Stackoverflow.com/questions/16097031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2297714/"
] | It seems that your codes are already random, so why not just take the first item; if you have many unsold records in your database, doing the typical `ORDER BY RAND()` will hurt the database performance.
```
SELECT *
FROM codes
WHERE sold = 0
LIMIT 1
FOR UPDATE;
```
I've also added `FOR UPDATE` to avoid race conditions, assuming that you're using transactions, as you update the record later (to actually sell it). | Have you tried
```
SELECT * FROM myTable WHERE sold = 0 ORDER BY RAND() LIMIT 1
``` |
16,097,031 | Alright, let's say my MySQL table is set up with entries similar to:
```
id code sold
1 JKDA983J1KZMN49 0
2 JZMA093KANZB481 1
3 KZLMMA98309Z874 0
```
I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it.
Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going. | 2013/04/19 | [
"https://Stackoverflow.com/questions/16097031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2297714/"
] | If you don't need the random, then don't use it. It can affect performance very negatively. Since you mentioned in your post that it wasn't necessary, I would recomment using Ezequiel's answer above and dropping the rand. See [Most Efficient Way To Retrieve MYSQL data in random order PHP](https://stackoverflow.com/questions/2564780/most-efficient-way-to-retrieve-mysql-data-in-random-order-php) for more info. | Adding `ORDER BY RAND()` to the rest of your `SELECT` query is the most straightforward way to accomplish this. |
16,097,031 | Alright, let's say my MySQL table is set up with entries similar to:
```
id code sold
1 JKDA983J1KZMN49 0
2 JZMA093KANZB481 1
3 KZLMMA98309Z874 0
```
I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it.
Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going. | 2013/04/19 | [
"https://Stackoverflow.com/questions/16097031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2297714/"
] | It seems that your codes are already random, so why not just take the first item; if you have many unsold records in your database, doing the typical `ORDER BY RAND()` will hurt the database performance.
```
SELECT *
FROM codes
WHERE sold = 0
LIMIT 1
FOR UPDATE;
```
I've also added `FOR UPDATE` to avoid race conditions, assuming that you're using transactions, as you update the record later (to actually sell it). | Adding `ORDER BY RAND()` to the rest of your `SELECT` query is the most straightforward way to accomplish this. |
5,337,279 | The scenario is: I current have an old website that runs on PHP. Over time, that code has become hacked up and messy. It's due for a rewrite. However, I don't have time to do that rewrite yet. But I'd like to plan for it in the future.
What I need to do now is add a 'welcome' type page to the website. I'd like to code that in Python using the Pyramid framework.
The old sites URL structure is this:
```
http://website.com/XXXXXX
```
Where the `X` is the short URL id.
What I was thinking of doing was using Apaches `LocationMatch` config to catch the short URL. Something like:
```
<LocationMatch "/^([a-zA-Z0-9]{6})$">
```
This would then redirect the request to the PHP portion of the website. Everything else would be caught by Pyramid.
I'm not sure how to action this. Does Apache have an `else` type clause for `LocationMatch`? How would I tell it to serve the PHP files for `/XXXXXX` matches and send everything else to Pyramid?
Server Notes:
* Apache2 + PHP (Debian package)
* mod\_wsgi 3.3
* Python2.7 | 2011/03/17 | [
"https://Stackoverflow.com/questions/5337279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/756597/"
] | You indicated in a comment that you're waiting for a `SocketException`. If so you need to catch `SocketTimeoutException` instead. For example, this code will output `timeout!` if you telnet to port 3434 and wait 3 seconds:
```
try {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
socket.setSoTimeout(3000);
InputStream socketInputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(socketInputStream);
dataInputStream.readByte();
} catch (SocketTimeoutException e) {
System.out.println("timeout!");
}
``` | Check the full thread dump for deadlock.
`ctrl + break` for windows.
`ctrl + |` or `kill -3 PID` for linux.
or Use `jvisualvm` or `jconsole` tools.
`timeout` value should be in milliseconds. |
51,438,410 | Can you guys tell me what is wrong here.
**RxJS**
[Jsfiddle Demo](http://jsfiddle.net/eqffs/1064/)
I was expecting the value will print only one time,but it is printing mulitple times
[](https://i.stack.imgur.com/a9VdN.png)
```
function Search(sel) {
let observable = Rx.Observable.fromEvent(document.getElementById('iCard'), 'input');
observable
.debounceTime(1000)
.distinctUntilChanged()
.subscribe({
next: this.callGlobalSearch
});
}
function callGlobalSearch(e){
console.log('VALUE : ', e.target.value); // NOT SURE, WHY THE VALUE IS PRINTED MULTIPLE TIMES
}
``` | 2018/07/20 | [
"https://Stackoverflow.com/questions/51438410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665864/"
] | Changed your code in fiddle [check here](http://jsfiddle.net/d2heokyn/). You don't need to subscribe to `input` event on every `keyup`. And `distinctUntilChanged` was getting event object which is different always. So it can't do anything. Before that event should be mapped to text, then it can be compared in `distinctUntilChanged`.
```
Rx.Observable.fromEvent(document.getElementById('iCard'), 'input')
.debounceTime(1000)
.map(e => e.target.value)
.distinctUntilChanged()
.subscribe({
next: callGlobalSearch
});
function callGlobalSearch(text) {
console.log('VALUE : ', text);
}
``` | Any time you `keyup` you run the function `Search(sel)`.
Any time you run the function `Search(sel)` you create an Observable and you subscribe to it.
So after **n** `keyup` events you end up having **n** active subscriptions to **n** different source Observables, and therefore you see **n** repetitions of the line logged on the console.
If change the html code such as
```
<body onload="Search(this)">
Global Search
<input id="iCard" type='text' />
</body>body>
```
you should get the right behavior.
Change the name of the function `Search` to something more aligned to the real stuff performed, e.g. `createInputObs`, according to your style. |
31,541,329 | I've create one content view for get news from `JSon`but i want load randomly.
I have 2 method:
```
- (void)radioNews {}
- (void)topNews {}
```
now i want get random radioNews or topNews in my `viewDidLoad`
```
- (void)viewDidLoad {
[self radioNews];
}
```
this is correct only to load one method, is possible tell getRandom from `radioNews` and `topNews` and then in didLoad `[self methodResult]` ?
Thanks | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071686/"
] | Try
```
- (void)viewDidLoad {
[super viewDidLoad];
NSInteger random = arc4random()%2;
if (random == 0) {
[self radioNews];
}else{
[self topNews];
}
}
``` | You can call a `selector` from a `NSString`
Start creating a `NSArray` with `NSString`
```
// Define an NSArray of NSString, where a single string is the method name
NSArray *methods = @[@"radioNews", @"topNews"];
// Retrieve a random index
NSUInteger index = arc4random()%methods.count;
// You can use objectAtIndex without check the array bounds because
// the mod operation you did before will always return a value in bounds
// Create a selector instance from a string
SEL randomSelector = NSSelectorFromString([methods objectAtIndex: index]);
// Call the selector
[self performSelector:randomSelector
withObject:nil];
``` |
16,749,354 | I really new to java and I've Googled this in every possible phrase i know how.
So I have a table made of 36 rows and 12 columns, I've been trying to write a method that will delete the a row when it becomes full and then move everything down one, I figured I could use a count to see if all spaces add up to 12 then delete the contents but it seems to delete randomly or not at all, can anyone help a java novice
```
int count = 0;
for (int i = 0; i < 36; i++){
for (int j = 0; j < 12; j++){
if (table[i][j] != null){
count++;
}
if (count == 12){
table[i][j] = null;
}
}
}
```
EDIT: hmm ive tried all the suggested answers none of them seem to work, what im trying to do it and out put like this
```
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| 1 . . 3 . . . . 5 . . . | < this line should take its place
| a b c d e f g h i j k l | < this line should delete
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| x y . r f s . . . . . . | < this line should move down one
| 1 2 3 4 5 6 7 8 9 0 . . | < this line should move down one
| A B C D E F G H I J K L | < this line should delete
| . . . . . . . . . . . . |
```
and output below
```
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| 1 . . 3 . . . . 5 . . . | < this line just moved down
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| x y . r f s . . . . . . | < this line just moved down one
| 1 2 3 4 5 6 7 8 9 0 . . | < this line just moved down one
| . . . . . . . . . . . . |
```
I've gotten the output to all work but deleting full rows doesn't work | 2013/05/25 | [
"https://Stackoverflow.com/questions/16749354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2420175/"
] | >
> since the size of union is the largest data member size
>
>
>
That need not be true. Consider
```
union Pad {
char arr[sizeof (double) + 1];
double d;
};
```
The largest member of that union is `arr`. But usually, a `double` will be aligned on a multiple of four or eight bytes (depends on architecture and size of `double`). On some architectures, that is even necessary since they don't support unaligned reads at all.
So `sizeof (union Pad)` is usually larger than `sizeof (double) + 1` [typically `16 = 2 * sizeof (double)` on 64-bit systems, and either 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit `char` and 64-bit `double`, the required alignment for `double` may still be only four bytes)].
That means there must then be padding in the union, and that can only be placed at the end.
Generally, the size of a `union` will be the smallest multiple of the largest alignment required by any member that is not smaller than the largest member. | Union when we use with primitive types inside it
```
union
{
char c;
int x;
}
```
It seems like it doesn't use padding because the largest size data is anyway is aligned to boundary.
But when we nest a structure within union it does.
```
union u
{
struct ss
{
char s;
int v;
}xx;
}xu;
```
It resulted in size 8.
so answer for your question is PADDING is persent in UNION. |
9,915,157 | I'm trying to pick out the word/phrase (wrapped in hashtags) after a certain string. For instance:
>
> This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#.
>
>
>
Now, I have been able to successfully grab all @words from the string using:
```
preg_match_all('!@(.+)(?:\s|$)!U', $string, $matches)
```
But is there a way I can easily grab the hashtag enclosed phrases (if they're there) after an @name? | 2012/03/28 | [
"https://Stackoverflow.com/questions/9915157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255109/"
] | Try the following regexp:
```
^@(.+)#(.+)#$
```
And if you want to remove spaces
```
^@(.+)\S*#(.+)\S*#$
```
And if you want to trim a lot
```
^@\S*(.+)\S*#\S*(.+)\S*#$
```
And you are not sure there is hashtag (or wathever it is called)
```
^@\S*(.+)\S*(#\S*(.+)\S*#)?$
``` | This should do the trick.
```
preg_match_all('/@(\w+)\s?(?:#([^#]+)#)?/', $string, $matches);
```
`$matches[1]` will contain the "artist name"
`$matches[2]` will contain the optional phrase |
9,915,157 | I'm trying to pick out the word/phrase (wrapped in hashtags) after a certain string. For instance:
>
> This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#.
>
>
>
Now, I have been able to successfully grab all @words from the string using:
```
preg_match_all('!@(.+)(?:\s|$)!U', $string, $matches)
```
But is there a way I can easily grab the hashtag enclosed phrases (if they're there) after an @name? | 2012/03/28 | [
"https://Stackoverflow.com/questions/9915157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255109/"
] | Try the following regexp:
```
^@(.+)#(.+)#$
```
And if you want to remove spaces
```
^@(.+)\S*#(.+)\S*#$
```
And if you want to trim a lot
```
^@\S*(.+)\S*#\S*(.+)\S*#$
```
And you are not sure there is hashtag (or wathever it is called)
```
^@\S*(.+)\S*(#\S*(.+)\S*#)?$
``` | Remember to make your character sets as specific as possible:
```
preg_match_all('!@([^\s]+) #([^#]+)#!U', $string, $matches)
```
`[^\s]+` will match up to the first white space, `[^#]+` will match up to the closing hash tag. |
9,915,157 | I'm trying to pick out the word/phrase (wrapped in hashtags) after a certain string. For instance:
>
> This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#.
>
>
>
Now, I have been able to successfully grab all @words from the string using:
```
preg_match_all('!@(.+)(?:\s|$)!U', $string, $matches)
```
But is there a way I can easily grab the hashtag enclosed phrases (if they're there) after an @name? | 2012/03/28 | [
"https://Stackoverflow.com/questions/9915157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255109/"
] | Try the following regexp:
```
^@(.+)#(.+)#$
```
And if you want to remove spaces
```
^@(.+)\S*#(.+)\S*#$
```
And if you want to trim a lot
```
^@\S*(.+)\S*#\S*(.+)\S*#$
```
And you are not sure there is hashtag (or wathever it is called)
```
^@\S*(.+)\S*(#\S*(.+)\S*#)?$
``` | This seems to do the trick (no / / delimiters included):
```
@(\S+)\s+#(.+?)#
```
"1 or more non-whitespace, followed by 1 or more whitespace, followed by some characters enclosed by #"
Note the use of the non-greedy operator (?) for the text inside the hash.
EDIT:
after `preg_match_all`, $match[1] will correspond to the artist name, $match[2] to the text in hash tags |
9,915,157 | I'm trying to pick out the word/phrase (wrapped in hashtags) after a certain string. For instance:
>
> This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#.
>
>
>
Now, I have been able to successfully grab all @words from the string using:
```
preg_match_all('!@(.+)(?:\s|$)!U', $string, $matches)
```
But is there a way I can easily grab the hashtag enclosed phrases (if they're there) after an @name? | 2012/03/28 | [
"https://Stackoverflow.com/questions/9915157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255109/"
] | Try the following regexp:
```
^@(.+)#(.+)#$
```
And if you want to remove spaces
```
^@(.+)\S*#(.+)\S*#$
```
And if you want to trim a lot
```
^@\S*(.+)\S*#\S*(.+)\S*#$
```
And you are not sure there is hashtag (or wathever it is called)
```
^@\S*(.+)\S*(#\S*(.+)\S*#)?$
``` | You can easily make this by using groups and preg\_match.
```
$name = "calvinharris";
preg_match('/@'.$name.' #([\w\s]+)#/', "This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#. ", $match);
echo '$match = ' . $match[1]; //feel so close
```
The idea is to use grouping (the things between brackets) and get this group. |
64,192,452 | I'm having issues with the below code displays Thursday as the dayOfTheWeek regardless of the date. Any ideas where I've gone wrong with this?
```java
public void CreatePlan() {
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Integer plan_recipe = 0;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, date, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
``` | 2020/10/04 | [
"https://Stackoverflow.com/questions/64192452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14216903/"
] | ```swift
var a = false
var b = false
var c = false
mutateValues(&a, &b, &c) { n in
n = true
}
print(a, b, c) // will be printed "true true true"
func mutateValues<Value>(_ values: UnsafeMutablePointer<Value>..., mutate: (inout Value) -> Void) {
values.forEach {
mutate(&$0.pointee)
}
}
``` | An Array in Swift is a struct, hence a value type.
Iterating over his children, and changing one, will not be possible unless:
* The type of child is aa class (which is reference typed)
* You iterate over the indices and change the real values!
+ E.G:
```
var a: Int = 1
var b: Int = 2
var array: [Int] = [a,b]
for index in array.indices {
array[index] += 1
}
print(array) // [2,3]
``` |
64,192,452 | I'm having issues with the below code displays Thursday as the dayOfTheWeek regardless of the date. Any ideas where I've gone wrong with this?
```java
public void CreatePlan() {
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Integer plan_recipe = 0;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, date, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
``` | 2020/10/04 | [
"https://Stackoverflow.com/questions/64192452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14216903/"
] | It is possible to do this with key paths. Let's say the properties are in a class `Foo`:
```
class Foo {
var a = false
var b = false
var c = false
func makeAllTrue() {
for n in [\Foo.a, \Foo.b, \Foo.c] {
self[keyPath: n] = true
}
}
}
```
If `Foo` is a struct, use `mutating func` instead:
```
struct Foo {
var a = false
var b = false
var c = false
mutating func makeAllTrue() {
for n in [\Foo.a, \Foo.b, \Foo.c] {
self[keyPath: n] = true
}
}
}
```
However, if the class name is long, I don't think it is worth doing this way.
If these three properties are *very* related, I would not bother with the key path stuff and replace `a`, `b` and `c` with an array:
```
var abc = [false, false, false]
```
and have the for loop loop over the indices:
```
for i in abc.indices {
abc[i] = true
}
``` | An Array in Swift is a struct, hence a value type.
Iterating over his children, and changing one, will not be possible unless:
* The type of child is aa class (which is reference typed)
* You iterate over the indices and change the real values!
+ E.G:
```
var a: Int = 1
var b: Int = 2
var array: [Int] = [a,b]
for index in array.indices {
array[index] += 1
}
print(array) // [2,3]
``` |
64,192,452 | I'm having issues with the below code displays Thursday as the dayOfTheWeek regardless of the date. Any ideas where I've gone wrong with this?
```java
public void CreatePlan() {
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Integer plan_recipe = 0;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, date, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
``` | 2020/10/04 | [
"https://Stackoverflow.com/questions/64192452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14216903/"
] | ```swift
var a = false
var b = false
var c = false
mutateValues(&a, &b, &c) { n in
n = true
}
print(a, b, c) // will be printed "true true true"
func mutateValues<Value>(_ values: UnsafeMutablePointer<Value>..., mutate: (inout Value) -> Void) {
values.forEach {
mutate(&$0.pointee)
}
}
``` | It is possible to do this with key paths. Let's say the properties are in a class `Foo`:
```
class Foo {
var a = false
var b = false
var c = false
func makeAllTrue() {
for n in [\Foo.a, \Foo.b, \Foo.c] {
self[keyPath: n] = true
}
}
}
```
If `Foo` is a struct, use `mutating func` instead:
```
struct Foo {
var a = false
var b = false
var c = false
mutating func makeAllTrue() {
for n in [\Foo.a, \Foo.b, \Foo.c] {
self[keyPath: n] = true
}
}
}
```
However, if the class name is long, I don't think it is worth doing this way.
If these three properties are *very* related, I would not bother with the key path stuff and replace `a`, `b` and `c` with an array:
```
var abc = [false, false, false]
```
and have the for loop loop over the indices:
```
for i in abc.indices {
abc[i] = true
}
``` |
2,762,398 | Suppose X and U are independent random variables with
$$P(X = k) =\frac{1}{N+1}\quad\quad\quad k=0,1,2,....N$$
and $U$ having a uniform distribution on $[0, 1]$. Let $Y = X + U$
a) Find the CDF of Y.
i know how to do transform continuous with continuous , but in mixed case i have no idea | 2018/05/01 | [
"https://math.stackexchange.com/questions/2762398",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Note that
$$ \begin{align}(x+y)(x^2+y^2)&=x^3+y^3+xy(x+y)\\&\tag1\ge 2+xy(x+y)\\&=2+\frac{(x+y)^2-(x^2+y^2)}{2}(x+y)\\
&=2+\frac 12(x+y)^3-\frac12(x+y)(x^2+y^2)\end{align}$$
Therefore,
$$ \tag2(x+y)(x^2+y^2)\ge \frac 43+\frac13(x+y)^3$$
So if the first factor is larger, we first find from $(1)$
$$ x+y>\sqrt2$$
and then from $(2)$
$$ x+y>\sqrt{\frac43+\frac13\sqrt 2^3},$$
which is larger. We can repeat this, i.e., if we know $x+y>a\_n$, then also $x+y>\sqrt{\frac43+\frac13a\_n^3}=:a\_{n+1}$. The sequence $\{a\_n\}\_n$, starting with $a\_1=\sqrt 2$, is strictly increasing. If it has a limit $a$, then $\sqrt{\frac43+\frac13a^3}=a$, i.e., $4+a^3-3a^2=0$, $a\in\{2,-1\}$.
We conclude $$x+y\ge 2$$
As the case $x,y\ge1$ is trivial, we assume wlog $x=1+a>1$ and $y=1-b< 1$ with $a>b$.
But then
$$ x^2+y^2=1+2a+a^2+1-2b+b^2>2+2(a-b)>2+a-b=x+y.$$ | By symmetry $x = y = z$
then
$$
2z^3 \ge 2 \Rightarrow z^3 \ge 1 \Rightarrow z^2 \ge z
$$
Comparison with $x^3+y^3 \ge 2$ (light blue) and the circle $(x-\frac{1}{2})^2+(y-\frac{1}{2})^2 = 1/2$ (red)
[](https://i.stack.imgur.com/uGGTb.jpg) |
2,762,398 | Suppose X and U are independent random variables with
$$P(X = k) =\frac{1}{N+1}\quad\quad\quad k=0,1,2,....N$$
and $U$ having a uniform distribution on $[0, 1]$. Let $Y = X + U$
a) Find the CDF of Y.
i know how to do transform continuous with continuous , but in mixed case i have no idea | 2018/05/01 | [
"https://math.stackexchange.com/questions/2762398",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Consider $f(x,y)=x^2+y^2-x-y$. The inequality is equivalent to the fact that the following minimum is non-negative
$$
\min f(x,y)\quad\text{subject to }x^3+y^3\ge 2,\ x\ge 0,\ y\ge 0.
$$
1. As $f(x,y)=(x-\frac12)^2+(y-\frac12)^2-\frac12$ has compact sublevel sets, the minimum exists. Apply the necessary condition for optimality.
2. The first constraint must be active at the minimum (otherwise we can make the variable that is greater than one a bit smaller, which makes $f(x,y)$ smaller, contradiction). It is also easy to rule out the case when the positivity constraints are active ($x=0$ or $y=0$), the function $f(x,y)\ge 0$ there. Thus the only interesting case is where the gradients of $f(x,y)$ and $x^3+y^3$ are parallel. It makes
$$
\begin{vmatrix}2x-1 & x^2\\2y-1 & y^2\end{vmatrix}=(x-y)(x+y-2xy)=0.
$$
3. The case when $x+y=2xy$ is not interesting again since then
$$
f(x,y)=x^2+y^2-2xy=(x-y)^2\ge 0.
$$
4. The case $x=y$ and $x^3+y^3=2$ gives $x=y=1$ where $f(1,1)=0$. Hence, it is the minimum. | By symmetry $x = y = z$
then
$$
2z^3 \ge 2 \Rightarrow z^3 \ge 1 \Rightarrow z^2 \ge z
$$
Comparison with $x^3+y^3 \ge 2$ (light blue) and the circle $(x-\frac{1}{2})^2+(y-\frac{1}{2})^2 = 1/2$ (red)
[](https://i.stack.imgur.com/uGGTb.jpg) |
29,466,351 | I have a series of rather large text files and am looking to resolve references in each file for a specific noun phrase eg. 'Harry Potter'
I wouldn't want to run the the pipeline in full for every single possibility of reference resolution as that would take far far too long.
Thanks very much!
Here is what I have so far...
```
import edu.stanford.nlp.io.*;
import edu.stanford.nlp.pipeline.*;
import java.io.*;
import java.util.Properties;
public class Main {
public static void main(String[] args) throws IOException
{
// SET INPUT AND OUTPUT FILES
FileOutputStream xmlOut = new FileOutputStream(new File("nlp.xml"));
String input_filename = "weblink_text.txt";
String file_contents = IOUtils.slurpFileNoExceptions(input_filename);
//SET PROPERTIES
Properties props = new Properties();
props.setProperty("annotators", "tokenize, cleanxml, ssplit, pos, lemma, ner, parse, dcoref");
// ANNOTATE AND OUTPUT
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation annotation = new Annotation(file_contents);
pipeline.annotate(annotation);
pipeline.xmlPrint(annotation, xmlOut);
System.out.println("Completed");
}
}
``` | 2015/04/06 | [
"https://Stackoverflow.com/questions/29466351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4753451/"
] | 1) If you only care about the co-reference resolution of pronominal antecedents, I would recommend checking out David Bamman's [book-nlp](https://github.com/dbamman/book-nlp).
It does very fast coref for novel-length texts, but only for pronominal antecedents (which are probably what you are most interested in anyways).
You can then read in the `.tokens` file and to build your own coreference graph.
2) If you really need to resolve coref for more than that, try setting the `dcoref.maxdist` parameter to prevent it from looking back to chapter 1 for material from chapter 20, for instance. I would then save some version of your annotated text (serialized, for instance) to load later so that you don't have to keep running this.
[edit]
3) In the relatively near future, there will be a new coref system (`hcoref`) in the Stanford CoreNLP build (<https://github.com/stanfordnlp/CoreNLP/tree/master/src/edu/stanford/nlp/hcoref>) that is based off of `depparse`, which is very much faster. I've been running that on 100 - 500 sentence-long chunks of text for a whole novel and that's been working for me. (there isn't yet an equivalent in `hcoref` to `dcoref.maxdist`)
Another note: if the parsing time is also prohibitively expensive, try setting `parse.maxlen`. | Unfortunately a full coreference analysis is required to get any usable annotations for a particular noun phrase. (Without a full analysis resolving tough anaphora like pronouns would be impossible.)
The best I can recommend is that you do processing in small blocks which are fairly "independent" in terms of coreferences (e.g., chapters of a book). |
21,816,241 | I am new to programing I need to write a code that finds the oldest person in Person Array. Please help. The program compiled but did not execute. it gave me only the size of the Array but not the oldest person. I would appreciate any help.
My code is bellow:
```
import java.util.ArrayList;
public class PersonCollection {
public static void main(String[] args) {
ArrayList<Person> aList = new ArrayList<Person>();
// Create 5 new Person objects and output their data
Person person1 = new Person("Diana", "Rockman", 38, 'F', "603-28-5324");
Person person2 = new Person("Arthur","Montgamery", 49, 'M',"402-23-5463");
Person person3 = new Person("Kim", "Balcer", 35, 'F',"607-34-5463");
Person person4 = new Person("Ghaffar","Kucher", 36, 'M',"537-52-6324");
Person person5 = new Person("Zach","Boot", 19, 'M', "732-65-7364");
aList.add(person1);
aList.add(person2);
aList.add(person3);
aList.add(person4);
aList.add(person5);
System.out.println("The size of the list is:" + aList.size());
}
public static void oldestPerson(String[] names, int[] ages)
{
int index = 0;
int oldest = ages[0];
for ( int i=0; i < ages.length; i++)
{
if(ages[i] > oldest)
{index = i;
oldest = ages[i];
}
System.out.println("Person" + names[index] + "is the oldest:" + ages [index]);
}
}
}
``` | 2014/02/16 | [
"https://Stackoverflow.com/questions/21816241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3316776/"
] | You are not calling the `oldestPerson` method anywhere (better to call it `findOldestPerson`). Further you should design that method to take a `List<Person>` as a parameter.
This might help:
```java
public static void findOldestPerson(List<Person> persons) {
Person oldest = null;
for (Person p : persons) {
if (oldest == null || p.getAge() > oldest.getAge()) oldest = p;
}
// Do something with the oldest person.
}
``` | After `System.out.println("The size of the list is:" + aList.size());`
you must add a call to yours `oldestPerson` method, and you can update your method in this way:
```
public static void oldestPerson(ArrayList<Person> aList)
{
Person oldest = new Person();
for (Person p : aList)
{
if(p.getAge() > oldest.getAge())
{
oldest = p;
}
System.out.println("Person" + p.getName() + "is the oldest:" + p.getAge());
}
```
I used a **getter** method, because I think that **attributes** about `Person` class are `private`, but if they are `public`, you can do: `p.age` or `p.name`.. |
21,816,241 | I am new to programing I need to write a code that finds the oldest person in Person Array. Please help. The program compiled but did not execute. it gave me only the size of the Array but not the oldest person. I would appreciate any help.
My code is bellow:
```
import java.util.ArrayList;
public class PersonCollection {
public static void main(String[] args) {
ArrayList<Person> aList = new ArrayList<Person>();
// Create 5 new Person objects and output their data
Person person1 = new Person("Diana", "Rockman", 38, 'F', "603-28-5324");
Person person2 = new Person("Arthur","Montgamery", 49, 'M',"402-23-5463");
Person person3 = new Person("Kim", "Balcer", 35, 'F',"607-34-5463");
Person person4 = new Person("Ghaffar","Kucher", 36, 'M',"537-52-6324");
Person person5 = new Person("Zach","Boot", 19, 'M', "732-65-7364");
aList.add(person1);
aList.add(person2);
aList.add(person3);
aList.add(person4);
aList.add(person5);
System.out.println("The size of the list is:" + aList.size());
}
public static void oldestPerson(String[] names, int[] ages)
{
int index = 0;
int oldest = ages[0];
for ( int i=0; i < ages.length; i++)
{
if(ages[i] > oldest)
{index = i;
oldest = ages[i];
}
System.out.println("Person" + names[index] + "is the oldest:" + ages [index]);
}
}
}
``` | 2014/02/16 | [
"https://Stackoverflow.com/questions/21816241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3316776/"
] | With Java 8...
```
public class PersonTest {
public static class Person {
public String first;
public String last;
public int age;
public char gender;
public String ssn;
public Person(String first, String last, int age, char gender, String ssn) {
this.first = first;
this.last = last;
this.age = age;
this.gender = gender;
this.ssn = ssn;
}
}
public static void main(String[] args) {
List<Person> aList = Arrays.asList(
new Person("Diana", "Rockman", 38, 'F', "603-28-5324"),
new Person("Arthur","Montgamery", 49, 'M',"402-23-5463"),
new Person("Kim", "Balcer", 35, 'F',"607-34-5463"),
new Person("Ghaffar","Kucher", 36, 'M',"537-52-6324"),
new Person("Zach","Boot", 19, 'M', "732-65-7364"));
Person oldest = aList.stream().max((a,b) -> a.age - b.age).get();
System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}
}
``` | After `System.out.println("The size of the list is:" + aList.size());`
you must add a call to yours `oldestPerson` method, and you can update your method in this way:
```
public static void oldestPerson(ArrayList<Person> aList)
{
Person oldest = new Person();
for (Person p : aList)
{
if(p.getAge() > oldest.getAge())
{
oldest = p;
}
System.out.println("Person" + p.getName() + "is the oldest:" + p.getAge());
}
```
I used a **getter** method, because I think that **attributes** about `Person` class are `private`, but if they are `public`, you can do: `p.age` or `p.name`.. |
40,419,595 | I am implementing a winform application in c# so that it contains four picture boxes and some control buttons in one corner.
[](https://i.stack.imgur.com/wclGK.png)
My main problem is that I cannot achieve the behaviour shown in the picture. The idea is to automatically resize the picture boxes when the form is resized. The area of the control panel should stay the same and only the area containing the boxes should be resized accordingly.
I have been playing with anchor and dock properties but I dont get the desire output.
Anyone could give me a hint?
Thanks and kind regards,
Bilbinight | 2016/11/04 | [
"https://Stackoverflow.com/questions/40419595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661551/"
] | So, let's say you have the following picture boxes:
```
pictureBox1 | pictureBox2 | panel
------------|------------
pictureBox3 | pictureBox4
```
Then the following should do the trick:
set the forms Resize event to this eventhandler:
```
private void Form1_Resize(object sender, EventArgs e)
{
int spaceBetweenPictures = 19;
int widthToFill = (this.Width - 40 - panel.Width) - spaceBetweenPictures;
int heightToFill = this.Height - 80;
pictureBox1.Width = widthToFill / 2;
pictureBox1.Height = heightToFill / 2;
// Setting the sizes of all the three pictureboxes to the sizes of the first one.
pictureBox2.Width = pictureBox1.Width;
pictureBox2.Height = pictureBox1.Height;
pictureBox3.Width = pictureBox1.Width;
pictureBox3.Height = pictureBox1.Height;
pictureBox4.Width = pictureBox1.Width;
pictureBox4.Height = pictureBox1.Height;
// Setting the positions:
pictureBox2.Location = new Point(pictureBox1.Width + spaceBetweenPictures, pictureBox1.Location.Y);
pictureBox3.Location = new Point(pictureBox1.Location.X, pictureBox1.Height + spaceBetweenPictures);
pictureBox4.Location = new Point(pictureBox2.Location.X, pictureBox3.Location.Y);
}
```
Of course you should modify the magic numbers in this code (19, 40, 80) accordingly, to suit your program (that depends a lot on whether you use border on your form or not).
UPDATE:
If you want your pictureboxes square shaped then just ignore the heightToFill variable and use widthToFill instead when setting the Height of pictureBox1. Or set:
```
pictureBox1.Height = pictureBox.Width;
```
And I also forgot to mention that the panel of course should be aligned Top, Right. So set the panel's Anchor property to:
```
AnchorStyles.Top | AnchorStyles.Right;
``` | Are four image boxes supposed to support resizing at runtime (allowing end user to resize)? if not then following will give you desired result.
1 TableLayoutPanel with 2 rows and two columns. Set the initial size to fill the desired area, set the anchor to all four directions.
Add 4 picture boxes to 4 cells and set Dock to Fill for all Picture Boxes.
Add a panel to the right side of form, and make it fit to cover your controls area. Set the anchor Top, Bottom, Right.
Here is sample code:
```
//frmResizing.cs
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class frmResizing : Form
{
public frmResizing()
{
InitializeComponent();
}
}
}
//frmResizing.Designer.cs code
namespace WindowsFormsApplication1
{
partial class frmResizing
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.Panel();
this.pictureBox4 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Controls.Add(this.pictureBox4, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.pictureBox3, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.pictureBox2, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.pictureBox1, 0, 0);
this.tableLayoutPanel1.Location = new System.Drawing.Point(2, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(544, 561);
this.tableLayoutPanel1.TabIndex = 0;
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BackColor = System.Drawing.Color.Red;
this.panel1.Location = new System.Drawing.Point(553, 1);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(107, 561);
this.panel1.TabIndex = 1;
//
// pictureBox4
//
this.pictureBox4.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox4.Image = global::WindowsFormsApplication1.Properties.Resources.download;
this.pictureBox4.Location = new System.Drawing.Point(275, 283);
this.pictureBox4.Name = "pictureBox4";
this.pictureBox4.Size = new System.Drawing.Size(266, 275);
this.pictureBox4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox4.TabIndex = 3;
this.pictureBox4.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox3.Image = global::WindowsFormsApplication1.Properties.Resources.pizza_page;
this.pictureBox3.Location = new System.Drawing.Point(3, 283);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(266, 275);
this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox3.TabIndex = 2;
this.pictureBox3.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox2.Image = global::WindowsFormsApplication1.Properties.Resources.images;
this.pictureBox2.Location = new System.Drawing.Point(275, 3);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(266, 274);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Image = global::WindowsFormsApplication1.Properties.Resources.download__1_;
this.pictureBox1.Location = new System.Drawing.Point(3, 3);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(266, 274);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(660, 562);
this.Controls.Add(this.panel1);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "Form2";
this.Text = "Form2";
this.tableLayoutPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Panel panel1;
}
}
``` |
11,703,311 | I am looking for a solution to multiple submit buttons using simple php.
Here is my form code
```
<!-- Widget Starts -->
<div class="widget">
<div class="title js_opened">
<div class="icon"><img src="themes/<?php echo WEBSITE_ADMIN_PANEL_THEME; ?>/images/icons/navigation/pages<?php echo $retina_suffix; ?>.png" width="24" height="24" alt="" /></div>
<span>Fill The Fields Marked With *</span>
</div>
<div class="content">
<div class="form_row first">
<label>Title<span class="star"> *</span></label>
<div class="form_right"><input type="text" name="title" maxlength="100" value="<?php echo $session->getSession("pages_title") ;?>" /></div>
<div class="clear"></div>
</div>
<div class="form_row last">
<label>Description<span class="star"> *</span></label>
<div class="form_right"><textarea name="description" class="Editor"><?php echo $session->getSession("pages_description") ;?></textarea></div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- Widget Ends -->
<!-- Widget Starts -->
<div class="widget">
<div class="title js_opened">
<div class="icon"><img src="themes/<?php echo WEBSITE_ADMIN_PANEL_THEME; ?>/images/icons/navigation/meta<?php echo $retina_suffix; ?>.png" width="24" height="24" alt="" /></div>
<span>Metadata Information</span>
</div>
<div class="content">
<div class="form_row first">
<label>Title</label>
<div class="form_right"><input type="text" name="meta_title" maxlength="250" value="<?php echo $session->getSession("pages_meta_title") ;?>" /></div>
<div class="clear"></div>
</div>
<div class="form_row">
<label>Keywords</label>
<div class="form_right"><textarea id="meta_keywords" name="meta_keywords"><?php echo $session->getSession("pages_meta_keywords") ;?></textarea></div>
<div class="clear"></div>
</div>
<div class="form_row">
<label>Description</label>
<div class="form_right"><textarea id="meta_description" name="meta_description"><?php echo $session->getSession("pages_meta_description") ;?></textarea></div>
<div class="clear"></div>
</div>
<div class="form_row">
<label>Robot</label>
<div class="form_right">
<select name="meta_robot">
<option value="">Please Choose An Option</option>
<option value="index, follow" <?php if ($session->getSession("pages_meta_robot")=="index, follow") echo "selected=\"selected\""; ?> >index, follow</option>
<option value="noindex, follow" <?php if ($session->getSession("pages_meta_robot")=="noindex, follow") echo "selected=\"selected\""; ?> >noindex, follow</option>
<option value="index, nofollow" <?php if ($session->getSession("pages_meta_robot")=="index, nofollow") echo "selected=\"selected\""; ?> >index, nofollow</option>
<option value="noindex, nofollow" <?php if ($session->getSession("pages_meta_robot")=="noindex, nofollow") echo "selected=\"selected\""; ?> >noindex, nofollow</option>
</select>
</div>
<div class="clear"></div>
</div>
<div class="form_row last">
<label>Author</label>
<div class="form_right"><input type="text" name="meta_author" maxlength="50" value="<?php echo $session->getSession("pages_meta_author") ;?>" /></div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- Widget Ends -->
<div class="form_buttons">
<input type="submit" name="add" value="Save" /> <span class="no_mobile"> </span>
<input type="submit" name="add" value="Save & New" /> <span class="no_mobile"> </span>
<input type="reset" value="Clear" />
</div>
</form>
<!-- Form Ends -->
```
and here is my php processing page code (I have omitted the part which saves the form results into the database.
```
<?php
$submit = $_POST["add"];
if ($submit == "Save")
{
header("location:pages_view.php?type=success&msg=" .urlencode($msg));
exit();
}
else
{
header("location:pages_add.php?type=success&msg=" .urlencode($msg));
exit();
}
?>
```
What I want to achieve is that if I press the 1st submit button in form i.e Save, then it should save the form and go to view page and if I press the 2nd submit button i.e Save & New then it should save the form data and go back to the same page i.e add page.
Please help me to find out the solution. | 2012/07/28 | [
"https://Stackoverflow.com/questions/11703311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1530513/"
] | Check whether the name of the submit button is set, and do the operation based on it.
For example:
```
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') // if form is submitted...
{
if(isset($_POST['save'])) // check whether it is the "Save" button that's being clicked
{
//code for saving
echo 'saved';
}
else // it's the "Save & New" button
{
//code for save and new
echo 'save and new';
}
}
?>
<html>
<body>
<form method="POST">
<input type="text" name="msg" />
<!-- and other input elements goes here.. -->
<input type="submit" name="save" value="Save" />
<input type="submit" name="savenew" value="Save & New" />
</form>
</body>
</html>
``` | Make a hidden field somewhere in your form:
```
<input type="hidden" id="myHiddenField" value="" name="add">
```
Make two buttons:
```
<button onclick="formSubmit(save)">Save!</button>
<button onclick="formSubmit(something)">Something else!</button>
```
Then apply some Javascript:
```
<script language="javascript">
function formSubmit(tobesend) {
document.getElementById("myHiddenField").value(tobesend);
document.form.submit();
}
</script>
```
What this does is: when a button is clicked, the value to the hiddenfield is set to something, and then the form is submitted. In your PHP-file you can check for the value of $\_POST['add'] and do whatever you want to be done.
NOTE: i'm fairly new to javascript, so this might be a nonfunctional code. It's merely to show how to achieve what you are trying to do. |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | I had the same problem, I imported the `NgSelectModule` at both the main application module and the component module and it was fixed.
You might also want to look at [this](https://github.com/ng-select/ng-select/issues/1464). | We had a different problem. We used @ng-select/ng-select": "3.7.2" and one of the third party component used the version 3.7.3.
After we updated to the same version the problem disappeared. |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | I had the same problem, I imported the `NgSelectModule` at both the main application module and the component module and it was fixed.
You might also want to look at [this](https://github.com/ng-select/ng-select/issues/1464). | I faced similar issue while running test case.
I resolved it by importing `NgSelectModule` under `imports` block.
If you are using `NgSelectComponent` in your code for some use-case/scenario purpose then you can also declare `NgSelectComponent` under `declarations` block if needed
```
TestBed.configureTestingModule({
imports: [... , NgSelectModule],
declarations: [MultiSelectCtrlComponent, NgSelectComponent],
providers: []
});
```
I hope it may help you or someone else! |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | I had the same problem, I imported the `NgSelectModule` at both the main application module and the component module and it was fixed.
You might also want to look at [this](https://github.com/ng-select/ng-select/issues/1464). | Do import `NgSelectModule` in your `app.module.ts` along with the component module. |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | I had the same problem, I imported the `NgSelectModule` at both the main application module and the component module and it was fixed.
You might also want to look at [this](https://github.com/ng-select/ng-select/issues/1464). | Only add `NgSelectModule` to `app.module.ts` and it works all across your app. This module doesn't work properly in a modal for example, because of it lazy loading. |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | We had a different problem. We used @ng-select/ng-select": "3.7.2" and one of the third party component used the version 3.7.3.
After we updated to the same version the problem disappeared. | I faced similar issue while running test case.
I resolved it by importing `NgSelectModule` under `imports` block.
If you are using `NgSelectComponent` in your code for some use-case/scenario purpose then you can also declare `NgSelectComponent` under `declarations` block if needed
```
TestBed.configureTestingModule({
imports: [... , NgSelectModule],
declarations: [MultiSelectCtrlComponent, NgSelectComponent],
providers: []
});
```
I hope it may help you or someone else! |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | We had a different problem. We used @ng-select/ng-select": "3.7.2" and one of the third party component used the version 3.7.3.
After we updated to the same version the problem disappeared. | Only add `NgSelectModule` to `app.module.ts` and it works all across your app. This module doesn't work properly in a modal for example, because of it lazy loading. |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | Do import `NgSelectModule` in your `app.module.ts` along with the component module. | I faced similar issue while running test case.
I resolved it by importing `NgSelectModule` under `imports` block.
If you are using `NgSelectComponent` in your code for some use-case/scenario purpose then you can also declare `NgSelectComponent` under `declarations` block if needed
```
TestBed.configureTestingModule({
imports: [... , NgSelectModule],
declarations: [MultiSelectCtrlComponent, NgSelectComponent],
providers: []
});
```
I hope it may help you or someone else! |
64,804,093 | I have the following code:
```
-module(a).
-compile(export_all).
say(2,0) ->
[1,2];
say(A,B) ->
say(A-1,B-1).
loop(0) ->
io:format("");
loop(Times) ->
L = spawn(a, say, [4,2]),
io:fwrite( "L is ~w ~n", [L] ),
loop(Times-1).
run() ->
loop(4).
```
I want to have the list [1,2] in L each time function 'say' completes. However, since the pid of the process is returned instead of the list from the function say due to use of spawn, I am getting the following output:
```
L is <0.113.0>
L is <0.114.0>
L is <0.115.0>
L is <0.116.0>
```
What I desire is
```
L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]
```
How can I achieve this? | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13692000/"
] | Do import `NgSelectModule` in your `app.module.ts` along with the component module. | Only add `NgSelectModule` to `app.module.ts` and it works all across your app. This module doesn't work properly in a modal for example, because of it lazy loading. |
60,191,572 | I want to inspect assemblies if they have a specific type without loading the assembly in the current scope, which is available via MetadataLoadContext in .NET Core 3.
But if I try the following example
```
internal static class Program
{
// ReSharper disable once UnusedParameter.Local
private static void Main(string[] args)
{
var paths = new string[] { @"Plugin.dll" };
var resolver = new PathAssemblyResolver(paths);
var pluginInterface = typeof(IPlugin);
using (var context = new MetadataLoadContext(resolver))
{
var assembly =
context.LoadFromAssemblyName(@"Plugin");
foreach (var type in assembly.GetTypes())
{
if (type.IsClass && pluginInterface.IsAssignableFrom(type))
Console.WriteLine("found");
}
}
}
}
```
I get an exception
>
> System.IO.FileNotFoundException: Could not find core assembly. Either specify a valid core assembly name in the MetadataLoadContext constructor or provide a MetadataAssemblyResolver that can load the core assembly.
>
>
>
at `var context = new MetadataLoadContext(resolver)`
What is meant by core assembly ? Or what I am doing wrong ?
<https://blog.vincentbitter.nl/net-core-3-0/> seems not working for me. | 2020/02/12 | [
"https://Stackoverflow.com/questions/60191572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616194/"
] | The existing answer didn't worked for me (.NET Core 2.1). It fails with error that System.Runtime is not found. If i hardcode full path to System.Runtime, it fails for other assemblies, like System.Private.CoreLib. Also checking types via IsAssignableFrom seems not working when one type isn't from MetadataLoadContext.
The possible solution for assembly load errors is to include all BCL assemblies (all .dll files in directory returned by [RuntimeEnvironment.GetRuntimeDirectory](https://learn.microsoft.com/dotnet/api/system.runtime.interopservices.runtimeenvironment.getruntimedirectory)). This feels somewhat dumb, because not all of them are actually managed assemblies, but it seems to work. Here's complete example of searching types that implement interface via MetadataLoadContext:
```
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
namespace MetadataLoadContextSample
{
class Program
{
static int Main(string[] args)
{
string inputFile = @"Plugin.dll";
string[] runtimeAssemblies = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");
var paths = new List<string>(runtimeAssemblies);
paths.Add(inputFile);
var resolver = new PathAssemblyResolver(paths);
var context = new MetadataLoadContext(resolver);
using (context)
{
Assembly assembly = context.LoadFromAssemblyPath(inputFile);
AssemblyName name = assembly.GetName();
foreach (TypeInfo t in assembly.GetTypes())
{
try
{
if (t.IsClass && t.GetInterface("IPlugin") != null)
{
Console.WriteLine(t.Name);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("FileNotFoundException: " + ex.Message);
}
catch (TypeLoadException ex)
{
Console.WriteLine("TypeLoadException: " + ex.Message);
}
}
}
Console.ReadLine();
return 0;
}
}
}
``` | Providing the following paths of the .NET core libs works
```
var paths = new string[] {@"Plugin.dll", @"netstandard.dll", "System.Runtime.dll"};
``` |
60,191,572 | I want to inspect assemblies if they have a specific type without loading the assembly in the current scope, which is available via MetadataLoadContext in .NET Core 3.
But if I try the following example
```
internal static class Program
{
// ReSharper disable once UnusedParameter.Local
private static void Main(string[] args)
{
var paths = new string[] { @"Plugin.dll" };
var resolver = new PathAssemblyResolver(paths);
var pluginInterface = typeof(IPlugin);
using (var context = new MetadataLoadContext(resolver))
{
var assembly =
context.LoadFromAssemblyName(@"Plugin");
foreach (var type in assembly.GetTypes())
{
if (type.IsClass && pluginInterface.IsAssignableFrom(type))
Console.WriteLine("found");
}
}
}
}
```
I get an exception
>
> System.IO.FileNotFoundException: Could not find core assembly. Either specify a valid core assembly name in the MetadataLoadContext constructor or provide a MetadataAssemblyResolver that can load the core assembly.
>
>
>
at `var context = new MetadataLoadContext(resolver)`
What is meant by core assembly ? Or what I am doing wrong ?
<https://blog.vincentbitter.nl/net-core-3-0/> seems not working for me. | 2020/02/12 | [
"https://Stackoverflow.com/questions/60191572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616194/"
] | Here is a method that works on `net6.0`. The method extracts custom attributes from the assembly that was provided as an argument.
```
public static FreshInfo GetInfo(string pathToMainExecutable) {
if (string.IsNullOrWhiteSpace(pathToMainExecutable))
throw new ArgumentException(@"Value cannot be null or whitespace.", nameof(pathToMainExecutable));
if (File.Exists(pathToMainExecutable) == false)
throw new FileNotFoundException($"File [{pathToMainExecutable}] does not exists on disk.");
var runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory();
var pathToSystemRuntime = Path.Combine(runtimeDirectory, "System.Runtime.dll");
if (File.Exists(pathToSystemRuntime) == false)
throw new FileNotFoundException($"Could not find [{pathToSystemRuntime}].");
var pathToSystemPrivateCoreLib = Path.Combine(runtimeDirectory, "System.Private.CoreLib.dll");
if (File.Exists(pathToSystemPrivateCoreLib) == false)
throw new FileNotFoundException($"Could not find [{pathToSystemPrivateCoreLib}].");
// make sure that we are referring to the .net dll/assembly but not the exe bootstrapper
// exe file in net6.0/core is not a managed file it's a native executable
// TODO do not assume that the exe file has the same name as the dll file
// managed dll filename can be extracted from a VERSIONINFO Resource in the native exe
pathToMainExecutable = pathToMainExecutable.ReplaceEnd("exe", "dll");
var assemblyNames = new List<string> {
Path.GetFileName(pathToMainExecutable)
, "Fresh.Updater.dll"
, pathToSystemRuntime
, pathToSystemPrivateCoreLib
};
var metadataAssemblyResolver = new PathAssemblyResolver(assemblyNames);
using (var mlc = new MetadataLoadContext(metadataAssemblyResolver)) {
var mainAssembly = mlc.LoadFromAssemblyPath(pathToMainExecutable);
var buildTime = ExtractBuildTime(mainAssembly);
var appId = ExtractAppId(mainAssembly);
var appFolder = Path.GetDirectoryName(pathToMainExecutable);
return new FreshInfo(appId, buildTime) {
AppFolder = appFolder
};
}
}
``` | Providing the following paths of the .NET core libs works
```
var paths = new string[] {@"Plugin.dll", @"netstandard.dll", "System.Runtime.dll"};
``` |
60,191,572 | I want to inspect assemblies if they have a specific type without loading the assembly in the current scope, which is available via MetadataLoadContext in .NET Core 3.
But if I try the following example
```
internal static class Program
{
// ReSharper disable once UnusedParameter.Local
private static void Main(string[] args)
{
var paths = new string[] { @"Plugin.dll" };
var resolver = new PathAssemblyResolver(paths);
var pluginInterface = typeof(IPlugin);
using (var context = new MetadataLoadContext(resolver))
{
var assembly =
context.LoadFromAssemblyName(@"Plugin");
foreach (var type in assembly.GetTypes())
{
if (type.IsClass && pluginInterface.IsAssignableFrom(type))
Console.WriteLine("found");
}
}
}
}
```
I get an exception
>
> System.IO.FileNotFoundException: Could not find core assembly. Either specify a valid core assembly name in the MetadataLoadContext constructor or provide a MetadataAssemblyResolver that can load the core assembly.
>
>
>
at `var context = new MetadataLoadContext(resolver)`
What is meant by core assembly ? Or what I am doing wrong ?
<https://blog.vincentbitter.nl/net-core-3-0/> seems not working for me. | 2020/02/12 | [
"https://Stackoverflow.com/questions/60191572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616194/"
] | The existing answer didn't worked for me (.NET Core 2.1). It fails with error that System.Runtime is not found. If i hardcode full path to System.Runtime, it fails for other assemblies, like System.Private.CoreLib. Also checking types via IsAssignableFrom seems not working when one type isn't from MetadataLoadContext.
The possible solution for assembly load errors is to include all BCL assemblies (all .dll files in directory returned by [RuntimeEnvironment.GetRuntimeDirectory](https://learn.microsoft.com/dotnet/api/system.runtime.interopservices.runtimeenvironment.getruntimedirectory)). This feels somewhat dumb, because not all of them are actually managed assemblies, but it seems to work. Here's complete example of searching types that implement interface via MetadataLoadContext:
```
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
namespace MetadataLoadContextSample
{
class Program
{
static int Main(string[] args)
{
string inputFile = @"Plugin.dll";
string[] runtimeAssemblies = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");
var paths = new List<string>(runtimeAssemblies);
paths.Add(inputFile);
var resolver = new PathAssemblyResolver(paths);
var context = new MetadataLoadContext(resolver);
using (context)
{
Assembly assembly = context.LoadFromAssemblyPath(inputFile);
AssemblyName name = assembly.GetName();
foreach (TypeInfo t in assembly.GetTypes())
{
try
{
if (t.IsClass && t.GetInterface("IPlugin") != null)
{
Console.WriteLine(t.Name);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("FileNotFoundException: " + ex.Message);
}
catch (TypeLoadException ex)
{
Console.WriteLine("TypeLoadException: " + ex.Message);
}
}
}
Console.ReadLine();
return 0;
}
}
}
``` | Here is a method that works on `net6.0`. The method extracts custom attributes from the assembly that was provided as an argument.
```
public static FreshInfo GetInfo(string pathToMainExecutable) {
if (string.IsNullOrWhiteSpace(pathToMainExecutable))
throw new ArgumentException(@"Value cannot be null or whitespace.", nameof(pathToMainExecutable));
if (File.Exists(pathToMainExecutable) == false)
throw new FileNotFoundException($"File [{pathToMainExecutable}] does not exists on disk.");
var runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory();
var pathToSystemRuntime = Path.Combine(runtimeDirectory, "System.Runtime.dll");
if (File.Exists(pathToSystemRuntime) == false)
throw new FileNotFoundException($"Could not find [{pathToSystemRuntime}].");
var pathToSystemPrivateCoreLib = Path.Combine(runtimeDirectory, "System.Private.CoreLib.dll");
if (File.Exists(pathToSystemPrivateCoreLib) == false)
throw new FileNotFoundException($"Could not find [{pathToSystemPrivateCoreLib}].");
// make sure that we are referring to the .net dll/assembly but not the exe bootstrapper
// exe file in net6.0/core is not a managed file it's a native executable
// TODO do not assume that the exe file has the same name as the dll file
// managed dll filename can be extracted from a VERSIONINFO Resource in the native exe
pathToMainExecutable = pathToMainExecutable.ReplaceEnd("exe", "dll");
var assemblyNames = new List<string> {
Path.GetFileName(pathToMainExecutable)
, "Fresh.Updater.dll"
, pathToSystemRuntime
, pathToSystemPrivateCoreLib
};
var metadataAssemblyResolver = new PathAssemblyResolver(assemblyNames);
using (var mlc = new MetadataLoadContext(metadataAssemblyResolver)) {
var mainAssembly = mlc.LoadFromAssemblyPath(pathToMainExecutable);
var buildTime = ExtractBuildTime(mainAssembly);
var appId = ExtractAppId(mainAssembly);
var appFolder = Path.GetDirectoryName(pathToMainExecutable);
return new FreshInfo(appId, buildTime) {
AppFolder = appFolder
};
}
}
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You're welcome to have one function call another. For example:
```
void ANewFunction() {
MainFunction(false);
}
void AnotherNewFunction() {
MainFunction(true);
}
```
You can even get fancy:
```
#include <functional>
auto ANewFunction = std::bind(&MainFunction, false);
auto AnotherNewFunction = std::bind(&MainFunction, true);
```
Either way, you can call `ANewFunction` or `AnotherNewFunction`, and `MainFunction` will get called with the given argument. (In the latter case, they're not really functions anymore. They're called function objects, or *functors*, but you cal still call them just like ordinary functions: `ANewFunction()`.) | You can't "re-use" functions, at least not in the way I understand your question.
But you can create a new function that calls the original function and then does some additional work of its own. For example:
```
void PrevFunction(int one)
{
int i = one;
// do whatever
}
void NewFunction(int one)
{
PrevFunction(one);
// do new stuff
// ...
}
```
You could also define a class, and then use inheritance and `virtual` functions to modify the behavior of a particular set of functions from the base class. |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You can't "re-use" functions, at least not in the way I understand your question.
But you can create a new function that calls the original function and then does some additional work of its own. For example:
```
void PrevFunction(int one)
{
int i = one;
// do whatever
}
void NewFunction(int one)
{
PrevFunction(one);
// do new stuff
// ...
}
```
You could also define a class, and then use inheritance and `virtual` functions to modify the behavior of a particular set of functions from the base class. | Simply call MainFunction from your other function?
```
void ANewFunction()
{
MainFunction(false);
}
void AnotherNewFunction()
{
MainFunction(true);
}
```
If your question is how do you make AnotherNewFunction refer to a different A and B than ANewFunction, the answer is you can't, at least not without help from MainFunction. You can, however, update MainFunction:
```
void MainFunction(bool Whatever, bool& A, bool& B) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
bool A1 = false;
bool B1 = true;
void ANewFunction()
{
MainFunction(false, A1, B1);
}
bool A2 = false;
bool B2 = true;
void AnotherNewFunction()
{
MainFunction(true, A2, B2);
}
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You can't "re-use" functions, at least not in the way I understand your question.
But you can create a new function that calls the original function and then does some additional work of its own. For example:
```
void PrevFunction(int one)
{
int i = one;
// do whatever
}
void NewFunction(int one)
{
PrevFunction(one);
// do new stuff
// ...
}
```
You could also define a class, and then use inheritance and `virtual` functions to modify the behavior of a particular set of functions from the base class. | Another new-fangled solution, using *lambda's*:
```
auto ANewFunction = [](){ MainFunction(false); }
auto AnotherNewFunction = [](){ MainFunction(true); }
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You're welcome to have one function call another. For example:
```
void ANewFunction() {
MainFunction(false);
}
void AnotherNewFunction() {
MainFunction(true);
}
```
You can even get fancy:
```
#include <functional>
auto ANewFunction = std::bind(&MainFunction, false);
auto AnotherNewFunction = std::bind(&MainFunction, true);
```
Either way, you can call `ANewFunction` or `AnotherNewFunction`, and `MainFunction` will get called with the given argument. (In the latter case, they're not really functions anymore. They're called function objects, or *functors*, but you cal still call them just like ordinary functions: `ANewFunction()`.) | Simply call MainFunction from your other function?
```
void ANewFunction()
{
MainFunction(false);
}
void AnotherNewFunction()
{
MainFunction(true);
}
```
If your question is how do you make AnotherNewFunction refer to a different A and B than ANewFunction, the answer is you can't, at least not without help from MainFunction. You can, however, update MainFunction:
```
void MainFunction(bool Whatever, bool& A, bool& B) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
bool A1 = false;
bool B1 = true;
void ANewFunction()
{
MainFunction(false, A1, B1);
}
bool A2 = false;
bool B2 = true;
void AnotherNewFunction()
{
MainFunction(true, A2, B2);
}
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You're welcome to have one function call another. For example:
```
void ANewFunction() {
MainFunction(false);
}
void AnotherNewFunction() {
MainFunction(true);
}
```
You can even get fancy:
```
#include <functional>
auto ANewFunction = std::bind(&MainFunction, false);
auto AnotherNewFunction = std::bind(&MainFunction, true);
```
Either way, you can call `ANewFunction` or `AnotherNewFunction`, and `MainFunction` will get called with the given argument. (In the latter case, they're not really functions anymore. They're called function objects, or *functors*, but you cal still call them just like ordinary functions: `ANewFunction()`.) | ```
typedef int (*function_t)(int); // new type - defines function type - address of function
// your function, PrevFunction is simply variable holding address of the function:
int PrevFunction(int one) { return one; }
// new variable of type function_t initialized by PrevFunction address:
function_t NewFunction = PrevFunction;
//And finally we can use either PrevFunction or NewFunction - they point to the same function body:
int a = PrevFunction(1); // a == 1
int b = NewFunction(2); // a == 2
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | You're welcome to have one function call another. For example:
```
void ANewFunction() {
MainFunction(false);
}
void AnotherNewFunction() {
MainFunction(true);
}
```
You can even get fancy:
```
#include <functional>
auto ANewFunction = std::bind(&MainFunction, false);
auto AnotherNewFunction = std::bind(&MainFunction, true);
```
Either way, you can call `ANewFunction` or `AnotherNewFunction`, and `MainFunction` will get called with the given argument. (In the latter case, they're not really functions anymore. They're called function objects, or *functors*, but you cal still call them just like ordinary functions: `ANewFunction()`.) | Another new-fangled solution, using *lambda's*:
```
auto ANewFunction = [](){ MainFunction(false); }
auto AnotherNewFunction = [](){ MainFunction(true); }
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | ```
typedef int (*function_t)(int); // new type - defines function type - address of function
// your function, PrevFunction is simply variable holding address of the function:
int PrevFunction(int one) { return one; }
// new variable of type function_t initialized by PrevFunction address:
function_t NewFunction = PrevFunction;
//And finally we can use either PrevFunction or NewFunction - they point to the same function body:
int a = PrevFunction(1); // a == 1
int b = NewFunction(2); // a == 2
``` | Simply call MainFunction from your other function?
```
void ANewFunction()
{
MainFunction(false);
}
void AnotherNewFunction()
{
MainFunction(true);
}
```
If your question is how do you make AnotherNewFunction refer to a different A and B than ANewFunction, the answer is you can't, at least not without help from MainFunction. You can, however, update MainFunction:
```
void MainFunction(bool Whatever, bool& A, bool& B) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
bool A1 = false;
bool B1 = true;
void ANewFunction()
{
MainFunction(false, A1, B1);
}
bool A2 = false;
bool B2 = true;
void AnotherNewFunction()
{
MainFunction(true, A2, B2);
}
``` |
8,799,518 | How can I re-use a function?
Okay lets say I have this "main" function below:
```
bool A = false;
bool B = true;
void MainFunction(bool Whatever) {
if(!Whatever) {
A = true;
if(A) {
B = false;
} else if(!A) {
B = true;
}
}
}
```
Now I want to make a new function using the MainFunction, something like this:
```
MainFunction ANewFunction(false);
MainFunction AnotherNewFunction(true);
```
Obviously that won't work, so is there any way to "re-use" a function as a different function? | 2012/01/10 | [
"https://Stackoverflow.com/questions/8799518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129071/"
] | ```
typedef int (*function_t)(int); // new type - defines function type - address of function
// your function, PrevFunction is simply variable holding address of the function:
int PrevFunction(int one) { return one; }
// new variable of type function_t initialized by PrevFunction address:
function_t NewFunction = PrevFunction;
//And finally we can use either PrevFunction or NewFunction - they point to the same function body:
int a = PrevFunction(1); // a == 1
int b = NewFunction(2); // a == 2
``` | Another new-fangled solution, using *lambda's*:
```
auto ANewFunction = [](){ MainFunction(false); }
auto AnotherNewFunction = [](){ MainFunction(true); }
``` |
55,681,995 | I have a series of unreferenced aerial images that I would like to georeference using python. The images are identical spatially (they are actually frames extracted from a video), and I obtained ground control points for them by manually georeferencing one frame in ArcMap. I would like to apply the ground control points I obtained to all the subsequent images, and as a result obtain a geo-tiff or a jpeg file with a corresponding world file (.jgw) for each processed image. I know this is possible to do using arcpy, but I do not have access to arcpy, and would really like to use a free open source module if possible.
My coordinate system is NZGD2000 (epsg 2193), and here is the table of control points I wish to apply to my images:
176.412984, -310.977264, 1681255.524654, 6120217.357425
160.386905, -141.487145, 1681158.424227, 6120406.821253
433.204947, -310.547238, 1681556.948690, 6120335.658359
Here is an example image: <https://imgur.com/a/9ThHtOz>
I've read a lot of information on GDAL and rasterio, but I don't have any experience with them, and am failing to adapt bits of code I found to my particular situation.
Rasterio attempt:
```
import cv2
from rasterio.warp import reproject
from rasterio.control import GroundControlPoint
from fiona.crs import from_epsg
img = cv2.imread("Example_image.jpg")
# Creating ground control points (not sure if I got the order of variables right):
points = [(GroundControlPoint(176.412984, -310.977264, 1681255.524654, 6120217.357425)),
(GroundControlPoint(160.386905, -141.487145, 1681158.424227, 6120406.821253)),
(GroundControlPoint(433.204947, -310.547238, 1681556.948690, 6120335.658359))]
# The function requires a parameter "destination", but I'm not sure what to put there.
# I'm guessing this may not be the right function to use
reproject(img, destination, src_transform=None, gcps=points, src_crs=from_epsg(2193),
src_nodata=None, dst_transform=None, dst_crs=from_epsg(2193), dst_nodata=None,
src_alpha=0, dst_alpha=0, init_dest_nodata=True, warp_mem_limit=0)
```
GDAL attempt:
```
from osgeo import gdal
import osr
inputImage = "Example_image.jpg"
outputImage = "image_gdal.jpg"
dataset = gdal.Open(inputImage)
I = dataset.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)
outdataset = gdal.GetDriverByName('GTiff')
output_SRS = osr.SpatialReference()
output_SRS.ImportFromEPSG(2193)
outdataset = outdataset.Create(outputImage,dataset.RasterXSize,dataset.RasterYSize,I.shape[0])
for nb_band in range(I.shape[0]):
outdataset.GetRasterBand(nb_band+1).WriteArray(I[nb_band,:,:])
# Creating ground control points (not sure if I got the order of variables right):
gcp_list = []
gcp_list.append(gdal.GCP(176.412984, -310.977264, 1681255.524654, 6120217.357425))
gcp_list.append(gdal.GCP(160.386905, -141.487145, 1681158.424227, 6120406.821253))
gcp_list.append(gdal.GCP(433.204947, -310.547238, 1681556.948690, 6120335.658359))
outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)
outdataset = None
```
I don't quite know how to make the above code work, and I would really appreciate any help with this. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55681995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8836524/"
] | I ended up reading a book "Geoprocessing with Python" and finally found a solution that worked for me. Here is the code I adapted to my problem:
```
import shutil
from osgeo import gdal, osr
orig_fn = 'image.tif'
output_fn = 'output.tif'
# Create a copy of the original file and save it as the output filename:
shutil.copy(orig_fn, output_fn)
# Open the output file for writing for writing:
ds = gdal.Open(output_fn, gdal.GA_Update)
# Set spatial reference:
sr = osr.SpatialReference()
sr.ImportFromEPSG(2193) #2193 refers to the NZTM2000, but can use any desired projection
# Enter the GCPs
# Format: [map x-coordinate(longitude)], [map y-coordinate (latitude)], [elevation],
# [image column index(x)], [image row index (y)]
gcps = [gdal.GCP(1681255.524654, 6120217.357425, 0, 176.412984, 310.977264),
gdal.GCP(1681158.424227, 6120406.821253, 0, 160.386905, 141.487145),
gdal.GCP(1681556.948690, 6120335.658359, 0, 433.204947, 310.547238)]
# Apply the GCPs to the open output file:
ds.SetGCPs(gcps, sr.ExportToWkt())
# Close the output file in order to be able to work with it in other programs:
ds = None
``` | For your gdal method, just using gdal.Warp with the outdataset should work, e.g.
```
outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)
gdal.Warp("output_name.tif", outdataset, dstSRS='EPSG:2193', format='gtiff')
```
This will create a new file, output\_name.tif. |
55,681,995 | I have a series of unreferenced aerial images that I would like to georeference using python. The images are identical spatially (they are actually frames extracted from a video), and I obtained ground control points for them by manually georeferencing one frame in ArcMap. I would like to apply the ground control points I obtained to all the subsequent images, and as a result obtain a geo-tiff or a jpeg file with a corresponding world file (.jgw) for each processed image. I know this is possible to do using arcpy, but I do not have access to arcpy, and would really like to use a free open source module if possible.
My coordinate system is NZGD2000 (epsg 2193), and here is the table of control points I wish to apply to my images:
176.412984, -310.977264, 1681255.524654, 6120217.357425
160.386905, -141.487145, 1681158.424227, 6120406.821253
433.204947, -310.547238, 1681556.948690, 6120335.658359
Here is an example image: <https://imgur.com/a/9ThHtOz>
I've read a lot of information on GDAL and rasterio, but I don't have any experience with them, and am failing to adapt bits of code I found to my particular situation.
Rasterio attempt:
```
import cv2
from rasterio.warp import reproject
from rasterio.control import GroundControlPoint
from fiona.crs import from_epsg
img = cv2.imread("Example_image.jpg")
# Creating ground control points (not sure if I got the order of variables right):
points = [(GroundControlPoint(176.412984, -310.977264, 1681255.524654, 6120217.357425)),
(GroundControlPoint(160.386905, -141.487145, 1681158.424227, 6120406.821253)),
(GroundControlPoint(433.204947, -310.547238, 1681556.948690, 6120335.658359))]
# The function requires a parameter "destination", but I'm not sure what to put there.
# I'm guessing this may not be the right function to use
reproject(img, destination, src_transform=None, gcps=points, src_crs=from_epsg(2193),
src_nodata=None, dst_transform=None, dst_crs=from_epsg(2193), dst_nodata=None,
src_alpha=0, dst_alpha=0, init_dest_nodata=True, warp_mem_limit=0)
```
GDAL attempt:
```
from osgeo import gdal
import osr
inputImage = "Example_image.jpg"
outputImage = "image_gdal.jpg"
dataset = gdal.Open(inputImage)
I = dataset.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)
outdataset = gdal.GetDriverByName('GTiff')
output_SRS = osr.SpatialReference()
output_SRS.ImportFromEPSG(2193)
outdataset = outdataset.Create(outputImage,dataset.RasterXSize,dataset.RasterYSize,I.shape[0])
for nb_band in range(I.shape[0]):
outdataset.GetRasterBand(nb_band+1).WriteArray(I[nb_band,:,:])
# Creating ground control points (not sure if I got the order of variables right):
gcp_list = []
gcp_list.append(gdal.GCP(176.412984, -310.977264, 1681255.524654, 6120217.357425))
gcp_list.append(gdal.GCP(160.386905, -141.487145, 1681158.424227, 6120406.821253))
gcp_list.append(gdal.GCP(433.204947, -310.547238, 1681556.948690, 6120335.658359))
outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)
outdataset = None
```
I don't quite know how to make the above code work, and I would really appreciate any help with this. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55681995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8836524/"
] | For your gdal method, just using gdal.Warp with the outdataset should work, e.g.
```
outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)
gdal.Warp("output_name.tif", outdataset, dstSRS='EPSG:2193', format='gtiff')
```
This will create a new file, output\_name.tif. | As an addition to @Kat's answer, to avoid quality loss of the original image file and set the nodata-value to 0, the following can be used.
```
#Load the original file
src_ds = gdal.Open(orig_fn)
#Create tmp dataset saved in memory
driver = gdal.GetDriverByName('MEM')
tmp_ds = driver.CreateCopy('', src_ds, strict=0)
#
# ... setting GCP....
#
# Setting no data for all bands
for i in range(1, tmp_ds.RasterCount + 1):
f = tmp_ds.GetRasterBand(i).SetNoDataValue(0)
# Saving as file
driver = gdal.GetDriverByName('GTiff')
ds = driver.CreateCopy(output_fn, tmp_ds, strict=0)
``` |
55,681,995 | I have a series of unreferenced aerial images that I would like to georeference using python. The images are identical spatially (they are actually frames extracted from a video), and I obtained ground control points for them by manually georeferencing one frame in ArcMap. I would like to apply the ground control points I obtained to all the subsequent images, and as a result obtain a geo-tiff or a jpeg file with a corresponding world file (.jgw) for each processed image. I know this is possible to do using arcpy, but I do not have access to arcpy, and would really like to use a free open source module if possible.
My coordinate system is NZGD2000 (epsg 2193), and here is the table of control points I wish to apply to my images:
176.412984, -310.977264, 1681255.524654, 6120217.357425
160.386905, -141.487145, 1681158.424227, 6120406.821253
433.204947, -310.547238, 1681556.948690, 6120335.658359
Here is an example image: <https://imgur.com/a/9ThHtOz>
I've read a lot of information on GDAL and rasterio, but I don't have any experience with them, and am failing to adapt bits of code I found to my particular situation.
Rasterio attempt:
```
import cv2
from rasterio.warp import reproject
from rasterio.control import GroundControlPoint
from fiona.crs import from_epsg
img = cv2.imread("Example_image.jpg")
# Creating ground control points (not sure if I got the order of variables right):
points = [(GroundControlPoint(176.412984, -310.977264, 1681255.524654, 6120217.357425)),
(GroundControlPoint(160.386905, -141.487145, 1681158.424227, 6120406.821253)),
(GroundControlPoint(433.204947, -310.547238, 1681556.948690, 6120335.658359))]
# The function requires a parameter "destination", but I'm not sure what to put there.
# I'm guessing this may not be the right function to use
reproject(img, destination, src_transform=None, gcps=points, src_crs=from_epsg(2193),
src_nodata=None, dst_transform=None, dst_crs=from_epsg(2193), dst_nodata=None,
src_alpha=0, dst_alpha=0, init_dest_nodata=True, warp_mem_limit=0)
```
GDAL attempt:
```
from osgeo import gdal
import osr
inputImage = "Example_image.jpg"
outputImage = "image_gdal.jpg"
dataset = gdal.Open(inputImage)
I = dataset.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)
outdataset = gdal.GetDriverByName('GTiff')
output_SRS = osr.SpatialReference()
output_SRS.ImportFromEPSG(2193)
outdataset = outdataset.Create(outputImage,dataset.RasterXSize,dataset.RasterYSize,I.shape[0])
for nb_band in range(I.shape[0]):
outdataset.GetRasterBand(nb_band+1).WriteArray(I[nb_band,:,:])
# Creating ground control points (not sure if I got the order of variables right):
gcp_list = []
gcp_list.append(gdal.GCP(176.412984, -310.977264, 1681255.524654, 6120217.357425))
gcp_list.append(gdal.GCP(160.386905, -141.487145, 1681158.424227, 6120406.821253))
gcp_list.append(gdal.GCP(433.204947, -310.547238, 1681556.948690, 6120335.658359))
outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)
outdataset = None
```
I don't quite know how to make the above code work, and I would really appreciate any help with this. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55681995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8836524/"
] | I ended up reading a book "Geoprocessing with Python" and finally found a solution that worked for me. Here is the code I adapted to my problem:
```
import shutil
from osgeo import gdal, osr
orig_fn = 'image.tif'
output_fn = 'output.tif'
# Create a copy of the original file and save it as the output filename:
shutil.copy(orig_fn, output_fn)
# Open the output file for writing for writing:
ds = gdal.Open(output_fn, gdal.GA_Update)
# Set spatial reference:
sr = osr.SpatialReference()
sr.ImportFromEPSG(2193) #2193 refers to the NZTM2000, but can use any desired projection
# Enter the GCPs
# Format: [map x-coordinate(longitude)], [map y-coordinate (latitude)], [elevation],
# [image column index(x)], [image row index (y)]
gcps = [gdal.GCP(1681255.524654, 6120217.357425, 0, 176.412984, 310.977264),
gdal.GCP(1681158.424227, 6120406.821253, 0, 160.386905, 141.487145),
gdal.GCP(1681556.948690, 6120335.658359, 0, 433.204947, 310.547238)]
# Apply the GCPs to the open output file:
ds.SetGCPs(gcps, sr.ExportToWkt())
# Close the output file in order to be able to work with it in other programs:
ds = None
``` | As an addition to @Kat's answer, to avoid quality loss of the original image file and set the nodata-value to 0, the following can be used.
```
#Load the original file
src_ds = gdal.Open(orig_fn)
#Create tmp dataset saved in memory
driver = gdal.GetDriverByName('MEM')
tmp_ds = driver.CreateCopy('', src_ds, strict=0)
#
# ... setting GCP....
#
# Setting no data for all bands
for i in range(1, tmp_ds.RasterCount + 1):
f = tmp_ds.GetRasterBand(i).SetNoDataValue(0)
# Saving as file
driver = gdal.GetDriverByName('GTiff')
ds = driver.CreateCopy(output_fn, tmp_ds, strict=0)
``` |
42,804,448 | I am new in Angular JS. And I am creating a custom service in it.
```js
var myApp = angular
.module("myModule", [])
.controller("myController", function ($scope, stringService) {
$scope.callMe = function (input) {
$scope.wish= stringService.processFunction(input);
};
});
myApp.factory('stringService', function () {
return {
processFunction: function(input){
//Manipulate you data here.
return "Hello " + input;
}
};
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">
<head>
<script src="Scripts/angular.js"></script>
<script src="JavaScriptCusomServiceMain.js"></script>
<script src="JavaScriptCustomService.js"></script>
<title></title>
</head>
<body ng-controller="myController">
<input type="text" placeholder="Your Name" ng-model="name" />
<input type="text" placeholder="Your Name" ng-model="wish" />
<input type="button" value="Click Here" ng-click="callMe(name)" />
<br />
</body>
</html>
```
Why do we have to give same name "myApp" in both the javascript code? | 2017/03/15 | [
"https://Stackoverflow.com/questions/42804448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7646829/"
] | `myApp` holds the reference to the module you defined using `angular.module('modulename', []);`
if you want to get the same module reference again without existing variable you can do so by using `.module` method without second argument, when second argument `dependency` is present it defines module and if second argument is not given it returns the module which is already defined so doing like below is also valid
```
angular
.module("myModule").service('stringService', function{/** return object of factory **/});
```
and above can go in seperate file as well, but make sure the file which defines module should be included first otherwise angular will give error about module is not defined | Adding to Sam answer, note the difference between:
```
angular.module("myModule", [])
```
and:
```
angular.module("myModule")
```
With a second argument (an array of dependencies), you *declare* a module. Without the dependencies argument, you get *a reference to an already-defined module*. Mixing the two forms might yield cryptic errors. |
26,560,838 | I'm following a video tutorial about underscoreJS and everything was going fine until I reached the point where you put logic inside templates
SampleData.js contains students array:
```
var students = [
{
"firstname": "Woody",
"lastname" : "Johnson",
"school" : "Thoreau",
"grade" : 12,
"midterm_score": 75,
"final_score": 85
},
{
"firstname" : "Jerry",
"lastname" : "Jones",
"school" : "Thoreau",
"grade" : 10,
"midterm_score": 50,
"final_score": 65
},
{
"firstname" : "Bill",
"lastname" : "Parcells",
"school" : "Franklin",
"grade" : 12,
"midterm_score": 82,
"final_score": 91
},
{
"firstname" : "Rex",
"lastname" : "Ryan",
"school" : "Franklin",
"grade" : 11,
"midterm_score": 60,
"final_score": 67
}];
```
HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>Using Underscore Templates</title>
<style type="text/css">
.studentRec {
border: 1px solid #777;
margin: 4pt;
padding: 4pt;
font-size: 14pt;
background-color: #ccc;
}
.passingStudent {
background-color: lightGreen;
}
.failingStudent {
background-color: pink;
}
</style>
<script type="text/javascript" src="../underscore.js"></script>
<script type="text/javascript" src="../SampleData.js"></script>
<script type="text/javascript">
function appendTemplateData(dataString) {
var container = document.getElementById("container");
container.innerHTML = container.innerHTML + dataString;
}
var studentInfo1 = "<% _.each(students, function(item) { %>" +
"<div class='studentRec " +
"<% (item.midterm_score + item.final_score) / 2 > 65 ? print('passingStudent') : print('failingStudent') %>'>" +
"<span style='font-weight:bold'>Name:</span> <span><%= item.lastname %>, <%= item.firstname %> </span>" +
"<span style='font-weight:bold'>School:</span> <span><%= item.school %></span></div>" +
"<% }); %>";
window.addEventListener("load", function(e) {
var result = _.template(studentInfo1, students);
appendTemplateData(result);
});
</script>
</head>
<body>
<h1>Using Underscore Templates</h1>
<h2>Student Information:</h2>
<div id="container">
</div>
</body>
</html>
```
Result:
function (n){return a.call(this,n,h)}
Any idea why I'm getting this error? I tried extracting the template to the `<body> like <script type="text/template" id="temp"> ....` and I got:
Uncaught TypeError: undefined is not a function underscore.js:1304
h.template underscore.js:1304
(anonymous function)
Hope you can help me out
**Solution**
```
var studentInfo1 = _.template("<% _.each(students, function(item) { %>" +
"<div class='studentRec " +
"<% (item.midterm_score + item.final_score) / 2 > 65 ? print('passingStudent') : print('failingStudent') %>'>" +
"<span style='font-weight:bold'>Name:</span> <span><%= item.lastname %>, <%= item.firstname %> </span>" +
"<span style='font-weight:bold'>School:</span> <span><%= item.school %></span></div>" +
"<% }); %>");
var result = studentInfo1(students);
appendTemplateData(result);
``` | 2014/10/25 | [
"https://Stackoverflow.com/questions/26560838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535267/"
] | Please look at the documentation for the `_.template()` function carefully. <http://underscorejs.org/#template>
The `template` utility function takes a template string as the first argument and returns a **function** that you can use to pass in your template data:
```
// `myTemplate` here is a function!
var myTemplate = _.template("<p><%= name %></p>");
// Now let's pass in the data for the template.
myTemplate({name: 'Joe Doe'}); // it returns: "<p>Joe Doe</p>"
``` | I've tried your code, it runs good
And my recommend is replacing your underscore.js with this underscore library
<https://github.com/thomasdavis/backbonetutorials/blob/gh-pages/examples/modular-backbone/js/libs/underscore/underscore-min.js>
I've gotten a problem like yours, library on underscorejs.org can't work
I hope that library can help you to solve your problem |
252,296 | I have the following problem:
A truck transports oranges. Each orange has a mean weight of 85g and a sd of 9 g.
If the truck transports 2000 oranges what is the probability that the total weight is greater than 175kg?
Now suppose that there are 3400 oranges and the total weight is 255kg. What is the probability that the mean weight of each orange is greater than 76g?
My attempt to the solution for the first question is obvious:
$\sigma\_{\bar{X}}=9/\sqrt{2000}$ and $\bar{X}=175000/2000=87.5g$. So I have to find
\begin{equation}
P\left(\frac{87.5-85}{\sigma\_{\bar{X}}}<Z\right)=P(12.5<Z)
\end{equation}
Which is essentially zero. This defies my intuition somehow... Am I doing something wrong?
For the second question I am a bit stuck. In this case $\bar{X}=255000/3400=75g$ and $\sigma\_{\bar{X}} = 9/\sqrt{3400}$. I think that the probability that the mean is greater than 76g is the same as saying what is the probability $P(Z<-6.47)$ but again this is counterintuitive... What am I doing wrong? | 2016/12/19 | [
"https://stats.stackexchange.com/questions/252296",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/133996/"
] | I don't see why you need any statistical calculations for the second problem.
There are 3400 oranges with a total weight is 255,000 g. So the average weight of an orange is 255000/3400= 75 grams. That is exact. There is zero (0.000000000000....) chance that the average weight is greater than 76 grams. The average weight of oranges in that truck is 75 grams exactly. | If we assume that the weight of an orange is normally distributed and that the weights of oranges are independent. Let $X$ be the weight of each orange. So:
$$X\sim N(\mu,\sigma^{2})$$
Define $Y$ as weight of oranges in the truck:
$$Y=\sum\_{i=1}^{2000}X\sim N(2000\mu,2000\sigma^{2})$$
Therefore you want:
$$\begin{align}
P\big(Y>175\big)&=P\Bigg(Z>\frac{175-2000(0.085)}{\sqrt{2000(0.000081)}}\Bigg)\\
&=P(Z>12.4226)\\
&=1-P(Z<12.4226)\\
&\approx 0
\end{align}$$
For the second question, we define:
$$\begin{align}
\bar{X}&=\dfrac{1}{3400}\sum\_{i=1}^{3400}X\_{i}=\dfrac{255000}{3400}=75
\end{align}$$
where $X\_{i}$ is the weight of the $i$th orange.
We know the standard deviation of $\bar{X}$ is:
$$\text{SD}\_{\bar{X}}=\frac{\sigma}{\sqrt{n}}=\frac{9}{\sqrt{3400}}$$
Finally, we want to know:
$$\begin{align}
P\big(\mu>76\big)&=P\Bigg(Z>\frac{76-75}{9/\sqrt{3400}}\Bigg)\\
&=1-P\Bigg(Z<\frac{76-75}{9/\sqrt{3400}}\Bigg)\\
&\approx 0
\end{align}$$ |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | ASP.Net Webforms is a completely different abstraction over the base framework than ASP.NET MVC. With MVC you've got more control over what happens under the covers than with ASP.NET Webforms.
In my opinion learning different ways to do things will usually make you a better programmer but in this case there might be better things to learn. | IMO, there are more pitfalls in normal web forms scenarios than with just MVC. Viewstate and databinding can be tricky at times.
But for MVC, it's just plain simple form post/render things old-school way. Not that it is bad, it is just different, and cleaner too. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | I agree with Nick: MVC is much closer to the *real* web paradigm and by using it you'll be confronted with how your website really works. WebForms astracts most of these things away from you and, coming from a PHP background, I found it really anti-intuitive.
I suggest you directly jump to MVC and skip WebForms. As said, you'll be able to get back to it if needed. | If you don't know how or haven't has experience with raw level web request / response and raw html/css rendering then MVC will would be good place to start.
You will then better understand the pros and cons of both webforms and mvc. They will both be around in the future as the both address different needs.
Though I will say webforms is a highly misused and abused platform.
So much of the "look no code" rubbish gives all who use it a bad name.
Put in the time to understand it and use it properly you'll find its a very extensible and robust platform. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed. | If you don't know how or haven't has experience with raw level web request / response and raw html/css rendering then MVC will would be good place to start.
You will then better understand the pros and cons of both webforms and mvc. They will both be around in the future as the both address different needs.
Though I will say webforms is a highly misused and abused platform.
So much of the "look no code" rubbish gives all who use it a bad name.
Put in the time to understand it and use it properly you'll find its a very extensible and robust platform. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | I agree with Nick: MVC is much closer to the *real* web paradigm and by using it you'll be confronted with how your website really works. WebForms astracts most of these things away from you and, coming from a PHP background, I found it really anti-intuitive.
I suggest you directly jump to MVC and skip WebForms. As said, you'll be able to get back to it if needed. | It depends on your motivations. If you're going to sell yourself as an ASP.NET developer, you will need both.
If this is just for your own pleasure, then go to MVC.
My personal feeling is that webforms will be around for quite a few years more. So many people have time and energy invested in them. However, I think people will slowly (or maybe not so slowly!) migrate. Webforms was always just a way to get drag-and-drop VB4 morts to think about web development. It kindof worked but it does take away alot of control. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | I agree with Nick: MVC is much closer to the *real* web paradigm and by using it you'll be confronted with how your website really works. WebForms astracts most of these things away from you and, coming from a PHP background, I found it really anti-intuitive.
I suggest you directly jump to MVC and skip WebForms. As said, you'll be able to get back to it if needed. | ASP.NET MVC is for developers who desire to decouple the client code from the server code. I have wanted to write JavaScript, XHTML, CSS clients that can move from server to server (without regard to server technology). Clients are time-consuming to fit and finish so you would want to use them (and sub-components) for as many servers as possible. Also this decoupling allows your server to support any client technology that supports HTTP and angle-brackets (and/or JSON) like WPF/Silverlight. Without ASP.NET MVC you were forced into a hostile relationship with the entire ASP.NET team---but Scott Guthrie is a cool dude and brings MVC to the table after years of his predecessors (and perhaps Scott himself) almost totally focused on getting Windows Forms programmers to write web applications.
Before ASP.NET MVC, I built ASP.NET applications largely based on ASHX files---HTTP handlers. I can assure you that no "real" Microsoft shop would encourage this behavior. It is easier from a (wise) management perspective to dictate that all your developers use the vendor-recommended way of using the vendor's tools. So IT shops that are one or two years behind will require you to know the pre-MVC way of doing things. This also comes in handy when you have a "legacy" system to maintain.
But, for the green field, it's MVC all the way! |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | ASP.NET MVC is for developers who desire to decouple the client code from the server code. I have wanted to write JavaScript, XHTML, CSS clients that can move from server to server (without regard to server technology). Clients are time-consuming to fit and finish so you would want to use them (and sub-components) for as many servers as possible. Also this decoupling allows your server to support any client technology that supports HTTP and angle-brackets (and/or JSON) like WPF/Silverlight. Without ASP.NET MVC you were forced into a hostile relationship with the entire ASP.NET team---but Scott Guthrie is a cool dude and brings MVC to the table after years of his predecessors (and perhaps Scott himself) almost totally focused on getting Windows Forms programmers to write web applications.
Before ASP.NET MVC, I built ASP.NET applications largely based on ASHX files---HTTP handlers. I can assure you that no "real" Microsoft shop would encourage this behavior. It is easier from a (wise) management perspective to dictate that all your developers use the vendor-recommended way of using the vendor's tools. So IT shops that are one or two years behind will require you to know the pre-MVC way of doing things. This also comes in handy when you have a "legacy" system to maintain.
But, for the green field, it's MVC all the way! | IMO, there are more pitfalls in normal web forms scenarios than with just MVC. Viewstate and databinding can be tricky at times.
But for MVC, it's just plain simple form post/render things old-school way. Not that it is bad, it is just different, and cleaner too. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | It depends on your motivations. If you're going to sell yourself as an ASP.NET developer, you will need both.
If this is just for your own pleasure, then go to MVC.
My personal feeling is that webforms will be around for quite a few years more. So many people have time and energy invested in them. However, I think people will slowly (or maybe not so slowly!) migrate. Webforms was always just a way to get drag-and-drop VB4 morts to think about web development. It kindof worked but it does take away alot of control. | I can't really speak technically about MVC vs "traditional" as I have only used the traditional model so far. From what I have read though, I don't think one is vastly superior to the other. I think once you "get it", you can be very productive in both.
Practically though, I would take into consideration that most books, code samples and existing applications out there are written for the "traditional" way. You have more help available and your skills will be more useful for employers with existing applications written in the "traditional" way. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed. | ASP.Net Webforms is a completely different abstraction over the base framework than ASP.NET MVC. With MVC you've got more control over what happens under the covers than with ASP.NET Webforms.
In my opinion learning different ways to do things will usually make you a better programmer but in this case there might be better things to learn. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed. | IMO, there are more pitfalls in normal web forms scenarios than with just MVC. Viewstate and databinding can be tricky at times.
But for MVC, it's just plain simple form post/render things old-school way. Not that it is bad, it is just different, and cleaner too. |
41,712 | As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site. | 2008/09/03 | [
"https://Stackoverflow.com/questions/41712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed. | I agree with Nick: MVC is much closer to the *real* web paradigm and by using it you'll be confronted with how your website really works. WebForms astracts most of these things away from you and, coming from a PHP background, I found it really anti-intuitive.
I suggest you directly jump to MVC and skip WebForms. As said, you'll be able to get back to it if needed. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be placed in `AssemblyInfo.cs`
```
[assembly: InternalsVisibleTo("OtherAssembly")]
``` | There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
```
public class Class1
{
private int CallMe()
{
return 1;
}
}
```
You can invoke it using this code:
```
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
```
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..." |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be placed in `AssemblyInfo.cs`
```
[assembly: InternalsVisibleTo("OtherAssembly")]
``` | Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be placed in `AssemblyInfo.cs`
```
[assembly: InternalsVisibleTo("OtherAssembly")]
``` | The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
``` |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be placed in `AssemblyInfo.cs`
```
[assembly: InternalsVisibleTo("OtherAssembly")]
``` | You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
```
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
```
The public key is optional, depending on your needs. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface. | There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
```
public class Class1
{
private int CallMe()
{
return 1;
}
}
```
You can invoke it using this code:
```
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
```
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..." |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
``` | There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
```
public class Class1
{
private int CallMe()
{
return 1;
}
}
```
You can invoke it using this code:
```
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
```
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..." |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
```
public class Class1
{
private int CallMe()
{
return 1;
}
}
```
You can invoke it using this code:
```
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
```
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..." | You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
```
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
```
The public key is optional, depending on your needs. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
``` | Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface. | You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
```
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
```
The public key is optional, depending on your needs. |
204,739 | >
> **Possible Duplicate:**
>
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
>
>
>
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example? | 2008/10/15 | [
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
``` | You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
```
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
```
The public key is optional, depending on your needs. |
49,811,904 | I have a question related to Monte Carlo simulation based on the probability of rolling 2 dices. How can you present when coding in python the fact that the sum is larger than n and smaller than m? As an example I made this in mathlab:
```
NT = 10^5; %number of throws
log = zeros(1,12);
for throw = 1:NT
dices = ceil(6*rand(1,2));
s = sum(dices);
log(s) = log(s)+1;
end
p = 36*log(6:9)/NT;
s1 = sum(round(p))
```
In the above example I presumed that n is 5 and m is 10.
Thank you | 2018/04/13 | [
"https://Stackoverflow.com/questions/49811904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9634762/"
] | The first red flag is that you use the database only to *hold data*. That beast can search way faster than you can, if you *let it*.
For each line in your excel, build a corresponding search statement for your database and fire it. Let your database worry about the best way to search through 10K records.
The second red flag is that your normalization is not done on your existing data. You want to compare two streets, but you have to normalize them *over and over*. Why is there no database field called "NormalizedStreet" that already *has* those methods applied *once on insertion* and where you can just fire an "equals" comparison against normalizing your input data?
So to summarize: scrap your loop-in-a-loop. You just reinvented the database. For each row of your excel, build a statement (or two) to find out if it exists in your database. If you want to be crafty, run them in parallel, but I doubt that you need that for a measly 700 input records. | If this is sql server then you should be using ssis.
It has fuzzy matching which is pretty much a must for matching records on addresses from two different sources.
I would import the data to a table using ssis as well and do any pre processing of data in the pipeline.
The whole thing could be run using a job then. |
49,811,904 | I have a question related to Monte Carlo simulation based on the probability of rolling 2 dices. How can you present when coding in python the fact that the sum is larger than n and smaller than m? As an example I made this in mathlab:
```
NT = 10^5; %number of throws
log = zeros(1,12);
for throw = 1:NT
dices = ceil(6*rand(1,2));
s = sum(dices);
log(s) = log(s)+1;
end
p = 36*log(6:9)/NT;
s1 = sum(round(p))
```
In the above example I presumed that n is 5 and m is 10.
Thank you | 2018/04/13 | [
"https://Stackoverflow.com/questions/49811904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9634762/"
] | The first red flag is that you use the database only to *hold data*. That beast can search way faster than you can, if you *let it*.
For each line in your excel, build a corresponding search statement for your database and fire it. Let your database worry about the best way to search through 10K records.
The second red flag is that your normalization is not done on your existing data. You want to compare two streets, but you have to normalize them *over and over*. Why is there no database field called "NormalizedStreet" that already *has* those methods applied *once on insertion* and where you can just fire an "equals" comparison against normalizing your input data?
So to summarize: scrap your loop-in-a-loop. You just reinvented the database. For each row of your excel, build a statement (or two) to find out if it exists in your database. If you want to be crafty, run them in parallel, but I doubt that you need that for a measly 700 input records. | First, nvoight is right: you should normalize data in database and use its power to do searches. However, if you can't change the database, then you can do improvements in your code.
1) Most important is to move out of loops things that can be done once. This is data normalization (replacements, tolower etc). Iterate through all your Excel data and database data once to build data that can be compared directly and then your your two inner loops for actual comparison. Also your configuration won't be changed while you are in loop, so that can be also moved away. Avoid extra string allocations. You can use StringBuilder to build strings instead of using +=
Something like that for Excel (and then similar loop for Db)
```
string[] criteriaFields = ConfigurationManager.AppSettings["strFilter"].Split(',').Select(x => x.Trim()).ToArray();
List<string> excelAddresses = new List<string>();
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
StringBuilder compareAdressExcel = new StringBuilder();
foreach (String cFieldTrimmed in criteriaFields)
{
if (cFieldTrimmed == "Strasse")
{
var normalizedValue = dtExcel.Rows[i][cFieldTrimmed].ToString()
.ToLower()
.Replace(" ", "")
.Replace("str", "strasse")
.Replace("straße", "strasse")
.Replace("str.", "strasse");
compareAdressExcel.Append(normalizedValue);
}
else
{
compareAdressExcel.Append(dtExcel.Rows[i][cFieldTrimmed].ToString().Replace(" ", "").ToLower());
}
}
excelAddresses.Add(compareAdressExcel.ToString());
}
```
Then you can use normalized values in your main loops
```
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
CurrentProgress++;
for (int y = 0; y < _dt.Rows.Count; y++)
{
// Criteria to check duplicates
string compareAdressExcel = excelAddresses[i];
string compareAdressDB = dbAddresses[y];
```
2) You can use Dictionaries or HashSets to speedup string searches and comparisons instead of loops.
3) How fast is that call to "\_crm"? Maybe that external call takes a while and that is reason of your slowness too.
```
_crm.CheckContactExists(...)
``` |
49,811,904 | I have a question related to Monte Carlo simulation based on the probability of rolling 2 dices. How can you present when coding in python the fact that the sum is larger than n and smaller than m? As an example I made this in mathlab:
```
NT = 10^5; %number of throws
log = zeros(1,12);
for throw = 1:NT
dices = ceil(6*rand(1,2));
s = sum(dices);
log(s) = log(s)+1;
end
p = 36*log(6:9)/NT;
s1 = sum(round(p))
```
In the above example I presumed that n is 5 and m is 10.
Thank you | 2018/04/13 | [
"https://Stackoverflow.com/questions/49811904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9634762/"
] | First, nvoight is right: you should normalize data in database and use its power to do searches. However, if you can't change the database, then you can do improvements in your code.
1) Most important is to move out of loops things that can be done once. This is data normalization (replacements, tolower etc). Iterate through all your Excel data and database data once to build data that can be compared directly and then your your two inner loops for actual comparison. Also your configuration won't be changed while you are in loop, so that can be also moved away. Avoid extra string allocations. You can use StringBuilder to build strings instead of using +=
Something like that for Excel (and then similar loop for Db)
```
string[] criteriaFields = ConfigurationManager.AppSettings["strFilter"].Split(',').Select(x => x.Trim()).ToArray();
List<string> excelAddresses = new List<string>();
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
StringBuilder compareAdressExcel = new StringBuilder();
foreach (String cFieldTrimmed in criteriaFields)
{
if (cFieldTrimmed == "Strasse")
{
var normalizedValue = dtExcel.Rows[i][cFieldTrimmed].ToString()
.ToLower()
.Replace(" ", "")
.Replace("str", "strasse")
.Replace("straße", "strasse")
.Replace("str.", "strasse");
compareAdressExcel.Append(normalizedValue);
}
else
{
compareAdressExcel.Append(dtExcel.Rows[i][cFieldTrimmed].ToString().Replace(" ", "").ToLower());
}
}
excelAddresses.Add(compareAdressExcel.ToString());
}
```
Then you can use normalized values in your main loops
```
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
CurrentProgress++;
for (int y = 0; y < _dt.Rows.Count; y++)
{
// Criteria to check duplicates
string compareAdressExcel = excelAddresses[i];
string compareAdressDB = dbAddresses[y];
```
2) You can use Dictionaries or HashSets to speedup string searches and comparisons instead of loops.
3) How fast is that call to "\_crm"? Maybe that external call takes a while and that is reason of your slowness too.
```
_crm.CheckContactExists(...)
``` | If this is sql server then you should be using ssis.
It has fuzzy matching which is pretty much a must for matching records on addresses from two different sources.
I would import the data to a table using ssis as well and do any pre processing of data in the pipeline.
The whole thing could be run using a job then. |
653,102 | I have a Compaq pc with Windows 7 64 bit. I am getting no audio from speakers. I do hear a clicking noise when I plug in or touch the audio cable/jack coming thru the speakers. I have upgraded drivers and checked the bios. Any suggestion? | 2013/10/02 | [
"https://superuser.com/questions/653102",
"https://superuser.com",
"https://superuser.com/users/258746/"
] | right click the sound icon in your Task Tray (next to the clock). Select Playback devices. Make sure your speakers are selected as the default sound device (should have a green check). If not, right click the speakers and select default sound device. | Noise in the way you describe it suggests a bad physical connection, most likely a problem with the receptacle in the computer rather than the cable.
You could try another cable first, but .... |
653,102 | I have a Compaq pc with Windows 7 64 bit. I am getting no audio from speakers. I do hear a clicking noise when I plug in or touch the audio cable/jack coming thru the speakers. I have upgraded drivers and checked the bios. Any suggestion? | 2013/10/02 | [
"https://superuser.com/questions/653102",
"https://superuser.com",
"https://superuser.com/users/258746/"
] | right click the sound icon in your Task Tray (next to the clock). Select Playback devices. Make sure your speakers are selected as the default sound device (should have a green check). If not, right click the speakers and select default sound device. | This seems like a duplicate question to me, but could be coincidence. In any case: go into Control Panel > Sound. Click the Communications tab & change from "reduce the volume of other sounds" to "Do nothing". And if this resolves your problem (since you say the sound is OK on VOIP calls) then I'll have to find out where that other question was, and upvote the person who wrote this answer originally! |
14,841,235 | I got a table that i'm quering to get the `DeliveryDate` but some of the records don't have `DeliveryDate` so VB considers that as 00:00:00.
How do I make an `IF` condition to check a date and see if it's 00:00:00?
Because I want to set a variable to **TRUE** when the date is nothing(00:00:00). | 2013/02/12 | [
"https://Stackoverflow.com/questions/14841235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1972768/"
] | You can check if your Date equals the date part:
`If DeliveryDate.Date = DeliveryDate Then ...` | I personally use `New Date` but it is a style choice - you can also use Nothing.
```
If DeliveryDate = New Date Then
```
or
```
If DeliveryDate = Nothing Then
``` |
14,841,235 | I got a table that i'm quering to get the `DeliveryDate` but some of the records don't have `DeliveryDate` so VB considers that as 00:00:00.
How do I make an `IF` condition to check a date and see if it's 00:00:00?
Because I want to set a variable to **TRUE** when the date is nothing(00:00:00). | 2013/02/12 | [
"https://Stackoverflow.com/questions/14841235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1972768/"
] | Looks like you want to check if date was assigned to `Nothing`, in which case it would default to [Date.MinValue](http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx). The quick and dirty approach would be to check:
```
If DeliveryDate = Date.MinValue Then
```
It will work fine for packages delivered at midnight, because you are unlikely to have any packages scheduled for delivery in year 1 BC.
The proper approach would be to have `DeliveryDate` of type `Nullable(Of Date)`, so you can actually store `Convert.DBNull` (=`Nothing`) in there. In this case, the code becomes easier to read:
```
If DeliveryDate Is Nothing Then
```
Note that you *could* have used a similar line at the start (with `DeliveryDate` being of type `Date`):
```
If DeliveryDate = Nothing Then
```
However, you would rather avoid implicit conversion of `Nothing` to `Date.MinValue`, which would happen behind the scenes in this case, even though it appears to be just as readable, as with `Is Nothing`. | I personally use `New Date` but it is a style choice - you can also use Nothing.
```
If DeliveryDate = New Date Then
```
or
```
If DeliveryDate = Nothing Then
``` |
26,991,680 | I have a Laravel Model:
```
class Order extends Eloquent{
protected $table = 'orders';
public function orderItems(){
return $this->hasMany('OrderItem');
}
public static function findByUserMonthYear($user_id, $month, $year){
return Order::where('user_id', '=', $user_id)
->where('month', '=', $month)
->get();
// ->where('year', '=', $year);
}
}
```
And of course I have an `OrderItem` class
```
class OrderItem extends Eloquent{ ...
```
But if I do:
```
$order = Order::findByUserMonthYear(Auth::user()->id, Date::getDate(), 2014);
$order->orderItems();
```
I get the following:
```
Call to undefined method Illuminate\Database\Eloquent\Collection::orderItems()
```
What am I doing wrong? If I were to change the statement to `Order::with('orderItems')` the relationship seems to work fine, but I'd like to delete all the `orderItems` associated to the current `Order`. | 2014/11/18 | [
"https://Stackoverflow.com/questions/26991680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/630203/"
] | Your `->get()` within you findByUserMonth is returning a Collection. If this query returns only one collection then use the `->first()` instead, but if your query returns multiple results then eager load the results of orderItems like so;
```
public static function findByUserMonthYear($user_id, $month, $year){
return self::with('orderItems')->where('user_id', '=', $user_id)
->where('month', '=', $month)
->get();
// ->where('user_id', '=', $year);
}
```
Then you can access the results like so;
```
@foreach($orders as $order)
{{$order->orderItem}}
@endforeach
```
This is because the return being a collection, so you have to loop through them. The use `{{$order->orderItem}}` to access the results
Im not too sure on this but i think you can delete all the models within a hasMany like so; `$order->orderItem()->delete();` as the return of `orderItem()` is a Query\Builder instance. | your second class must be extends Order class
use this line for OrderItem class :
```
class OrderItem extends Order {
``` |
1,553,594 | I have an experience about the compiler phrases and I interested in Programming Languages & Compilers field and I hope somebody gives me some explanation about what is the good approach to write a new compiler from scratch for a new programming language ? (**I mean STEPS**). | 2009/10/12 | [
"https://Stackoverflow.com/questions/1553594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The first step is to read the [Dragon Book](http://en.wikipedia.org/wiki/Principles_of_Compiler_Design).
It offers a good introduction to the whole field of compiler building, but also goes into enough detail to actually build your own.
As for the following steps I suggest following the chapters of the book. It's not written as a tutorial, but nevertheless offers much practical advice, which makes it an ideal hub for your own ideas and research. | I would look at integrating your langauge/front end with the GNU compiler framework.
That way you only (ONLY!) need to write the parser and translator to gcc's portable object format. You get the optimiser, object code generation for the chip of choice, linker etc for free.
Another alternative would be to target a Java JVM, the virtual machine is well documented and the JVM instruction set is much more staighforward than x86 machine code. |
1,553,594 | I have an experience about the compiler phrases and I interested in Programming Languages & Compilers field and I hope somebody gives me some explanation about what is the good approach to write a new compiler from scratch for a new programming language ? (**I mean STEPS**). | 2009/10/12 | [
"https://Stackoverflow.com/questions/1553594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The first step is to read the [Dragon Book](http://en.wikipedia.org/wiki/Principles_of_Compiler_Design).
It offers a good introduction to the whole field of compiler building, but also goes into enough detail to actually build your own.
As for the following steps I suggest following the chapters of the book. It's not written as a tutorial, but nevertheless offers much practical advice, which makes it an ideal hub for your own ideas and research. | I managed to write a compiler without any particular book (though I had read some compiler books in the past, just not in any real detail).
The first thing you should do is play with any of the "Compiler compiler" type tools (flex, bison, antlr, javacc) and get your grammar working. Grammars are mostly straightforward, but there's always nitty bits that get in the way and make a ruin of everything. Especially things like expressions, precedence, etc.
Some of the older simpler language are simpler for a reason. It makes the parsers "Just Work". Consider a Pascal variant that can be processed solely through recursive decent.
I mention this because without your grammar, you have no language. If you can't parse and lex it properly, you get nowhere very fast. And watching a dozen lines of sample code in your new language get turned in to a slew of tokens and syntax nodes is actually really amazing. In a "wow, it really works" kind of way. It's literally almost an "it all works" or "none of it works" kind of thing, especially at the beginning. Once it actually works, you feel like you might be able to really pull it off.
And to some extent that's true, because once you get that part done, you have to get your fundamental runtime going. Once you get "a = 1 + 1" compiled, the bulk of the new work is behind your and now you just need to implement the rest of the operators. It basically becomes an exercise of managing lookup tables and references, and having some idea where you are at any one time in the process.
You can run out on your own with a brand new syntax, innovative runtime, etc. But if you have the time, it's probably best to do a language that's already been done, just to understand and implement all of the steps, and think about if you were writing the language you really want, how you would do what you're doing with this existing one differently.
There are a lot of mechanics to compiler writing and just doing the process successfully once will give you a lot more confidence when you want to come back and do it again with your own, new language. |
1,553,594 | I have an experience about the compiler phrases and I interested in Programming Languages & Compilers field and I hope somebody gives me some explanation about what is the good approach to write a new compiler from scratch for a new programming language ? (**I mean STEPS**). | 2009/10/12 | [
"https://Stackoverflow.com/questions/1553594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Please don't use the Dragon Book, it's old and mostly outdated (and uses weird names for most of the stuff).
For books, I'd recommand Apple's Tiger Book, or Cooper's Engineering a compiler. I'd strongly suggest you to use a framework like [llvm](http://llvm.org) so you don't have to re-implement a bunch of stuff for code generation etc.
Here is the tutorial for building your language with llvm: <http://llvm.org/docs/tutorial/> | I would look at integrating your langauge/front end with the GNU compiler framework.
That way you only (ONLY!) need to write the parser and translator to gcc's portable object format. You get the optimiser, object code generation for the chip of choice, linker etc for free.
Another alternative would be to target a Java JVM, the virtual machine is well documented and the JVM instruction set is much more staighforward than x86 machine code. |
1,553,594 | I have an experience about the compiler phrases and I interested in Programming Languages & Compilers field and I hope somebody gives me some explanation about what is the good approach to write a new compiler from scratch for a new programming language ? (**I mean STEPS**). | 2009/10/12 | [
"https://Stackoverflow.com/questions/1553594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Please don't use the Dragon Book, it's old and mostly outdated (and uses weird names for most of the stuff).
For books, I'd recommand Apple's Tiger Book, or Cooper's Engineering a compiler. I'd strongly suggest you to use a framework like [llvm](http://llvm.org) so you don't have to re-implement a bunch of stuff for code generation etc.
Here is the tutorial for building your language with llvm: <http://llvm.org/docs/tutorial/> | I managed to write a compiler without any particular book (though I had read some compiler books in the past, just not in any real detail).
The first thing you should do is play with any of the "Compiler compiler" type tools (flex, bison, antlr, javacc) and get your grammar working. Grammars are mostly straightforward, but there's always nitty bits that get in the way and make a ruin of everything. Especially things like expressions, precedence, etc.
Some of the older simpler language are simpler for a reason. It makes the parsers "Just Work". Consider a Pascal variant that can be processed solely through recursive decent.
I mention this because without your grammar, you have no language. If you can't parse and lex it properly, you get nowhere very fast. And watching a dozen lines of sample code in your new language get turned in to a slew of tokens and syntax nodes is actually really amazing. In a "wow, it really works" kind of way. It's literally almost an "it all works" or "none of it works" kind of thing, especially at the beginning. Once it actually works, you feel like you might be able to really pull it off.
And to some extent that's true, because once you get that part done, you have to get your fundamental runtime going. Once you get "a = 1 + 1" compiled, the bulk of the new work is behind your and now you just need to implement the rest of the operators. It basically becomes an exercise of managing lookup tables and references, and having some idea where you are at any one time in the process.
You can run out on your own with a brand new syntax, innovative runtime, etc. But if you have the time, it's probably best to do a language that's already been done, just to understand and implement all of the steps, and think about if you were writing the language you really want, how you would do what you're doing with this existing one differently.
There are a lot of mechanics to compiler writing and just doing the process successfully once will give you a lot more confidence when you want to come back and do it again with your own, new language. |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | Multiple issues here, the correct syntax is
```
$url: 'siteurl.com';
#some-div{
background-image: url($url + '/images/img.jpg');
}
```
* When you assign a value to the variable, you need to use `:` and not `=`
* You should quote the image path as it's a string.
* Remove the stray `+` symbol before `$url`
You can see the above code in action at [SassMeister](https://www.sassmeister.com/) | Use this:
```
$domain: 'domain.ru';
#some-div {
background-image: url('#{$domain}/images/img.jpg');
}
``` |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | Multiple issues here, the correct syntax is
```
$url: 'siteurl.com';
#some-div{
background-image: url($url + '/images/img.jpg');
}
```
* When you assign a value to the variable, you need to use `:` and not `=`
* You should quote the image path as it's a string.
* Remove the stray `+` symbol before `$url`
You can see the above code in action at [SassMeister](https://www.sassmeister.com/) | The best to do it via interpolation `( #{} )`, where all strings become unquoted.
```
$basePath= 'example.com';
#some-div{
background-image: url('#{$basePath}/images/photo.jpg');
}
```
This is a safer way for this particular use-case as you won't want any additional quotes added to your url. |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | Multiple issues here, the correct syntax is
```
$url: 'siteurl.com';
#some-div{
background-image: url($url + '/images/img.jpg');
}
```
* When you assign a value to the variable, you need to use `:` and not `=`
* You should quote the image path as it's a string.
* Remove the stray `+` symbol before `$url`
You can see the above code in action at [SassMeister](https://www.sassmeister.com/) | A example:
```
$dot: '0.';
@for $i from 1 through 9 {
.op#{$i} {
opacity: #{$dot}#{$i};
}
}
```
By logic, the variable is declared in `$dot: '0.';` and I called her in `#{$dot}`.
This example above shows two concatenated variables in SCSS. |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | Use this:
```
$domain: 'domain.ru';
#some-div {
background-image: url('#{$domain}/images/img.jpg');
}
``` | The best to do it via interpolation `( #{} )`, where all strings become unquoted.
```
$basePath= 'example.com';
#some-div{
background-image: url('#{$basePath}/images/photo.jpg');
}
```
This is a safer way for this particular use-case as you won't want any additional quotes added to your url. |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | Use this:
```
$domain: 'domain.ru';
#some-div {
background-image: url('#{$domain}/images/img.jpg');
}
``` | A example:
```
$dot: '0.';
@for $i from 1 through 9 {
.op#{$i} {
opacity: #{$dot}#{$i};
}
}
```
By logic, the variable is declared in `$dot: '0.';` and I called her in `#{$dot}`.
This example above shows two concatenated variables in SCSS. |
46,293,017 | How can I concatenate a Sass variable?
This is the the code in the scss file.
```
$url = 'siteurl.com';
#some-div{
background-image: url(+ $url +/images/img.jpg);
}
```
I want the result in the CSS file to be:
```
#some-div{
background-image: url('siteurl.com/images/img.jpg');
}
```
I found this question, but it didn't worked for me:
*[Trying to concatenate Sass variable and a string](https://stackoverflow.com/questions/42364017/trying-to-concatenate-sass-variable-and-a-string)* | 2017/09/19 | [
"https://Stackoverflow.com/questions/46293017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | The best to do it via interpolation `( #{} )`, where all strings become unquoted.
```
$basePath= 'example.com';
#some-div{
background-image: url('#{$basePath}/images/photo.jpg');
}
```
This is a safer way for this particular use-case as you won't want any additional quotes added to your url. | A example:
```
$dot: '0.';
@for $i from 1 through 9 {
.op#{$i} {
opacity: #{$dot}#{$i};
}
}
```
By logic, the variable is declared in `$dot: '0.';` and I called her in `#{$dot}`.
This example above shows two concatenated variables in SCSS. |
48,061,053 | I have a below HTML structure :
```
<ol class="slds-progress__list" id="olid">
<li class="slds-progress__item"> 123 </li>
<li class="slds-progress__item"> 345 </li>
</ol>
```
I have written below Jquery to get selected li element and apply other class to it :
```
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#olid li').click(function() {
$(this).addClass("slds-is-active");
});
})
```
Problem :
The class `slds-is-active` is getting applied to the selected element but the page is getting refreshed and selection is getting disappeared.
How to avoid the page refresh here? Is there any other way to get the selected `li` element and apply a class and avoid page refresh. | 2018/01/02 | [
"https://Stackoverflow.com/questions/48061053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9163729/"
] | Using `android:tint` property you can set the color like this
```
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:tint="@android:color/white"
android:src="@android:drawable/ic_input_add"/>
```
You can change it programmatically using `ColorFilter.`
```
//get the drawable
Drawable myFabSrc = getResources().getDrawable(android.R.drawable.ic_input_add);
//copy it in a new one
Drawable willBeWhite = myFabSrc.getConstantState().newDrawable();
//set the color filter, you can use also Mode.SRC_ATOP
willBeWhite.mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
//set it to your fab button initialized before
myFabName.setImageDrawable(willBeWhite);
``` | Simply, to change color of `drawable`, locate `res/drawable` folder and open your desired `drawable` which code looks like,
```
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="26dp"
android:height="26dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FFFFFF" <!-- change color here -->
android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>
```
Here you can change color of your `drawable` by using, `android:fillColor` attribute.
**Edit --** or if you want to change color of drawable icon in `fab` xml then you can use `android:tint` in fab as,
```
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#FFFFFF" <!-- your color here -->
app:src="@drawable/ic_search" />
``` |
14,247,932 | I'm sorry to say that I cannot describe my problem more to the core or more abstractly. I feel the best way to explain my problem is by means of this quite specific example.
I want to define a function 'readCollection' which would parse a String and give me a specific collection of a specific type, based on how I call the function.
For example, I would like to use it as such:
```
ArrayList<Foo> fb = readCollection("Foo1\n Foo2\n Foo3\n");
```
or
```
LinkedList<Bar> fb = readCollection("Bar1\n Bar2\n Bar3\n");
```
Of course I have defined an interface for every class which has a 'read' method for reading one instance ("Bar..").
I am caught between a couple of problems:
-naturally the function readCollection should be a static function, but an interface cannot have static methods.
-the method readCollection should return a new object of type Foo or Bar or etc, but I 'cannot instantiate the type', which is generically defined in the class i have defined readCollection.
-supposing the method isn't defined statically, i cannot call it without making reference to a specific object of that type, which I cannot do because of the previous point.
How can I write my method without copying it for each Foo and Bar etc.?
I seem to have found a solution myself, but it is very ugly and nasty.
I now have
```
public interface Readable<T> {
public T read(String str); }
```
and
```
public class ReadCollection<T extends Readable<T>> {
public Collection<T> read(File file, Collection<T> ts, T t) {
...
ts.add(t.read(strLine));
...
return ts;
} }
```
and
```
public class Bars extends ReadCollection<Bar>{
...
public static void main(String[] args) {
new Bars().read(new File("fake/path"), new ArrayList<Bar>(), new Bar()); }
```
Here I sent along new instances of an ArrayList, to give back the result in, and for Bar, in order to refer te the method 'read'. I cannot see how I could have avoided that.
Please tell me there is a better way.
Somewhere I'd like for me to feel very dumb in hindsight. | 2013/01/09 | [
"https://Stackoverflow.com/questions/14247932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648459/"
] | Think about splitting up the parsing/construction from the object itself. In many cases, the two are very separate concerns.
You're on the right track, but I would recommend:
1. Don't have your element types inherit from the `Readable` interface
2. Rename the `Readable` interface to `Reader`
3. Implement a `Reader` for each type you would like to parse.
4. Update the signature of your `ReadCollection.read` method to take a `Reader` instead of a `T`
You'll then have:
```
public class ReadCollection<T,C extends Collection<T>> {
public C read(File file, C ts, Reader<T> reader) {
...
ts.add(reader.read(strLine));
...
return ts;
}
}
```
This gives you a good separation of concerns that should solve all the problems you listed. | APIs should be defined through interfaces.
Shared implementations should be through abstract base classes.
So how do you use an abstract base class without losing the benefits of an interface?
Easy! Simply have the abstract base class implement the interface.
Then any class that needs the shared functionality can extend the abstract base class, but you do not tie yourself in to any specific implementation, which will be handy for writing unit tests, for example. |
14,247,932 | I'm sorry to say that I cannot describe my problem more to the core or more abstractly. I feel the best way to explain my problem is by means of this quite specific example.
I want to define a function 'readCollection' which would parse a String and give me a specific collection of a specific type, based on how I call the function.
For example, I would like to use it as such:
```
ArrayList<Foo> fb = readCollection("Foo1\n Foo2\n Foo3\n");
```
or
```
LinkedList<Bar> fb = readCollection("Bar1\n Bar2\n Bar3\n");
```
Of course I have defined an interface for every class which has a 'read' method for reading one instance ("Bar..").
I am caught between a couple of problems:
-naturally the function readCollection should be a static function, but an interface cannot have static methods.
-the method readCollection should return a new object of type Foo or Bar or etc, but I 'cannot instantiate the type', which is generically defined in the class i have defined readCollection.
-supposing the method isn't defined statically, i cannot call it without making reference to a specific object of that type, which I cannot do because of the previous point.
How can I write my method without copying it for each Foo and Bar etc.?
I seem to have found a solution myself, but it is very ugly and nasty.
I now have
```
public interface Readable<T> {
public T read(String str); }
```
and
```
public class ReadCollection<T extends Readable<T>> {
public Collection<T> read(File file, Collection<T> ts, T t) {
...
ts.add(t.read(strLine));
...
return ts;
} }
```
and
```
public class Bars extends ReadCollection<Bar>{
...
public static void main(String[] args) {
new Bars().read(new File("fake/path"), new ArrayList<Bar>(), new Bar()); }
```
Here I sent along new instances of an ArrayList, to give back the result in, and for Bar, in order to refer te the method 'read'. I cannot see how I could have avoided that.
Please tell me there is a better way.
Somewhere I'd like for me to feel very dumb in hindsight. | 2013/01/09 | [
"https://Stackoverflow.com/questions/14247932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648459/"
] | Think about splitting up the parsing/construction from the object itself. In many cases, the two are very separate concerns.
You're on the right track, but I would recommend:
1. Don't have your element types inherit from the `Readable` interface
2. Rename the `Readable` interface to `Reader`
3. Implement a `Reader` for each type you would like to parse.
4. Update the signature of your `ReadCollection.read` method to take a `Reader` instead of a `T`
You'll then have:
```
public class ReadCollection<T,C extends Collection<T>> {
public C read(File file, C ts, Reader<T> reader) {
...
ts.add(reader.read(strLine));
...
return ts;
}
}
```
This gives you a good separation of concerns that should solve all the problems you listed. | I'm glad that I'm able to tell you that I have found the final and best answer myself, with the help of your comment (@stevevls) and the help of a friend.
I now have
```
public interface Reader {
public Reader read(String str); }
```
so I've removed the generic argument, shich was unneccesary
```
public class ReadCollection { // no generic class!
public static <R extends Reader, C extends Collection<R>> // generic static function!
C readColl(File file, Class<? extends C> collClass, Class<? extends R> readClass) {
C ts = collClass.newInstance()
Reader t = readClass.newInstance()
...
ts.add(readClass.cast(t.read(strLine)));
...
return ts;
} }
```
and, now I can call the function from anywhere:
```
ArrayList<Point> l = ReadCollection.readColl(new File("examples/ex1.csv"), ArrayList.class, Point.class);
```
(assuming Point implements Reader / has the read-method...)
without sending along a new instance, and moer importantly: without ever having to extend the class ReadCollection anywhere.
the problem that the read method cannot be static, cause it is defined in the interface Reader, persists. This is the reason I use readClass.newInstance() etc.
Still I think this solution is not so ugly anymore.
Do you guys agree this is a good solution? |
40,107,754 | >
> I have two kind of profiles in database.one is candidate
> prodile,another is job profile posted by recruiter.
>
>
> in both the profiles i have 3 common field say location,skill and
> experience
>
>
> i know the algorithm but i am having problem in creating training data
> set where my input feature will be location,skill and salary chosen
> from candidate profile,but i am not getting how to choose output
> (relevant job profile).
>
>
> as far as i know output can only be a single variable, then how to
> choose relevant job profile as a output in my training set
>
>
>
or should i choose some other method?another thought is clustering. | 2016/10/18 | [
"https://Stackoverflow.com/questions/40107754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411933/"
] | As I understand you want to predict job profile given candidate profile using some prediction algorithm.
Well, if you want to use regression you need to know some historical data -- which candidates were given which jobs, then you can create some model based on this historical data. If you don't have such training data you need some other algorithm. Say, you could set `location,skill and experience` as features in 3d and use clustering/nearest neighbors to find candidate profile closest to a job profile. | You could look at "recommender systems", they can be an answer to your problem.
Starting with a content based algorithm (you will have to find a way to automate the labels of the jobs, or manually do them), you can improve to an hybrid one by gathering which jobs your users were actually interested (and become an hybrid recommender) |
379,044 | Cannot access SAMBA share on Ubuntu 12.04 box from XP box.
SAMBA is up and running on the Ubuntu box. `smb.conf` has the correct windows workgroup name in it, and I can see the Ubuntu box from the XP machine.
On the Ubuntu box, I have set up a UNIX username `CCD1` with a password for the purposes of sharing. I have added a Samba username in Samba Server Configuration of `UNIX name: ccd1`, `Windows Username: Mike` (username on the XP box), and put in password (same as used for the UNIX username).
I have given access to the Samba shared folder for this username.
On the XP box I can browse the Network Neighborhood, drill down to the workgroup shares and see the Ubuntu box. I can see the shared folder on the Ubuntu box. It is also sharing printers. I can access the printers, I cannot access the shared folder.
Here is how /etc/samba/smb.conf lists the two shares:
```
[PRINT$]
comment = all printers
browseable = no
path = var/spool/samba
printable = yes
; guest ok = no
; read only = yes
create mask = 6766
[CCD_Staff_Dailies]
comment = Shared Folder
path = /media/HDD 1/CCD/CCD_Staff_Dailies
writeable = yes
; browseable = yes
valid users = sysadmin, ccd1
```
If I attempt to view the contents of the shared folder from the XP box it doesn't ask for my credentials, I just get:
>
> \Ccd-files-linux\CCD\_Staff\_Dailies is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. Access is denied."
>
>
> | 2013/11/18 | [
"https://askubuntu.com/questions/379044",
"https://askubuntu.com",
"https://askubuntu.com/users/112740/"
] | I just want to get into a public record that nowadays you need to add these configurations into the [Global] section of /etc/samba/smb.conf to make Windows XP able to connect to your Samba 4.5 server:
```
server max protocol = NT1
lanman auth = yes
ntlm auth = yes
```
Of course that compromises the security on some level I am deliberately unaware of. | For me it works:
Edit `/etc/samba/smb.cfg`.
Add the following at beginning (global):
```
server min protocol = NT1
lanman auth = yes
ntlm auth = yes
```
NT1 is a old version of security: SMBv1... necessary for Windows XP!
The other 2 lines is necessary to make logon, if not, you cannot make login. |
379,044 | Cannot access SAMBA share on Ubuntu 12.04 box from XP box.
SAMBA is up and running on the Ubuntu box. `smb.conf` has the correct windows workgroup name in it, and I can see the Ubuntu box from the XP machine.
On the Ubuntu box, I have set up a UNIX username `CCD1` with a password for the purposes of sharing. I have added a Samba username in Samba Server Configuration of `UNIX name: ccd1`, `Windows Username: Mike` (username on the XP box), and put in password (same as used for the UNIX username).
I have given access to the Samba shared folder for this username.
On the XP box I can browse the Network Neighborhood, drill down to the workgroup shares and see the Ubuntu box. I can see the shared folder on the Ubuntu box. It is also sharing printers. I can access the printers, I cannot access the shared folder.
Here is how /etc/samba/smb.conf lists the two shares:
```
[PRINT$]
comment = all printers
browseable = no
path = var/spool/samba
printable = yes
; guest ok = no
; read only = yes
create mask = 6766
[CCD_Staff_Dailies]
comment = Shared Folder
path = /media/HDD 1/CCD/CCD_Staff_Dailies
writeable = yes
; browseable = yes
valid users = sysadmin, ccd1
```
If I attempt to view the contents of the shared folder from the XP box it doesn't ask for my credentials, I just get:
>
> \Ccd-files-linux\CCD\_Staff\_Dailies is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. Access is denied."
>
>
> | 2013/11/18 | [
"https://askubuntu.com/questions/379044",
"https://askubuntu.com",
"https://askubuntu.com/users/112740/"
] | Just to update on the answer from @loop. I'd recommend using `min protocol = NT1` instead of `server max protocol = NT1` to allow other clients to use the more up-to-date and secure versions of SMB. | For me it works:
Edit `/etc/samba/smb.cfg`.
Add the following at beginning (global):
```
server min protocol = NT1
lanman auth = yes
ntlm auth = yes
```
NT1 is a old version of security: SMBv1... necessary for Windows XP!
The other 2 lines is necessary to make logon, if not, you cannot make login. |
58,097,820 | Given this json object
```
{
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
```
How do I return a new array of telephone numbers where the group equals a given value.
So, for example, I'd expect a single array of "07123456789" where the contact group = "Exec"
Also, where the Group = "Everyone" i'd expect an array of 2 items: "07123456789" and "07987654321"
I've tried:
```
var data = require('../data/data.json')
var peopleInGroup = data.contacts.filter(function (value) {
value.groups.filter(function (type) {
return type.group === recipients[i];
})
});
```
recipients is an array of groups "Everyone, "Exec", "Overseas" | 2019/09/25 | [
"https://Stackoverflow.com/questions/58097820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483212/"
] | Following this [post](https://stackoverflow.com/questions/38375646/filtering-array-of-objects-with-arrays-based-on-nested-value) i changed the second most upvoted answer code a bit to have this :
```
const getContactsByGroupName = (groupName) => {
return a.contacts
.filter((element) =>
element.groups.some((subElement) => subElement.group === groupName))
.map(element => {
return Object.assign({}, element, { group: element.groups.filter(subElement => subElement.group === groupName) });
});
}
console.log(getContactsByGroupName("Exec"))
```
This should do the trick. the variable **a** here is of course your json object name | You could simply run trough every entry of contacts and generate an output-object containing arrays of numbers for each group. Here is an example.
```js
var input_json = {
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
//define the output objects that will contain the number-arrays by group-key
var output = {}
//run trough every contact
for (let i in input_json.contacts)
//run trough every group of current contact
for (let j in input_json.contacts[i].groups)
//run trough every contact-number for current contact-group
for (let k in input_json.contacts[i].numbers)
//if group-key already exists in output -> push number in array
if (output[input_json.contacts[i].groups[j].group])
output[input_json.contacts[i].groups[j].group].push (input_json.contacts[i].numbers[k].number)
//if group-key does not exist -> add new key-array pair
else
output[input_json.contacts[i].groups[j].group] = [input_json.contacts[i].numbers[k].number]
//write output as JSON to document
document.write (JSON.stringify (output))
``` |
58,097,820 | Given this json object
```
{
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
```
How do I return a new array of telephone numbers where the group equals a given value.
So, for example, I'd expect a single array of "07123456789" where the contact group = "Exec"
Also, where the Group = "Everyone" i'd expect an array of 2 items: "07123456789" and "07987654321"
I've tried:
```
var data = require('../data/data.json')
var peopleInGroup = data.contacts.filter(function (value) {
value.groups.filter(function (type) {
return type.group === recipients[i];
})
});
```
recipients is an array of groups "Everyone, "Exec", "Overseas" | 2019/09/25 | [
"https://Stackoverflow.com/questions/58097820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483212/"
] | The following can do what you want with simply using the Array prototype methods:
```
function filterByGroup(obj, val) {
const objArray = obj.contacts.filter((innerObj, index, array) => {
a = innerObj.groups.filter(group => group.group === val)
return a.length > 0 ? innerObj : false;
});
return (objArray.map(obj => obj.numbers.map( number =>number.number))).flat();
}
```
You can then call it:
`filterByGroup(obj, 'Exec')`
Where `obj` is your initial object! | You could simply run trough every entry of contacts and generate an output-object containing arrays of numbers for each group. Here is an example.
```js
var input_json = {
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
//define the output objects that will contain the number-arrays by group-key
var output = {}
//run trough every contact
for (let i in input_json.contacts)
//run trough every group of current contact
for (let j in input_json.contacts[i].groups)
//run trough every contact-number for current contact-group
for (let k in input_json.contacts[i].numbers)
//if group-key already exists in output -> push number in array
if (output[input_json.contacts[i].groups[j].group])
output[input_json.contacts[i].groups[j].group].push (input_json.contacts[i].numbers[k].number)
//if group-key does not exist -> add new key-array pair
else
output[input_json.contacts[i].groups[j].group] = [input_json.contacts[i].numbers[k].number]
//write output as JSON to document
document.write (JSON.stringify (output))
``` |
58,097,820 | Given this json object
```
{
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
```
How do I return a new array of telephone numbers where the group equals a given value.
So, for example, I'd expect a single array of "07123456789" where the contact group = "Exec"
Also, where the Group = "Everyone" i'd expect an array of 2 items: "07123456789" and "07987654321"
I've tried:
```
var data = require('../data/data.json')
var peopleInGroup = data.contacts.filter(function (value) {
value.groups.filter(function (type) {
return type.group === recipients[i];
})
});
```
recipients is an array of groups "Everyone, "Exec", "Overseas" | 2019/09/25 | [
"https://Stackoverflow.com/questions/58097820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483212/"
] | Here is piece of code which creates a JSON which has three groups of numbers:
```
final_data = {"Everyone": [], "Exec": [], "Overseas": [] }
data.contacts.forEach( (contact) => {
contact.groups.forEach(group => {
final_data[group.group].push(contact.numbers);
})
})
console.log(final_data);
``` | You could simply run trough every entry of contacts and generate an output-object containing arrays of numbers for each group. Here is an example.
```js
var input_json = {
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
//define the output objects that will contain the number-arrays by group-key
var output = {}
//run trough every contact
for (let i in input_json.contacts)
//run trough every group of current contact
for (let j in input_json.contacts[i].groups)
//run trough every contact-number for current contact-group
for (let k in input_json.contacts[i].numbers)
//if group-key already exists in output -> push number in array
if (output[input_json.contacts[i].groups[j].group])
output[input_json.contacts[i].groups[j].group].push (input_json.contacts[i].numbers[k].number)
//if group-key does not exist -> add new key-array pair
else
output[input_json.contacts[i].groups[j].group] = [input_json.contacts[i].numbers[k].number]
//write output as JSON to document
document.write (JSON.stringify (output))
``` |
58,097,820 | Given this json object
```
{
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
```
How do I return a new array of telephone numbers where the group equals a given value.
So, for example, I'd expect a single array of "07123456789" where the contact group = "Exec"
Also, where the Group = "Everyone" i'd expect an array of 2 items: "07123456789" and "07987654321"
I've tried:
```
var data = require('../data/data.json')
var peopleInGroup = data.contacts.filter(function (value) {
value.groups.filter(function (type) {
return type.group === recipients[i];
})
});
```
recipients is an array of groups "Everyone, "Exec", "Overseas" | 2019/09/25 | [
"https://Stackoverflow.com/questions/58097820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483212/"
] | Following this [post](https://stackoverflow.com/questions/38375646/filtering-array-of-objects-with-arrays-based-on-nested-value) i changed the second most upvoted answer code a bit to have this :
```
const getContactsByGroupName = (groupName) => {
return a.contacts
.filter((element) =>
element.groups.some((subElement) => subElement.group === groupName))
.map(element => {
return Object.assign({}, element, { group: element.groups.filter(subElement => subElement.group === groupName) });
});
}
console.log(getContactsByGroupName("Exec"))
```
This should do the trick. the variable **a** here is of course your json object name | The following can do what you want with simply using the Array prototype methods:
```
function filterByGroup(obj, val) {
const objArray = obj.contacts.filter((innerObj, index, array) => {
a = innerObj.groups.filter(group => group.group === val)
return a.length > 0 ? innerObj : false;
});
return (objArray.map(obj => obj.numbers.map( number =>number.number))).flat();
}
```
You can then call it:
`filterByGroup(obj, 'Exec')`
Where `obj` is your initial object! |
58,097,820 | Given this json object
```
{
"contacts": [
{
"name": "Jane doe",
"numbers": [
{
"number": "07123456789"
}
],
"groups": [
{
"group": "Everyone"
},
{
"group": "Exec"
}
]
},
{
"name": "John Smith",
"numbers": [
{
"number": "07987654321"
}
],
"groups": [
{
"group": "Everyone"
}
]
}
]
}
```
How do I return a new array of telephone numbers where the group equals a given value.
So, for example, I'd expect a single array of "07123456789" where the contact group = "Exec"
Also, where the Group = "Everyone" i'd expect an array of 2 items: "07123456789" and "07987654321"
I've tried:
```
var data = require('../data/data.json')
var peopleInGroup = data.contacts.filter(function (value) {
value.groups.filter(function (type) {
return type.group === recipients[i];
})
});
```
recipients is an array of groups "Everyone, "Exec", "Overseas" | 2019/09/25 | [
"https://Stackoverflow.com/questions/58097820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483212/"
] | Following this [post](https://stackoverflow.com/questions/38375646/filtering-array-of-objects-with-arrays-based-on-nested-value) i changed the second most upvoted answer code a bit to have this :
```
const getContactsByGroupName = (groupName) => {
return a.contacts
.filter((element) =>
element.groups.some((subElement) => subElement.group === groupName))
.map(element => {
return Object.assign({}, element, { group: element.groups.filter(subElement => subElement.group === groupName) });
});
}
console.log(getContactsByGroupName("Exec"))
```
This should do the trick. the variable **a** here is of course your json object name | Here is piece of code which creates a JSON which has three groups of numbers:
```
final_data = {"Everyone": [], "Exec": [], "Overseas": [] }
data.contacts.forEach( (contact) => {
contact.groups.forEach(group => {
final_data[group.group].push(contact.numbers);
})
})
console.log(final_data);
``` |
8,143,321 | i want my bitmap in the center of my screen..i m trying it that way but its not working...
```
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
int w = canvas.getWidth();
int h = canvas.getHeight();
int bw=myBitmap.getWidth();
int bh=myBitmap.getHeight();
int cx = w / 2;
int cy = h / 2;
Display d = getWindowManager().getDefaultDisplay();
int x = d.getWidth();
int y = d.getHeight();
int dx = x / 2;
int dw = y /2;
canvas.translate(cx, cy);
if (mValues != null) {
canvas.rotate(-mValues[0]);
}
int centreX = (x - bw) /2;
int centreY = (cy - bh) /2;
//canvas.drawPath(mPath, mPaint);
canvas.drawBitmap(myBitmap, centreX,centreY, null);
``` | 2011/11/15 | [
"https://Stackoverflow.com/questions/8143321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519526/"
] | Here's the code you need in your view:
```java
private int mWidth;
private int mHeight;
private float mAngle;
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
mHeight = View.MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
@Override protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
// Here's the magic. Whatever way you do it, the logic is:
// space available - bitmap size and divide the result by two.
// There must be an equal amount of pixels on both sides of the image.
// Therefore whatever space is left after displaying the image, half goes to
// left/up and half to right/down. The available space you get by subtracting the
// image's width/height from the screen dimensions. Good luck.
int cx = (mWidth - myBitmap.getWidth()) >> 1; // same as (...) / 2
int cy = (mHeight - myBitmap.getHeight()) >> 1;
if (mAngle > 0) {
canvas.rotate(mAngle, mWidth >> 1, mHeight >> 1);
}
canvas.drawBitmap(myBitmap, cx, cy, null);
}
```
Screenshot just for fun: [http://imgur.com/EYpMJ](https://imgur.com/EYpMJ)
(Diagonal lines not part of the code posted here)
EDIT: Added NickT's solution.
EDIT 2: Changed mvalues[0] to mAngle and made it conditional. Changed divide by 2 operations to bitshifts. Remove rotation code if you don't need it. | You can try this :
```
int width = containerBitmap.getWidth();
int height = containerBitmap.getHeight();
float centerX = (width - centeredBitmap.getWidth()) * 0.5f;
float centerY = (height- centeredBitmap.getHeight()) * 0.5f;
```
You can use it to draw a bitmap at the center of another bitmap. |
53,234,529 | So this is new on V2, when I publish with Visual Studio (probably with vsts publishing as well). It says the dll is busy, it didn't used to do that in V1.
I suppose it's fine to stop the functions (Or probably I can do slot deployment as well, although all mine are triggered and scheduled, so I don't really need slots).
So on the "stop" it will still do that 30 seconds of graceful stop that the functions do before shutting down / switching (Heard this on a podcast when I asked).
If I redeploy after the stop, I suppose it's ok this way. Things will wait on my triggers from azure queue and schedule.
Only thing is it's sort of a pain to have to press start and stop rather than just publish. I'm not sure if it's supposed to be doing this or not. Doesn't seem publish will ever work unless it's stopped, why not have it auto-stop the function? | 2018/11/09 | [
"https://Stackoverflow.com/questions/53234529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1216820/"
] | Looks like you meet [ERROR\_FILE\_IN\_USE](https://learn.microsoft.com/en-us/iis/publish/troubleshooting-web-deploy/web-deploy-error-codes#errorfileinuse).
You can configure the appOffline rule in the publishing profile (In Solution explorer> Properties>PublishProfiles>\*.pubxml). Set the EnableMSDeployAppOffline to true as below.
```
<PropertyGroup>
...
<EnableMSDeployAppOffline>true</EnableMSDeployAppOffline>
...
</PropertyGroup>
```
This setting take the app offline so the file lock is released and your app will start automatically after deploy. | With the caveat that ZIP deployment is now preferred, the solution to this is to add an app setting MSDEPLOY\_RENAME\_LOCKED\_FILES with value 1. |
178,951 | "A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?
### Example:
Here are a few headlines about a recent Broadway play:
1. David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway
2. Al Pacino in 'Glengarry Glen Ross': What did the critics think?
3. Al Pacino earns lackluster reviews for Broadway turn
4. Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard
5. Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?
### Problem:
Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.
How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.
Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?
### Goal:
Given 1,000 headlines, a system that automatically suggests that these 5 items are all *probably* about the same thing.
To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).
This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers! | 2012/12/10 | [
"https://softwareengineering.stackexchange.com/questions/178951",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/74763/"
] | It's called [cluster analysis](http://en.wikipedia.org/wiki/Cluster_analysis), which is basically grouping objects into clusters with similar properties. It's a huge topic, but that should give you a place to start. | You're entering the world of Semantics. There are public services that will parse text and pull out the major concepts (a quick search for [Semantic API](http://www.bing.com/search?q=semantic%20api&src=ie9tr) turned up a few) that will parse a free form document and return the major topics encountered including people, places, things, dates, and concepts. Some of the better ones will return in a format known as [RDF]
If you want to build your own system that can do this, the field is [Natural Language Processing](http://en.wikipedia.org/wiki/Natural_language_processing) and that is a very intriguing rabbit hole to dive down. |
178,951 | "A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?
### Example:
Here are a few headlines about a recent Broadway play:
1. David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway
2. Al Pacino in 'Glengarry Glen Ross': What did the critics think?
3. Al Pacino earns lackluster reviews for Broadway turn
4. Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard
5. Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?
### Problem:
Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.
How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.
Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?
### Goal:
Given 1,000 headlines, a system that automatically suggests that these 5 items are all *probably* about the same thing.
To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).
This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers! | 2012/12/10 | [
"https://softwareengineering.stackexchange.com/questions/178951",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/74763/"
] | It's called [cluster analysis](http://en.wikipedia.org/wiki/Cluster_analysis), which is basically grouping objects into clusters with similar properties. It's a huge topic, but that should give you a place to start. | If at all possible, get the story along with the headline. Headlines can sometimes get "cute" and make only tangential reference to what is being discussed. This works OK with humans (because they have *global context*), but not so well with NLP.
As mentioned in Karl Bielefeldt's answer, clustering is a good approach, but the Devil is in the details. You not only have to pick a clustering approach that fits your problem/user space, you also have to figure out *what* is being clustered.
My background is in Information Retrieval (IR) from the 80's-90's, and we focused on *similarity searching* and *centroid-based clustering*. Our documents were represented by *weighted attribute vectors*, which is basically a list of terms and their relative importance in the doc. This approach can work (although better with some collections than others), but it has problems with short-cute headlines, because they lack key vocabulary terms to tie things together. But if you use the whole document, then you get a much richer list of terms (and probably a better sense of importance), and that list of terms will probably make the connection easier to spot (i.e. compute) when you have headlines that are "cute".
My email is in my profile if you would like to get into vector generation issues, etc. |
178,951 | "A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?
### Example:
Here are a few headlines about a recent Broadway play:
1. David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway
2. Al Pacino in 'Glengarry Glen Ross': What did the critics think?
3. Al Pacino earns lackluster reviews for Broadway turn
4. Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard
5. Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?
### Problem:
Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.
How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.
Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?
### Goal:
Given 1,000 headlines, a system that automatically suggests that these 5 items are all *probably* about the same thing.
To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).
This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers! | 2012/12/10 | [
"https://softwareengineering.stackexchange.com/questions/178951",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/74763/"
] | You're entering the world of Semantics. There are public services that will parse text and pull out the major concepts (a quick search for [Semantic API](http://www.bing.com/search?q=semantic%20api&src=ie9tr) turned up a few) that will parse a free form document and return the major topics encountered including people, places, things, dates, and concepts. Some of the better ones will return in a format known as [RDF]
If you want to build your own system that can do this, the field is [Natural Language Processing](http://en.wikipedia.org/wiki/Natural_language_processing) and that is a very intriguing rabbit hole to dive down. | If at all possible, get the story along with the headline. Headlines can sometimes get "cute" and make only tangential reference to what is being discussed. This works OK with humans (because they have *global context*), but not so well with NLP.
As mentioned in Karl Bielefeldt's answer, clustering is a good approach, but the Devil is in the details. You not only have to pick a clustering approach that fits your problem/user space, you also have to figure out *what* is being clustered.
My background is in Information Retrieval (IR) from the 80's-90's, and we focused on *similarity searching* and *centroid-based clustering*. Our documents were represented by *weighted attribute vectors*, which is basically a list of terms and their relative importance in the doc. This approach can work (although better with some collections than others), but it has problems with short-cute headlines, because they lack key vocabulary terms to tie things together. But if you use the whole document, then you get a much richer list of terms (and probably a better sense of importance), and that list of terms will probably make the connection easier to spot (i.e. compute) when you have headlines that are "cute".
My email is in my profile if you would like to get into vector generation issues, etc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.