Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
55,515,807 | Is is possible in regex to allow float numbers between 0 to 2? | I need to validate text input through regex expression. Text input only accept float numbers between 0 and 2 else it through validation error. Currently I'm using this expression
> ^\d+\.\d{0,2}$
But it only validate on numbers (1.0,2.0...). Following are the valid/invalid input for text.
**Valid:**
- 0
- 1
- 2
- 0.1
- 1.9
- 2.0
- 0.01
- 1.09
- 1.009
**Invalid:**
- -1
- 3
- 2.1
- 2.01
- 2.001 | <javascript><regex><validation><numbers> | 2019-04-04 12:16:00 | LQ_EDIT |
55,516,445 | Uncaught DOMException: Failed to execute 'postMessage' on 'Window' | <p>I'm getting error </p>
<pre><code>content-script.js:24 Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'Window': An object could not be cloned.
at Object.t.messageJumpContext (chrome-extension://elgalmkoelokbchhkhacckoklkejnhcd/build/content-script.js:24:9921)
at chrome-extension://elgalmkoelokbchhkhacckoklkejnhcd/build/content-script.js:24:8583
</code></pre>
<p>I haven't used window.postMessage any where in my code. Any idea why this happens?</p>
| <angular><window><postmessage> | 2019-04-04 12:50:16 | HQ |
55,516,596 | Why do we declare pointers | Why do we use pointers in c to store addresses of variables?? Why can't we simply use an unsigned int instead??
I mean we could simply declare an unsigned int to store the addresses | <c><pointers><int> | 2019-04-04 12:57:35 | LQ_EDIT |
55,518,453 | How can i return multiple values from a function seperatly | i'm a newb, please help!
So the issue is quite simple, I need to return multiple values from a function, can anyone suggest how I do it? Code below:
<?php
abstract class Products
{
protected $name;
protected $price;
public function __construct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
}
// A new class extension
class Furniture extends Products
{
protected $width;
protected $height;
protected $length;
public function getSize()
{
// return $this->width;
// return $this->height;
// return $this->length;
// return array($this->width, $this->height, $this->length);
}
}
So as far as I understand, when I return something, it will stop the function, so I understand why I cant just do return 3 times. Attempt to return an array didn't work with an error "Notice: Array to string conversion".
Could anyone please let me know how I can return all 3 of those? | <php><oop> | 2019-04-04 14:26:20 | LQ_EDIT |
55,519,669 | How can I type symbols in string | <p>How can I type “” in string.like he said “felt not well.” But it show error. How can I type “” in string python ? I tried so many method can’t make it.</p>
| <python> | 2019-04-04 15:24:58 | LQ_CLOSE |
55,519,820 | Hash an integer in Python to match Oracle's STANDARD_HASH | <p>In Oracle, my data has been hashed by passing an integer into `STANDARD_HASH' as follows. How can I get the same hash value using Python?</p>
<p>Result in Oracle when an integer passed to STANDARD_HASH:</p>
<pre><code>SELECT STANDARD_HASH(123, 'SHA256') FROM DUAL;
# A0740C0829EC3314E5318E1F060266479AA31F8BBBC1868DA42B9E608F52A09F
</code></pre>
<p>Result in Python when a string is passed in:</p>
<pre><code>import hashlib
hashlib.sha256(str.encode(str(123))).hexdigest().upper()
# A665A45920422F9D417E4867EFDC4FB8A04A1F3FFF1FA07E998E86F7F7A27AE3
# I want to modify this function to get the hash value above.
</code></pre>
<p>Maybe this information will also help. I cannot change anything on the Oracle side, but if I could, I would convert the column to <code>CHAR</code> and it would give the same value as my current Python implementation. An example follows.</p>
<p>Result in Oracle when a string passed to STANDARD_HASH:</p>
<pre><code>SELECT STANDARD_HASH('123', 'SHA256') FROM DUAL;
# A665A45920422F9D417E4867EFDC4FB8A04A1F3FFF1FA07E998E86F7F7A27AE3 (matches Python result)
</code></pre>
<p>I've made several attempts, like simply passing in an integer to Python, but this results in the error that a string is required. I've also searched for a way to encode the integer, but haven't made any progress.</p>
| <python><oracle><hash> | 2019-04-04 15:32:38 | HQ |
55,520,829 | How to get response body with request.send() in dart | <p>I'm doing an api request uploading an image with</p>
<pre><code>var request = new http.MultipartRequest("POST", uri);
var response = await request.send()
</code></pre>
<p>in dart using flutter. I can then check the response code with for instance </p>
<pre><code>if (response.statusCode == 200) {
print('ok');
}
</code></pre>
<p>with other calls I can also get the response body with</p>
<pre><code>var result = response.body;
</code></pre>
<p>however when using request.send() I can't seem to find out how to get the response body result.</p>
<p>Any help or input is very much appreciated, thanks!</p>
| <dart><flutter> | 2019-04-04 16:23:44 | HQ |
55,521,488 | Microsoft Edge isPersonal SavePersonalAndPaymentData brake React app | <p>I have a simple form, one input and one submit button inside the React app. It works well in every web browsers. Now I started testing in the IE and Edge (<code>Edge/18.17763</code>).</p>
<p>When I hit the submit button I got errors in the console:</p>
<pre><code>Unable to get property 'isPersonal' of undefined or null reference
Unable to get property 'SavePersonalAndPaymentData' of undefined or null reference
</code></pre>
<p>They brake the app completely. Any idea of what they are and where they came from?</p>
<p>I do not have anything remotely related in the codebase to <code>isPersonal</code> and <code>SavePersonalAndPaymentData</code>.</p>
| <reactjs><microsoft-edge> | 2019-04-04 17:06:47 | HQ |
55,522,300 | SSIS packages deployed on SQL Sever 2016 | I have deployed SSIS packages on sql server 2016 and these packages use tables on sql server 2008. Can I able work on tables that is sql server 2008 | <sql-server><ssis> | 2019-04-04 17:57:30 | LQ_EDIT |
55,524,855 | $(document).ready vs window.onload vs window.addEventListener | <p>I had been researching on the above 3 JS/jQuery commands and I want to execute the JavaScript after EVERYTHING is loaded, but seems all the above 3 scripts are fired before the DIV is loaded. Can anyone tell me how to execute a JS script after EVERYTHING is loaded. Please see the following html : If you carefully notice this, you will see the alert pop up window before the DIV is loaded. I am running it in Chrome. </p>
<pre><code> <script>
window.addEventListener( 'load', function( event ) {
alert("test");
});
$(document).ready(function(){
alert("test");
});
window.onload = function(e){
alert("test");
}
</script>
<body>
<div>
Hello There!!!
</div>
</body>
</code></pre>
| <javascript><jquery> | 2019-04-04 21:03:14 | LQ_CLOSE |
55,525,372 | Where do I start with first c# project using amazon and netflix? | <p>I need to learn c# for work and I thought the best way for me to get started would be with a passion project. </p>
<p>I love movies and tv and was thinking about creating a c# database app that would take data from my netflix and amazon accounts and show me exactly what I've already watched.</p>
<p>Is this possible? If so, where do I start?</p>
| <c#><project><netflix> | 2019-04-04 21:44:31 | LQ_CLOSE |
55,525,773 | Don't really understand the $_SESSION variable | I'm trying to create a login form (new to php and coding) and I made it work but I don't exactly understand what I'm doing in my code and would love to understand it. I included notes about what I understand and what I dont understand in my code.
1.Anyways, my main problem is with the "$_SESSION['umsco'] = $username" why do you need to apply the $username variable to it for it to work?
2.I don't really understand the $result thing in general.
Thank you to anyone who is willing to help me in advance, it's honestly appreciated.
```php
// I include the database file so we can get the information from there and apply it in here as well.
include "dbc.php";
// here we select the variables we want from the table 'members'.
$sql = "SELECT id, firstName, lastName FROM members";
// here we do something that I dont really know but this is standard procedure.
$result = mysqli_query($conn, $sql);
// declaring username
$username = $_POST["username"];
$password = $_POST["password"];
// my result thing, again, standard procedure.
$result = $conn->query($sql);
// we insert all values in row, standard procedure.
$row = $result->fetch_assoc();
// here we check if the username is the same as the database.
if ($username == $row["firstName"]) {
// if it's correct then we start a session
session_start();
// we give a session some random letters or numbers and set it to $username, not exactly sure why, but it wont work without it.
$_SESSION['umsco'] = $username;
// we change the location to secrect.php
header("location: secret.php");
}
// we close the connection, not sure if this is needed, but it seems logical.
$conn->close();
``` | <php><session-variables><session-state> | 2019-04-04 22:23:55 | LQ_EDIT |
55,526,046 | Is there a way to create an unordered from an array in Javascript? | I want to use pure html and javascript instead of HAML.
Before when I was working with this form project I loop through the array like this
- @item1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
- item1.each_with_index do |item, i|
%li.option
%input.option-input{name: 'options', type: 'radio', value: i, id: 'options-#{i}"}/
%label.option-label{:for => "options-#{i}"}= item1 | <javascript><html><ruby><haml> | 2019-04-04 22:56:19 | LQ_EDIT |
55,526,064 | TryGetValue pattern with C# 8 nullable reference types | <p>I'm playing with porting some code to C# to enable nullable reference types, and I've encountered some functions in our code that use the <code>TryGetValue</code> pattern.</p>
<p>That is, something like this:</p>
<pre><code>public bool TryGetSession(string key, out Session session) {
session = null; // assign default
// code which looks for a session based on the key, etc
// return true or false if we found the session key
}
</code></pre>
<p>The pattern which we're trying to express here is "if the return value is true, then <code>session</code> is non-null. If false, then don't even attempt to look at the session, it's garbage.</p>
<p>The problem is I now get a warning on <code>session = null</code>, but I'm forced to put <em>something</em> there as <code>out</code> parameters MUST be populated by the function.</p>
<p>Is there a good answer here? My thoughts:</p>
<p>I could drop the <code>TryGet</code> pattern and embrace the nullable reference types (This is what other languages like Swift seem to do) e.g. </p>
<pre><code>Session? GetSession(string key);
</code></pre>
<p>Or, I could live up to my "non-null" promise using a placeholder value e.g.</p>
<pre><code>public bool TryGetSession(string key, out Session session) {
session = new InvalidSession(); // assign default
...
}
</code></pre>
<p>Are there any other options?</p>
| <c#><nullable> | 2019-04-04 22:58:40 | HQ |
55,529,555 | Could someone help me understand why this code actually works? | <p>I've been following the Laracasts "PHP Practitioner" series to help me get a basic understanding of PHP and at this point, my code works fine and doesn't return any errors, but I can't quite grasp how it actually works.</p>
<p>If you've watched the series, in <a href="https://laracasts.com/series/php-for-beginners/episodes/20" rel="nofollow noreferrer">Episode 20</a>, in our QueryBuilder.php file, we create an insert method with 2 parameters "$table" and "$parameters". I get why "$table" works as we assign it to the 'users' table in the add-name.php file, but how does the text in the form get submitted to the database via the $parameters param? I'm not exactly following the logic so well and I just want to fully understand what's happening here. </p>
<p>For those of you who haven't watched the series and have no idea what I'm talking about, we basically make a simple form with an input and a submit button and at this point, we are sending the info from the form into a DB. Here's the snippet from the QueryBuilder.php file:</p>
<pre><code>public function insert($table, $parameters)
{
$sql = sprintf(
'INSERT INTO %s(%s) values (%s)',
$table,
implode(', ', array_keys($parameters)),
':' .implode(', :', array_keys($parameters))
);
try{
$statement = $this->pdo->prepare($sql);
$statement->execute($parameters);
} catch (Exception $e){
die($e->getMessage());
}
}
</code></pre>
<p>and here's the add-name.php file:</p>
<pre><code><?php
$app['database']->insert('users', [
'name' => $_POST['name']
]);
header('Location: /laracasts/PHP');
</code></pre>
| <php> | 2019-04-05 06:38:17 | LQ_CLOSE |
55,529,788 | Get each elements of JSONArray | <p>i have a jsonArray like this. how can i get each array element form java</p>
<pre><code>[{"subjectname":"Health","classKey":5084485095784448,"staffKeyId":4819823842295808,"subjectKeyId":5756749483081728,"class":"8C"},{"subjectname":"Civics","classKey":5641826627223552,"staffKeyId":4549155540172800,"subjectKeyId":5563198258282496,"class":"8B"}]
</code></pre>
| <java><json> | 2019-04-05 06:55:59 | LQ_CLOSE |
55,529,878 | I need to remove multiple occurrence of char and leave only one | I need the code in C to replace multiple occurrences of individual characters with a single char
For Example:
char = {A,a,B,b,b}
output:
A,B | <c> | 2019-04-05 07:01:58 | LQ_EDIT |
55,531,599 | perfomance mixing javascript and jquery | <p>There are lots of discussion about this topic, but I wanna clear my ambiguity or confusion - <strong>my mixed code make sense or not.</strong> </p>
<p>Previously I thought <code>Jquery</code> is most comfortable in every aspects, from easiness to the level of flexibility. There is no doubt we can create the vast and robust client side application with the usage of Jquery.</p>
<p>So I had been using <code>Jquery</code> even in small and simple tasks. But while concerning about performance, I found peoples are recommending pure JavaScript if you can. I read in lot of forums, question/answers about the performance, then I realized I am using Jquery unnecessarily.</p>
<p>For example, I had using to do simple task </p>
<pre><code>var value = $('#div').text();
</code></pre>
<p>instead of </p>
<pre><code>var value = document.getElementById('div').innerHTML;
</code></pre>
<p>In addition, I had used maximum <code>$.each</code> even in simple selection which can be done with <code>document.querySelector</code> or pure javascript <code>for</code> loop </p>
<p>I can't avoid the usage of Jquery, but can minimize. So, browser have to load jquery. </p>
<p>Now I have minimized jquery usage in external <code>.js</code> file, using pure javascript code for simple task and using jquery for only complex. </p>
<p><em>Now my question is</em> </p>
<p><strong>Now would my perfomance be better and fast than previous my way (where I had used jquery only) ?</strong></p>
<p>OR</p>
<p><strong>if $ is initialized once, does it affect other pure javascript code ?</strong></p>
<p>To be more clear,</p>
<p><strong>Does second one is faster than first one ?</strong></p>
<p><strong>Jquery only</strong></p>
<pre><code>function purchase(){
$.ajax({
url:"fetch.php",
method:"POST",
data:{prch_id:'pty'},
beforeSend: function() {
$('.pty').html('Processsing');
},
success:function(data){
$('.pty').html(data);
auto_select();
}
});
}
</code></pre>
<p><strong>Javascript with Jquery</strong></p>
<pre><code>function purchase(){
var http = null;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}
else{
http = new ActiveXObject('Microsoft.XMLHTTP');
}
var vars = "prch_id=pty";
http.open('POST','fetch.php',true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
var data = http.responseText;
$('.pty').html(data);
auto_select();
}
}
http.send(vars);
$('.pty').html('Processsing');
}
</code></pre>
<p>if we used pure JavaScript only - it is sure it is speedy, but I want to know mixing of jquery and JavaScript improves or does not make any sense.</p>
| <javascript><jquery> | 2019-04-05 08:51:32 | LQ_CLOSE |
55,532,451 | mysqli_fetch_all() not working when table name is a variable | <p>I am trying to get an array from a database. I got the table name from a previous PHP file and I am trying to return the array. However, it only responds with an error.</p>
<p>If I replace the $db_name in the query with the name as a string it works fine but that is not what I want. I don't know why it is not working. Is it just not liking the query? It only does not work when I put in the table name as a variable.</p>
<pre><code> $db_name = $_SESSION['databaseMenu'];
echo $db_name;
$sql="SELECT feed FROM '".$db_name."' ";
$result=mysqli_query($con,$sql);
// Fetch all
$outp = mysqli_fetch_all($result,MYSQLI_ASSOC);
$arra = array_values($outp);
return $arra;
</code></pre>
<p>Like I said earlier, when the query is a simple text it returns the array however when I put in the variable it responds with the error:
'''
Warning: mysqli_fetch_all() expects parameter 1 to be mysqli_result, boolean given in
'''</p>
<p>Any advice is appreciated.</p>
| <php> | 2019-04-05 09:39:22 | LQ_CLOSE |
55,533,312 | How to create a letter spacing attribute with pycairo? | <p>I'm using Pango + Cairo (through GObject) to render text with python3.7, and would like to set the <em>letter spacing</em> by creating an attribute and attaching that attribute to my pango layout.</p>
<p>In the gnome documentation for pango, I can see that there should be a function called <a href="https://developer.gnome.org/pango/stable/pango-Text-Attributes.html#pango-attr-letter-spacing-new" rel="noreferrer"><code>pango_attr_letter_spacing_new</code></a> (since v1.6). However, if I run <code>Pango.attr_letter_spacing_new</code>, I get the error:</p>
<pre><code>AttributeError: 'gi.repository.Pango' object has no attribute 'attr_letter_spacing_new'
</code></pre>
<p>This feels a bit strange, since I can use the <a href="https://developer.gnome.org/pango/stable/pango-Text-Attributes.html#pango-attr-type-get-name" rel="noreferrer"><code>pango_attr_type_get_name</code></a> which should only have been available since v1.22.</p>
<p>I have a work-around by using markup with <code><span letter_spacing="1234"></code> but I would rather not go down this route.</p>
<h2>Minimal "Working" Example</h2>
<pre class="lang-py prettyprint-override"><code># pip install pycairo==1.18.0 pygobject==3.32.0
import cairo
import gi
gi.require_version('Pango', '1.0')
gi.require_version('PangoCairo', '1.0')
from gi.repository import Pango, PangoCairo
width, height = 328, 48
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
context = cairo.Context(surface)
layout = PangoCairo.create_layout(context)
font_desc = Pango.font_description_from_string('Sans, 40px')
layout.set_font_description(font_desc)
# What I can do
layout.set_markup(f'<span letter_spacing="{1024 * 10}">Hello World</span>')
# What I would like to do
if False:
letter_spacing_attr = Pango.attr_letter_spacing_new(1024 * 10)
attr_list = Pango.AttrList()
attr_list.insert(letter_spacing_attr)
layout.set_attributes(attr_list)
layout.set_text('Hello World')
PangoCairo.show_layout(context, layout)
with open('help-me.png', 'wb') as image_file:
surface.write_to_png(image_file)
</code></pre>
<h3>Manually creating a LetterSpacing attribute</h3>
<p>I have been able to find the enum value <code>Pango.AttrType.LETTER_SPACING</code>, which allows me to do something like this:</p>
<pre><code>c = Pango.AttrClass()
c.type = Pango.AttrType.LETTER_SPACING
a = Pango.Attribute()
a.init(c)
</code></pre>
<p>However, I haven't been able to find a way to set the value of it, and it makes me think it is the wrong way to approach things :|</p>
<p>Insert this into an <code>Pango.AttrList</code>, gave an error (not surprisingly) and made the python process segfault next time I did something with Pango: </p>
<pre><code>** (process:17183): WARNING **: 12:00:56.985: (gi/pygi-struct-marshal.c:287):pygi_arg_struct_from_py_marshal: runtime check failed: (g_type_is_a (g_type, G_TYPE_VARIANT) || !is_pointer || transfer == GI_TRANSFER_NOTHING)
</code></pre>
<h3>Other leads</h3>
<p>.. that sadly have lead nowhere :(</p>
<ul>
<li><a href="https://developer.gnome.org/pygtk/stable/class-pangoattribute.html" rel="noreferrer">pygtk listing a function <code>pango.AttrLetterSpacing</code></a>
<ul>
<li><code>Pango.AttrLetterSpacing</code> => <code>'gi.repository.Pango' object has no attribute 'AttrLetterSpacing'</code></li>
<li><code>Pango.Attrbute.LetterSpacing</code> => <code>type object 'Attribute' has no attribute 'LetterSpacing'</code></li>
</ul></li>
<li>the documentation for the pango packge for Vala (which seems to use GObject as well), also shows the <a href="https://valadoc.org/pango/Pango.attr_letter_spacing_new.html" rel="noreferrer"><code>attr_letter_spacing_new</code> function</a> -- this doesn't really help that much, but suggests that the function should be available through GObject, although I haven't tried.</li>
</ul>
| <python><pygobject><pango> | 2019-04-05 10:22:32 | HQ |
55,533,718 | PostgreSQL Why where does not work with age function | I use age function in where but i don't know why it dose not work
```
select t1.id,date_part('year',age(t1.tdate,t2.birthday)) as age
FROM table t1
LEFT JOIN table2 t2 ON t1.id = t1.id
WHERE date_part('year',age(t1.tdate,t2.birthday)) >= 10
```
the result is incorrect
-----------------
![the result][1]
[1]: https://i.imgur.com/WeRPAqa.jpg "result"
<br/>
the result should be <br/>
-----------------
![the result][2]
[2]: https://i.imgur.com/pPvzcvA.jpg "result" | <postgresql> | 2019-04-05 10:46:41 | LQ_EDIT |
55,534,025 | How to generate new image using deep learning, from new features | <p>If i have a dataset consisting by a list of images each associated with a series of features; there is a model that, once trained, generates new images upon entering a new list of features?</p>
| <python><keras><deep-learning><conv-neural-network><dcgan> | 2019-04-05 11:06:09 | LQ_CLOSE |
55,534,481 | How would I submit my form data in a proper way by mailing in a simple HTML website? | <p>I'm tried to get this type of mail from my HTML website.</p>
<p><strong>Name:</strong> XYZ</p>
<p><strong>Email:</strong> xyz@gmail.com</p>
<p><strong>Message:</strong> msg</p>
<p>Can anybody help me to get this type of mail when somebody fills my HTML form, Remember I don't want to use any programming language like PHP. If anyone has javascript code for it then please share it.</p>
| <javascript><html> | 2019-04-05 11:34:07 | LQ_CLOSE |
55,535,436 | Taking more time if value is not available in drop down using selenium | I'm trying to select the value but if value is not available in dropdown ,selenium code taking too much time to go to next line,Please provide help how to resolve this problem.
Code:
System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
String baseURL = "http://demo.guru99.com/test/newtours/register.php";
WebDriver driver = new FirefoxDriver();
driver.get(baseURL);
try{
Select drpCountry = new Select(driver.findElement(By.name("country")));
drpCountry.selectByVisibleText("ANTARCTICAS");
}catch(Exception e){
System.out.println(e.getMessage());
} | <java><selenium><firefox><geckodriver><selenium-firefoxdriver> | 2019-04-05 12:29:55 | LQ_EDIT |
55,536,299 | check id jquery object is empty | <p>I'm trying to check if a jquery object is null to use it this way</p>
<pre><code>var reminder_history_div = $(".history-container");
if(reminder_history_div)
reminder_history_div.scrollTop(reminder_history_div[0].scrollHeight);
</code></pre>
<p>but <code>reminder_history_div</code> is not null or empty its and object ,with some info ,what is the correct way to check if is empty?maybe:</p>
<pre><code>if(reminder_history_div.length > 0)
</code></pre>
| <javascript><jquery> | 2019-04-05 13:17:19 | LQ_CLOSE |
55,536,461 | flutter: Unhandled Exception: Bad state: Cannot add new events after calling close | <p>I am trying to use the bloc pattern to manage data from an API and show them in my widget. I am able to fetch data from API and process it and show it, but I am using a bottom navigation bar and when I change tab and go to my previous tab, it returns this error: </p>
<blockquote>
<p>Unhandled Exception: Bad state: Cannot add new events after calling
close.</p>
</blockquote>
<p>I know it is because I am closing the stream and then trying to add to it, but I do not know how to fix it because not disposing the <code>publishsubject</code> will result in <code>memory leak</code>.
here is my Ui code:</p>
<pre><code>class CategoryPage extends StatefulWidget {
@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
@override
void initState() {
serviceBloc.getAllServices();
super.initState();
}
@override
void dispose() {
serviceBloc.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: serviceBloc.allServices,
builder: (context, AsyncSnapshot<ServiceModel> snapshot) {
if (snapshot.hasData) {
return _homeBody(context, snapshot);
}
if (snapshot.hasError) {
return Center(
child: Text('Failed to load data'),
);
}
return CircularProgressIndicator();
},
);
}
}
_homeBody(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
return Stack(
Padding(
padding: EdgeInsets.only(top: screenAwareSize(400, context)),
child: _buildCategories(context, snapshot))
],
);
}
_buildCategories(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, crossAxisSpacing: 3.0),
itemCount: snapshot.data.result.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: CategoryWidget(
title: snapshot.data.result[index].name,
icon: Icons.phone_iphone,
),
onTap: () {},
);
},
),
);
}
</code></pre>
<p>here is my bloc code:</p>
<pre><code>class ServiceBloc extends MainBloc {
final _repo = new Repo();
final PublishSubject<ServiceModel> _serviceController =
new PublishSubject<ServiceModel>();
Observable<ServiceModel> get allServices => _serviceController.stream;
getAllServices() async {
appIsLoading();
ServiceModel movieItem = await _repo.getAllServices();
_serviceController.sink.add(movieItem);
appIsNotLoading();
}
void dispose() {
_serviceController.close();
}
}
ServiceBloc serviceBloc = new ServiceBloc();
</code></pre>
<p>I did not include the repo and API code because it is not in the subject of this error.</p>
| <dart><flutter><bloc> | 2019-04-05 13:25:15 | HQ |
55,536,977 | What is this time format? "2019-03-31T08:29:00" | <p>I am trying to determine what time format is this string "<strong>2019-03-31T08:29:00</strong>" so I can convert it to datetime object but I can't find the answer to this.</p>
<p>Can somebody help please?</p>
| <python><datetime> | 2019-04-05 13:54:19 | LQ_CLOSE |
55,538,543 | Relational DB : is it a bad practice to store data on relationships? | <p>I work for a firm with a relational database. Some of my colleagues once told me that storing data directly on relationships (and not on entities) was a bad pratice. I can't remember why. Can you help me with that ? Do you agree ? What are the risks ?</p>
<p>Many thanks !</p>
| <sql><database><relational-database><relationship> | 2019-04-05 15:13:22 | LQ_CLOSE |
55,539,274 | Check null or empty IEnumerable<double> in c# | What is the best way to check null of empty for IEnumerable<double> ReturnsList in c#
What I have tried so far is
return returnList != null && returnList.Any();
but I get a message that it will always return of this expression will always return true
| <c#><math.net> | 2019-04-05 15:54:13 | LQ_EDIT |
55,539,328 | How to configure service provider with spring-security-saml2 to consume EncryptedAssertions? | <p>I am using this excellent repo <a href="https://github.com/vdenotaris/spring-boot-security-saml-sample" rel="noreferrer">vdenotaris/spring-boot-security-saml-sample</a> as a guide and I am trying to set it up to verify and decrypt incoming SAML messages that contain <code>EncryptedAssertion</code>.</p>
<p>The idP's metadata defines the signing and encrypting key in the XML. That is setup in the service provider.</p>
<pre><code>@Bean
public ExtendedMetadata extendedMetadata() {
ExtendedMetadata extendedMetadata = new ExtendedMetadata();
extendedMetadata.setIdpDiscoveryEnabled(false);
extendedMetadata.setSignMetadata(false);
extendedMetadata.setEcpEnabled(true);
return extendedMetadata;
}
@Bean
@Qualifier("metadata")
public CachingMetadataManager metadata() throws MetadataProviderException {
List<MetadataProvider> providers = new ArrayList<MetadataProvider>();
try {
ClasspathResource metadata = new ClasspathResource("/metadata/the-idp-metadata.xml");
Timer timer = new Timer(true);
ResourceBackedMetadataProvider provider = new ResourceBackedMetadataProvider(timer, metadata);
provider.setParserPool(ParserPoolHolder.getPool());
provider.initialize();
ExtendedMetadataDelegate exMetadataDelegate = new ExtendedMetadataDelegate(provider, extendedMetadata());
exMetadataDelegate.setMetadataTrustCheck(true);
exMetadataDelegate.setMetadataRequireSignature(false);
providers.add(exMetadataDelegate);
}
catch(ResourceException ex) {
throw new MetadataProviderException(ex.getMessage(), ex);
}
CachingMetadataManager cmm = new CachingMetadataManager(providers);
cmm.setRefreshCheckInterval(0);
return cmm;
}
</code></pre>
<p>When I manually send it a sample of a SAML message that has an encrypted assertion it fails with the following message.</p>
<pre><code>org.springframework.security.authentication.AuthenticationServiceException: Incoming SAML message is invalid
at org.springframework.security.saml.SAMLProcessingFilter.attemptAuthentication(SAMLProcessingFilter.java:91)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.saml.metadata.MetadataGeneratorFilter.doFilter(MetadataGeneratorFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.opensaml.common.SAMLException: Unsupported request
at org.springframework.security.saml.processor.SAMLProcessorImpl.getBinding(SAMLProcessorImpl.java:265)
at org.springframework.security.saml.processor.SAMLProcessorImpl.retrieveMessage(SAMLProcessorImpl.java:172)
at org.springframework.security.saml.SAMLProcessingFilter.attemptAuthentication(SAMLProcessingFilter.java:80)
... 53 common frames omitted
</code></pre>
<p>I've read here <a href="https://docs.spring.io/spring-security-saml/docs/current/reference/html/configuration-metadata.html#configuration-metadata-extended" rel="noreferrer">Metadata Configuration</a> that you can configure the signing and encryption key that the idp uses in order for the assertion to be decrypted (at least that is what I am assuming).</p>
<p>Is that the correct way to go about having the service consume <code>EncryptedAssertion</code>s? I keep hitting this invalid message wall and not finding a good solid tutorial or documentation that explicitly describe how to handle this. Also unsure if the solution lies in the <code>WebSSOProfileConsumerImpl</code> class that I have to modify?</p>
<p>Any help or examples would be greatly appreciated.</p>
| <java><spring-boot><spring-security><saml-2.0><spring-security-saml2> | 2019-04-05 15:57:36 | HQ |
55,539,523 | How to reverse the scroll movement? | <p>I try to make a reverse navigation. I show the page from the bottom with scrollTo.
I want reverse the wheel movement, when the whell movement is down the page goes to the top.</p>
<p>The body has a fix height so I use:</p>
<pre><code> window.scrollTo(0, 2000);
</code></pre>
| <jquery> | 2019-04-05 16:10:32 | LQ_CLOSE |
55,539,578 | call service from diffrenent component to display a message | I have a a shared comPonent alert wHich display different alerts (error, success..) that uses a service alertService.
and I have diffeent component that uses the alertServices.
the alert component is called in the appComponent
<app-alert></app-alert>
when I call the service from another component the alert don't displayed it displyaed only when I call <app-alert></app-alert> in the component that call the service. | <angular><typescript><observable><angular2-services> | 2019-04-05 16:15:25 | LQ_EDIT |
55,540,296 | correct below tsql. I am getting error below | DECLARE @hashThis nvarchar(max);
SET @hashThis = CONCAT(
Branch | '|' |
DiscountGroup | '|' |
ItemNumber | '|' |
PriceColumn |'|' |
LastUpdatedDate |'|' |
PMBasis |'|' |
PMOper |'|' |
PMMult |'|' |
DeletedOnDate |'|' |
PriceMatrixKey |'|' |
ODS_INSERT_TS
)
SELECT HASHBYTES('MD5', @hashThis); | <sql-server><tsql> | 2019-04-05 17:02:43 | LQ_EDIT |
55,541,817 | What would be the correct view that needs to be created to meet the requirements? | I have a set of tables given to me and a specific business requirement that needs to be solved by creating a View in SQL. I am having trouble with understanding joins and stuff etc. I have made an attempt, but I think I am completely wrong and need some help.
The tables are as follows:
tblClients (ClientID, ClientName, ClientAddress, ClientCity, ClientProvince, ClientPostalCode, ClientPhone, ClientEmail)
tblVehicle (VehicleID, VehicleMake, VehicleModel, VehicleYear, ClientID)
tblEmployees (EmployeeID, EmployeeFirstName, EmployeeLastName, EmployeeAddress, EmployeeCity, EmployeeProvince, EmployeePostalCode, EmployeePhone, EmployeeEmail)
tblWorkOrders (OrderID, VehicleID, EmployeeID, WorkDescription, PartsCost, LabourCost, IssueDate, CompletionDate)
________________________________________________________________________________
and the Requirement is this:
A web application is being considered that will allow customers with accounts – using their email address as a login – to view their invoice / work order history with the garage.
Using SQL, create a view that will allow a customer to see work done on each of their cars, including the work description, costs and dates but not which employee completed the work.
________________________________________________________________________________
WHAT I HAVE SO FAR:
CREATE VIEW WORK_HISTORY AS
SELECT WORKDESCRIPTION, PARTSCOST,LABOURCOST, ISSUEDATE, COMPLETIONDATE
FROM TBLWORKORDERS LEFT OUTER JOIN TBLVEHICLE
ON TBLWORKORDERS.VEHICLEID = TBLVEHICLE.VEHICLEID
I dont think its too complicated, but I am new to SQL, so all your help and criticism will be appreciated. If you need anything else please let me know and I will edit as necessary. Thank you! | <sql><sql-server> | 2019-04-05 18:58:11 | LQ_EDIT |
55,541,912 | Using an app.config file with NUnit3 in a .NET Core console app | <p><strong>The Environment:</strong></p>
<p>I've got three projects in my solution currently:</p>
<ul>
<li>A .NET Standard 2.0 library with some code I'd like to test.</li>
<li>A .NET Core 2.2 console app that references the library to make sure it works.</li>
<li>A .NET Core 2.2 console app created by using the "NUnit Test Project" template in VS.</li>
</ul>
<p>The dependencies in my test project all are all from NuGet:</p>
<ul>
<li>Moq Version="4.10.1"</li>
<li>nunit" Version="3.11.0"</li>
<li>NUnit.ConsoleRunner" Version="3.10.0"</li>
<li>NUnit3TestAdapter" Version="3.13.0"</li>
<li>Microsoft.NET.Test.Sdk" Version="16.0.1"</li>
</ul>
<hr>
<p><strong>The Problem:</strong></p>
<p>The .NET standard library relies on an app.config file being present in any application that uses it. It uses <a href="https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationsection?view=netframework-4.7.2" rel="noreferrer">ConfigurationSection</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationelement?view=netframework-4.7.2" rel="noreferrer">ConfigurationElement</a> attributes to map the values to a class, very similar to this answer: <a href="https://stackoverflow.com/a/14782024/301857">A custom config section with nested collections</a></p>
<p>The .NET Core console app has an app.config file in it, and the library is able to parse values out of it just fine and use them. Yay.</p>
<p>The NUnit console app, on the other hand, has the same app.config file in it, but the library can't seem to see it. As soon as it tries to read a value using <code>ConfigurationManager.GetSection("...")</code> it returns <code>null</code>.</p>
<p>Has anyone gotten an app.config file to work with NUnit3 in an environment like this?</p>
<hr>
<p><strong>What I've Tried:</strong></p>
<p>It <em>seems</em> like <a href="https://github.com/nunit/docs/wiki/Configuration-Files" rel="noreferrer">it supports config files</a>, but I'm not sure if the docs are referring to some special NUnit config file or an app.config file.</p>
<ul>
<li>I tried renaming app.config to my_test_project_name.dll.config</li>
<li>I set the config file "Copy to output directory" setting to "Copy always"</li>
<li>I tried every similar name I could think of <em>(app.config, App.config, my_test_project_name.config, my_test_project_name.dll.config, etc)</em></li>
</ul>
<p>I also tried a few things inside the one test I've written so far, to attempt to set the config file somehow, such as a suggestion to use <code>AppDomain.CurrentDomain.SetData()</code> (didn't work, possibly because NUnit3 doesn't support AppDomain):</p>
<pre><code>AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Path\To\My\Tests\my_test_project_name.dll.config");
</code></pre>
<p>Although there are tests in the NUnit repo that seem to suggest <a href="https://github.com/nunit/nunit3-vs-adapter-demo/blob/master/src/csharp/ConfigFileTests.cs" rel="noreferrer">using a configuration file in NUnit3 is possible</a>, that particular test file is only referenced in the <a href="https://github.com/nunit/nunit3-vs-adapter-demo/blob/master/solutions/vs2017/CSharpTestDemo/CSharpTestDemo.csproj#L49" rel="noreferrer">.NET 4.5 demo project</a>, not the <a href="https://github.com/nunit/nunit3-vs-adapter-demo/blob/master/solutions/vs2017/NUnit3CoreTestDemo/NUnit3CoreTestDemo.csproj#L10" rel="noreferrer">.NET Core demo project</a>.</p>
| <c#><.net-core><nunit><app-config><nunit-3.0> | 2019-04-05 19:06:18 | HQ |
55,543,462 | How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 5 alamofire 5.0.3 | <p>in alamofire 4 I used this code to disable sever evaluation:</p>
<pre><code>private var Manager : Alamofire.Session = {
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = ["serverurl.com": .disableEvaluation]
// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.Session.defaultHTTPHeaders
let man = Alamofire.Session(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustManager(policies: serverTrustPolicies)
)
return man
}()
</code></pre>
<p>but is not working anymore in alamofire 5 with swift 5 xcode 10.2, I got this errors.</p>
<blockquote>
<p>Use of undeclared type 'ServerTrustPolicy'
Type 'Session' has no member 'defaultHTTPHeaders'</p>
</blockquote>
<p>but I cant find a new way to make this work with alamofire 5.</p>
| <ios><swift><alamofire> | 2019-04-05 21:14:38 | HQ |
55,544,389 | Auto update isn't working in VSCode: Could not create temporary directory: Permission denied | <p>From certain point I started getting this error from time to time(I suppose it fires when editor tries to check for updates), and manual/auto update doesn't work. The only way I can update the editor is re-download the app and replace it manually.</p>
<p>Does someone face same issue and successfully resolved? </p>
<p><a href="https://i.stack.imgur.com/8tpAO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8tpAO.png" alt="Screenshot"></a></p>
| <visual-studio-code><access-rights> | 2019-04-05 23:12:04 | HQ |
55,545,086 | Why is the compiler still demanding a return statement? | <p>Why is my java compiler asking for a return statement when I've already placed one in my if statement loop? And how to I fix this so it returns the proper value?</p>
<pre><code>public static String checkNumbers(int x1, int y1, int x2, int y2, int x3, int y3) {
String x = "True";
String y = "False";
int[][] array = {{x1, y1}, {x2, y2}, {x3, y3}};
for (int i = 0; i < array.length; i++) {
if (array[0][0] == 5) {
return x;
} else return y;
}
}
</code></pre>
| <java><loops><methods><return> | 2019-04-06 01:27:50 | LQ_CLOSE |
55,545,448 | How can I use PHP in HTML? do I need to include a tag? | <p>I am trying to do something basic with PHP and HTML first before I get into something big. However, my html page doesn't seem to be processing PHP correctly.</p>
<p>I have the following php code in my html:</p>
<pre><code><?php echo '<p>Hello World</p>'; ?>
</code></pre>
<p>However, the output on the html page is:
'Hello World' on one line
but:</p>
<p>'; ?>
follows hello world
How can I fix this so I get 'hello world'?</p>
| <php><html> | 2019-04-06 02:55:41 | LQ_CLOSE |
55,546,873 | How do I flatten a tensor in pytorch? | <p>Given a tensor of multiple dimensions, how do I flatten it so that it has a single dimension?</p>
<p>Eg:</p>
<pre><code>>>> t = torch.rand([2, 3, 5])
>>> t.shape
torch.Size([2, 3, 5])
</code></pre>
<p>How do I flatten it to have shape:</p>
<pre><code>torch.Size([30])
</code></pre>
| <pytorch> | 2019-04-06 07:34:45 | HQ |
55,547,700 | who to initialise all the value of an array to zero | In cpp imagine if I am writing like
int n;cin>>n;
int a[n]={0};
what I am expecting is that this code will convert all the n elements value to zero but instead this is giving me error
"variable sized object may not be initialised" | <c++> | 2019-04-06 09:29:14 | LQ_EDIT |
55,548,153 | Flutter Navigator.of(context).pop vs Navigator.pop(context) difference | <p>What's the difference between <code>Navigator.of(context).pop</code> and <code>Navigator.pop(context)</code>?</p>
<p>To me both seems to do the same work, what is the actual difference. Is one deprecated? </p>
| <dart><flutter> | 2019-04-06 10:25:57 | HQ |
55,549,311 | how to clear screen in runtime in C++ using XCODE? | #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(){
printf("*********");
system("clear");
printf("#####");
}
Usually its works but it is networking in XCODE. | <c++><xcode> | 2019-04-06 13:00:28 | LQ_EDIT |
55,549,843 | Pytorch doesn't support one-hot vector? | <p>I am very confused by how Pytorch deals with one-hot vectors. In this <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="noreferrer">tutorial</a>, the neural network will generate a one-hot vector as its output. As far as I understand, the schematic structure of the neural network in the tutorial should be like:</p>
<p><a href="https://i.stack.imgur.com/1v35k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1v35k.png" alt="enter image description here"></a></p>
<p>However, the <code>labels</code> are not in one-hot vector format. I get the following <code>size</code></p>
<pre><code>print(labels.size())
print(outputs.size())
output>>> torch.Size([4])
output>>> torch.Size([4, 10])
</code></pre>
<p>Miraculously, I they pass the <code>outputs</code> and <code>labels</code> to <code>criterion=CrossEntropyLoss()</code>, there's no error at all.</p>
<pre><code>loss = criterion(outputs, labels) # How come it has no error?
</code></pre>
<h2>My hypothesis:</h2>
<p>Maybe pytorch automatically convert the <code>labels</code> to one-hot vector form. So, I try to convert labels to one-hot vector before passing it to the loss function.</p>
<pre><code>def to_one_hot_vector(num_class, label):
b = np.zeros((label.shape[0], num_class))
b[np.arange(label.shape[0]), label] = 1
return b
labels_one_hot = to_one_hot_vector(10,labels)
labels_one_hot = torch.Tensor(labels_one_hot)
labels_one_hot = labels_one_hot.type(torch.LongTensor)
loss = criterion(outputs, labels_one_hot) # Now it gives me error
</code></pre>
<p>However, I got the following error</p>
<blockquote>
<p>RuntimeError: multi-target not supported at
/opt/pytorch/pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15</p>
</blockquote>
<p>So, one-hot vectors are not supported in <code>Pytorch</code>? How does <code>Pytorch</code> calculates the <code>cross entropy</code> for the two tensor <code>outputs = [1,0,0],[0,0,1]</code> and <code>labels = [0,2]</code> ? It doesn't make sense to me at all at the moment.</p>
| <python><machine-learning><pytorch> | 2019-04-06 14:02:52 | HQ |
55,549,874 | Verify if the user exists using Bcrypt and Spring | <p>I'm developing a login with sping and currently I have my password encrypted with Bcrypt.
I have a user on my h2 database and to verify if the user credentials are correct and don't know what is advised.Should decrypt both passwords and compare them (I think that not the correct way to do it of course) or should I use another mechanism to verify if the user's credetials are right?</p>
| <java><spring><spring-boot><bcrypt> | 2019-04-06 14:06:25 | LQ_CLOSE |
55,550,027 | c language homework... not solved | I'm homeworking now. Then one problem about increase/decrease operator err when I upload my explanation..
I tried while code to my problem then increase operator solved, but the decrease operator not solved..
the problem =
input variable x, and output x~x+5.After, output x~x-5. Use Increase / decrease operator to solve problem.
int x;
x = 10;
scanf("%d", &x);
int y = x + 6;
while (x < y)
{
printf("%d ", x);
++x;
}
output x~x+5 and after output x~x-5
[enter image description here][1]
[1]: https://i.stack.imgur.com/TFFNk.png | <c> | 2019-04-06 14:24:06 | LQ_EDIT |
55,550,033 | When I pass a list to another method, it returns NoneType. How can I fix this? | <p>I am trying to write a <code>main()</code> method that will call another method that reads the individual records within a .txt file; this is the <code>loadFile()</code> method. I've tested that the <code>loadFile()</code> method works and that the list it returns is ListType. However, when I call <code>loadFile()</code> within <code>main()</code> and try to act upon the list generated, I get an error like <code>TypeError: 'NoneType' object is not subscriptable</code>. Can someone help me ensure that the list I'm passing from one method to the next remains ListType? </p>
<pre><code>def loadFile(fileName):
openFile = open(fileName, 'r')
records = openFile.readlines()
recordList = []
for item in records:
recordList.append(item.rstrip('\n'))
print(recordList)
openFile.close()
def main():
nameFile = 'names.txt'
names = loadFile(nameFile)
print(names[12])
main()
</code></pre>
| <python><python-3.x> | 2019-04-06 14:25:28 | LQ_CLOSE |
55,551,038 | Program stuck after compilation when trying to acsses private multy-dimensional array | <p>After the code get compile my , while the program trying to access the private array it got stucked. i build a constructor and in this function i can print the array but after that if im trying to access the array from another function its not working.</p>
<p>In this code it stuck while working on mat(1,2) - trying to return arr[1][2]:</p>
<p>i tried to allocate the array in a different way, to make [] operator but nothing seems to work.</p>
<p>main file :</p>
<pre><code> #include "matrix.h"
#include <iostream>
int main() {
Matrix<4, 4> mat;
mat(1,2);
std::cout << mat << std::endl;
return 0;
}
</code></pre>
<p>.h file :</p>
<pre><code> #ifndef matrix_h
#define matrix_h
#include <iostream>
template <int row, int col ,typename T=int>
class Matrix {
public:
Matrix(int v = 0) { // constructor with deafault value of '0'
int **arr = new int*[row]; //initializing place for rows
for (int j = 0;j < row;j++) {
arr[j] = new int[col];
}
for (int i = 0;i < row;i++)
for (int j = 0;j < col;j++)
arr[i][j] = v;
}
T& operator () (int r, int c) const {
return arr[r][c];
}
friend std::ostream& operator<<(std::ostream& out,const Matrix <row,col,T> mat) {
for (int i = 0;i < row;i++) {
for (int j = 0;j < col;j++) {
out << mat(i,j) << " ";
}
out << std::endl;
}
return out;
}
private:
T** arr;
};
#endif //matrix_h
</code></pre>
| <c++><oop><templates><multidimensional-array><private> | 2019-04-06 16:23:14 | LQ_CLOSE |
55,551,587 | Creating new bash var from value of json bash var | My environment created a variable that looks like this:
SM_TRAINING_ENV={"additional_framework_parameters":{},"channel_input_dirs":{"training":"/opt/ml/input/data/training"},"current_host":"algo-1","framework_module":"sagemaker_tensorflow_container.training:main","hosts":["algo-1"],"hyperparameters":{"bool_param":true,"float_param":1.25,"int_param":5,"model_dir":"s3://bucket/detection/prefix/testing-2019-04-06-02-24-20-194/model","str_param":"bla"},"input_config_dir":"/opt/ml/input/config","input_data_config":{"training":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}},"input_dir":"/opt/ml/input","is_master":true,"job_name":"testing-2019-04-06-02-24-20-194","log_level":20,"master_hostname":"algo-1","model_dir":"/opt/ml/model","module_dir":"s3://bucket/prefix/testing-2019-04-06-02-24-20-194/source/sourcedir.tar.gz","module_name":"launcher.sh","network_interface_name":"ethwe","num_cpus":8,"num_gpus":1,"output_data_dir":"/opt/ml/output/data","output_dir":"/opt/ml/output","output_intermediate_dir":"/opt/ml/output/intermediate","resource_config":{"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"ethwe"},"user_entry_point":"launcher.sh"}
How can I create a new bash variable that is equal to the value of `SM_TRAINING_ENV["hyperparameters"]["model_dir"]`? | <bash><dictionary><indexing><awk><environment-variables> | 2019-04-06 17:19:46 | LQ_EDIT |
55,551,821 | Typescript 3 Angular 7 StopPropagation and PreventDefault not working | <p>I have a text input inside a div. Clicking on the input should set it to focus and stop the bubbling of the div click event. I've tried the <code>stopPropagation</code> and <code>preventDefault</code> on the text input event but to no avail. The console logs shows that the div click still executes regardless. How to stop the div click event from executing?</p>
<pre><code>// html
<div (click)="divClick()" >
<mat-card mat-ripple>
<mat-card-header>
<mat-card-title>
<div style="width: 100px">
<input #inputBox matInput (mousedown)="fireEvent($event)" max-width="12" />
</div>
</mat-card-title>
</mat-card-header>
</mat-card>
</div>
// component
@ViewChild('inputBox') inputBox: ElementRef;
divClick() {
console.log('click inside div');
}
fireEvent(e) {
this.inputBox.nativeElement.focus();
e.stopPropagation();
e.preventDefault();
console.log('click inside input');
return false;
}
</code></pre>
| <javascript><angular7><event-bubbling><typescript3.0> | 2019-04-06 17:47:23 | HQ |
55,551,910 | Why I got x=0.15000000000000002 during adding 0.050 in each step using while lopp in python | <p>I run the below python code, </p>
<pre><code>x=0
while x<1:
x+=0.050
print(x)
</code></pre>
<p>and got the following result. Which I don't understand. </p>
<p>0.05
0.1
0.15000000000000002
0.2
0.25
0.3
0.35
0.39999999999999997
0.44999999999999996
0.49999999999999994
0.5499999999999999
0.6
0.65
0.7000000000000001
0.7500000000000001
0.8000000000000002
0.8500000000000002
0.9000000000000002
0.9500000000000003
1.0000000000000002</p>
| <python-3.x> | 2019-04-06 17:57:56 | LQ_CLOSE |
55,551,911 | Newtonsoft exception throws, "Input string '08' is not a valid number" | <p>I am trying to make a basic c# code copied from the web (<a href="http://scriptopia.co.uk/Post.php?id=8" rel="nofollow noreferrer">http://scriptopia.co.uk/Post.php?id=8</a>) so as to familiarize myself with firebase. The code seems to work fine by sending the Time data to the database except for the 8th second. Can someone tell me why this strange behavior? </p>
<pre><code> while (true)
{
DateTime date = DateTime.Now;
string hour = date.ToString("HH");
string minutes = date.ToString("mm");
string seconds = date.ToString("ss");
string jsondata = "{'Time':{'Hour': " + hour + ",'Minute': " + minutes + ", 'Second': " + seconds + ", }}";
JObject data = JObject.Parse(jsondata);
string json = JsonConvert.SerializeObject(data);
var request = System.Net.WebRequest.CreateHttp("https://******.firebaseio.com/.json?auth=***db**secret***");
request.Method = "PATCH";
request.ContentType = "json";
var buffer = Encoding.UTF8.GetBytes(json);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
var response = request.GetResponse();
json = (new System.IO.StreamReader(response.GetResponseStream())).ReadToEnd();
}
</code></pre>
<p>I was hoping to receive continuous time data without any error, however in this case at the 8th second of every minute the code crashes. I tried running it in an online compiler and observed the same results.</p>
| <c#><firebase> | 2019-04-06 17:58:04 | LQ_CLOSE |
55,554,124 | Deleting element from List of object pointers with iterator pointer (C++) | <p>I have a List of object pointers, and I'm trying to delete an element with an iterator pointer and I keep getting build errors as I'm not sure what the proper way to go about this is. Here is some of the code in question. Also, here is my error in a pastebin.</p>
<pre>
class PlaneManager{
private:
list * planes = new list;
list::iterator * iter = new list::iterator;
public:
void DeletePlane(const string& tailNumber);
</pre>
<p>Here is the function in question that throws errors.</p>
<p><pre></p>
<code>void PlaneManager::DeletePlane(const string& tailNumber){
if(PlaneExists(tailNumber)){
for (iter = planes->begin(); iter != planes->end();++iter){
if(iter.GetTailNumber() == tailNumber)
planes->erase(iter);
}
}else
cout << "Couldn\'t find that plane." << endl;
}
</code></pre>
<p>Thanks for any insight you can provide, as I'm still a little lost with pointers.</p>
| <c++> | 2019-04-06 22:47:40 | LQ_CLOSE |
55,554,245 | LocalDateTime variable stopped being live | <p>When I first ran my code (below) it printed out the live time (ignore the "LOL", that was for debugging purposes..), but I've been running it over and over for a while now while doing other stuff and I realized it wasn't printing the live time anymore, just the time it registered the first time I ran it.
Code:</p>
<pre class="lang-java prettyprint-override"><code> public static String classCheck(){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:MM");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)+"LOL");
int currentTime = toMins(dtf.format(now));
//Beging collecting preset class timings..
String classOneBegin = "11:00", classTwoBegin = "12:30", classThreeBegin = "14:00", classFourBegin = "16:30", classFourEnd = "18:00";
int classOneBeginX, classTwoBeginX, classThreeBeginX, classFourBeginX, classFourEndX;
classOneBeginX = timeCheck.toMins(classOneBegin);
classTwoBeginX = timeCheck.toMins(classTwoBegin);
classThreeBeginX = timeCheck.toMins(classThreeBegin);
classFourBeginX = timeCheck.toMins(classFourBegin);
classFourEndX = timeCheck.toMins(classFourEnd);
//...End. I feel confident that I could've found a faster, more inclusive solution to this, but time is of the essence..
//Now to compare the time with each "cycle" and return an int that represent the current class.
if (currentTime >= classOneBeginX && currentTime <= classTwoBeginX) {
return "4";
}else if(currentTime >= classTwoBeginX && currentTime <= classThreeBeginX){
return "1";
}else if(currentTime >= classThreeBeginX && currentTime <= classFourBeginX){
return "2";
}else if(currentTime >= classFourBeginX && currentTime <= classFourEndX){
return "3";
}else return "0"; //Outside of class time ..
}
</code></pre>
<p>I'm not sure where the issue is to be honest, the lines of code of focus here is lines 2~4</p>
<pre class="lang-java prettyprint-override"><code>DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:MM");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)+"LOL");
</code></pre>
<p>It's stuck at 2:04, but it's currently 3:08 right now, I was expecting that each time I ran my code it'd print the live time (+"LOL"..)</p>
| <java><date><format><formatter> | 2019-04-06 23:09:03 | LQ_CLOSE |
55,555,089 | Image wont load. ive used the jpg and i havent made any typos | I've been trying to load an image from my hard drive, but it wont show. i honestly dont know what im doing as im new to code.
just learning to code
<img src="SPQR.img.jpg" alt="SPQR"> | <html> | 2019-04-07 02:23:52 | LQ_EDIT |
55,555,237 | Why is "bdefh" the output of a java recursion code in which the call to the method preceds and follows the System.out.print? | Is anyone able to figure out how this recursion code works and why it outputs what it does? maybe you could include the steps it goes through to get to what it outputs? Thank you so much! The code is attached... ( it outputs bdefh). the language is java. Please also note that I am a beginner. | <java><string><recursion><methods><substring> | 2019-04-07 03:06:11 | LQ_EDIT |
55,557,177 | C# reverse complement of a sequence | Problem is below: (need to write ReserveComplemenet method in c#)
--------------
The reverse complement of a sequence is formed by exchanging all of its nucleobases with their base complements, and then reversing the resulting sequence. The reverse complement of a DNA sequence is formed by exchanging all instances of:
A with T
T with A
G with C
C with G
and then reversing the resulting sequence.
For example, given the DNA sequence AAGCT the reverse complement is AGCTT
This method, ReverseComplement, must take the following parameter:
a reference to a DNA sequence
This method should return void and mutate the referenced DNA sequence to its reverse complement.
Im stuck and wondering how I do this? Any help would be greatly appreciated. | <c#> | 2019-04-07 08:46:59 | LQ_EDIT |
55,557,265 | how to find the solution for to find the difference between last two entries in Mysql | I need a solution regarding the Fine the difference between the last two entries difference in mysql
SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date, SUM(order_total_after_tax) as number FROM tbl_order where status='Confirmed' GROUP BY DATE_FORMAT(order_datetime,'%Y/%m') Limit 2
OutPut :
date number
02/2019 2345.01
03/2019 103751.05
But i need exact soltion is i need to find difference between the last 2 result
2345.01 -103751.05
Result : -101406.04
how to do in mysql What is the Query ?
| <php><mysql><sql> | 2019-04-07 09:00:48 | LQ_EDIT |
55,557,598 | How to restrict recycler row in UI in android | When recycler view is shown I need to show only first 4 list from array list. how to restrict recycler view row in android?
Any help is appreciated | <android><android-layout><android-recyclerview> | 2019-04-07 09:45:22 | LQ_EDIT |
55,558,402 | What is the mean of "bodyParser.urlencoded({ extended: true }))" and "bodyParser.json()" in NodeJS? | <pre><code>const bp = require("body-parser");
const express = require("express");
const app = express();
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));
</code></pre>
<p>I need to know what they do. I couldn't find any detailed information. Can you help me? And what is different between <code>extended:true</code> and <code>extended:false</code></p>
| <node.js> | 2019-04-07 11:17:42 | HQ |
55,558,557 | How i break out while loop in this case? | i don't know how to break out while loop when turtle arrived on t.ycor == 0
import turtle
import msvcrt
turtle.setup(700, 300, 0, 0)
t=turtle.Turtle()
t.up()
t.goto(-300,0)
t.down()
t.write("Start\n(" + str(t.xcor()) + ", " + str(t.ycor()) + ")", False,
"center", ("",15))
while True:
if msvcrt.kbhit():
c = msvcrt.getch().decode(encoding = 'UTF-8')
if c == 'j':
t.left(3)
elif c == 'k':
t.right(3)
elif c == 'g':
t.forward(5)
t.right(3)
while t.ycor() > 0:
t.forward(10)
t.right(3)
i want to break out out side while loop when turtle arrived t.ycor == 0 after arc.
but i don't know how.... | <python> | 2019-04-07 11:34:23 | LQ_EDIT |
55,558,838 | Html to content management system | <p>Hi I started learning web design couple of months ago and I just made my first functional site using HTML, CSS and JavaScript and PHP for my form. I wanted to find out if there is anyway I can transfer my whole site to a CMS without redesigning it. Thanks</p>
| <javascript><css><html> | 2019-04-07 12:05:59 | LQ_CLOSE |
55,559,079 | How to check if integer array is spiral sorted? | <p>Spiral Sort Involves: a[0] <= a[n-1] <= a[1] <= a[n-2] <= a[2]....
How would i check if a given array is spiral sorted or not?</p>
<p>I have tried this the brute force way.</p>
| <java><arrays><algorithm><list><sorting> | 2019-04-07 12:36:12 | LQ_CLOSE |
55,559,577 | I want to make a parking fee program by using visual stidio | int min1, min2, won;
printf("parking minutes(분)? ");
scanf("%d", &min1);
min2 = (min1 - 30) % 10;
if (min1 <= 39)
won = 2000;
else
{
if (min2 = 0)
won = 2000 + 1000 * (min1 - 30) % 10;
else
won = 2000 + 1000 * (min1 - min2 - 20) % 10;
}
printf("parking fee: %d", won);
The conditions of this program
1.until 30min, 2000won
2. after 30min, 1000won per 10min
3.max 25000won per a day
4.parking minutes cant be over than 24 hours
I thought that '%' means remainder so i write like that but when i input 52, the results say 5200! I want to make result to be 5000. And i want to know what to do for condition 3&4. What can i do? Should i use 'for' and 'sum'? | <c> | 2019-04-07 13:35:53 | LQ_EDIT |
55,560,027 | declaring a variable twice in IIFE | <p>I came through this fun quiz on the internet.</p>
<pre><code>console.log((function(x, f = (() => x)){
var x;
var y = x;
x = 2;
return [x, y, f()]
})(1))
</code></pre>
<p>and the choices were:</p>
<ol>
<li><p>[2,1,1]</p></li>
<li><p>[2, undefined, 1]</p></li>
<li><p>[2, 1, 2]</p></li>
<li><p>[2, undefined, 2]</p></li>
</ol>
<p>I picked solution 2 TBH, basing that on that x has been redefined, y was declared and defined with no value, and that f has a different scope hence getting the global x memory spot than function x memory spot.</p>
<p>However, I tried it in <a href="https://jsbin.com/cakiheqita/1/edit?js,console" rel="noreferrer">jsbin.com</a></p>
<p>and I found it was solution 1, while I was not sure why that happened I messed with the function body and I removed <code>var x</code> from the function body, I found that the response changed to #3 which makes sense as x value changed and hence it showed x and f as 2 and y as 1 which was declared globally.</p>
<p>but still I can't get why it shows 1 instead of undefined.</p>
| <javascript><iife> | 2019-04-07 14:28:47 | HQ |
55,560,140 | javascript array remove every other element | i'm looking for a way to remove array other elements.
but i don't know how to do it.
this is my array:
```
musics: [
{
id: 1,
cover: require('~/assets/images/cover/music/ali_zand_vakili_jadeh_shab.jpg'),
title: 'جاده شب',
artist: 'علی زند وکیلی',
source: 'http://media.mtvpersian.net/2019/Mar/21/Ali%20Zand%20Vakili%20-%20Jadeh%20Shab.mp3'
},
{
id: 2,
cover: require('~/assets/images/cover/music/amin_hayaei_divoone_misazi.jpg'),
title: 'دیوونه میسازی',
artist: 'امین حیایی',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Amin_Hayaei/Singles/amin_hayaei_divoone_misazi.mp3'
},
{
id: 3,
cover: require('~/assets/images/cover/music/emad_talebzadeh_maghrour.jpg'),
title: 'مغرور',
artist: 'عماد طالب زاده',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Emad_Talebzadeh/Singles/emad_talebzadeh_maghrour.mp3'
},
{
id: 4,
cover: require('~/assets/images/cover/music/farzad_farzin_jazzab.jpg'),
title: 'جذاب',
artist: 'فرزاد فرزین',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Farzad_Farzin/Singles/farzad_farzin_jazzab.mp3'
},
{
id: 5,
cover: require('~/assets/images/cover/music/hamid_sefat_ajayeb_shahr_merat_remix.jpg'),
title: 'عجایب شهر رمیکس',
artist: 'حمید صفت',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Hamid_Sefat/Singles/hamid_sefat_ajayeb_shahr_merat_remix.mp3'
}
],
```
how to remove all elements except element with id of 3 ? | <javascript><arrays><filter> | 2019-04-07 14:41:16 | LQ_EDIT |
55,562,113 | i am not getting the installation of the pyaudio library into my system | running build_py creating build creating build\lib.win-amd64-3.7 copying src\pyaudio.py -> build\lib.win-amd64-3.7 running build_ext building '_portaudio' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- Command "c:\users\vishwas\appdata\local\programs\python\python37\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Vishwas\\AppData\\Local\\Temp\\pip-install-g9skf8fa\\PyAudio\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Vishwas\AppData\Local\Temp\pip-record-8gf9jsxc\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Vishwas\AppData\Local\Temp\pip-install-g9skf8fa\PyAudio\
"Where is it releated to python and c++"
i have tried all the methods even easy_install but didn't work
C:\Users\Vishwas>pip install PyAudio Collecting PyAudio Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz Installing collected packages: PyAudio Running setup.py install for PyAudio ... error Complete output from command c:\users\vishwas\appdata\local\programs\python\python37\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Vishwas\\AppData\\Local\\Temp\\pip-install-g9skf8fa\\PyAudio\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Vishwas\AppData\Local\Temp\pip-record-8gf9jsxc\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win-amd64-3.7 copying src\pyaudio.py -> build\lib.win-amd64-3.7 running build_ext building '_portaudio' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- Command "c:\users\vishwas\appdata\local\programs\python\python37\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Vishwas\\AppData\\Local\\Temp\\pip-install-g9skf8fa\\PyAudio\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Vishwas\AppData\Local\Temp\pip-record-8gf9jsxc\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Vishwas\AppData\Local\Temp\pip-install-g9skf8fa\PyAudio\ | <python-3.x><pip><setup.py><pyaudio> | 2019-04-07 18:05:23 | LQ_EDIT |
55,564,317 | Can I integrate or import code from visual studio code to Microsoft visual studio? | I Just started a new job and they use Microsoft visual studio for web development work and source control. And I have been learning/using visual studio code for a while now and I loved it. now that I'm with visual studio, there are a lot of things I don't like about it.
It's much slower and it's not appealing to work with. so my questions is, is there any way I can use studio code IDE and somehow integrate it to Microsoft visual studio just to use for version control after I'm done?
I mainly code with HTML, CSS, and javascript. | <visual-studio><visual-studio-code> | 2019-04-07 22:42:41 | LQ_EDIT |
55,565,511 | How to change date format in Ruby | I'm stuck on a question. How to return the incoming dates with the valid formats?
I want to change_date_format(["2010/03/30","15/12/2016","11-15-2012, 20130720"] should return the list ["20100330","2016215", "2012115"]
def change_date_format(dates)
return []
end
p change_date_format(["2010/03/30", "15/12/2016", "11-15-2012", "20130720"]) | <ruby> | 2019-04-08 02:30:56 | LQ_EDIT |
55,565,964 | how to Load a file in parallel arrays in java | i have a file that has 30 line of: month-day-year- gas price ex:
May 02, 1994 1.04
can someone tell me how to load this file in a parallel arrays of months , days, price in java? because after this
i will have to display the lowest price , and also the highest price, and the average price for each month
can someone help please | <java> | 2019-04-08 03:45:36 | LQ_EDIT |
55,566,419 | Why are packages installed rather than just linked to a specific environment? | <p>I've noticed that normally when packages are installed using various package managers (for python), they are installed in <code>/home/user/anaconda3/envs/env_name/</code> on conda and in <code>/home/user/anaconda3/envs/env_name/lib/python3.6/lib-packages/</code> using pip on conda. </p>
<p>But conda caches all the recently downloaded packages too.</p>
<p>So, my question is:
Why doesn't conda install all the packages on a central location and then when installed in a specific environment create a link to the directory rather than installing it there?</p>
<p>I've noticed that environments grow quite big and that this method would probably be able to save a bit of space.</p>
| <python><pip><conda><package-managers> | 2019-04-08 04:48:49 | HQ |
55,566,735 | Creating objects in android studio | I am having issues with creating objects of a class on android studio. I have created a few classes called Fan, Light and Device.
When i try to instantiate Fan and Light in MainActivity.java I get these errors:
- Field 'myFan' is never used
- Cannot resolve symbol 'breakDevice'
The code is shown below . I'd appreciate any solution to this problem.
Thanks
>MainActivity.java
```
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public Light myLight = new Light();
Fan myFan = new Fan();
myFan.breakDevice();
myLight.breakDevice();
}
```
>Fan.java
```
package com.example.codealong3;
import android.util.Log;
public class Fan extends Device{
public Fan() {
setDeviceName("FAN");
}
@Override
public void breakDevice() {
Log.e(getDeviceName(), "BANG ! It's broken");
}
}
```
>Light.java
```
package com.example.codealong3;
import android.util.Log;
public class Light extends Device {
public Light() {
setDeviceName("LIGHT");
}
@Override
public void breakDevice() {
Log.e(getDeviceName(), "Glass Everywhere! .. I guess that's not bad");
}
}
``` | <java><android> | 2019-04-08 05:26:08 | LQ_EDIT |
55,568,655 | How to avoid repetitive long generic constraints in Rust | <p>I'm trying to make my own implementation of big integers (just for education). The implementation is generic by data type:</p>
<pre><code>struct LongNum<T>
where T: Integer + MulAssign + CheckedMul + CheckedAdd + Copy + From<u8>
{
values: Vec<T>,
powers: Vec<u8>,
radix: u8,
}
</code></pre>
<p>The problem is that I need to repeat this verbose constraint for T in all impls. It's too cumbersome.</p>
<p>I can make my own trait combining these constraints, like this:</p>
<pre><code>trait LongNumValue: Integer + MulAssign + CheckedMul + CheckedAdd + Copy + From<u8> {}
struct LongNum<T: LongNumValue>
{
values: Vec<T>,
powers: Vec<u8>,
radix: u8,
}
</code></pre>
<p>But in this case I have to add impls for this LongNumValue trait to all types which can be used in LongNum:</p>
<pre><code>impl LongNumValue for u8 {}
impl LongNumValue for u16 {}
impl LongNumValue for u32 {}
...
</code></pre>
<p>This means that if I don't add some type to this list of impls, the user of my crate will be unable to use this type for LongNum, even if this type is passes all constraints.</p>
<p>Is there any way to avoid writing long repetitive costraints without adding unnecessary restrictions to user?</p>
| <generics><rust><constraints><traits> | 2019-04-08 07:56:37 | HQ |
55,569,929 | Why does printf modify previous local variables? | <p>I tried to understand C behavior and found some weird things.
I debugged and found out that table values are correct until calling printf.
I create a void function to test whether it is a problem of scope but after calling this function the table values still remained correct.
I wonder now if printf delete previous local variables.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
void invertTable(int** tableau,int size){
int temp[size];
for(int i = 0; i < size; i++)
{
temp[i]=-1*tableau[0][i];
}
tableau[0]=temp;
}
void test(){
}
int main(int argc, char const *argv[])
{
int* table=(int*)malloc(5*sizeof(int));
table[0]=1;
table[1]=2;
table[2]=3;
table[3]=4;
table[4]=5;
invertTable(&table,5);
test();
for(int i = 0; i < 5; i++)
{
//Here is the problem
printf("\n %d \n",table[i]);
}
free(table);
return 0;
}
</code></pre>
<p>Expected -1 -2 -3 -4 -5</p>
<p>Output: -1 1962295758 1 1962550824 1962295741</p>
| <c> | 2019-04-08 09:14:32 | LQ_CLOSE |
55,569,979 | Merge JSON objects inside a array | <p>I have a JSON Array as below</p>
<pre><code>[
{"Name" : "Arrow",
"Year" : "2001"
},
{"Name" : "Arrow",
"Type" : "Action-Drama"
},
{ "Name" : "GOT",
"Type" : "Action-Drama"
}
]
</code></pre>
<p>and I am trying to convert this into </p>
<pre><code>[
{
"Name" : "Arrow",
"Year" : "2001",
"Type" : "Action-Drama",
},
{
"Name" : "GOT",
"Type" : "Action-Drama"
}
]
</code></pre>
<p>Any help greatly appreciated. </p>
<p>Thank you. </p>
| <javascript><arrays><json> | 2019-04-08 09:16:25 | LQ_CLOSE |
55,570,206 | Is there a wildcard character in Express.js routing? | <p>I want to create a web application structure like the following:</p>
<pre><code>rootUrl/shopRecords/shop1
rootUrl/shopRecords/shop2
rootUrl/shopRecords/shop3...
</code></pre>
<p>where there can be any limit of shops, but all of the shop pages will have the same page layout (same HTML/Pug page, just populated with different data from a database). These URLs will be accessed from a list of buttons/links on a home page. </p>
<p>Does Express.js have a wildcard character so that I can specify behavior for all pages with link format <code>rootUrl/shopRecords/*</code> to be the same?</p>
| <javascript><node.js><express> | 2019-04-08 09:28:06 | LQ_CLOSE |
55,570,990 | Kotlin: call a function every second | <p>I want to create a simple countdown for my game, when the game starts I want this function to be called every second:</p>
<pre><code>fun minusOneSecond(){
if secondsLeft > 0{
secondsLeft -= 1
seconds_thegame.text = secondsLeft.toString()
}
}
</code></pre>
<p>I tried this:</p>
<pre><code>var secondsLeft = 15
timer.scheduleAtFixedRate(
object : TimerTask() {
override fun run() {
minusOneSecond()
}
},0, 1000
) // 1000 Millisecond = 1 second
</code></pre>
<p><strong>But the app unfortunately stops, the 2nd time the run function is called</strong></p>
<p>I just started with android development and Kotlin 3 weeks ago and so far I understand the most out of it.</p>
<p>With swift in Xcode I use this line and I thought something similar would work with Kotlin</p>
<pre><code>setTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(minusOneSecond), userInfo: nil, repeats: true)
</code></pre>
| <android><kotlin> | 2019-04-08 10:10:20 | HQ |
55,571,474 | How to extract the dynamically generated access token from the text file in perl | I am Beginner to perl programming and I want know solution for this problem. I have this below information in the text file called token.txt. I want to extract only dynamically generated access_token value and store that value to mysql database.As mentioned access_token will be auto generated everytime so how I need to store this access_token value everytime. Anyone help me with the perl code. Thanks in advance
{
"access_token" : "JgV8Ln1lRGE8JTz4olEQW0rJJHUYsq2LO8Ny9o6m",
"token_type" : "abcdef",
"expires_in" : 123456
} | <regex><perl><text-processing><dbi> | 2019-04-08 10:36:59 | LQ_EDIT |
55,571,520 | write if condition with two execution statement in single line python | Here is what I am looking for:
if 1: print("hello")
hello
But when I tried something like this:
>>> if 1: print("hello") print("end")
File "<stdin>", line 1
if 1: print("hello") print("end")
^
SyntaxError: invalid syntax
Why there is a syntax error? What is the right way to write multiple execution statement in single line with the `if` condition? | <python> | 2019-04-08 10:38:46 | LQ_EDIT |
55,572,928 | how to solve these nin javascript | Locate the displayBirthdate function you initially defined, which took no parameter. Modify it to use object de-structuring to get just the 'dob' property of the parameter object it will receive
here's the code
const displayBirthdate = () => {
};
const displayExtraUserInfo = (extra) => {
document.getElementById("btn-birthdate").addEventListener("click", ()=> {
displayBirthdate(extra)
})
"dob": {
"date": "1986-02-19T23:25:07Z",
"age": 33
}
const getUser = () => ({
date: 156-888,
age: 20,
}); | <destructuring> | 2019-04-08 11:56:13 | LQ_EDIT |
55,574,835 | please can someone help it shows only assignment,cal | <pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movingplayer1 : MonoBehaviour
{
private Rigidbody2D reg;
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update(){
var Newx = 0f;
var Newy = 0f;
reg = GetComponent<Rigidbody2D> ();
if(Input.GetKey("right")){
Newx+speed;
}
else if(Input.GetKey("left")){
Newx-speed;
}
reg.AddForce (new vector2 (Newx,Newy));
}
}
</code></pre>
<p>im new in oop and i need some help guys it shows only assignment call increment decrement await and new object expressions can be used as a statement. </p>
| <c#> | 2019-04-08 13:41:03 | LQ_CLOSE |
55,575,449 | Android Studio 3.3 folder icons | <p>On the new Android Studio 3.3 some icons have change and I'm looking to understand what each one of the mean.</p>
<p><a href="https://stackoverflow.com/questions/25991228/android-studio-icons-meaning">This</a> and <a href="https://stackoverflow.com/questions/38815719/what-do-graphical-icons-and-symbols-in-android-studio-mean?rq=1">this</a> answers are outdated.</p>
<p>For example in this picture I have two modules inside my project, but one have a green dot and the other this bar chart. What it means?</p>
<p><a href="https://i.stack.imgur.com/GTCqF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GTCqF.png" alt="enter image description here"></a></p>
| <android-studio><intellij-idea> | 2019-04-08 14:12:10 | HQ |
55,575,651 | How to render table from json array? | <p>I've JSON array and I need to render it to table using React </p>
<pre><code>lockers: [
{ id: 1, status: 0, size: "s" },
{ id: 2, status: 0, size: "m" },
{ id: 3, status: 0, size: "l" },
{ id: 4, status: 0, size: "s" },
{ id: 5, status: 0, size: "m" },
{ id: 6, status: 0, size: "l" },
{ id: 7, status: 0, size: "s" },
{ id: 8, status: 0, size: "m" },
{ id: 9, status: 0, size: "l" },
{ id: 10, status: 0, size: "s" },
{ id: 11, status: 0, size: "m" },
{ id: 12, status: 0, size: "l" },
{ id: 13, status: 0, size: "xl" }
]
</code></pre>
<p>I expect the output like this, please help</p>
<pre><code>s m l xl
1 2 3 13
4 5 6 -
7 8 9 -
10 11 12 -
</code></pre>
| <javascript><json><reactjs> | 2019-04-08 14:24:30 | LQ_CLOSE |
55,575,843 | how to test react-select with react-testing-library | <p>App.js</p>
<pre><code>import React, { Component } from "react";
import Select from "react-select";
const SELECT_OPTIONS = ["FOO", "BAR"].map(e => {
return { value: e, label: e };
});
class App extends Component {
state = {
selected: SELECT_OPTIONS[0].value
};
handleSelectChange = e => {
this.setState({ selected: e.value });
};
render() {
const { selected } = this.state;
const value = { value: selected, label: selected };
return (
<div className="App">
<div data-testid="select">
<Select
multi={false}
value={value}
options={SELECT_OPTIONS}
onChange={this.handleSelectChange}
/>
</div>
<p data-testid="select-output">{selected}</p>
</div>
);
}
}
export default App;
</code></pre>
<p>App.test.js</p>
<pre><code>import React from "react";
import {
render,
fireEvent,
cleanup,
waitForElement,
getByText
} from "react-testing-library";
import App from "./App";
afterEach(cleanup);
const setup = () => {
const utils = render(<App />);
const selectOutput = utils.getByTestId("select-output");
const selectInput = document.getElementById("react-select-2-input");
return { selectOutput, selectInput };
};
test("it can change selected item", async () => {
const { selectOutput, selectInput } = setup();
getByText(selectOutput, "FOO");
fireEvent.change(selectInput, { target: { value: "BAR" } });
await waitForElement(() => getByText(selectOutput, "BAR"));
});
</code></pre>
<p>This minimal example works as expected in the browser but the test fails. I think the onChange handler in is not invoked. How can I trigger the onChange callback in the test? What is the preferred way to find the element to fireEvent at? Thank you</p>
| <reactjs><integration-testing><react-select><react-testing-library> | 2019-04-08 14:33:43 | HQ |
55,576,030 | React Native Android error in com.facebook.react.bridge.NoSuchKeyException | <p>I'm getting an error caught by Crashlytics and it's happening to almost 45% of the users but it doesn't seem to happen when the user is using the app but when it's in the background.</p>
<p>The stacktrace shown on Crashlytics is:</p>
<p><code>Fatal Exception: com.facebook.react.bridge.NoSuchKeyException ReadableNativeMap.java:124
lineNumber
</code></p>
<p>I have no clue what can be causing this issue, if it's a Javascript error or a native library error</p>
| <android><reactjs><react-native> | 2019-04-08 14:44:16 | HQ |
55,576,953 | useRef "refers to a value, but is being used as a type here." | <p>I'm trying to figure out how to tell react which element is being used as ref i.e. in my case</p>
<pre><code>const circleRef = useRef<AnimatedCircle>(undefined);
</code></pre>
<p><code>AnimatedCircle</code> is an SVG component from a third party library, and defining it this way causes error</p>
<p><a href="https://i.stack.imgur.com/KjlOp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KjlOp.png" alt="enter image description here"></a></p>
<p>Is there some universal way to define which element is ref?</p>
| <reactjs><typescript><react-hooks> | 2019-04-08 15:32:22 | HQ |
55,577,710 | do you know how to fix this UPDATE errpr? | when this code runs, it says there is an UPDATE writing error. dose anybody knows whats the problem or how to fix it?
this is the cood:
string sql2 = "UPDATE ezuser";
sql2 += " SET fname = '" + Request.Form["fname"]+ "'";
sql2 += " , lname = '" + Request.Form["lname"] + "'";
sql2 += " , fav = '" + Request.Form["fav"] + "'";
sql2 += " , pw='" + Request.Form["pw"] + "'";
sql2 += " , order = '" + Request.Form["order"] + "'";
sql2 += " WHERE email = '" + Request.Form["email"] + "'";
MyAdoHelper.DoQuery(fileName, sql2); | <sql> | 2019-04-08 16:20:08 | LQ_EDIT |
55,578,496 | Update Xcode 10.1 to 10.2 on High Sierra 10.13.6 | <p>I'm trying to update Xcode 10.1 to 10.2 on my High Sierra 10.13.6 version.</p>
<p>The App Store window shows the update button, but the problem is after hitting that button, the circle on the upper-left corner is just rotating for hours and nothing else happens!</p>
<p><a href="https://i.stack.imgur.com/DZjZM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DZjZM.png" alt="enter image description here"></a></p>
<p>Since the difference between the two versions is not that huge, the update naturally must be downloaded and installed after some time, but in effect it's not that way! </p>
<p>How to solve that issue, please?</p>
| <xcode><macos-high-sierra> | 2019-04-08 17:12:18 | HQ |
55,578,678 | How to writing a "if/unless" for an integer variable | I am trying to write a conditional where if a ends in 1 then it will answer with "st root" unless it ends with an 11 so it will be like 1st root or 11th root
(Then also work in similar ways for 2/12 and 3/13)
Here is the code I have tried
def n():
print("Only enter whole numbers\n ")
base = float(input("Enter number to take the root of, then hit enter:\n "))
input_string = input("Enter degree of roots (if more than one, separate by space) then hit enter:\n ")
list = input_string.split()
a = 1
for num in list:
base **= (1/float(num))
for num in list:
a *= int(num)
if str(a)[-1] == '1':
if str(a)[-1] != '11':
print(a,"st root",base)
elif str(a)[-1] == '2':
if str(a)[-1] != '12':
print(a,"nd root",base)
elif str(a)[-1] == '3':
if str(a)[-1] != '13':
print(a,"rd root",base)
else:
print(a,"th root",base)
n() | <python><if-statement> | 2019-04-08 17:24:37 | LQ_EDIT |
55,580,903 | how do I Include partial html files into index.html? | <p>I'm using python & django and tying to include html files in my index.html file but cant seem to get it to work - any help will be appreciated.</p>
<p>I'll add some context..
I've downloaded a theme via Keentheme and want to use it in my project.
The getting started tutorial (<a href="https://www.youtube.com/watch?v=ApO_obOK_00" rel="nofollow noreferrer">https://www.youtube.com/watch?v=ApO_obOK_00</a>) at around 14:20 instructs me to change all html files to php files and to use
This doesn't work.</p>
<p>The html files contain numerous instructions like the following:
'''[html-partial:include:{"file":"partials/_mobile-header-base.html"}]/'''</p>
<p>The file location for the above is as follows:
./partials/_mobile-header-base.html</p>
<p>The tutorial only walks through the php include method - can anyone help?</p>
| <python><html><django> | 2019-04-08 20:00:07 | LQ_CLOSE |
55,581,293 | Covert nvarchar to int | // https://www.codeproject.com/Questions/823002/How-to-clear-Request-Querystring
string url = context.Request.Url.AbsoluteUri; // Henter URL
string[] separateURL = url.Split('?'); // Splitter URL
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(separateURL[0]); // Parameterne
string categoryId = queryString[0]; // Indeks 0 er categoryId
StringBuilder table = new StringBuilder();
con.Open();
SqlCommand cmd = new SqlCommand("uspPasteDataSubCategories", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@categoryid", categoryId);
SqlDataReader rd = cmd.ExecuteReader();
Recieving the error: System.Data.SqlClient.SqlException: 'Error converting data type nvarchar to int.'
which doesn't make sense for me because the datatype is not nvarchar in the database.
Error happens at:
SqlDataReader rd = cmd.ExecuteReader(); | <c#><sql-server> | 2019-04-08 20:29:07 | LQ_EDIT |
55,582,277 | Visual Studio Code quick-fix & python | <p>Visual Studio Code is never able to populate the 'Quick Fix' contextual drop down, only displaying 'No Code Actions Available'</p>
<p>Python extension is installed, along with python3.7.3 and flake8, pep8.</p>
| <python><visual-studio-code> | 2019-04-08 21:52:22 | HQ |
55,582,983 | Haskell function non-exaustive patters in function error | <p>I'm trying to make a function that finds the local Maximum number in a list.</p>
<pre><code>localMaxima :: [Integer] -> [Integer]
localMaxima [] = []
localMaxima [x] = []
localMaxima (e1:e2:e3:xs)
| (e2 > e3) && (e2 > e1) = e2 : (localMaxima (e2:(e3:xs)))
| otherwise = (localMaxima (e2:(e3:xs)))
</code></pre>
<p>After inputting a list of [2,3,4,1,5], the console outputs: </p>
<p>Non-exhaustive patterns in function localMaxima</p>
| <haskell> | 2019-04-08 23:09:37 | LQ_CLOSE |
55,582,996 | need to remove a scroll on mobile view | mobile view of website allows me to scroll to the right when it shouldnt allow it to happen.
@media screen and (max-width:768px){
body{
overflow-x: hidden;
width: 100%;
}
.nav-links{
position: absolute;
right:0px;
height: 92vh;
top: 8vh;
background-color: #4A4F52;
display: flex;
flex-direction: column;
align-items: center;
transform: translateX(100%);
transition: transform 0.5s ease-in;
z-index: -1;
}
.nav-links li{
opacity: 0;
}
.burger{
display: block;
cursor: pointer;
}
}
.nav-active{
transform: translateX(0%);
z-index: 1;
width: 100%;
height: 100%;
}
Hi all,
I am building a website and i have a new bar thats working greating in terms of sliding across from the right hand side, shoing the menus etc. however when on mobile i can scroll my screen across and see part of the back ground for the nav bar. I have tried the "overfloe-x:hidden" approach on the body and html elementsand that hasn't worked. i have tried various solutions mentioned in old posts on stackoverflow. is there anything any could suggest ?
If anything else is needed just let me know and i can post it. | <javascript><html><css> | 2019-04-08 23:11:20 | LQ_EDIT |
55,583,360 | Is window.confirm() accessible? | <p>Are native browser modals like <code>window.confirm</code>, <code>window.alert</code>, and <code>window.prompt</code> accessible, or is it better to implement something custom?</p>
| <javascript><accessibility> | 2019-04-09 00:02:17 | HQ |
55,583,815 | Formik - How to reset form after confirmation | <p>In <a href="https://github.com/jaredpalmer/formik" rel="noreferrer">Formik</a>, how to make the Reset button reset the form only <strong>after confirmation</strong>?</p>
<p>My code below still resets the form even when you click Cancel.</p>
<pre><code>var handleReset = (values, formProps) => {
return window.confirm('Reset?'); // still resets after you Cancel :(
};
return (
<Formik onReset={handleReset}>
{(formProps) => {
return (
<Form>
...
<button type='reset'>Reset</button>
</Form>
)}}
</Formik>
);
</code></pre>
| <reactjs><forms><formik> | 2019-04-09 01:19:53 | HQ |
55,584,094 | Failed to demangle superclass with Cocoapods in Xcode 10.2 | <p>After moving to Xcode 10.2, when running my app I get a crash with the error <code>failed to demangle superclass of MyClass from mangled name MySuperClass</code>.</p>
<p>The crash occurs when I try to create an instance of MyClass. I am using CocoaPods 1.6.1 and have not yet upgraded to Swift 5. The class in question is defined inside a Pod, and is a subclass of a class defined a different Pod (listed as a sub dependency of the first Pod). </p>
<p>Adding to the complexity (unsure if it is related) is that the super class takes a generic, and the sub class defines a concrete type and does not take a generic. I.e.</p>
<pre><code>// Inside Pod B:
open class MySuperClass<DataType: Decodable> { ... }
// Inside Pod A:
open class MySubClass: MySuperClass<AConcreteStructConformingToCodable> { ... }
// Inside my project:
let myClass = MySubClass()
</code></pre>
<p>I have tried overriding the Pod build settings to build with and without optmisation without any change in behaviour.</p>
| <ios><swift><xcode><cocoapods> | 2019-04-09 02:04:22 | HQ |
55,584,391 | laravel orm : How to treat obsessive-compulsive disorder | <p><strong>chinese description:</strong></p>
<p>laravel orm的命名规范对强迫症来说简直是一种灾难,为什么会有这样的设计。。</p>
<p>数据库字段设计成小写字母+下划线,例如order_item表中有个字段goods_name</p>
<p>那么laravel代码中,就得这样写:$orderItem->goods_name</p>
<p>驼峰和全小写混合,强迫症表示实在受不了啊。。。受不了。。。受不了。。。</p>
<p><strong>english description:</strong>
for example: I have a table named order_item and the table have a column named goods_name
in laravel orm I will write code such as: $orderItem->goods_name</p>
<p>the hump naming with the whole lower case,,,,</p>
<p>why why why</p>
<p>why the laravel design so。why not design like:$orderItem->goodsName</p>
<p>I am going nuts.</p>
| <laravel> | 2019-04-09 02:47:08 | LQ_CLOSE |
55,585,411 | Whats wrong with my code for checking if a site is online or not in android app? | I had been working on a app for my college project. It that application i just want to check if a website is available(online) or not. If it is available then open it in webview and if it isn't open a pre specified website.
After some research I landed up till the following code but it does not seem to work. App always opens bing.com (i.e value of flag does not get updated after running pingHost)
public class MainActivity extends Activity {
WebView web1;
String Address;
int flag=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
pingHost("http://www.google.com", 80, 5000);
if (flag==1) {
web1 = (WebView) findViewById(R.id.webView1);
Address = "https://learn2lead.home.blog";
WebSettings webSetting = web1.getSettings();
webSetting.setBuiltInZoomControls(true);
webSetting.setJavaScriptEnabled(true);
web1.setWebViewClient(new WebViewClient());
web1.loadUrl(Address);
} else if (flag==0){
web1 = (WebView) findViewById(R.id.webView1);
Address = "http://bing.com";
WebSettings webSetting = web1.getSettings();
webSetting.setBuiltInZoomControls(true);
webSetting.setJavaScriptEnabled(true);
web1.setWebViewClient(new WebViewClient());
web1.loadUrl(Address);
}
}
});
}
}, 0, 10000);
public void pingHost(final String host, final int port, final int timeout) {
new Thread(new Runnable() {
@Override
public void run() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
flag = 1;
} catch (IOException e) {
flag = 0;
}
}
}).start();
}
}
PLEASE HELP ME OUT ASAP... I AM SO CLOSE TO DEADLINE FOR SUBMISSION OF PROJECT!!!! | <java><android><android-webview><android-websettings> | 2019-04-09 05:03:09 | LQ_EDIT |
55,587,161 | iOS Logging: How to Formatting Log Messages(get time_t, timeval, errno) in swift | How to the use System log through Logging. I go throw this apple Document
> https://developer.apple.com/documentation/os/logging for logging.
But cant get the Formatting Log Messages.
Using this code
> os_log(OS_LOG_DEFAULT, "Time: %{time_t}d", time_t)
OS_LOG_DEFAULT is show an Error
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/CHXya.png
How to use this OS_LOG_DEFAULT, How to get a all Formatting Log Messages (time_t,timeval,timespec,errno,iec-bytes,bitrate,iec-bitrate,uuid_t)
Want to know how to use this Performing Logging
os_log("This is a log message.")
os_log("This is additional info that may be helpful for troubleshooting.", log: OSLog.default, type: .info)
let customLog = OSLog(subsystem: "com.your_company.your_subsystem_name.plist", category: "your_category_name")
os_log("This is info that may be helpful during development or debugging.", log: customLog, type: .debug)
How to Use this in my application, want to get Formatting Log Messages,Performing Logging Help me. Thanks advance.
| <ios><swift><logging> | 2019-04-09 07:21:44 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.