Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
2,015
So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic.
2011/09/04
[ "https://meta.serverfault.com/questions/2015", "https://meta.serverfault.com", "https://meta.serverfault.com/users/33118/" ]
Hear ye, hear ye, hear ye, -------------------------- Three days have passed. Since then: * 30% of our >10K users have voted to delete that question, independent of the vote going on here. * 22 upvotes for sun-based disposal * 4 upvotes for 'send it back from whence it came' * Showers of hate upon 'Leave it'. Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting. It is gone. ![Record of destruction](https://i.stack.imgur.com/3jY0B.png)
I've certainly done my bit to try and get rid of that question, as well as similar ones, but the system is against us. If Jeff brought it back from the dead I'd love to hear his reasoning for doing so. The only reasoning I can think of is that it brings traffic due to Google and traffic translates to revenue and revenue is the reason Stack Exchange exists. That question is part of the history of SF only in the sense of being a great example of what NOT to post. Rather than adding value it merely detracts from SF and on at least one occasion I've seen it referenced as an excuse to post an off-topic question ("if they can do it why can't I?").
2,015
So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic.
2011/09/04
[ "https://meta.serverfault.com/questions/2015", "https://meta.serverfault.com", "https://meta.serverfault.com/users/33118/" ]
It needs to be burniated. It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that. Perhaps it should be locked while its fate is being debated?
Leave it, just keep it locked down.
115,769
I have a 40 gallon (bladdered) pressure tank in the basement which keeps pressure to my office building, and a 2-inch 2 horsepower submersible pump in a dug well 450 feet away. The pump is cycling waaay too fast, and the tank will hold pressure at 41 pounds to 43 pounds but not at 60 pounds at shut-off pressure. (The pump comes on at 40 and shuts off at 60). It only takes 6 seconds for the pump to come on and shut off and I fear I will cook the pump if this keeps up. I have recently tested the pressure in the tank and it is 50 pounds. Does this mean the bladder leaked and caused pressure to increase in the tank? I know the tank pressure should be set at around 39, or a little below the 'turn-on' pressure. Could this be the cause of the short cycle?
2017/06/02
[ "https://diy.stackexchange.com/questions/115769", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/70373/" ]
The bladder is there to flatten the pressure/volume curve so pressure doesn't change rapidly as water is pumped. This allows for a longer duty cycle. The expected symptom of a burst bladder is just as you describe.
It needs air. Get hold of an air compressor and give it a charge. Be sure to be running water while charging, and the pump is off. Easy. If you need to do this more than once a year there might be a problem with the bladder.
9,482,602
I'm working on a Google Chrome extension with a popup, in which I load a page from a node.js + express.js server. The page I load changes depending on the status of the `req.session.user` in this way: ``` app.get('/', function(req, res){ if(req.session.user){ res.render(__dirname + '/pages/base.jade', {}); } else{ res.render(__dirname + '/pages/login_register.jade', {}); } }); ``` If `req.session.user` is null I send a page in which the user can do the login or register. If he/she does a login, this is what happens in the server: ``` app.post('/login', function(req, res){ var user = {}; user.username = req.body.username; user.password = req.body.password; checkLogin(user, function(foundUser){ //login correct console.log("login!"); req.session.user = foundUser; res.render(__dirname + '/pages/base.jade', { }); }); }); ``` So if the user logs in correctly `req.session.user` should be set with the credentials of the current user. The problem is that once I log in and then close the popup of the Chrome extension, whenever I reopen it I still receive the login page. My question is: does the popup supports session storage in the express.js server? If yes, then there is something wrong with my code, can anyone point out what am I doing wrong? Thanks. EDIT: This is how I setup the server: ``` var app = express.createServer( express.logger(), express.cookieParser(), express.session({ secret: 'keyboard cat' }) ); app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); app.set('view engine', 'ejs'); app.set("view options", { layout: true }); ``` I might be doing something redundant here, since I still don't have a deep understanding of how that works.
2012/02/28
[ "https://Stackoverflow.com/questions/9482602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617461/" ]
The problem is how you have set up your server - you're using the `cookieParser` and `session` middlewares twice: ``` var app = express.createServer( express.logger(), express.cookieParser(), express.session({ secret: 'keyboard cat' }) ); app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); ``` You should only use *either* middlewares as parameters to `createServer`, *or* `use`, so: ``` var app = express.createServer(); app.use(express.logger()); app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); ```
Popup page probably reloads every time you open it. You should create a backgroundpage for your extension where you could store/manage sessions. Then you can communicate from popup to backgroundpage passing messages [docs](http://code.google.com/chrome/extensions/messaging.html). Using messaging you can send login data to backgroundpage and also ask whether user has already logged in.
19,270,638
I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?
2013/10/09
[ "https://Stackoverflow.com/questions/19270638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664010/" ]
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
19,270,638
I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?
2013/10/09
[ "https://Stackoverflow.com/questions/19270638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664010/" ]
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance.
19,270,638
I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?
2013/10/09
[ "https://Stackoverflow.com/questions/19270638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664010/" ]
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64.
19,270,638
I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?
2013/10/09
[ "https://Stackoverflow.com/questions/19270638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664010/" ]
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance.
19,270,638
I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?
2013/10/09
[ "https://Stackoverflow.com/questions/19270638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664010/" ]
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64.
41,004,429
hi guys this is my "login.php": ``` <?php session_start(); // connect to database if (isset($_POST['login_btn'])) { $username =$_POST['username']; $password =$_POST['password']; $_SESSION['username'] = $_POST['username']; $conn = oci_connect('insidedba', 'progetto16', 'localhost/XE'); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); } $password = md5($password); // remember we hashed password before storing last time $sql = oci_parse($conn,"SELECT * FROM UTENTI WHERE USERNAME='$username' AND PASSWORD='$password'"); $result =oci_execute($sql); if ($result) { $stid = oci_parse($conn, "SELECT * FROM UTENTI WHERE username='$username' AND password='$password'"); oci_execute($stid); oci_fetch($stid); if (oci_num_rows($stid) == 1) { $_SESSION['message'] = "You are now logged in"; $_SESSION['username'] = $username; header("location: panel/index.php"); //redirect to home page } else{ $_SESSION['message'] = "Username/password combination incorrect"; } } else { $_SESSION['message'] = "Query error"; } } ?> ``` and it works,and i'm asking if i can use the $username variable in another php. "myorder.php": ``` <?php session_start() $conn = oci_connect('insidedba', 'progetto16', 'localhost/XE'); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); } $columns = array( 'Nome cinema ' => 'NOME_CINEMA', 'Ora' => 'ORARIO', 'Data' => 'DATA', 'Titolo' => 'TITOLO', 'Numero prenotazione' =>'Codice_della_prenotazione', 'Numero sala' =>'Numero_sala', 'Fila' =>'fila', 'Numero sala' =>'numero', ); // Run the query $sql = oci_parse($conn,"SELECT DISTINCT CIN.NOME AS NOME_CINEMA,PAL.DATA as DATA,PAL.ORA ORARIO,F.Titolo as TITOLO, PRE.ID as Codice_della_prenotazione,S.CODS AS Numero_sala,P.FILA as fila,P.NUMERO as numero FROM (((((UTENTI U JOIN PRENOTAZIONI PRE ON PRE.UTENTE=U.ID AND U.USERNAME='$username') JOIN PALINSESTI PAL ON PAL.ID=PRE.PALINSESTO) JOIN FILM F ON F.ID=PAL.FILM) JOIN CINEMA CIN ON CIN.ID=PAL.CINEMA ) JOIN POSTI P ON P.PRENOTAZIONE=PRE.ID AND P.CINEMA=CIN.ID) JOIN SALE S ON S.CINEMA=CIN.ID and p.SALA=S.CODS WHERE BOOL_PAGATO=1 ORDER BY PRE.ID"); oci_execute($sql); // Output table header echo "<table border=\"1px solid black\" width=\"95%\"><tr>"; foreach ($columns as $name => $col_name) { echo "<th>$name</th>"; } echo "</tr>"; // Output rows while($row = oci_fetch_array($sql)) { echo "<tr>"; foreach ($columns as $name => $col_name) { echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>"; } echo "</tr>"; } // Close table echo "</table>" ?> ``` it says undefined variable, How can i solve this? i tried " but it still doesnt work.
2016/12/06
[ "https://Stackoverflow.com/questions/41004429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7160791/" ]
If it's stored in session you can. ``` session_start(); if(!empty($_SESSION['username'])) $username = $_SESSION['username']; else $username = "guest"; ```
You need to use the `U.USERNAME=$_SESSION['username']` variable in your *myorder.php* file. By the way, in the code you're showing you don't have a `$username` variable in *myorder.php*, I guess you had in the SQL query that you now have: `U.USERNAME='$prova'`
65,915,932
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ```
2021/01/27
[ "https://Stackoverflow.com/questions/65915932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13533843/" ]
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
65,915,932
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ```
2021/01/27
[ "https://Stackoverflow.com/questions/65915932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13533843/" ]
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
{% url 'deletedata' pk = st.id %} in thr URL just remove the spaces, bellow code it should work ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ```
65,915,932
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ```
2021/01/27
[ "https://Stackoverflow.com/questions/65915932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13533843/" ]
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
You can also write it with one a tag ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a> <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` and then your views.py ``` def delete_data(request,id): pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') ``` Urls.py ``` urlpatterns=[ path('<int:pk>/',views.delete_data,name="deletedata") ] ```
65,915,932
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ```
2021/01/27
[ "https://Stackoverflow.com/questions/65915932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13533843/" ]
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
{% url 'deletedata' pk = st.id %} in thr URL just remove the spaces, bellow code it should work ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ```
65,915,932
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ```
2021/01/27
[ "https://Stackoverflow.com/questions/65915932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13533843/" ]
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
You can also write it with one a tag ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a> <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` and then your views.py ``` def delete_data(request,id): pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') ``` Urls.py ``` urlpatterns=[ path('<int:pk>/',views.delete_data,name="deletedata") ] ```
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
12,165,002
You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it?
2012/08/28
[ "https://Stackoverflow.com/questions/12165002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
75,277
I've seen quite a few security camera examples and many have options for a duty schedule that activates the camera during certain specified days/hours to set up a routine. However I have fairly dynamic schedule and would like for my security cameras to turn on when our phones are not on the WiFi network. This would be an easy shortcut to "on when we're not home" and prevents it from taking intrusive pictures when we are. Is there a way to configure OpenCV or Motion, or to run a python script to activate a camera when our phones are off the WiFi network? I would like to take advantage of some features of the above software to email or stream footage, so I would like to avoid redesigning a system from the ground up to do this. Any advice? Thanks!
2017/11/16
[ "https://raspberrypi.stackexchange.com/questions/75277", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/54665/" ]
You'd need to know either the MAC or IP address of the phones you want to monitor but you could just `ping` or `arping` each one in turn and if none reply start your recording otherwise stop recording. Calling something like this from `cron` might do the trick: ``` #!/bin/bash # # Determine if we should be recording or not by pinging each phone in the list # and setting the variable to "NO" if any reply. If the variable is still "YES" # at the end we check if the recording process is running and start it if not. # LIST="192.168.123.25 192.168.123.56 192.168.123.13 MyPhone.local 192.168.123.78" RECORD_CMD="RecordingCommand" RECORD="YES" for HOST in $LIST; do ping -c1 "$HOST" &> /dev/null && RECORD="NO" done if [ "$RECORD" == "YES" ]; then # Start or continue recording? if [ $(pgrep -c "$RECORD_CMD") -eq 0 ]; then # Not currently recording so we need to start... "$RECORD_CMD" fi else # Stop recording... killall "$RECORD_CMD" fi exit 0 ```
Your question appears to be about ***activating*** and ***disabling*** the cameras when you are not able to connect to them directly when your phones are not on the same local subnet. So it seems to be about ***networking*** and access to control them, rather than the phones themselves that you reference. That's what I *believe* that I see here. Since the cameras are on an RFC 1918 non-routable address, when you're away from home you can't connect to 192.168.1.1 for example as it's *not routable across the Internet*. The solution is a VPN. Many routers now have this functionality as standard and make it easy to set up a VPN connection back to your home network just by adding a username and password for the VPN account and off you go. Once you connect to your home router via that VPN connection, you can now be connect to the cameras, switch, etc on their non-public IP addresses. With a VPN you'd just ssh into the Pi-Cam via it's local address and execute `sudo systemctl stop/start motion` and directly issue commands to control it. Further, with a VPN connection back to your home network, you will be able to view streams from the cameras directly on a web browser on your phone.
58,655,207
I'm currently trying to extend [a model](https://github.com/microsoft/MASS) that is based on FairSeq/PyTorch. During training I need to train two encoders: one with the target sample, and the original one with the source sample. So the current forward function looks like this: ``` def forward(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs): encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs) return decoder_out ``` And based on this [this idea](https://github.com/golsun/SpaceFusion) i want something like this: ``` def forward_test(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs): encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs) return decoder_out def forward_train(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs): encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs) concat = some_concatination_func(encoder_out, autoencoder_out) decoder_out = self.decoder(prev_output_tokens, encoder_out=concat, **kwargs) return decoder_out ``` Is there any way to do this? Edit: These are the constraints that I have, since I need to extend *FairseqEncoderDecoderModel*: ``` @register_model('transformer_mass') class TransformerMASSModel(FairseqEncoderDecoderModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) ``` Edit 2: The parameters passed to the forward function in Fairseq can be altered by implementing your own Criterion, see for example [CrossEntropyCriterion](https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/cross_entropy.py#L28), where `sample['net_input']` is passed to the `__call__` function of the model, which invokes the `forward` method.
2019/11/01
[ "https://Stackoverflow.com/questions/58655207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128562/" ]
First of all you should **always use and define `forward`** not some other methods that you call on the `torch.nn.Module` instance. **Definitely do not overload `eval()` as shown by [trsvchn](https://stackoverflow.com/a/58659193/10886420) as it's evaluation method defined by PyTorch ([see here](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.eval)).** This method allows layers inside your model to be put into evaluation mode (e.g. specific changes to layers like inference mode for `Dropout` or `BatchNorm`). Furthermore you should call it with `__call__` magic method. Why? Because hooks and other PyTorch specific stuff is registered that way properly. **Secondly, do not use some external `mode` string variable as suggested by [@Anant Mittal](https://stackoverflow.com/questions/58655207/pytorch-different-forward-methods-for-train-and-test-validation/58655415#58655415)**. That's what `train` variable in PyTorch is for, it's standard to differentiate by it whether model is in `eval` mode or `train` mode. That being said you are the best off doing it like this: ``` import torch class Network(torch.nn.Module): def __init__(self): super().__init__() ... # You could split it into two functions but both should be called by forward def forward( self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs ): encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) if self.train: return self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs) autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs) concat = some_concatination_func(encoder_out, autoencoder_out) return self.decoder(prev_output_tokens, encoder_out=concat, **kwargs) ``` You could (and arguably should) split the above into two separate methods, but that's not too bad as the function is rather short and readable that way. Just stick to PyTorch's way of handling things if easily possible and not some ad-hoc solutions. And no, there will be no problem with backpropagation, why would there be one?
By default, calling `model()` invoke `forward` method which is train forward in your case, so you just need to define new method for your test/eval path inside your model class, smth like here: Code: ```py class FooBar(nn.Module): """Dummy Net for testing/debugging. """ def __init__(self): super().__init__() ... def forward(self, x): # here will be train forward ... def evaltest(self, x): # here will be eval/test forward ... ``` Examples: ```py model = FooBar() # initialize model # train time pred = model(x) # calls forward() method under the hood # test/eval time test_pred = model.evaltest(x) ``` **Comment:** I would like to recommend you to split these two forward paths into 2 separate methods, because it easier to debug and to avoid some possible problems when backpropagating.
3,829,211
I did some changes at my CoreData Model. So far, I added a attribute called 'language'. When my application is launched and I click on "Create new Customer" a instance variable Customer is created. This variable is created by: ``` Customer *newCustomer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:appDelegate.managedObjectContext]; ``` Before I did these changes everything worked fine and as planned. But now i get a dump with this error message:`reason = "The model used to open the store is incompatible with the one used to create the store";` What do I have to do to solve this? reseting the persistence store didn't help so far.
2010/09/30
[ "https://Stackoverflow.com/questions/3829211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455928/" ]
What I did to get around this problem was to add this > > [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; > > > to my appDelegate in the persistentStoreCoordinator before adding the persistent store. This deletes the existing store that no longer is compatible with your data model. Remember to comment this line before you run the application the next time if you want to keep what is stored. My implementation of the persistentStoreCoordinator looks like this when I have to remove an old store. ``` - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator_ != nil) { return persistentStoreCoordinator_; } NSError *error = nil; NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyPinballScore.sqlite"]]; //The following line removes your current store so that you can create a new one that is compatible with your new model [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return persistentStoreCoordinator_; ``` }
The answer is a bit tricky but this always works for me. This is for a **clean** installation of a new compatible .sqlite file, **not a migration**! launch simulator, delete the app and the data (the popup after you delete the app). quit simulator open X-Code, after making any edits to your data model delete the `{*appname*}.sqlite` file (or back it up, remove it from project folder, and delete reference) clean the app (`Product > Clean`) Run the app in a simulator (for this tutorial I will assume 4.2) While the simulator is running, in a Finder window, navigate to: `{*home*} > Library > Application Support > iPhone Simulator > 4.2 > Applications > {*random identifier*} > Documents > {*appname*}.sqlite` **Copy** this file to another location Stop running your app in X-Code Drag and drop the {*appname*}.sqlite file into the files list in X-Code. In the dialog that pops up, make sure the `copy to folder` checkbox, is checked. `Product > Clean` Then run the app in the simulator again Now you should have a working sqlite file! Cheers, Robert
11,678,794
I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe>
2012/07/26
[ "https://Stackoverflow.com/questions/11678794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539124/" ]
Here are the steps: 1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE) 2. Select `Add Reference` 3. In the window that opens, Select `Assemblies > Framework` 4. Check the `PresentationFramework` component box and click ok
This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace. <http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx> You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL
11,678,794
I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe>
2012/07/26
[ "https://Stackoverflow.com/questions/11678794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539124/" ]
This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace. <http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx> You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL
I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll" Hope this helps!
11,678,794
I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe>
2012/07/26
[ "https://Stackoverflow.com/questions/11678794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539124/" ]
Here are the steps: 1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE) 2. Select `Add Reference` 3. In the window that opens, Select `Assemblies > Framework` 4. Check the `PresentationFramework` component box and click ok
I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll" Hope this helps!
9,525,464
So I am figuring out how to set up some options for a class. 'options' is a hash. I want to 1) filter out options I don't want or need 2) set some instance variables to use elsewhere 3) and set up another hash with the processed options as @current\_options. ``` def initialize_options(options) @whitelisted_options, @current_options = [:timestamps_offset, :destructive, :minimal_author], {} n_options = options.select { |k,v| @whitelisted_options.include?(k) } @current_options[:timestamps_offset] = @timestamp_offset = n_options.fetch(:timestamps_offset, 0)*(60*60*24) @current_options[:destructive] = @destructive = n_options.fetch(:destructive, false) @current_options[:minimal_author] = @minimal_author = n_options.fetch(:minimal_author, false) end ``` I'm guessing this is a bit much, no matter what I pass in I get: ``` {:timestamps_offset=>0, :destructive=>false, :minimal_author=>false} ``` When I do this line by line from the command line, it works as I want it to but not in my class. So what is going on and how do I clean this up? EDIT: this actually works disembodied from the class I'm using it in, but inside it doesn't so the reality is something is going on I'm not aware of right now. attr\_reader :current\_options is how this is set on the class, perhaps that needs some revision. EDIT2: line 2 of the method is supposed to select from @whitelisted\_options EDIT3: Actually turned out to be something I wasn't thinking of..."options" comes in parsed from a yaml file as strings....and I was fetching symbols, changing that around makes a difference where before the method was looking for symbols and finding none, e.g. "destructive" vs :destructive, so always defaulting to the defaults. In short, I just needed to symbolize the hash keys when options are imported.
2012/03/01
[ "https://Stackoverflow.com/questions/9525464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697364/" ]
Your `@current_options` is initialized as an empty hash. When you filter the `options` passed as params, none of the keys will be present in `@current_options` so `n_options` will end up empty. Then when you set up `@current_options` in the following lines, it will always grab the default values `(0, false, false)`, and that's why your output's always the same. You solve this problem by conditionally initializing @current\_options so that it's only set to `{}` once: @current\_options ||= {} **Post-OP edit:** Your issue's with `options.select` -- in Ruby 1.8, it doesn't return a Hash, but rather an Array. Your calls to `fetch` are then always failing (as symbols can't be array indexes), so always returning defaults. Instead, try: ``` n_options = options.inject({}) {|h, p| h[p[0]] = p[1] if @whitelisted_options.include? p[0]; h } ``` where `p` is an array containing each key/value pair. In Ruby 1.9.2, `Hash.select` behaves the way you expected it to. **Edit 2: Here's how I'd approach it:** ``` class Foo @@whitelisted_options= {:timestamps_offset => 0, :destructive => false, :minimal_author =>false} @@whitelisted_options.keys.each do |option| define_method(option) { return @current_options[option] rescue nil} end def initialize_options(options) @current_options = {} @@whitelisted_options.each {|k, v| @current_options[k] = options[k] || v} @current_options end end ``` In use: ``` f = Foo.new f.destructive #=> nil f.initialize_options(:minimal_author => true, :ignore => :lol) f.destructive #=> false f.minimal_author #=> true f.timestamps_offset #=> 0 ```
1. What is `@whitelisted_options` for? 2. What do you want to happen if `:destructive` is not a key in `options`? Do you want to have `:destructive => false`, or do you want `@current_options` to not mention `:destructive` at all?
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
If you want to change the action bar, call this from your activity: > > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ``` > >
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
If you want to change the action bar, call this from your activity: > > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ``` > >
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
62,287,390
I am working on a web application at the moment that has a an api at the top level domain (mydomain.com) and an SPA at subdomain (spa.mydomain.com). In the SPA I have added, `axios.defaults.withCredentials = true` To login in I run the following code, ``` axios.get('/sanctum/csrf-cookie').then(response => { axios.post('/login', {email: this.email, password: this.password}).then(response => { this.$router.push({ name: 'Account' }); }); }); ``` The get request responds with a 204 as expected and the post request to login responds successfully too, at this point I get redirected and another GET is sent to /api/users/me at this point the server responds with a 401 unauthorized response. I would have assumed that seen as though I can login everything would be working as expected but sadly not, the key bits of my `.env` file from my api are below to see if I am missing anything obvious. `SESSION_DRIVER=cookie SESSION_LIFETIME=120 SESSION_DOMAIN=.mydomain.com SANCTUM_STATEFUL_DOMAINS=spa.mydomain.com` My request headers look like this, `Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Cookie: XSRF-TOKEN=eyJpdiI6InZDRTAvenNlRGhwdVNzY2p5VUFQeFE9PSIsInZhbHVlIjoiVzBLT0wyNTI2Vk5la3hiQ1M1TXpRU2pRQ3pXeGk1Nkc1eW5QN0F5ZjNFUmdIVmlaWGNqdXZVcU9UYUNVTzhXbiIsIm1hYyI6IjJmMmIyMjc4MzNkODA4ZDdlZjRhZTJhM2RlMTQ5NDg1MWM2MjdhMzdkMTFjZGNiMzdkMDM3YjNjNzM1ZmY5NjAifQ%3D%3D; at_home_club_session=eyJpdiI6ImxLYjlRNHplcGh1d2RVSEtnakxJNmc9PSIsInZhbHVlIjoiWnBjN0xheWlaNDdDUWZnZGxMUzlsM0VzbjZaZVdUSTBZL0R1WXRTTGp5emY0S2NodGZNN25hQmF1ajYzZzU3MiIsIm1hYyI6ImNlMWRmNWJhYmE1ODU3MzM1Y2Q4ZDI0MDIzNTU1OWQ4MDE3MGRiNTJjY2NjNmFmZDU5YzhjZTM4NGJlOGU5ZTkifQ%3D%3D; XSRF-TOKEN=eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ%3D%3D; at_home_club_session=eyJpdiI6IjZxWXZSYjdGWXU5SHBKSFFRdGQycWc9PSIsInZhbHVlIjoiU3RyTDdoNGJBUW93ck9CTmFjVFpjRTRxMVVwQzZmcjJJTXJUNFU0UUZVcnkzcWdBbzZxWjNvTWZrZmFuMXBrbSIsIm1hYyI6IjFkOTFiNDg5YmZjYmE0NGZiZDg3ZGY5ZDQyMDg2MGZjNzFlMmI0OTA1OGY2MzdkMmFmOGI0ZTlkOTE4ZDM0NWUifQ%3D%3D; XLtgHBp79G2IlVzFPoHViq4wcAV1TMveovlNr1V4=eyJpdiI6ImZiRThmNUpBb3N0Z21MVHJRMVIvRFE9PSIsInZhbHVlIjoiVDV5S2tDOTFNcElqc1NINVpsdi9Ibk04cFVSekkvSytvY01YUDFIbENhZkV3VnVTaHpOTjlwUjROVnFlMk96SWgwUlByZFU3MlA0YVhTelFDaEVTdndkQnczUFZ3bXJlVHpUTkZwb3Z2d1Z1VUI1STJkeG1ZMm13N0h3S282V2l3MmlvUmFrQXY4SXFFaHcrNjBucktJcmRmSk81UUtFcUFlOCtNaUZHelJpRmxkY2gyZVFOWWRUWTdqZ2NFYi85WlVBeFJ2bm5xU05IU3F1aE0ybXlzUnltRUh6eG1qZklaVW9GSDRsU3RMWmRrL242WjJ5VFZVa3dDTWtIN051SThUa0FjZDFsSXp6SmNSTWFWTDl5dk5IczFKcEpSWS9qZUZiMGVENTdKcjVrTlBITWRjV2dUY1RmcElNL0FUSzQxS0JGZFBzUWVha3ZIOVh6YWpTZnNZa202bHB1akQvakVHWTRZU1Z1WWFZZmxIcDN2bDZrek9JRHkybE01b3BlTWErYmhKK2xQN0FmTzhZS3M3bTBHUVJaSzhIdzBGWlc4Vjd1QVJCSFovZz0iLCJtYWMiOiI2ZWZlYWIwYzhlZjMyZjlkNTI0ZWJmYjFhMzExYTIxZTkyNDM1ODM3ODg1YjlmM2ZiOTVhMTMwYTAwYjk4NjhiIn0%3D Host: mydomain.com Origin: http://spa.mydomain.com Referer: http://spa.mydomain.info/account User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 X-XSRF-TOKEN: eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ==` and my cors, ``` 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ``` Everything works perfectly on localhost.
2020/06/09
[ "https://Stackoverflow.com/questions/62287390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57872/" ]
Turns out when our Azure DevOps instance was first set up, all our users set up Microsoft accounts with their company emails. Later when we finally stood up Azure AD but before we connected it to DevOps we added a new project and set the permissions for a few existing employees. For some reason the user permissions on the new DevOps project were listed as "aaduser" type instead of the standard "user" type (ms account) that all the users in other projects in DevOps had. In other words duplicate UPNs but different accounts (but sort of the same). What's weird is that DevOps managed to find the Azure AD user account before we even connected the two together services together. We removed the offending users with the standard "user" type and re-added them so they were now all listed as "aaduser." We were then able to connect Azure AD. To be clear, this was all done on the DevOps side and had nothing to do with AD. Not sure why it was finding Azure AD users when we weren't even connected to it yet.
It sounds like you have multiple users in your azure ad tenant with the same UPN. maybe you created a cloud account with the same UPN before sync'ing the on premise with azure ad connect? or something else of that nature. try to go to graph explorer <https://developer.microsoft.com/en-us/graph/graph-explorer> log in with a azure ad admin account and type in a query like this ``` https://graph.microsoft.com/v1.0/users?$filter=startswith(UserPrincipalName,'##UPNHavingIssues##') ``` That should get you users with a UPN of whatever it having problems. There should only be entry, but if there are multiple, then that's where the problem is. The other option is to remove the user having issues from devops completely, then try to connect, then re-add him. because when you try to connect devops to an azure ad domain it will try to match the UPNs of users in your devops with users in your tenant.
62,287,390
I am working on a web application at the moment that has a an api at the top level domain (mydomain.com) and an SPA at subdomain (spa.mydomain.com). In the SPA I have added, `axios.defaults.withCredentials = true` To login in I run the following code, ``` axios.get('/sanctum/csrf-cookie').then(response => { axios.post('/login', {email: this.email, password: this.password}).then(response => { this.$router.push({ name: 'Account' }); }); }); ``` The get request responds with a 204 as expected and the post request to login responds successfully too, at this point I get redirected and another GET is sent to /api/users/me at this point the server responds with a 401 unauthorized response. I would have assumed that seen as though I can login everything would be working as expected but sadly not, the key bits of my `.env` file from my api are below to see if I am missing anything obvious. `SESSION_DRIVER=cookie SESSION_LIFETIME=120 SESSION_DOMAIN=.mydomain.com SANCTUM_STATEFUL_DOMAINS=spa.mydomain.com` My request headers look like this, `Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Cookie: XSRF-TOKEN=eyJpdiI6InZDRTAvenNlRGhwdVNzY2p5VUFQeFE9PSIsInZhbHVlIjoiVzBLT0wyNTI2Vk5la3hiQ1M1TXpRU2pRQ3pXeGk1Nkc1eW5QN0F5ZjNFUmdIVmlaWGNqdXZVcU9UYUNVTzhXbiIsIm1hYyI6IjJmMmIyMjc4MzNkODA4ZDdlZjRhZTJhM2RlMTQ5NDg1MWM2MjdhMzdkMTFjZGNiMzdkMDM3YjNjNzM1ZmY5NjAifQ%3D%3D; at_home_club_session=eyJpdiI6ImxLYjlRNHplcGh1d2RVSEtnakxJNmc9PSIsInZhbHVlIjoiWnBjN0xheWlaNDdDUWZnZGxMUzlsM0VzbjZaZVdUSTBZL0R1WXRTTGp5emY0S2NodGZNN25hQmF1ajYzZzU3MiIsIm1hYyI6ImNlMWRmNWJhYmE1ODU3MzM1Y2Q4ZDI0MDIzNTU1OWQ4MDE3MGRiNTJjY2NjNmFmZDU5YzhjZTM4NGJlOGU5ZTkifQ%3D%3D; XSRF-TOKEN=eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ%3D%3D; at_home_club_session=eyJpdiI6IjZxWXZSYjdGWXU5SHBKSFFRdGQycWc9PSIsInZhbHVlIjoiU3RyTDdoNGJBUW93ck9CTmFjVFpjRTRxMVVwQzZmcjJJTXJUNFU0UUZVcnkzcWdBbzZxWjNvTWZrZmFuMXBrbSIsIm1hYyI6IjFkOTFiNDg5YmZjYmE0NGZiZDg3ZGY5ZDQyMDg2MGZjNzFlMmI0OTA1OGY2MzdkMmFmOGI0ZTlkOTE4ZDM0NWUifQ%3D%3D; XLtgHBp79G2IlVzFPoHViq4wcAV1TMveovlNr1V4=eyJpdiI6ImZiRThmNUpBb3N0Z21MVHJRMVIvRFE9PSIsInZhbHVlIjoiVDV5S2tDOTFNcElqc1NINVpsdi9Ibk04cFVSekkvSytvY01YUDFIbENhZkV3VnVTaHpOTjlwUjROVnFlMk96SWgwUlByZFU3MlA0YVhTelFDaEVTdndkQnczUFZ3bXJlVHpUTkZwb3Z2d1Z1VUI1STJkeG1ZMm13N0h3S282V2l3MmlvUmFrQXY4SXFFaHcrNjBucktJcmRmSk81UUtFcUFlOCtNaUZHelJpRmxkY2gyZVFOWWRUWTdqZ2NFYi85WlVBeFJ2bm5xU05IU3F1aE0ybXlzUnltRUh6eG1qZklaVW9GSDRsU3RMWmRrL242WjJ5VFZVa3dDTWtIN051SThUa0FjZDFsSXp6SmNSTWFWTDl5dk5IczFKcEpSWS9qZUZiMGVENTdKcjVrTlBITWRjV2dUY1RmcElNL0FUSzQxS0JGZFBzUWVha3ZIOVh6YWpTZnNZa202bHB1akQvakVHWTRZU1Z1WWFZZmxIcDN2bDZrek9JRHkybE01b3BlTWErYmhKK2xQN0FmTzhZS3M3bTBHUVJaSzhIdzBGWlc4Vjd1QVJCSFovZz0iLCJtYWMiOiI2ZWZlYWIwYzhlZjMyZjlkNTI0ZWJmYjFhMzExYTIxZTkyNDM1ODM3ODg1YjlmM2ZiOTVhMTMwYTAwYjk4NjhiIn0%3D Host: mydomain.com Origin: http://spa.mydomain.com Referer: http://spa.mydomain.info/account User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 X-XSRF-TOKEN: eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ==` and my cors, ``` 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ``` Everything works perfectly on localhost.
2020/06/09
[ "https://Stackoverflow.com/questions/62287390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57872/" ]
Turns out when our Azure DevOps instance was first set up, all our users set up Microsoft accounts with their company emails. Later when we finally stood up Azure AD but before we connected it to DevOps we added a new project and set the permissions for a few existing employees. For some reason the user permissions on the new DevOps project were listed as "aaduser" type instead of the standard "user" type (ms account) that all the users in other projects in DevOps had. In other words duplicate UPNs but different accounts (but sort of the same). What's weird is that DevOps managed to find the Azure AD user account before we even connected the two together services together. We removed the offending users with the standard "user" type and re-added them so they were now all listed as "aaduser." We were then able to connect Azure AD. To be clear, this was all done on the DevOps side and had nothing to do with AD. Not sure why it was finding Azure AD users when we weren't even connected to it yet.
According to [this doc](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/faq-azure-access?view=azure-devops#q-why-did-i-get-an-error-stating-that-my-organization-has-multiple-active-identities-with-the-same-upn): > > During the connect process, we map existing users to members of the Azure AD tenant, based on their UPN, which is often known as sign-in address. If we detect multiple users with the same UPN, we don't know how to map these users. > > > The cause of this issue is that the target user has the same UPN as other user. A UPN must be unique among all security principal objects within a directory forest. The UPN contains UPN prefix (the user account name) and a UPN suffix (a DNS domain name). For example:`someone@example.com` You can compare the target account with other user accounts. Then you could find the duplicate UPN. You could try to remove the duplicate one or [change the UPN](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/howto-troubleshoot-upn-changes#learn-about-upns-and-upn-changes) as unique. Hope this helps.
31,079,002
I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ```
2015/06/26
[ "https://Stackoverflow.com/questions/31079002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
I finally realized that since May 1, it is **necessary** to create an app and then generate a token and use it in my JSON call URL. So this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?limit=100&callback=? ``` Became this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=123456789123456789|ajdkajdlajfldkeieflejejf&limit=100&callback=? ``` I've replaced my actual token with random numbers, but it's basically a giant string of numbers and letters with a pipe in the middle. For me the confusing part was needing an "app" when I'm not using a mobile device. I also didn't realize that Facebook had actually deprecated the old methond. Creating an app is simple... go here and follow the steps: <https://developers.facebook.com/apps/> Leave the "NameSpace" field blank... not sure what that is exactly and it's not required. Generating the token string took a few more steps which a friend from work walked me through... I can't remember off the top of my head, but once you get the string and insert it into your JSON call, it will definitely work. The REASON for this is so when Facebook receives a data request from some random website, the request comes with a built-in ID so Facebook knows who is asking for the data.
31,079,002
I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ```
2015/06/26
[ "https://Stackoverflow.com/questions/31079002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
You need an App Access Token. Go to <http://developers.facebook.com/apps/> and create an app for the client's Facebook page. When you're presented with the options, select the "Website" type of app. You can skip the configuration option using the "Skip and Create App ID" button in the top right corner. Give it a Display Name, don't worry about the Namespace, and give it a applicable category. Once the app is created, go to "Tools & Support" > "Access Token Tool" in the top menu. You should see an App Token listed in green text. Copy that into your JSON call, and it should work. ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=PASTE_APP_TOKEN_HERE&limit=100&callback=?', function(json) { $.each(json.data, function(i, photo) { $('<li></li>').append('<span class="thumb" style="background: url(' + ((photo.images[1]) ? photo.images[1].source : '') + ') center center no-repeat; background-size: cover;"><a href=' + ((photo.images[0]) ? photo.images[0].source : '') + ' rel="gallery"></a></span>').appendTo('#timeline'); }); ``` });
334,167
I am late game Alien Crossfire, attacking with gravitons aremed with [string disruptor](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#String_Disruptor). Unfortunately, the others have gotten wise and are building everything [AAA](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Special_Ability#AAA_Tracking). In a way, that's good, as it is expensive, and diverts their resources. However, I can no longer "one hit kill", and am losing gravitons. Should I replace the weapons with [Psi attack](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#Psi_Attack)?
2018/06/24
[ "https://gaming.stackexchange.com/questions/334167", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/92813/" ]
Psi attack/defense is orthogonal to conventional weapons. Its result depends on *Morale* levels of attacking/defending units. If an attacker/defender is a *Mind Worm*, they have their own class, plus both faction's *Planet (Green)* scores/attitudes largely affect the outcome of the fight. **Answer:** see what's your faction's Morale and/or Green score. You may also trick the system by changing your *Government/Economy* type before the attack. Say, if you possess some *Mind Worms* and you are planning to give them a victorious ride, switch to *Green* several turns before the planned invasion. Or to *Fundamentalist + Power* if you are planning Psi attacks with conventional units. --- Personally, I *love* Green because if you are lucky enough, you can capture native life forms, making a considerable amount of your units Mind Worms **(Independent)** which means it requires no support from a home base, still performing as police in "at least one unit defending each Base" paradigm.
If you have dominant weapons, mixing in hovertanks and even air-dropped infantry will let you continue leveraging those dominant weapons. Psi-combat is mostly useful when facing technologically superior enemies that your weapons cannot defeat. Switching from overwhelming firepower to psi-attack will make you lose as many (if not more) units, since psi-combat is less lopsided in general. I'd say consider changing your gravs to transports and using their mobility to deploy slower, ground-based units that ignore AAA. At least until your opponents stop putting all of their eggs in one basket.
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
From the author himself (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). > > > So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. > > > You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
From the author himself (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). > > > So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. > > > You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
62,380,246
As the title says is there a way to programmatically render (into a DOM element) a component in angular? For example, in React I can use `ReactDOM.render` to turn a component into a DOM element. I am wondering if it's possible to something similar in Angular?
2020/06/15
[ "https://Stackoverflow.com/questions/62380246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6009213/" ]
At first you'll need to have a template in your HTML file at the position where you'll want to place the dynamically loaded component. ```html <ng-template #placeholder></ng-template> ``` In the component you can inject the `DynamicFactoryResolver` inside the constructor. Once you'll execute the `loadComponent()` function, the `DynamicComponent` will be visible in the template. `DynamicComponent` can be whatever component you would like to display. ```js import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('placeholder', {read: ViewContainerRef}) private viewRef: ViewContainerRef; constructor(private cfr: ComponentFactoryResolver) {} loadComponent() { this.viewRef.clear(); const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent); const componentRef = this.viewRef.createComponent(componentFactory); } } ``` Here is a [Stackblitz](https://stackblitz.com/edit/angular-ivy-dynamic-components?file=src%2Fapp%2Fapp.component.ts). What the `loadComponent` function does is: 1. It clears the host 2. It creates a so called factory object of your component. (`resolveComponentFactory`) 3. It creates an instance of your factory object and inserts it in the host reference (`createComponent`) 4. You can use the `componentRef` to, for example, modify public properties or trigger public functions of that components instance.
If you want to render the angular component into a Dom element which is not compiled by angular, Then we can't obtain a ViewContainerRef. Then you can use Angular cdk portal and portal host concepts to achieve this. Create portal host with any DOMElememt, injector, applicationRef, componentFactoryResolver. Create portal with the component class. And attach the portal to host. <https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c>
12,881
No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ```
2015/06/24
[ "https://arduino.stackexchange.com/questions/12881", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10817/" ]
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
The error is due to wrong expectations on operators precedence: ++ and -> have the same precedence, so they are evaluated left to right. See <http://en.cppreference.com/w/c/language/operator_precedence> . Overall, the lack of parenthesis makes the readability poor. The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period. Then read the value and decide if it's high or low. But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling. Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.
12,881
No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ```
2015/06/24
[ "https://arduino.stackexchange.com/questions/12881", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10817/" ]
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
```C++ if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; ``` I'm going to agree with user3877595 but explain why, as his/her answer got a downvote. `DBNC_TICS` has to be > 1, right? Otherwise what is the point? We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero. If `DBNC_TICS` is == 1 then this is always true: ```C++ ++ptrButton->debounceTics == DBNC_TICS ``` Therefore that test is useless. If `DBNC_TICS` > 1 then it will not execute the "if" block and execute this instead: ```C++ ptrButton->debounceTics = 0; ``` So `ptrButton->debounceTics` is back to zero, and we are back to square 1. Therefore the test will always be false. > > No matter how I rearrange this, the increment compare always returns false.... > > > As stated in the question.
64,999,490
Hi I'm learning right now how to upload images to database, but I'm getting this error/notice. ``` </select> <input type="text" name="nama" class="input-control" placeholder="Nama Produk" required> <input type="text" name="harga" class="input-control" placeholder="Harga Produk" required> <input type="file" name="img" class="input-control" required> <textarea class="input-control" name="deskripsi" placeholder="Desrkipsi"></textarea> <select class="input-control" name="status"> <option value="">--Pilih--</option> <option value="1">Aktif</option> <option value="0">Tidak Aktif</option> </select> <input type="submit" name="submit" value="Submit" class="btn-login"> </form> <?php if(isset($_POST['submit'])){ $kategori = $_POST['kategori']; $nama = $_POST['nama']; $harga = $_POST['harga']; $deskripsi = $_POST['deskripsi']; $status = $_POST['status']; $filename = $_FILES['img']['name']; $tmp_name = $_FILES['img']['tmp_name']; } ``` the error output ``` Notice: Undefined index: img in C:\xampp\htdocs\pa_web\tambah_produk.php on line 66 ```
2020/11/25
[ "https://Stackoverflow.com/questions/64999490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14704128/" ]
You need to add `enctype="multipart/form-data"` to your form <https://www.php.net/manual/en/features.file-upload.post-method.php> > > **Note:** > Be sure your file upload form has attribute > enctype="multipart/form-data" otherwise the file upload will not work. > > >
When you want to submit file from form you should put "enctype="multipart/form-data". ``` <form "enctype="multipart/form-data" ...> </form> ``` Do you put it?
21,657,910
Can we change the color of the text based on the color of the background image? I have a background image which i have appended it to body. When you reload the page every time the background image gets changed. But i have my menus which are positioned on the image having text color as black. If the background image is black, menus wont be visible. Any solutions for my problem? Thanks in advance.
2014/02/09
[ "https://Stackoverflow.com/questions/21657910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999172/" ]
use switch case to handle ``` switch(backgroundimage){ case "black.jpg": document.body.color = "white"; break; case "white.jpg": document.body.color = "black"; break; case "green.jpg": document.body.color = "gray"; break; } ```
If you know what will be the image that will be loaded you can create a dictionary with the image name and the css class that will be appended to the text for it. then on page load attach the class to the body classes. If you dont know the image that will be loaded there are some solutions but they are not complete. look at this [answer](https://stackoverflow.com/a/2541680/395890)
2,274,695
My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > > * weird construction. Delete 'new' > > > We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?
2010/02/16
[ "https://Stackoverflow.com/questions/2274695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188740/" ]
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
Your code is just similar to the less weird construct ``` function Foo () { var inner = 'some value'; this.foo = 'blah'; ... }; var someObj = new Foo; ```
2,274,695
My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > > * weird construction. Delete 'new' > > > We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?
2010/02/16
[ "https://Stackoverflow.com/questions/2274695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188740/" ]
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
To clarify some aspects and make Douglas Crockford's JSLint not to complain about your code here are some examples of instantiation: ```javascript 1. o = new Object(); // normal call of a constructor 2. o = new Object; // accepted call of a constructor 3. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; })(); // normal call of a constructor 4. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }); // accepted call of a constructor ``` In example 3. expression in (...) as value is a function/constructor. It looks like this: new (function (){...})(). So if we omit ending brackets as in example 2, the expression is still a valid constructor call and looks like example 4. Douglas Crockford's JSLint "thinks" you wanted to assign the function to someObj, not its instance. And after all it's just an warning, not an error.
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
Have you included the spider in `SPIDER_MODULES` list in your scrapy\_settings.py? It's not written in the tutorial anywhere that you should to this, but you do have to.
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
I believe you have syntax errors there. The `name = hxs...` will not work because you don't get defined before the `hxs` object. Try running `python yourproject/spiders/domain.py` to get syntax errors.
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
These two lines look like they're causing trouble: ``` u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) ``` * Only one rule will be followed each time the script is run. Consider creating a rule for each URL. * You haven't created a `parse_item` callback, which means that the rule does nothing. The only callback you've defined is `parse`, which changes the default behaviour of the spider. Also, here are some things that will be worth looking into. * `CrawlSpider` doesn't like having its default `parse` method overloaded. Search for `parse_start_url` in the documentation or the docstrings. You'll see that this is the preferred way to override the default `parse` method for your starting URLs. * `NuSpider.hxs` is called before it's defined.
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
You are overriding the `parse` method, instead of implementing a new `parse_item` method.
20,931,619
I got nearly 10 functions in class having similar pattern like following function ``` SQLiteDatabase database = this.getWritableDatabase(); try { //Some different code , all other code(try,catch,finally) is same in all functions } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` I want to remove that common code from all functions (try ,catch , finally) and move it to a single place How can I achieve this?
2014/01/05
[ "https://Stackoverflow.com/questions/20931619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1033305/" ]
There are a number of frameworks out there that drastically simplify database interaction that you can use, but if you want to do things on your own, and are interested in the Java way to do things like this, here's the idea: Make your "executor" like so: ``` public class Executor { public static void runOperation(Operation operation) { SQLiteDatabase database = this.getWritableDatabase(); try { operation.run(database); } catch (SQLiteException e) { Log.e(operation.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` Now each of the 10 things you want to do will be operations: ``` public interface Operation { void run(SQLiteDatabase database) throws SQLiteException; } ``` Here is what a particular operation would look like: ``` Operation increaseSalary = new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // .... write the new increased salary to the database } }; ``` And you run it with: ``` . . Executor.runOperation(increaseSalary); . . ``` You can also make the implementation of the interface an anonymous inner class, but that may make it a little less readable. ``` . . Executor.runOperation(new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // put the increase salary database-code in here } }); . . ``` You can look through a list of classic Design Patterns to find out which one this is.
**To expand further on [Ray Toal's original answer](https://stackoverflow.com/a/20931708/1134080),** it is worth noting that using anonymous inner class will help avoid creating a separate class file for each operation. So the original class with 10 or so functions can remain the same way, except being refactored to use the `Executor` pattern. Also, when using the `Executor` pattern, you have to take care of the usage of `this` in the original code. Assume the original functions are as follows: ``` public boolean operation1() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 1 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } public boolean operation2() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 2 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` With the `Executor` class defined as follows: ``` public class Executor { public static boolean runOperation(SQLiteOpenHelper helper, Operation operation) { SQLiteDatabase database = helper.getWritableDatabase(); try { operation.run(database); return true; } catch (SQLiteException e) { Log.e(helper.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } } ``` And the `Operation` interface defined as follows: ``` public interface Operation { public void run(SQLiteDatabase database) throws SQLiteException; } ``` The original functions can now be rewritten as follows: ``` public boolean operation1() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 1 } }); } public boolean operation2() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 2 } }); } ``` *This expansion also corrects mistakes Ray has overlooked in his original answer.*
32,580,318
Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax
2015/09/15
[ "https://Stackoverflow.com/questions/32580318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003128/" ]
You can load a placeholder image, but then you must *load* that image (when you're already loading another image). If you load something like a spinner via a `GET` request, that should be ok since you can set cache headers from the server so the browser does not actually make any additional requests for that loading image. A way that Pinterest gets around this is by loading a solid color and the title of each of their posts in the post boxes while the images are loading, but now we're getting into a design discussion. There are multiple ways to skin a cat. Regarding loading several images, you have to understand a couple considerations: 1. The time it takes to fetch and download an image. 2. The time it takes to decode this image. 3. The maximum number of concurrent sockets you may have open on a page. If you don't have a ton of images that need to be loaded up front, consideration 3 is typically not a problem since you can *optimistically* load images under the fold, but if you have 100s of images on the page that need to be loaded quickly for a good user experience, then you may need to find a better solution. Why? Because you're incurring 100s of additional round trips to your server just load each image which makes up a small portion of the total loading spectrum (the spectrum being 100s of images). Not only that, but you're getting choked by the browser limitation of having X number of concurrent requests to fetch these images. If you have many small images, you may want to go with an approach similar to what [Dropbox describes here](https://blogs.dropbox.com/tech/2014/01/retrieving-thumbnails/). The basic gist is that you make one giant request for multiple thumbnails and then get a chunked encoding response back. That means that each packet on the response will contain the payload of each thumbnail. Usually this means that you're getting back the base64-encoded version of the payload, which means that, although you are reducing the number of round trips to your server to potentially just one, you will have a greater amount of data to transfer to the client (browser) since the string representation of the payload will be larger than the binary representation. Another issue is that you can no longer safely cache this request on the browser without using something like [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). You also incur a decode cost when you set the background image of each `img` tag to a base64 string since the browser now must convert the string to binary and then have the `img` tag decode that as whatever file format it is (instead of skipping the `base64`->`binary` step altogether when you request an image and get a binary response back).
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
32,580,318
Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax
2015/09/15
[ "https://Stackoverflow.com/questions/32580318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003128/" ]
I found a good solution on GitHub. Just use the **CSS** code below: ```css img[src=""], img:not([src]) { visibility: hidden; } ``` Link: <https://github.com/wp-media/rocket-lazy-load/issues/60>
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
9,458,253
Perhaps I am worrying over nothing. I desire for data members to closely follow the RAII idiom. How can I initialise a protected pointer member in an abstract base class to null? I know it should be null, but wouldn't it be nicer to ensure that is universally understood? Putting initialization code outside of the initializer list has the potential to not be run. Thinking in terms of the assembly operations to allocate this pointer onto the stack, couldn't they be interrupted in much the same way (as the c'tor body) in multithreading environments or is stack expansion guaranteed to be atomic? If the destructor is guaranteed to run then might not the stack expansion have such a guarantee even if the processor doesn't perform it atomically? How did such a simple question get so expansive? Thanks. If I could avoid the std:: library that would be great, I am in a minimilist environment.
2012/02/26
[ "https://Stackoverflow.com/questions/9458253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866333/" ]
I have had this problem in the past - and fixed it. The images you're displaying are much too large. I love using html or css to resize my images (because who wants to do it manually), but the fact remains that most browsers will hiccup when moving them around. I'm not sure why. With the exception of Opera, which usually sacrifices resolution and turns websites into garbage. Resize the largest images, and see if that helps.
Performance in JavaScript is slow, as you're going through many layers of abstraction to get any work done, and many manipulations with objects on the screen are happening in the background. Performance cannot be guaranteed from system to system. You'll find that with all jQuery animation, you will get a higher "frame rate" (not the right term here, but I can't think of a better one) on faster machines and better-performing browsers (such as Chrome) than you will on slower machines. If you are curious what all happens in the background when you set a scroll position, or other property, use one of the many tools for profiling your code. Google Chrome comes with one built-in, and for Firefox, you can use Firebug to give you some insight. See also this question: [What is the best way to profile javascript execution?](https://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution)
34,211,201
I have a Python script that uploads a Database file to my website every 5 minutes. My website lets the user query the Database using PHP. If a user tries to run a query while the database is being uploaded, they will get an error message > > PHP Warning: SQLite3::prepare(): Unable to prepare statement: 11, database disk image is malformed in XXX on line 127 > > > where line 127 is just the `prepare` function ``` $result = $db->prepare("SELECT * FROM table WHERE page_url_match = :pageurlmatch"); ``` Is there a way to test for this and retry the users request once the database is done uploading?
2015/12/10
[ "https://Stackoverflow.com/questions/34211201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2893712/" ]
First of all there is a weird thing with your implementation: you use a parameter `n` that you never use, but simply keep passing and you never modify. Secondly the second recursive call is incorrect: ``` else: m = y*power(y, x//2, n) #Print statement only used as check print(x, m) return m*m ``` If you do the math, you will see that you return: *(y yx//2)2=y2\*(x//2+1)* (mind the `//` instead of `/`) which is thus one *y* too much. In order to do this correctly, you should thus rewrite it as: ``` else: m = power(y, x//2, n) #Print statement only used as check print(x, m) return y*m*m ``` (so removing the `y*` from the `m` part and add it to the `return` statement, such that it is not squared). Doing this will make your implementation at least semantically sound. But it will not solve the performance/memory aspect. Your [comment](https://stackoverflow.com/questions/34211198/using-recursion-to-calculate-powers-of-large-digit-numbers#comment56167183_34211198) makes it clear that you want to do a modulo on the result, so this is probably *Project Euler*? The strategy is to make use of the fact that modulo is closed under multiplication. In other words the following holds: *(a b) mod c = ((a mod c) \* (b mod c)) mod c* You can use this in your program to prevent generating **huge numbers** and thus work with small numbers that require little computational effort to run. Another optimization is that you can simply use the square in your argument. So a faster implementation is something like: ``` def power(y, x, n): if x == 0: #base case return 1 elif (x%2==0): #x even return power((y*y)%n,x//2,n)%n else: #x odd return (y*power((y*y)%n,x//2,n))%n ``` If we do a small test with this function, we see that the two results are identical for small numbers (where the `pow()` can be processed in reasonable time/memory): `(12347**2742)%1009` returns `787L` and `power(12347,2742,1009)` `787`, so they generate the same result (of course this is no *proof*), that both are equivalent, it's just a short test that filters out obvious mistakes.
here is my approach accornding to the c version of this problem it works with both positives and negatives exposents: ``` def power(a,b): """this function will raise a to the power b but recursivelly""" #first of all we need to verify the input if isinstance(a,(int,float)) and isinstance(b,int): if a==0: #to gain time return 0 if b==0: return 1 if b >0: if (b%2==0): #this will reduce time by 2 when number are even and it just calculate the power of one part and then multiply if b==2: return a*a else: return power(power(a,b/2),2) else: #the main case when the number is odd return a * power(a, b- 1) elif not b >0: #this is for negatives exposents return 1./float(power(a,-b)) else: raise TypeError('Argument must be interfer or float') ```
38,921,847
I want to remove the card from the `@hand` array if it has the same rank as the given input. I'm looping through the entire array, why doesn't it get rid of the last card? Any help is greatly appreciated! Output: ``` 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Clubs 3 of Spades ------------ 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Spades ``` Code: ``` deck = Deck.new hand = Hand.new(deck.deal, deck.deal, deck.deal, deck.deal, deck.deal, deck.deal) puts hand.to_s hand.remove_cards("3") puts "------------" puts hand.to_s ``` Hand class: ``` class Hand def initialize(*cards) @hand = cards end def remove_cards(value) @hand.each_with_index do |hand_card, i| if hand_card.rank == value @hand.delete_at(i) end end end def to_s output = "" @hand.each do |card| output += card.to_s + "\n" end return output end end ``` Card class: ``` class Card attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def to_s "#{@rank} of #{@suit}" end end ```
2016/08/12
[ "https://Stackoverflow.com/questions/38921847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5140582/" ]
`remove_cards(value)` has an issue: one should not `delete` during iteration. The correct way would be to [`Array#reject!`](http://ruby-doc.org/core-2.3.1/Array.html#method-i-reject-21) cards from a hand: ``` def remove_cards(value) @hands.reject! { |hand_card| hand_card.rank == value } end ```
Your issue is in this line ``` @hands.each_with_index do |hand_card, i| ``` You have an instance variable `@hand`, not `@hands`
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
What about oldskool `strtoupper()`?
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
What about oldskool `strtoupper()`?
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
14,847,913
I try to implement the zoom in/out by spread/pinch gesture and the drag and drop functions on a Relative Layout. This is the code of my OnPinchListener to handle the zoom effect. The **mainView** is the RelativeLayout defined in the layout xml file. I implement the touch listener in the **fakeview** which should be in front of all view. The touch event will change the **mainview** according to the code. **I want to ask if it is possible to get the actual left, top, width and height after the scale?** It always return 0,0 for left and top, and the original width and height after zoom. Thanks very much! ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linear_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/zoomable_relative_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/background" /> </RelativeLayout> <RelativeLayout android:id="@+id/relative_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:orientation="vertical" > </RelativeLayout> </RelativeLayout> public class MainActivity extends Activity { //ZoomableRelativeLayout mainView = null; RelativeLayout mainView = null; RelativeLayout rl = null; public static final String TAG = "ZoomText." + MainActivity.class.getSimpleName(); private int offset_x; private int offset_y; private boolean dragMutex = false; RelativeLayout fakeView = null; float width = 0, height = 0; private OnTouchListener listener = new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { // Log.e(TAG, event + ""); // Log.e(TAG, "Pointer Count = "+event.getPointerCount()); Log.e(TAG, event.getX() + "," + event.getY() + "|" + mainView.getX() + "(" + mainView.getWidth() + ")," + mainView.getY() + "(" + mainView.getHeight() + ")"); if (event.getX() >= mainView.getLeft() && event.getX() <= mainView.getLeft() + mainView.getWidth() && event.getY() >= mainView.getTop() && event.getY() <=mainView.getTop() + mainView.getHeight()) if (event.getPointerCount() > 1) { return scaleGestureDetector.onTouchEvent(event); } else { return llListener.onTouch(arg0, event); } return false; } }; private ScaleGestureDetector scaleGestureDetector; private OnTouchListener llListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub // Log.d(TAG, event + ",LL"); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: offset_x = (int) event.getX(); offset_y = (int) event.getY(); // Log.e(TAG, offset_x + "," + offset_y); dragMutex = true; return true; case MotionEvent.ACTION_MOVE: // Log.e(TAG, "Finger down"); int x = (int) event.getX() - offset_x; int y = (int) event.getY() - offset_y; Log.e(TAG, event.getX() + "," + event.getY()); float _x = mainView.getX(); float _y = mainView.getY(); mainView.setX(_x + x); mainView.setY(_y + y); offset_x = (int) event.getX(); offset_y = (int) event.getY(); return true; case MotionEvent.ACTION_UP: dragMutex = false; return true; } return false; } }; private OnDragListener dragListener = new View.OnDragListener() { @Override public boolean onDrag(View arg0, DragEvent arg1) { Log.e(TAG, "DRAG Listener = " + arg1); return false; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainView = (RelativeLayout) findViewById(R.id.zoomable_relative_layout); // mainView.setOnTouchListener(new OnPinchListener()); // mainView.setOnTouchListener(listener); scaleGestureDetector = new ScaleGestureDetector(this, new OnPinchListener()); rl = (RelativeLayout) findViewById(R.id.linear_layout); mainView.setOnDragListener(dragListener); // mainView.setOnTouchListener(llListener); fakeView = (RelativeLayout) findViewById(R.id.relative_layout); fakeView.setOnTouchListener(listener); } class OnPinchListener extends SimpleOnScaleGestureListener { float startingSpan; float endSpan; float startFocusX; float startFocusY; public boolean onScaleBegin(ScaleGestureDetector detector) { startingSpan = detector.getCurrentSpan(); startFocusX = detector.getFocusX(); startFocusY = detector.getFocusY(); return true; } public boolean onScale(ScaleGestureDetector detector) { // mainView.scale(detector.getCurrentSpan() / startingSpan, // startFocusX, startFocusY); // if(width==0) // width = mainView.getWidth(); // if(height==0) // height = mainView.getHeight(); mainView.setPivotX(startFocusX); mainView.setPivotY(startFocusY); mainView.setScaleX(detector.getCurrentSpan() / startingSpan); mainView.setScaleY(detector.getCurrentSpan() / startingSpan); // LayoutParams para = mainView.getLayoutParams(); // width*=detector.getCurrentSpan() / startingSpan; // height*=detector.getCurrentSpan() / startingSpan; // para.width = (int)width; // para.height = (int)height; // mainView.setLayoutParams(para); return true; } public void onScaleEnd(ScaleGestureDetector detector) { //mainView.restore(); mainView.invalidate(); Log.e(TAG, mainView.getLeft()+","+mainView.getRight()); } } } ```
2013/02/13
[ "https://Stackoverflow.com/questions/14847913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2067294/" ]
you need to get the transformation matrix and use that to transform your original points. so something like this (after you do the scaling): ``` Matrix m = view.getMatrix(); //gives you the transform matrix m.mapPoints(newPoints, oldPoints); //transform the original points. ```
This is how I solved it in my case (`getViewRect` should be called after view was laid out, for example through `view.post(Runnable)`, so `view.getWidth()/getHeight()` returns actual values): ``` public static Rect getViewRect(View view) { Rect outRect = new Rect(); outRect.right = (int)(view.getWidth() * getScalelX(view)); outRect.bottom = (int)(view.getHeight() * getScalelY(view)); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); return outRect; } public static float getScalelX(View view) { float scaleX = view.getScaleX(); view = getParent(view); while (view != null) { scaleX *= view.getScaleX(); view = getParent(view); } return scaleX; } public static float getScalelY(View view) { float scaleX = view.getScaleY(); view = getParent(view); while (view != null) { scaleX *= view.getScaleY(); view = getParent(view); } return scaleX; } public static ViewGroup getParent(View view) { if (view == null) { return null; } ViewParent parent = view.getParent(); if (parent instanceof View) { return (ViewGroup) parent; } return null; } ``` however it just turned out that android 3.1 (probably 3.0 also) doesn't take in account scale factor while dealing with `getLocationOnScreen` method. I'm gonna to manually scale the rect before returning it from my `getViewRect(View)` function in case of android 3.1 api like this: ``` public static void scaleRect(Rect rect, float scaleX, float scaleY, float pivotX, float pivotY) { rect.left = (int) ((rect.left - pivotX) * scaleX + pivotX); rect.right = (int) ((rect.right - pivotX) * scaleX + pivotX); rect.top = (int) ((rect.top - pivotY) * scaleY + pivotY); rect.bottom = (int) ((rect.bottom - pivotY) * scaleY + pivotY); } ``` However one should know a pivot coordinates for every view in the hierarchy from the current view to the root and corresponding zoom levels to handle this transformation correctly. If someone has any straightforward solution it will be appreciated **EDIT:** This is how I modified the `getViewRect(View)` method so it works on 3.1 also: ``` public static Rect getViewRect(View view) { Rect outRect = new Rect(); if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2){ outRect.right = (int)(view.getWidth() * getScalelX(view)); outRect.bottom = (int)(view.getHeight() * getScalelY(view)); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); } else { outRect.right = view.getWidth(); outRect.bottom = view.getHeight(); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); View parent = view; while(parent != null){ parent.getLocationOnScreen(location); scaleRect(outRect, parent.getScaleX(), parent.getScaleY(), parent.getPivotX() + location[0], parent.getPivotY() + location[1]); parent = getParent(parent); } } return outRect; } ``` I think `if`- clause could be removed so that the second branch (`else`) should work for all versions. However I prefer to use straightforward solution (the first branch of the `if`) so that the second is just a workaround :)
3,851,022
$A^{2}-2A=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}$ Can someone help me solve this? I've been trying to solve it for a while, but no matter what I try, the only information that I manage to get about A is that if $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ then $c=\frac{2b}{3}$. Any help would be appreciated, thanks!
2020/10/04
[ "https://math.stackexchange.com/questions/3851022", "https://math.stackexchange.com", "https://math.stackexchange.com/users/832188/" ]
Denote by $I$ the identity matrix. Then, completing squares you can write $$A^2 - 2A = A^2 -2IA + I^2 -I^2 = (A-I)^2 -I^2.$$ Hence, your equation is equivalent to $$(A-I)^2 = X + I$$ since $I^2 = I$. Denote by $Y=X+I$ the new matrix (which is known). You want to find $B$ such that $B^2=Y.$ Here, I recommend to diagonalize $Y$, i.e. find $U$ and diagonal $D$ such that $$Y=UDU^{-1}.$$ Thus, $$B= Y^{1/2} = UD^{1/2}U^{-1}.$$ See [this link](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_diagonalization) for more information. Once you have found $B$, $A$ is given by $$A=B+I.$$ Remember that you may have more than one square root of the matrix $Y$.
$$A^{2}-2A+I=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}+I \\ (A-I)^2=\begin{bmatrix} 6 & -6 \\ -4 & 3 \end{bmatrix} $$ We know that, if$$\begin{align}M&=PDP^{-1} \\ M^n&=PD^nP^{-1}\end{align}$$ Let $B=A-I$ then, $$B=\sqrt{\begin{bmatrix} 6 & -6 \\ -4 & 3 \end{bmatrix}}$$ Diagonalise $B^2$ as, $$\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right).\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)$$ From this, $$B=\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right)^{\frac{1}{2}}.\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)$$ From this $$A=\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right)^{\frac{1}{2}}.\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)+\left(\begin{matrix} 1&0\\0&1\end{matrix}\right)$$ The required matrix is approximately $$\tiny{\left(\begin{matrix} \frac{\left(481173769149-31173769149\*i\right)\*\sqrt{105}+\left(20341081920215+1091081920215\*i\right)}{3500000000000} & \frac{\left(-481173769149+31173769149\*i\right)\*\sqrt{105}+875000000000}{875000000000} \\ \frac{\left(-160391256383+10391256383\*i\right)\*\sqrt{105}}{437500000000} & \frac{\left(-481173769149+31173769149\*i\right)\*\sqrt{105}+\left(20341081920215+1091081920215\*i\right)}{3500000000000} \end{matrix}\right)}$$
3,851,022
$A^{2}-2A=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}$ Can someone help me solve this? I've been trying to solve it for a while, but no matter what I try, the only information that I manage to get about A is that if $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ then $c=\frac{2b}{3}$. Any help would be appreciated, thanks!
2020/10/04
[ "https://math.stackexchange.com/questions/3851022", "https://math.stackexchange.com", "https://math.stackexchange.com/users/832188/" ]
Denote by $I$ the identity matrix. Then, completing squares you can write $$A^2 - 2A = A^2 -2IA + I^2 -I^2 = (A-I)^2 -I^2.$$ Hence, your equation is equivalent to $$(A-I)^2 = X + I$$ since $I^2 = I$. Denote by $Y=X+I$ the new matrix (which is known). You want to find $B$ such that $B^2=Y.$ Here, I recommend to diagonalize $Y$, i.e. find $U$ and diagonal $D$ such that $$Y=UDU^{-1}.$$ Thus, $$B= Y^{1/2} = UD^{1/2}U^{-1}.$$ See [this link](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_diagonalization) for more information. Once you have found $B$, $A$ is given by $$A=B+I.$$ Remember that you may have more than one square root of the matrix $Y$.
$\newcommand{\Tr}{\mathrm{Tr}\,}$ Let $Y=A-I$, $X=B+I$, $B$ for the rhs matrix. Then $\Tr X = 9$, $\det X=-6$, and we need to solve $$Y^2=X$$ for $Y$. Write $\alpha=\Tr Y$, $\beta = \det Y$. Then $$Y^2-\alpha Y + \beta I=0$$ or $$\alpha Y = \beta I + X$$ so that finding allowed values of $\alpha$, $\beta$ solves the problem. Take the trace and determinant of both sides of $Y^2=X$. Then $$\begin{align} \alpha^2 - 2\beta &= \Tr X = 9 \\ \beta^2 &= \det X = -6 \end{align}$$ which means that $$\begin{align} \alpha A &= (\alpha+\beta +1)I + B \\ \alpha^2 & = 9 +2\beta \\ \beta^2 &= -6\text{.} \end{align}$$ Note that there are four solutions.
68,767,520
I have a discord bot that gets info from an API. The current issue I'm having is actually getting the information to be sent when the command is run. ``` const axios = require('axios'); axios.get('https://mcapi.us/server/status?ip=asean.my.to') .then(response => { console.log(response.data); }); module.exports = { name: 'serverstatus', description: 'USes an API to grab server status ', execute(message, args) { message.channel.send(); }, }; ```
2021/08/13
[ "https://Stackoverflow.com/questions/68767520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15076973/" ]
probably your page is refreshed, try to use preventDefault to prevent the refresh ``` $('#submit').click(function(event){ //your code here event.preventDefault(); } ```
You have a button with type `"submit"`. ```html <input type="submit" id="submit" value="Save"> ``` As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL. As [Sterko](https://stackoverflow.com/users/13474687/sterko) stated, you could use a event-handler to prevent the submission of your form due to the submit button.
238,163
I have Echo's buried in code all over my notebook, I'd like a flag to turn them all on or off globally. * Sure `Unprotect[Echo];Echo=Identity` would disable them, but then you can't re-enable them * A solution that works for all the various types of Echos (EchoName, EchoEvaluation, ...) would be nice * `QuietEcho` doesn't work because I'd have to write it add it around every blob of code
2021/01/13
[ "https://mathematica.stackexchange.com/questions/238163", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/403/" ]
[`Echo`](http://reference.wolfram.com/language/ref/Echo) has an autoload, so you need to make sure the symbol is autoloaded before you modify its values: ``` DisableEcho[] := (Unprotect[Echo]; Echo; Echo = #&; Protect[Echo];) EnableEcho[] := (Unprotect[Echo]; Echo=.; Protect[Echo];) ``` Test: ``` DisableEcho[] Echo[3] EnableEcho[] Echo[3, "EchoLabel"] ``` > > 3 > > > > > EchoLabel 3 > > > > > 3 > > >
I would recommend using `QuietEcho` rather than redefining `Echo`: ``` In[62]:= $Pre = QuietEcho; In[63]:= Echo[3] Out[63]= 3 ``` This has the added benefit of disabling printing for all `Echo` functions, not just `Echo`.
29,922,241
Here is my Database: `bott_no_mgmt_data` ``` random_no ; company_id ; bottle_no ; date ; returned ; returned_to_stock ; username 30201 ; MY COMP ; 1 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30202 ; MY COMP ; 2 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30205 ; MY COMP ; 5 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30208 ; MY COMP ; 8 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30209 ; MY COMP ; 9 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30210 ; MY COMP ; 10 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30211 ; MY COMP ; 1 ; 2015-04-29 ; 20 ; NULL ; ANDREW 30212 ; MY COMP ; 2 ; 2015-04-29 ; 20 ; NULL ; ANDREW 30213 ; MY COMP ; 9 ; 2015-04-29 ; 30 ; NULL ; ANDREW 30214 ; MY COMP ; 10 ; 2015-04-29 ; 30 ; NULL ; ANDREW ``` I have successfully pulled all the entire unique rows from `bott_no_mgmt_data` where the field `random_no` is highest and `bottle_no` is unique with the following code: ``` select yt.* from bott_no_mgmt_data yt<br> inner join(select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no where returned < 15 and date > '2015-04-01' ``` So for example one of the rows it returns will be ``` 30214;MY COMP;10;2015-04-29;30;NULL;ANDREW ``` and NOT ``` 30210;MY COMP;10;2015-04-28;10;NULL;ANDREW ``` because while their bottleno's are the same the former's random\_no is higher. My Problem: I now wish to compare each returned rows 'bottleno' with another table 'sample' which simply contains field 'bottleno' with a list of bottle numbers. I wish to compare them and only return those that match. I assume we would then 'LEFT JOIN' the results above with database 'sample' as below: ``` select yt.* from bott_no_mgmt_data yt<br> inner join(select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no where returned < 15 and date > '2015-04-01' LEFT JOIN sample ON sample.bottleno = yt.bottle_no ``` The extra left join gives me an error > > 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN sample ON sample.bottleno = yt.bottleno WHERE sample.bottleno IS NULL ' at line 7 > > >
2015/04/28
[ "https://Stackoverflow.com/questions/29922241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4842148/" ]
All joins should be written before Where clause as Daan mentions: ``` select yt.* from bott_no_mgmt_data yt inner join( select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no ) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no LEFT JOIN sample ON sample.bottleno = yt.bottle_no where returned < 15 and date > '2015-04-01' ```
A couple of things. You don't need that first inner join at all, it's pointless. Also, you said "I wish to compare them and only return those that match." - so that means you want INNER JOIN not LEFT JOIN. ``` SELECT MAX(random_no) AS random_no, company_id, yt.bottle_no, `date`, returned, username FROM bott_no_mgmt_data yt INNER JOIN sample ON sample.bottle_no=yt.bottle_no WHERE yt.username = 'ANDREW' AND yt.returned < 15 AND yt.date > '2015-04-01' GROUP BY company_id, yt.bottle_no, `date`, returned, username ```
17,435,721
I have a project with multiple modules say "Application A" and "Application B" modules (these are separate module with its own pom file but are not related to each other). In the dev cycle, each of these modules have its own feature branch. Say, ``` Application A --- Master \ - Feature 1 Application B --- Master \ - Feature 1 ``` Say Application A is independent and has its own release cycle/version. Application B uses Application A as a jar. And is defined in its pom dependency. Now, both teams are working on a feature branch say "Feature 1". What is the best way to setup Jenkins build such that, Build job for Application B is able to use the latest jar from "Feature 1" branch of Application A. Given Feature 1 is not allowed to deploy its artifacts to maven repository. Somehow I want the jar from Application A's Feature 1 branch to be supplied as the correct dependency for Application B?
2013/07/02
[ "https://Stackoverflow.com/questions/17435721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710802/" ]
You can do this with a before update trigger. You would use such a trigger to assign the value of `offer_nr` based on the historical values. The key code would be: ``` new.offer_nr = (select coalesce(1+max(offer_nr), 1) from offers o where o.company_id = new.company_id ) ``` You might also want to have `before update` and `after delete` triggers, if you want to keep the values in order. Another alternative is to assign the values when you query. You would generally do this using a variable to hold and increment the count.
Don't make it this way. Have autoincremented company ids as well as independent order ids. That's how it works. There is no such thing like "number" in database. Numbers appears only at the time of select.
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
28,808,099
I am writing a script which will pick the last created file for the given process instance. The command I use in my script is ``` CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT/console/*${INSTANCE}*" | tail -1` ``` but while the script is getting executed, the above command changes to ``` ls -1 '....../console/*ABP*' ``` because of the single quotes, `*` is not being treated as a wildcard character and it is giving output like: ``` ls -1 $ABP_AJTUH_ROOT/console/*${INSTANCE}* | tail -1 + ls -1 '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*' + tail -1 ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory + CONSOLE_FILE='' ``` --- it is working on command line after removing ' from the command but not working while using in script as mentioned above ``` tc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*' ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory devtc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085* -rw-r--r-- 1 devtc1 aimsys 72622 Feb 17 20:55 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_205519.log -rw-r--r-- 1 devtc1 aimsys 177039 Feb 17 21:02 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_210203.log ```
2015/03/02
[ "https://Stackoverflow.com/questions/28808099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4623068/" ]
You cannot use double quotes around the wildcard, because that turns the asterisks into literal characters. ``` CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT"/console/*"$INSTANCE"* | tail -1` ``` should work, but see the caveats against <http://mywiki.wooledge.org/ParsingLs> and generally <http://mywiki.wooledge.org/BashPitfalls>
Try ``` CONSOLE_FILE=`eval ls -1 "$ABP_AJTUH_ROOT/console/*${INSTANCE}*" | tail -1` ``` Also, if you want the last created file, use `ls -1tr`
60,744,543
I'm trying to get the Download Folder to show on my file explorer. However on Android 9, when I use the getexternalstoragedirectory() method is showing self and emulated directories only and if I press "emulated" I cannot see more folders, it shows an empty folder. So this is how I'm getting the path, it's working fine in other Android versions but Android 9. Any guide would be appreciated ``` val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath ```
2020/03/18
[ "https://Stackoverflow.com/questions/60744543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10871734/" ]
This is because [dictionaries](https://docs.julialang.org/en/v1/base/collections/#Dictionaries-1) in Julia (`Dict`) are not ordered: each dictionary maintains a *set* of keys. The order in which one gets keys when one iterates on this set is not defined, and can vary as one inserts new entries. There are two things that one can do to ensure that one iterates on dictionary entries in a specific order. The first method is to get the set of keys (using [`keys`](https://docs.julialang.org/en/v1/base/collections/#Base.keys)) and sort it yourself, as has been proposed in another answer: ``` julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> for key in sort!(collect(keys(fruits))) val = fruits[key] println("$key => $val") end Apples => 8 Mangoes => 5 Pomegranates => 4 ``` That being said, if the order of keys is important, one might want to reflect that fact in the type system by using an *ordered* dictionary ([OrderedDict](https://juliacollections.github.io/OrderedCollections.jl/latest/ordered_containers.html#OrderedDicts-and-OrderedSets-1)), which is a data structure in which the order of entries is meaningful. More precisely, an `OrderedDict` preserves the order in which its entries have been inserted. One can either create an `OrderedDict` from scratch, taking care of inserting keys in order, and the order will be preserved. Or one can create an `OrderedDict` from an existing `Dict` simply using `sort`, which will sort entries in ascending order of their key: ``` julia> using OrderedCollections julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> ordered_fruits = sort(fruits) OrderedDict{String,Int64} with 3 entries: "Apples" => 8 "Mangoes" => 5 "Pomegranates" => 4 julia> keys(ordered_fruits) Base.KeySet for a OrderedDict{String,Int64} with 3 entries. Keys: "Apples" "Mangoes" "Pomegranates" ```
Try this: ``` fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); for key in sort(collect(keys(fruits))) println("$key => $(fruits[key])") end ``` It gives this result: ``` Apples => 8 Mangoes => 5 Pomegranates => 4 ```
5,803,170
I have encountered a problem when trying to select data from a table in MySQL in Java by a text column that is in utf-8. The interesting thing is that with code in Python it works well, in Java it doesn't. The table looks as follows: ``` CREATE TABLE `x` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `text` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; ``` The query looks like this: ``` SELECT * FROM x WHERE text = 'ěščřž'" ``` The Java code that doesn't work as exptected is the following: ``` public class test { public static void main(String [] args) { java.sql.Connection conn = null; System.out.println("SQL Test"); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = java.sql.DriverManager.getConnection( "jdbc:mysql://127.0.0.1/x?user=root&password=root&characterSet=utf8&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf8"); } catch (Exception e) { System.out.println(e); System.exit(0); } System.out.println("Connection established"); try { java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery("SELECT * FROM x WHERE text = 'ěščřž'"); while(r.next()) { System.out.println ( r.getString("id") + " " + r.getString("text") ); } } catch (Exception e) { System.out.println(e); System.exit(0); } } } ``` The Python code is: ``` # encoding: utf8 import MySQLdb conn = MySQLdb.connect (host = "127.0.0.1", port = 3307, user = "root", passwd = "root", db = "x") cursor = conn.cursor () cursor.execute ("SELECT * FROM x where text = 'ěščřž'") row = cursor.fetchone () print row cursor.close () conn.close () ``` Both are stored on the filesystem in utf8 encoding (checked with hexedit). I have tried different versions of mysql-connector (currently using 5.1.15). Mysqld is 5.1.54. Mysqld log for the Java code and Python code respectively: ``` 110427 12:45:07 1 Connect root@localhost on x 110427 12:45:08 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'net_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set_connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower_case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' OR Variable_name = 'query_cache_size' OR Variable_name = 'init_connect' 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment 1 Query SHOW COLLATION 1 Query SET autocommit=1 1 Query SET sql_mode='STRICT_TRANS_TABLES' 1 Query SELECT * FROM x WHERE text = 'ěščřž' 110427 12:45:22 2 Connect root@localhost on x 2 Query set autocommit=0 2 Query SELECT * FROM x where text = 'ěščřž' 2 Quit ``` Does anybody have any suggestions what might be the cause why the Python code works and why the Java code does not? (by not working I mean not finding the desired data -- the connection works fine) Many thanks.
2011/04/27
[ "https://Stackoverflow.com/questions/5803170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429274/" ]
Okay, my bad. The database was wrongly built. It was built through the mysql client that by default is latin1 so in the database the data were encoded by utf8 twice. The problem and the major difference between the two source codes is in that the Python code doesn't set the default charset (therefore it is latin1) whereas the Java code does (therefore it is utf8). So it was coincidence of many factors that made me think that something peculiar is actually going on. Thanks for your responses anyway.
Use PreparedStatement and set your search string as a positional parameter into that statement. Read this tutorial about PreparedStatements -> <http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html> Also, never create a String literal in Java code that contains non-ASCII characters. If you want to pass non-ASCII characters do a unicode escaping on them. This should give you an idea what I am talking about -> <http://en.wikibooks.org/wiki/Java_Programming/Syntax/Unicode_Escape_Sequences>
24,220,365
I have this SQL server instance which is shared by several client-processes. I want queries to finish taking as little time as possible. Say a call needs to read 1k to 10k records from this shared Sql Server. My natural choice would be to use ExecuteReaderAsync to take advantage of async benefits such as reusing threads. I started wondering whether async will pose some overhead since execution might stop and resume for every call to ExecuteReaderAsync. That being true, seems that overall time for query to complete would be longer if compared to a implementation that uses ExecuteReader. Does that make (any) sense?
2014/06/14
[ "https://Stackoverflow.com/questions/24220365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298622/" ]
Whether you use sync or async to call SQL Server makes no difference for the work that SQL Server does and for the CPU-bound work that ADO.NET does to serialize and deserialize request and response. So no matter what you chose the difference will be small. Using async is not about saving CPU time. It is about saving memory (less thread stacks) and about having a nice programming model in UI apps. In fact async never saves CPU time as far as I'm aware. It adds overhead. If you want to save CPU time use a synchronous approach. On the server using async in low-concurrency workloads adds no value whatsoever. It adds development time and CPU cost.
The difference between the async approach and the sync approach is that the async call will cause the compiler to generate a state machine, whereas the sync call will simply block while the work agains't the database is being done. IRL, the best way to choose is to benchmark both approaches. As usr said, usually those differrences are neglectable compared to the time the query takes to execute. Async will shine brighter in places where it may save resources such as allocating a new thread There are many posts about async performance: 1. [*Async await performance*](https://stackoverflow.com/questions/23871806/async-await-performance) 2. [*The zen of async: best practices for best performance*](http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-829T) 3. [*Async Performance: Understanding the Costs of Async and Await*](http://msdn.microsoft.com/en-us/magazine/hh456402.aspx)
3,398,839
I'm trying to prove this by induction, but something doesn't add up. I see a solution given [here](https://www.algebra.com/algebra/homework/word/misc/Miscellaneous_Word_Problems.faq.question.29292.html), but it is actually proving that the expression is **greater** than $2\sqrt{n}$. I'd appreciate some insight.
2019/10/18
[ "https://math.stackexchange.com/questions/3398839", "https://math.stackexchange.com", "https://math.stackexchange.com/users/209695/" ]
Base step: 1<2. Inductive step: $$\sum\_{j=1}^{n+1}\frac1{\sqrt{j}} < 2\sqrt{n}+\frac1{\sqrt{n+1}}$$ So if we prove $$2\sqrt{n}+\frac1{\sqrt{n+1}}<2\sqrt{n+1}$$ we are done. Indeed, that holds true: just square the left hand side sides to get $$4n+2\frac{\sqrt{n}}{\sqrt{n+1}}+\frac1{n+1}<4n+3<4n+4$$ which is the square of the right end side. Errata: I forgot the double product in the square. The proof must be amended as follows: $$2\sqrt{n}<2\sqrt{n+1}-\frac1{\sqrt{n+1}}$$ since by squaring it we get $$4n<4n+4-4+\frac1{n+1}$$ which is trivially true.
Note that $$ 2\sqrt{n+1}-2\sqrt n=2\cdot\frac{(\sqrt{n+1}-\sqrt{n})(\sqrt{n+1}+\sqrt{n})}{\sqrt{n+1}+\sqrt{n}}=2\cdot \frac{(n+1)-n}{\sqrt{n+1}+\sqrt{n}}<\frac 2{\sqrt n+\sqrt n}$$
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
37,455,599
When I run my project on my iphone or in the simulator it works fine. When I try to run it on an ipad I get the below error: *file was built for arm64 which is not the architecture being linked (armv7)* The devices it set to Universal. Does anybody have an idea about what else I should check?
2016/05/26
[ "https://Stackoverflow.com/questions/37455599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5367540/" ]
Just in case somebody has the same problem as me. Some of my target projects had different iOS Deployment target and that is why the linking failed. After moving them all to the same the problem was solved.
I should have added armv6 for iPad 2. Done that and it works now
2,315,242
I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs.
2010/02/23
[ "https://Stackoverflow.com/questions/2315242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266159/" ]
If you are choosing to use the Membership API for your site, then this [link](http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/security/tutorial-08-cs.aspx) has information regarding how to add extra information to a user. I was faced with the same scenario recently and ended up ditching the membership functionality and rolled my own db solution in tandem with the DotNetOpenAuth library.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.
2,315,242
I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs.
2010/02/23
[ "https://Stackoverflow.com/questions/2315242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266159/" ]
I would create [custom membership provider](http://www.15seconds.com/issue/050216.htm) and omit those `aspnet_x` tables completely. I've seen what happens when one `join`s these tables and custom ones with nhibernate mappings - pure nightmare.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.