text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How do I find all elements with a specific attribute? I have a number of elements on my page that have a lang attribute. How do I select only the elements with a lang attribute?
i.e.
<div lang="english">Test</div>
<span lang="english">is cool</span>
<span lang="anotherlanguage">is also good</span>
A: You need to use attribute selector.
Live Demo
var res = $('[lang=english]')
You can iterate through each item use each()
$('[lang=english]').each(function () {
alert($(this).text());
});
A: $('*[lang]').each(function () {
//Your Code
}
A: You can do this via HTML5 data-* attribute. Set the attribute like this
``
To fetch all elements with data-lang set to "english" use:
document.querySelectorAll('[data-lang="english"]');
A: While you already have an (accepted) answer to this question, I thought I'd post an additional answer, to more completely answer the question as asked, also to cover the various issues I've raised in comments to those other answers.
Each approach I discuss in my answer will be applied to the following HTML mark-up:
<div class="langContainer">
<span lang="english">Some text in an English span</span>
<span lang="french">Some text in an French span</span>
<span lang="algerian">Some text in an Algerian span</span>
<span lang="urdu">Some text in an Urdu span</span>
</div>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<ol>
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
<li>List item four</li>
<li>List item five</li>
<li>List item six</li>
<li>List item seven</li>
</ol>
<ul class="langContainer">
<li><div lang="english">Some text in an English div</div></li>
<li><div lang="french">Some text in an French div</div></li>
<li><div lang="algerian">Some text in an Algerian div</div></li>
<li><div lang="urdu">Some text in an Urdu div</div></li>
</ul>
The easiest way to style elements with a lang attribute is CSS, for example:
:lang(english),
:lang(french) {
color: #f90;
}
JS Fiddle demo.
The above will style all elements with a lang attribute equal to english or french. Of course, this being CSS, it's possible to modify the selector to apply to only specific elements with those attributes:
span:lang(english),
div:lang(french) {
color: #f90;
}
JS Fiddle demo.
This, as you would imagine, styles a span with a lang attribute equal to english and a div element with a lang attribute equal to french.
Using the :lang() pseudo-class, without passing a value, does not, unfortunately, select elements that simply possess a lang attribute.
However, using the CSS attribute-selector [lang] does:
[lang] {
color: #f90;
}
JS Fiddle demo.
The absence of an element in that selector, of course, implies the universal selector so to select more accurately it might be wise to modify the selector to apply to either specific element-types (span[lang]) or to elements within a specific parent element (div.langContainer [lang]).
However, for other purposes, such as modifying the content, or element-nodes themselves, using jQuery you have the same selectors available, for example.
In the following examples I'll be assigning the element's original text to jQuery's data object (with the variable-name of original-text) and replacing the element's visible text (as a demonstration of passing an anonymous function to a method, to avoid having to iterate through the matched elements with each(), though you can do that if you want to), with that in mind I'll post only the selector:
// selecting elements with lang equal to 'english':
$(':lang(english)')
JS Fiddle demo.
// selecting all elements with the lang attribute:
$('[lang]')
JS Fiddle demo.
// specifying the element-type:
$('span[lang]')
JS Fiddle demo.
// specifying the element-type:
$('div.langContainer [lang]')
JS Fiddle demo.
It seems, incidentally, from a jsPerf comparison of the jQuery approaches, that defining the element type (for example $('span[lang]')) is the fastest means by which to select (that said, of course, if you're only styling the content then CSS would be faster yet).
A brief discussion of using each() versus an anonymous function passed to a method.
Using this approach depends entirely on what you want to do, but if you want to, for example, modify the text of each matched-element, the two following approaches are equivalent:
$('span[lang]').each(function(i){
$(this).text('matched element ' + i);
});
JS Fiddle demo;
$('span[lang]').text(function(i) { return 'matched element ' + i; });
JS Fiddle demo;
There is, however, no significant difference between the time it takes to run either.
A: Try this
$('[lang="english"],[lang="anotherlanguage"]')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14498576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP echoing / with attributes I need some help with echoing a <img> tag with attributes like title, rel, and class.
I have made it this far, when I'm echoing a filename from a db to search in a catalogue to find it. But I'm not sure how to write some attributes to it since I'm going to display it with Pirobox.
This is what i got working:
echo '<a href="uploads/'.$row['bildnamn'].'">';
echo '<img src="uploads/'.$row['thumb_bildnamn'].'">';
echo '</a>';
But I also need these attributes for the <A> tag which makes the image large.
rel="gallery" class="pirobox_gall" title="$row['uploaded']" . " " . "$row['user']";
What I don't get to work is how to get that line together with:
echo '<a href="uploads/'.$row['bildnamn'].'">';
A: You should be able to concatenate everything in the <a> tag like so:
echo '<a href="uploads/' . $row['bildnamn'] . '" rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">';
echo '<img src="uploads/' . $row['thumb_bildnamn'] . '">';
echo '</a>';
I inserted spaces to help emphasize where PHP does concatenation. In your case, a single quote starts/ends the string for PHP; a double quote is ignored and goes into the HTML. So this part:
title="' . $row['uploaded'] . ' ' . $row['user'] . '"
will make the title be the value of the uploaded column, then a space, then the value of the user column. Then just end the a tag with a >.
A: you could continue to concatenate the string
echo '<a href="uploads/'.$row['bildnamn'].'"'. 'rel="gallery" class="pirobox_gall" title="'.$row['uploaded'].' '.$row['user'].'">';
A: Try this:
echo '<a href="uploads/' . $row['bildnamn'] . '" rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">';
echo '<img src="uploads/' . $row['thumb_bildnamn'] . '">';
echo '</a>';
A: You can do this using string concatenation, like this:
$anchor = '<a href="uploads/'.$row['bildnamn'].'"';
$anchor .= 'rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">';
$anchor .= '<img src="uploads/'.$row['thumb_bildnamn'].'"></a>';
echo $anchor;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35382445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ExecuteNonQuery : incorrect syntax near / I get the following error and I have been trying to figure out what the problem is for a few weeks but nothing, could someone help ?
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near '/'.
And here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace WindowsFormsApplication4
{
public partial class Add_Position : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Add_Position()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'position_ListDataSet.Table' table. You can move, or remove it, as needed.
this.tableTableAdapter.Fill(this.position_ListDataSet.Table);
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(@"Data Source=sqlserver;Initial Catalog=Position_List;Integrated Security=False;User ID=administrator;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
con.Open();
cmd = new SqlCommand("INSERT INTO Table (Name, Dwt, Built, Position, Area, L/C from, L/C to, Contact) Values (@Name, @Dwt, @Built, @Position, @Area, @L/C from, @L/C to, @Contact)", con);
cmd.Parameters.Add("@Name", nametxt.Text);
cmd.Parameters.Add("@Dwt", dwttxt.Text);
cmd.Parameters.Add("@Built", builttxt.Text);
cmd.Parameters.Add("@Position", postxt.Text);
cmd.Parameters.Add("@Area", areatxt.Text);
cmd.Parameters.Add("@L/C from", lcftxt.Text);
cmd.Parameters.Add("@L/C to", lcttxt.Text);
cmd.Parameters.Add("@Contact", contxt.Text);
cmd.ExecuteNonQuery();
}
}
Thanks
A: Please change your column names in database L/C from to LC_Fromand L/C T0 = LC_To
I thing then i would not get any error .
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(@"Data Source=sqlserver;Initial Catalog=Position_List;Integrated Security=False;User ID=administrator;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
con.Open();
cmd = new SqlCommand("INSERT INTO Table (Name, Dwt, Built, Position, Area, LC_from, LC_to, Contact) Values (@Name, @Dwt, @Built, @Position, @Area, @LC_from, @LC_to, @Contact)", con);
cmd.Parameters.Add("@Name", nametxt.Text);
cmd.Parameters.Add("@Dwt", dwttxt.Text);
cmd.Parameters.Add("@Built", builttxt.Text);
cmd.Parameters.Add("@Position", postxt.Text);
cmd.Parameters.Add("@Area", areatxt.Text);
cmd.Parameters.Add("@LC_from", lcftxt.Text);
cmd.Parameters.Add("@LC_to", lcttxt.Text);
cmd.Parameters.Add("@Contact", contxt.Text);
cmd.ExecuteNonQuery();
con.Close();
}
A: as adviced in comments and other answers,i also recommend you to change columnnames with /'s as it will give further unexpected erros.Though i can give another quick fix,ie In SQL Server, identifiers can be delimited using square brackets, e.g.
SELECT [table/1] ...
in you case,pls try using
cmd = new SqlCommand("INSERT INTO Table (Name, Dwt, Built, Position, Area, [L/C from], [L/C to], Contact) Values (@Name, @Dwt, @Built, @Position, @Area, @L/C from, @L/C to, @Contact)", con);
cmd.Parameters.Add("@Name", nametxt.Text);
hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34132643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Playing HTML video while taking a screenshot (drawHierarchy) I'm having issues with thumbnailWebView.drawHierarchy(in:,afterScreenUpdates:) method and loading HTML code with a local video in it.
The issue comes when I capture the webview to get a tumbnail and then I click the video on the webview, the video start running (because the sound works) but the image keeps black. Also if I click the full screen option the video shows right.
The code is simple. Image capture:
UIGraphicsBeginImageContextWithOptions(self.thumbnailWebView.bounds.size, true, UIScreen.main.scale)
thumbnailWebView.drawHierarchy(in: thumbnailWebView.bounds, afterScreenUpdates: true)
let screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
Init WKWebView:
let conf = WKWebViewConfiguration()
self.thumbnailWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 768, height: 1024), configuration: conf)
thumbnailGeneratorView.addSubview(self.thumbnailWebView)
thumbnailControl = ThumbnailControl()
thumbnailControl.delegate = self
thumbnailWebView.uiDelegate = thumbnailControl
thumbnailWebView.navigationDelegate = thumbnailControl
Loading the HTML:
self.thumbnailWebView.loadFileURL(contentURL!, allowingReadAccessTo: contentURL!.deletingLastPathComponent())
If I comment the drawHierarchy line, the video shows right.
I have also tried to use view.layer.renderInContext(UIGraphicsGetCurrentContext()!) instead drawHierarchy but the screenshot obtained is white.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45877144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to understand array sorting in Swift Can someone please visualize the process of sorting?
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.
How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?
A: Run it like this in a playground, and you will see how it works in more detail:
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted {
print("0: \($0), 1: \($1), returning \($0 > $1)")
return $0 > $1
}
$0 is simply the first argument, and $1 is the second. The output with your numbers array is:
0: 2, 1: 0, returning true
0: 1, 1: 0, returning true
0: 1, 1: 2, returning false
A: It is a syntactic simplification, it is equivalent to:
numbers.sorted {(a, b) -> Bool in
return a > b
}
In fact $0 is the first parameter of the closure, $1 is the second one...
Edit: The fact that it is called 4 times, it's just because of the sort algorithm used. And you should not take care of it.
A: It's shortly but comprehensively described in the documentation:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
...
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Shorthand Argument Names
Swift automatically provides shorthand argument names to inline
closures, which can be used to refer to the values of the closure’s
arguments by the names $0, $1, $2, and so on.
If you use these shorthand argument names within your closure
expression, you can omit the closure’s argument list from its
definition, and the number and type of the shorthand argument names
will be inferred from the expected function type. The in keyword can
also be omitted, because the closure expression is made up entirely of
its body:
reversedNames = names.sorted(by: { $0 > $1 } )
Here, $0 and $1 refer to the closure’s first and second String arguments.
A: The sorted function takes a closure which defines the ordering of any two elements. The sorting algorithm does a series of comparisons between items, and uses the closure to determine the ordering amongst them.
Here's an example which prints out all the comparisons done in the sorting of an example array of numbers:
let numbers = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
let sorted = numbers.sorted { (a: Int, b: Int) -> Bool in
let result = a < b
print("\(a) is \(result ? "" : "not") before \(b)")
return result
}
print(sorted)
$0 and $1 are implicit closure parameters. They're names implicitly given to the parameters of a closure. They're often used in cases where the names given to parameters of a closure are rather arbitrary, such as in this case.
In your example, the closure behaves as if it was like so:
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { leftElement, rightElement in
return leftElement > rightElement
}
As you can see leftElement and rightElement don't add much information to the code, which is why it's preferred to use implicit closure parameters in a case like this.
A: The "(4 times)" means your closure ({ $0 > $1 }) is getting invoked 4 times by the sorted function.
I don't know what the false means, but presumably it's the last return value from your closure, which depends entirely on the internal sorting algorithm used by sorted (which you can visualize e.g. with David Shaw's method). I.e. $0 and $1 are not "changing their positions".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43097618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Letter segmentation: openCV findContours does not work I have a binary image contains a word, I want to slice the image into pieces, each contains a single character.
I tried to use opencv's findcontours to get the bounding box of each character. However, the findContours does not work as expect.
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
How should I solve this issue?
Is another a better approach for this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41083772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I have installed mysqlclient , but not able to run server I am a beginner in python and Django.
I would like to connect my Django project to MySQL database,I have installed mysqlclient
brew install mysql
pipenv install mysqlclient
but after changing the settings to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'storefront',
'HOST': 'localhost',
'USER': 'root',
'PASSWORD': 'my_password',
}
}
I get an error for running server: (NameError: name '_mysql' is not defined)
source /Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/bin/activate
(base) niloufar@Niloufars-MacBook-Air site-functions % source /Users/niloufar/.local/share/virtualenvs/
site-functions-HFSltvjv/bin/activate
(site-functions) (base) niloufar@Niloufars-MacBook-Air site-functions % python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: dlopen(/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/niloufar/anaconda3/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/Users/niloufar/anaconda3/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/apps/config.py", line 304, in import_models
self.models_module = import_module(models_module_name)
File "/Users/niloufar/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
class AbstractBaseUser(models.Model):
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/models/base.py", line 141, in __new__
new_class.add_to_class("_meta", Options(meta, app_label))
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/models/base.py", line 369, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/models/options.py", line 235, in contribute_to_class
self.db_table, connection.ops.max_name_length()
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/connection.py", line 15, in __getattr__
return getattr(self._connections[self._alias], item)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/connection.py", line 62, in __getitem__
conn = self.create_connection(alias)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/utils.py", line 208, in create_connection
backend = load_backend(db["ENGINE"])
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/utils.py", line 113, in load_backend
return import_module("%s.base" % backend_name)
File "/Users/niloufar/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
import MySQLdb as Database
File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 24, in <module>
version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
I have already checked the status of MySQL , and it is installed properly:
mysql -u root -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.29 MySQL Community Server - GPL
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
Also I have added the directory of MySQL to the PATH
echo $PATH
export PATH=$PATH:/opt/homebrew/opt/mysql
What's the problem then ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72195278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Session variables lost after redirect - PHP 7.3 I am trying to forward session variables from page1.php to page2.php.
Session variables lost after redirect.
In PHP version 5.3.28 it was working properly. The problem started occuring after upgrade to PHP ver. 7.3.9.
page1.php
session_start();
$_SESSION['myvar']=1;
session_write_close();
header( 'Location: page2.php' );
exit();
page2.php
session_start();
echo $_SESSION['myvar'];
if ( isset($_SESSION['myvar']) && $_SESSION['myvar'] == 1 ){
echo "OK";
unset($_SESSION['myvar']);}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58024416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python: how to read .csv file in an efficient way? I have to read some .csv files and do some operations. In particular I have to read .csv where the data is stored in different columns. In particular the data has the following format:
myfile_0.csv
Time InfD Com ComN
0 3 4 0
1 2 5 1
The file contains many entries and I have to do that for different parameters an the process is really slow. In the following the task that I have to accomplish
for i in parameters:
f = folder+'myfile_%d.csv'%i
df = pd.read_csv(f)
D = df.InfD / V
C = (df.Com/df.ComN)
size = TC - len(C)
if len(C) < TC:
CC = np.lib.pad(C, (0,size), 'constant', constant_values=(1))
DD = np.lib.pad(D, (0,size), 'constant', constant_values=(0))
cf = CC*(1-DD)
else:
C = C[0:TC]
D = D[0:TC]
cf = C*(1-D)
I am wondering if there is a more efficient to solve the same problem.
A: Try the python csv library
import csv
with open('myfile_0.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
print ', '.join(row)
# output:
# Time, InfD, Com, ComN
# 0, 3, 4, 0
# 1, 2, 5, 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36182402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: jQuery Dialog showing input item I have two boxes, "box1" contains listed items (text) and "box2" is empty. The objective is that the user can drag the items from box1 to box2, then press a button to register to open a dialog box. I got that working! But the problem is that I need the dialog box to show the items that have been dragged into box2.
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
draggable: false,
});
$( "#register" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
$(function() {
$( "#box1 li" ).draggable({
appendTo: "body",
helper: "clone"
});
$( "#box2 ol" ).droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function( event, ui ) {
$( this ).find( ".respondlist" ).remove();
$( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );
}
}).sortable({
items: "li:not(.respondlist)",
sort: function() {
$( this ).removeClass( "ui-state-default" );
}
});
});
I currently have no idea how to do it. Would be thankful if someone could help me out.
Edit: https://jsfiddle.net/Kasper_J/Lwqbbapu/
A: When you click on register. You can find all the <li> elements in #box2 ol and append it to #dialog. Do it after $( "#dialog" ).dialog( "open" ); as when the dialog box is close its css has display:none and because of that you probably cannot add any element on it(probably).
you can do it something like below. (Tested)
$( "#register" ).click(function() {
$( "#dialog" ).dialog("open");
var newcontent = document.createElement('div');
newcontent.innerHTML = $("#box2 ol").html();
document.getElementById("dialog").appendChild(newcontent);
});
Update: I updated the solution (working). (thanks for the fiddle).
Here is the working fiddle : Working Fiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34698020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Go: compile to static binary with PIE I am looking to create a binary that can execute in an environment without a linked but also where a linker is available but PIE is required.
The closes I've gotten is where the linker states that it is statically linked but 'file' still says it is a dynamic binary.
Is there any way to get a binary that does not have an external dependency on a linker and is not a LSB shared object?
Example with go1.15.2:
% echo "package main;import \"fmt\";func main() {fmt.Println(\"Simple Example\")}" > main.go
% GOOS=linux go build -ldflags "-linkmode=internal -s -w" -buildmode=pie -o mainProc main.go
% ldd mainProc
statically linked
% file mainProc
mainProc: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, Go BuildID=8mM4GRs9zxgrVjDRg2Ch/efne9QJbJLpmKT6hRtJm/JWUYVr1m9OhJoV0v1uwq/1IZdDT8CvBOOywiI8eQq, stripped
A: Solved it:
go build -ldflags '-linkmode external -s -w -extldflags "--static-pie"' -buildmode=pie -tags 'osusergo,netgo,static_build' -o /hello hello.go
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64019336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to download images async for WidgetKit I am developing Widgets for iOS and I really don't know how to download images for the widgets.
The widget currently downloads an array of Objects, and every object has a URL of an image. The idea is that every object makes a SimpleEntry for the Timeline.
What's the best way of achieving this? I read that Widgets shouldn't use the ObservableObject. I fetch the set of objects in the timeline provider, which seems to be what Apple recommends. But do I also download the images there and I wait until all are done to send the timeline?
Any advice would be very helpful,
A: Yes, you should download the images in the timeline provider and send the timeline when they are all done. Refer to the following recommendation by an Apple frameworks engineer.
I use a dispatch group to achieve this.
Something like:
let imageRequestGroup = DispatchGroup()
var images: [UIImage] = []
for imageUrl in imageUrls {
imageRequestGroup.enter()
yourAsyncUIImageProvider.getImage(fromUrl: imageUrl) { image in
images.append(image)
imageRequestGroup.leave()
}
}
imageRequestGroup.notify(queue: .main) {
completion(images)
}
I then use SwiftUI's Image(uiImage:) initializer to display the images
A: I dont have a good solution, but I try to use WidgetCenter.shared.reloadAllTimelines(), and it make sence.
In the following code.
var downloadImage: UIImage?
func downloadImage(url: URL) -> UIImage {
var picImage: UIImage!
if self.downloadImage == nil {
picImage = UIImage(named: "Default Image")
DispatchQueue.global(qos: .background).async {
do {
let data = try Data(contentsOf: url)
DispatchQueue.main.async {
self.downloadImage = UIImage.init(data: data)
if self.downloadImage != nil {
DispatchQueue.main.async {
WidgetCenter.shared.reloadAllTimelines()
}
}
}
} catch { }
}
} else {
picImage = self.downloadImage
}
return picImage
}
Also you have to consider when to delete this picture.
This like tableView.reloadData().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63173928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Check if url has specific string in python 3 I am new to python and I couldn't figure this out
In this code I need to check if the url has http or not
for link in links:
if "http" in link.get("href"):
print("<a href='%s'>%s</a>" % (link.get("href"), link.text))
When running I got this error:
TypeError: argument of type 'NoneType' is not iterable
How can I fix that?
Thanks in advance for the help.
A: You can just try using string.find.
But it seems like your problem is that link.get("href") returned None.
Your link probably has no "href".
A: I had to guess a little bit what exactly your context was. But this might help you.
You can check if something is None by "if var is None:" and continuing the loop.
But my recommendation is to start with basic tutorials instead of jumping right into some concrete tasks... this might be easier for you :)
from bs4 import BeautifulSoup
import re
website = """#INSERT_HTML_CODE"""
soup = BeautifulSoup(website, 'html.parser')
p = re.compile("https://")
soup = BeautifulSoup(website, 'html.parser')
soup_links = soup.find_all("a")
print(len(soup_links))
counter = 0
for link in soup_links:
if link is None: # <---- Handle None value with continuing the loop
continue
if p.match(link.get("href", "")) is not None: # <--- Handle link element, if https is in href String.
# If href is not existing. .get() returns "" and nothing is broken
print("HTTPS found")
print("<a href='%s'>%s</a>" % (link.get("href"), link.string) )
print("")
counter = counter + 1
print(counter)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53028728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Need Help For VBScript Regex I wannt to build VbScript regex for string having format like
XX-XX-XX-XX
XX= \w (Alphanumeric)
Note : Number of Hyphen are dynamic.
Sample i/p
ABSCD123
ABC-123
ABC-234-PQ3
A-B-C
I created something like
^\w+\-*\w+$
But it is not working.Can anybody help me?
A: I think you want to group the first "word" with the hyphen
^(\w+\-)*\w+$
This assumes that you want to match things like
XX-XX
XXX-X
XX-XX-XX-XX-XX-XX-XX-XX
XXX
But not
XX-
XX--XX
If there has to be a hyphen then this would work
^(\w+\-)+\w+$
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31990619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I control multiple input object value in map this is a sample in code sand box
https://codesandbox.io/s/restless-shadow-iiw4p?file=/src/App.jsx
I want to create table that can be added.
However can not control input value.
How can I control multiple input object value in map?
A: In your code sample you did not call the setValues() function. That's why you could not control the input. Here are some modifications to your code:
const inputName = (index, event) => {
let tempValues = [...values];
tempValues[index].name = event.target.value;
setValues(tempValues);
};
I hope this code will work now. I have tested it in your codesandbox example also.
here is the link to that: https://codesandbox.io/s/purple-water-d74x5?file=/src/App.jsx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64979751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to execute multi factor auth from powershell I need to execute this PowerShell script from C#. I want to disable MFA for a single user.
I have not installed Azure PowerShell. So to execute below script, what prerequisites are needed?
I am unable to find this .dll in my system:
Microsoft.Online.Administration.StrongAuthenticationRequirement.dll
My code:
string script = "$auth = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement " +
"$auth.RelyingParty = '*' " +
"$auth.State = 'Enforced' " +
"$auth.RememberDevicesNotIssuedBefore = 'Tuesday, November 28, 2017 10:26:43 AM' " +
//"$upn ="+txtUserName.Text+" "[email protected]
"$upn [email protected] " +
"Set-MsolUser -UserPrincipalName $upn -StrongAuthenticationRequirements $auth ";
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(scriptText);
ps.Invoke();
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result);
}
return "";
}
A: 1. Prerequisites:
Download and Install the following modules.
First install the Microsoft Online Services Sign-In Assistant for IT Professionals RTW from the Microsoft Download Center.
Then install the Azure Active Directory Module for Windows PowerShell (64-bit version), and click Run to run the installer package.
*Open Windows PowerShell
*Run the following command
Get-ExecutionPolicy
If the output is anything other than
"unrestricted", run the following command.
Set-ExecutionPolicy Unrestricted –Scope CurrentUser
Confirm the change of settings.
*Connect to MsolService via PowerShell
Running the command below will bring up a popup would require you to enter your Office 365 Administrator Credentials.
$UserCredential = Get-Credential
Import-Module MSOnline
Connect-MsolService –Credential $UserCredential
Enable
$St = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$St.RelyingParty = "*"
$Sta = @($St)
Set-MsolUser -UserPrincipalName [email protected] -StrongAuthenticationRequirements $Sta
Disable
$Sta = @()
Set-MsolUser -UserPrincipalName [email protected] -StrongAuthenticationRequirements $Sta
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48376971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to single out the first bit and retaining the last bit of the filename using grep(find) Greeting
I am writing a bash code to convert decimal to binary from a file name (Ex: 023-124.grf) and unfortunately, I only need to only convert the last 3 numbers of the file without interfering with the first bit
(it looks something like this: 124.grf)
I had already tried using cut but it is only ethical with a text file and as for grepping, i am still trying to figure out on using this command since I am still relatively new to bash
Is there a way to single out the first bit of the filename?
A: Well, I'm not sure you completely specified your problem, but luckily, even a very general variation of it can be solved fairly easily, considering that grep allows you to match both digit and non-digit characters.
So to match "the last 3 consecutive digits that are not succeeded by a digit" in any text (even if it looks like "234_blablabla_lololol_343123_blablabla_abc.ext" or "blabla_987123, rather than "555-123.ext"), you could literally translate the quoted definition to a regular expression, and get "123", by using [0-9] to match a digit and [^0-9] to match a non-digit. The latter serves the purpose of narrowing your digits down to the last ones present in the text, by stating that only non-digits may (optionally) succeed them.
E.g.:
echo 234_blablabla_lololol_343999_blablabla_abc.txt | grep '[0-9][0-9][0-9][^0-9]*$' | grep '^...'
999
Of course, there are many other ways to do this. For instance, grep has a -P flag to enable the most powerful kind of regular expression syntax it supports, namely Perl regex. With this, you can avoid a lot of redundant code.
E.g. with Perl regex, you can shorten repeats of the same regex unit ("atom"):
[0-9][0-9][0-9] -> [0-9]{3}
It even provides shorthands for common concepts as "character classes". One of these is "decimal digit", a shorthand for [0-9], denoted as \d:
[0-9]{3} -> \d{3}
You could also use lookaheads and lookbehinds to fetch your 3 digits in one pass, alleviating the need of grepping for the first 3 characters afterwards (the grep '^...' part), but I can't be bothered to look up the particular syntax for that in grep right now.
Now sadly, I would have to think a lot how to generalize the above definition of "the last 3 consecutive digits that are not succeeded by a digit" into "the last 3 consecutive digits", meaning the above regular expression would not match file names where the last run of 3 digits is succeeded by a digit anywhere later in the file name, such as "blabla_12_blabla_123_blabla_56.ext", but I am optimistic that your naming convention does not allow that.
A: You can use bash primitives to separate out the desired portion of the name. There's probably a slicker way to get the binary conversion of the decimal number, but I like dc:
$ name=023-124.grf
$ base=${name%.*}
$ echo "$base"
023-124
$ suffix=${base##*-}
$ echo $suffix
124
$ echo "$suffix" 2 o p | dc
1111100
$ new_name="${base%%-*}-$(echo $suffix 2 o p | dc).${name##*.}"
$ echo "$new_name"
023-1111100.grf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73959624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MongoError: failed to connect to server [localhost:27017] When I type node server.js it returns me this error
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/home/islam/workspace/project/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:327:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:191:7)
at Connection.<anonymous> (/home/islam/workspace/project/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:274:12)
at Object.onceWrapper (events.js:293:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:194:7)
at Socket.<anonymous> (/home/islam/workspace/project/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:177:49)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at emitErrorNT (net.js:1283:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
**
When I type in command line mongod it returns me this
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] MongoDB starting : pid=24805 port=27017 dbpath=/data/db 64-bit host=user
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] db version v3.4.4
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] git version: 888390515874a9debd1b6c5d36559ca86b44babd
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2g 1 Mar 2016
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] allocator: tcmalloc
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] modules: none
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] build environment:
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] distmod: ubuntu1604
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] distarch: x86_64
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] target_arch: x86_64
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] options: {}
2017-05-05T23:33:06.816+0600 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
2017-05-05T23:33:06.816+0600 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2017-05-05T23:33:06.816+0600 I NETWORK [initandlisten] shutdown: going to flush diaglog...
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] now exiting
2017-05-05T23:33:06.816+0600 I CONTROL [initandlisten] shutting down with code:100
**
However the mongo command gives me this error
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
2017-05-05T23:34:21.724+0600 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-05-05T23:34:21.724+0600 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed
I need to access to my database collections,
Any help will be appreciated!
A: Looks like you need to create the /data/db folder
try doing this in the terminal
sudo mkdir /data/db
then start mongodb
A: Mongo by default writes data to /data folder and the user who is running mongo service does not have permission to create /data folder.
You can get this information from this log snippet
2017-05-05T23:33:06.816+0600 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
2017-05-05T23:33:06.816+0600 I NETWORK [initandlisten] shutdown: going to close listening sockets...
So, you need to do this
sudo mkdir /data/db
sudo chown $USER -R /data/db # give permission to the user who is running mongo service
A: first run mongod.exe If it gives any warnings regarding unsafe shutdowns, metrics, diagnostics ignore them and run mongo.exe in another CLI(command line Interface).
Even then if it does not work, just backup the ../data/db directories and redo the database.
Before access the db using a database driver(eg: mongoose,mongojs) make sure that the database is up and running.
$ mongo MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
use YourAwesomeDatabaseName
switched to db YourAwesomeDatabaseName
You are good to go!
A: I had an issue /mongo.js:237:13 in local terminal trying to run GCP-hosted mongo. I fixed it by removing tags in GCP
A: hey there This is the issue because of your mongodb server is not running
you can verify this by
sudo service mongodb status
**
you need to start the server by running command
sudo service mongodb start
Good Luck
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43810833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dynamic add component using gridstack and angular2? Jquery $.parseHTML does not work I have the following jsfiddle
I want to be able to stick my custom component into a specific grid (e.g. "")
Right now without Angular2, I just use:
var el = $.parseHTML("<div><div class=\"grid-stack-item-content\" data-id=\""+id+"\"/><div/>");
this.grid.add_widget(el, 0, 0, 6, 5, true);
The issue is, I have no idea how I could do something like:
var el = $.parseAndCompileHTMLWithComponent("<div><div class=\"grid-stack-item-content\" data-id=\""+id+"\"/><fancy-button></fancy-button><div/>");
this.grid.add_widget(el, 0, 0, 6, 5, true);
In angular1, I know there is a compile, but in angular2, there is no such thing.
My fancy-button component is straightforward and is as follows:
@Component({
selector: 'fancy-button',
template: `<button>clickme</button>`
})
export class FancyButton {}
How can I dynamically add the fancy-button component?
A: The easist way to add fancy-button component dynamically might be as follows:
1) Add component to entryComponents array of your module
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, GridStackComponent, FancyButtonComponent ],
entryComponents: [ FancyButtonComponent ], // <== here
bootstrap: [ AppComponent ]
})
export class AppModule { }
2) Get root node from compiled component
constructor(private vcRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) { }
getRootNodeFromParsedComponent(component) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
const ref = this.vcRef.createComponent(componentFactory, this.vcRef.length, this.vcRef.injector);
const hostView = <EmbeddedViewRef<any>>ref.hostView;
return hostView.rootNodes[0];
}
3) Use it anywhere
const fancyBoxElement = this.getRootNodeFromParsedComponent(FancyBoxComponent);
$('#someId').append(fancyBoxElement);
Here's Plunker Example for your case
If you're looking for something more complicated then there are a lot of answers where you can use angular compiler to do it working
*
*Load existing components dynamically Angular 2 Final Release
*Equivalent of $compile in Angular 2
*How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
*Angular 2.1.0 create child component on the fly, dynamically
*How to manually lazy load a module?
A: You need to use Angular 2’s ViewContainerRef class, which provides a handy createComponent method. The ViewContainerRef can be informally thought of as a location in the DOM where new components can be inserted.
this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
Here's a working plunker example.
Or you can use the generic HTML outlete from this post
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40314136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: C+Ctrl KeyBinding is not causing copying to happen I have set up a ListBox like so:
<ListBox ItemsSource="{Binding Logs, Mode=OneWay}" x:Name="logListView">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=.}">
<TextBlock.InputBindings>
<KeyBinding Key="C"
Modifiers="Ctrl"
Command="Copy"/>
</TextBlock.InputBindings>
<TextBlock.CommandBindings>
<CommandBinding Command="Copy"
Executed="KeyCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</TextBlock.CommandBindings>
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Command="Copy">
<MenuItem.CommandBindings>
<CommandBinding Command="Copy"
Executed="MenuCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</MenuItem.CommandBindings>
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As you can see, in the template, each TextBlock has a context menu that allows the user to copy the text. This works.
Also in the TextBlock there is an KeyBinding to ctrl+c and a CommandBinding to copy. When I press ctrl+c the method KeyCopyLog_Executed is not executed. I've checked with the debugger.
How should I be binding the keys to the TextBlock?
A: There are a couple of problems here.
First of all, KeyBindings will work only if currently focused element is located inside the element where KeyBindings are defined. In your case you have a ListBoxItem focused, but the KeyBindings are defined on the child element - TextBlock. So, defining a KeyBindings on a TextBlock will not work in any case, since a TextBlock cannot receive focus.
Second of all, you probably need to know what to copy, so you need to pass the currently selected log item as parameter to the Copy command.
Furthermore, if you define a ContextMenu on a TextBlock element it will be opened only if your right-click exactly on the TextBlock. If you click on any other part of the list item, it will not open. So, you need to define the ContextMenu on the list box item itself.
Considering all of that, what I believe you are trying to do can be done in the following way:
<ListBox ItemsSource="{Binding Logs, Mode=OneWay}"
x:Name="logListView"
IsSynchronizedWithCurrentItem="True">
<ListBox.InputBindings>
<KeyBinding Key="C"
Modifiers="Ctrl"
Command="Copy"
CommandParameter="{Binding Logs/}" />
</ListBox.InputBindings>
<ListBox.CommandBindings>
<CommandBinding Command="Copy"
Executed="CopyLogExecuted"
CanExecute="CanExecuteCopyLog" />
</ListBox.CommandBindings>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Command="Copy"
CommandParameter="{Binding}" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here we define a KeyBinding on the ListBox itself and specify as a CommandParameter currently selected list box item (log entry).
CommandBinding is also defined at the ListBox level and it is a single binding for both right click menu and the keyboard shortcut.
The ContextMenu we define in the style for ListBoxItem and bind CommandParameter to the data item represented by this ListBoxItem (log entry).
The DataTemplate just declares a TextBlock with binding to current data item.
And finally, there is only one handler for the Copy command in the code-behind:
private void CopyLogExecuted(object sender, ExecutedRoutedEventArgs e) {
var logItem = e.Parameter;
// Copy log item to the clipboard
}
private void CanExecuteCopyLog(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
A: Thanks to Pavlov Glazkov for explaining that the key and command bindings need to go at the ListBox level, rather than the item template level.
This is the solution I now have:
<ListBox ItemsSource="{Binding Logs, Mode=OneWay}">
<ListBox.InputBindings>
<KeyBinding Key="C"
Modifiers="Ctrl"
Command="Copy"/>
</ListBox.InputBindings>
<ListBox.CommandBindings>
<CommandBinding Command="Copy"
Executed="KeyCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</ListBox.CommandBindings>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=.}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Command="Copy">
<MenuItem.CommandBindings>
<CommandBinding Command="Copy"
Executed="MenuCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</MenuItem.CommandBindings>
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Where KeyCopyLog_Executed is:
private void KeyCopyLog_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
if ((sender as ListBox).SelectedItem != null)
{
LogItem item = (LogItem) (sender as ListBox).SelectedItem;
Clipboard.SetData("Text", item.ToString());
}
}
and MenuCopyLog_Executed is:
private void MenuCopyLog_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
LogItem item = (LogItem) ((sender as MenuItem).TemplatedParent as ContentPresenter).DataContext;
Clipboard.SetData("Text", item.ToString());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5041275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Javascript this.href from asp.net code behind How do I pass this.href from asp.net code behind? Here is what I have, and in javascript I added a alert to see the value and it says 'undefined'
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript(this.href);", true);
function Callscript(href)
{
alert(href);
}
A: href is not a property of the global object. i believe you are looking for window.location.href:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript(window.location.href);", true);
A: You are not passing the href from aspx.cs file properly. It should be something like below.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript('" + this.href + "');", true);
function Callscript(href)
{
alert(href);
}
Hope this Helps!!
A: "This" is two different things - it's one thing on the server and another on the client.
You may try modifying your startup script like so:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript('" + this.href + "');", true);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10805451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ImageView keeps reloading while scrolling the ListView I have a list that contains an ImageView and a Textview. I'm trying to display video thumbnails in the ImageView. The problem is that when I scroll down the list the ImageView keeps reloading the thumbnails until it gets the correct one. Same thing happens when I scroll back up the list.
I'm using a CursorAdapter and an AsyncTask class. Here's the code:
public class VideoAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public TheAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mInflater=LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(VideoColumns.DISPLAY_NAME));
int path = cursor.getColumnIndexOrThrow(VideoColumns.DATA);
ViewHolder holder = (ViewHolder)view.getTag();
holder.thumb.setId(cursor.getPosition());
holder.title.setText(name);
GetThumbnail newImg = new GetThumbnail(holder.thumb);
newImg.execute(cursor.getString(path));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view=mInflater.inflate(R.layout.main_list,parent,false);
ViewHolder holder = new ViewHolder(view);
view.setTag(holder);
return view;
}
private static class ViewHolder{
TextView title;
ImageView thumb;
public ViewHolder(View base) {
title = (TextView)base.findViewById(R.id.text);
thumb = (ImageView)base.findViewById(R.id.image);
}
}
private class GetThumbnail extends AsyncTask<String, Void, Bitmap> {
private ImageView imv;
private int mPosition;
public GetThumbnail(ImageView i){
imv = i;
mPosition = i.getId();
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bm;
bm = ThumbnailUtils.createVideoThumbnail(params[0], Thumbnails.MINI_KIND);
return bm;
}
@Override
protected void onPostExecute(Bitmap result) {
if(result != null && mPosition == imv.getId()){
imv.setImageBitmap(result);
}
}
}
}
Any suggestions would be appreciated. Thanks.
A: Your List view Recycle the rows when you scroll up or down It improver the performance of list view. But if you dont want to recycle it you can stop it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23678116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replacing a shared member variable in a Spring binded class A yet-to-be production released java application code has the below structure(this is there in numerous places). The class loads only once during application context load. This worked fine previously. However when moving to regression environment with multiple threads this will cause concurrency issues due to the shared member variable.
Class A {
private Set<String> codeSet = null;
public void method() {
codeSet = SomeRepo.someMethod(session.getUser()); // Heavy repo call, returns user specific data.
method1();
method2();
....
methodn();
}
private methodn() {
codeSet.iterator().next();
}
}
This issue can be mitigated by changing the variable scope to the method, and having it passed across all subsequent private methods which use this variable. However this involves a lot of changes in the application code.
Is there any clean solution which can resolve the below without much changes. Thanks in advance.
A: Yes, the issue can be easily solved by applying the following refactoring:
// singleton used by multiple threads
class A {
public void method() {
Set<String> codeSet = SomeRepo.someMethod(session.getUser()); // Heavy repo call.
new AProcessor(codeSet).method();
}
}
// not a singleton, only one thread uses an instance of this class
class AProcessor {
private final Set<String> codeSet;
AProcessor(Set<String> codeSet) {
this.codeSet = codeSet;
}
public void method() {
method1();
method2();
....
methodn();
}
private methodn() {
codeSet.iterator().next();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42274517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send a object through the dynamic form control in Angular? I want to send a whole object instead of just a single string value for example. How can I do this?
The object type is:
description: {
type: string;
value: string;
}[];
I have a normal formcontrolTextbox written like this:
new FormControlTextBox({
key: 'description.type',
label: 'profiles.description',
placeholder: '',
required: true,
}),
I would like to send an object now instead?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71631366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Allowing one vote per computer (not IP, not logged in user) I have a site where i want to allow a 5 star rating on various things. However, like many other people asking questions on SO, i only want to allow one vote per person.
At first i was planning on logging the IP address when a vote happens and just scan to see if the current IP had voted before or not which would work great.
But then i realized a problem, the site is designed for college students at one particular school. A couple issues with this if i understand IP correctly:
*
*People using school computers/connected to the school wifi will have the same IP(maybe a handful, but not unique to each computer)
*Many people live in houses of 4-8 people, where they would all share the same IP(assuming they are on the same network)
How could i detect unique votes without using IP addresses or having a user login? Is there any other way to do something like this?
Or maybe i am misunderstanding how IP addresses work and i can still use that - hopefully this is the case.
Thanks
A: You can do this any way you want. There is no "one right way".
On the extreme end, you can have users submit a blood sample when they request an account. You can then check new blood samples against your database. This could result in people submitting family member's blood samples. If that's a concern, you may wish to have them sign a contract, notarized most likely, stating that they have submitted their own blood sample.
You could also have them personally register at your office. You could, for example, collect fingerprints and compare them to your database.
IP addresses are not very useful for this purpose. Some people have access to dozens of IP addresses and in some cases many people share a single IP address.
You could only give a vote to users who have made a large number of intelligent posts to a forum. That would at least cut down on the ease with which people can create voting accounts.
A: I am not sure if it can be implemented in your application but try logging for unique MAC address instead of unique IP address. MAC address are universally unique for each network controller and usually PC just has one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11708251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JList to list toString() of an ArrayList of Objects I have an ArrayList of objects (A class called OrderItem). OrderItem has a toString() method in it.
I also have a GUI class in which I have a JList. I want to list all the toString()'s for the elements of the arrayLists.
I know that for an arrayList of strings you can make them show in a JList by using:
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("Value1");
myArrayList.add("Value2");
myJList = new JList(myArrayList.toArray());
But I want to list the toString() methods of an object arrayList, i.e. have something like:
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
myJList = new JList(myArrayList.toString());
I realise that there is a possibility that JList doesn't support such a feature or that there is some sort of logic problem with this. If that is so could you inform me as to why? Because surely an arrayList of strings should work in a similar way to an object arrayList's toString(). I merely want to be pulling out a String value for the elements and using those values for my list.
I've searched the web for an answer and have not been able to find one that helps me, so I've come here to try to get this resolved.
Thanks a lot!
A: By default, JList shows the toString value of the object. So there is no need to convert your objects to strings.
You can override that behavior of JList if needed by creating custom cell renderers. See How to Use Lists for more details.
A: You can convert the list to an array and then put it in the list.
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
OrderItem[] items = new OrderItem[myArrayList.size()];
myArrayList.toArray(items);
myJList = new JList(items);
A: Actually, the toArray() method displays each item in the arrayList. JList doesn't show anything by default. You have to set the visibility according to your needs.
It sounds like you are trying to simply display the object's toString method in the list instead of the full object; in other words, you simply want to display the string representation. instead of the array representation.
You can rewrite the array to represent the data you want to show (provide the "toString construct as the array is built):
ArrayList<> myNewArrayList = new ArrayList<OrderItem>();
for (int i=0; i< oldArray.size(); i++)
{
newArray.add(oldArray.get)i).toString();
}
... rest of code ...
Then use the new array in the panel and use the index as reference to the object array for object processing.
HTH
LLB
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10320325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When code is in loadView: Could not execute support code to read Objective-C class data in the process Say I create a tableView in navigation controller programmatically. After removing storyboard file and its reference. I put all UI initialization and constraints code into loadView() as below code.
Running with real device, but the table view is not showed up, and soon this waring pops up.
If I put those code in viewDidLoad, everything works fine. So, how could I track down this issue? I have searched some similar threads but without fixing my problem.
warning: could not execute support code to read Objective-C class data
in the process. This may reduce the quality of type information
available.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let table = UITableView()
var pictures = [Picture]()
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// if put code in loadView() into here, everything works fine.
loadData()
}
override func loadView() {
title = "My Pictures"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPicture))
view.addSubview(table)
table.delegate = self
table.dataSource = self
table.register(PictureCell.self, forCellReuseIdentifier: "picture")
table.translatesAutoresizingMaskIntoConstraints = false
table.rowHeight = 120
NSLayoutConstraint.activate([
table.topAnchor.constraint(equalTo: view.topAnchor),
table.leadingAnchor.constraint(equalTo: view.leadingAnchor),
table.trailingAnchor.constraint(equalTo: view.trailingAnchor),
table.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
func loadData() {
DispatchQueue.global().async { [weak self] in
if let savedPcitures = self?.defaults.object(forKey: "pictures") as? Data {
let jsonDecoder = JSONDecoder()
do {
self?.pictures = try jsonDecoder.decode([Picture].self, from: savedPcitures)
} catch {
print("Failed to load pictures.")
}
}
DispatchQueue.main.async {
self?.table.reloadData()
}
}
}
@objc func addPicture() {
let picker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = .camera
} else {
fatalError("Camera is not available, please use real device")
}
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
...
A: If you override loadView(), it is up to you to create and set the controllers "root" view.
If you add this to your code:
override func loadView() {
title = "My Pictures"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPicture))
// add these three lines
let newView = UIView()
newView.backgroundColor = .white
view = newView
view.addSubview(table)
// ... rest of your original code
You should be able to navigate to your controller.
That said --- unless you have a specific reason to override loadView(), you probably shouldn't. All the code in your example would normally go in viewDidLoad().
Edit - for some clarification...
I think Apple's documentation is a bit ambiguous...
As I understand it, any view controller that is a descendant of UIViewController created via code only (UIViewController, UITableViewController, UICollectionViewController, etc) generates its own "root" view unless we override loadView() in which case it is up to us to instantiate and provide that root view.
So, why would we want to provide that view? We may want to provide a custom UIView subclass. For example, if I have a "Gradient" view that sets its base layer class to a CAGradientLayer - so I don't have to add and manage a sublayer. I can override loadView() and set the root view of my controller to that Gradient view.
I've put up a complete example on GitHub. The only Storyboard in the project is the required LaunchScreen --- everything else is done via code only.
It starts with 3 buttons in a navigation controller:
*
*The first button pushes to a simple UIViewController with a label
*The second button pushes to a UITableViewController, where selecting a row pushes to a "Detail" UIViewController
*The third button pushes to a simple UIViewController with a label and a gradient background
The third example is the only one where I override loadView() to use my custom Gradient view. All the others handle all the setup in viewDidLoad()
Here's the link to the project: https://github.com/DonMag/CodeOnly
A: As DonMag said above, I need to give view a value here as it is nil by default(without using interface builder).
And here is a reference I found could explain when to use viewDidLoad or loadView, in my case I used the 2nd way to create all the views programatically.
Reference: https://stackoverflow.com/a/3423960/10158398
When you load your view from a NIB and want to perform further
customization after launch, use viewDidLoad.
If you want to create your view programtically (not using Interface
Builder), use loadView.
Update:
Per DonMag's example. It is clearly that we could use both of way to set the view, either in viewDidLoad or in loadView. And the best practice to use loadView is when we need to use some custom UIView as root view. Meantime, I find a good article about this topic. It is an old one, though I think the concepts will not change.
http://roopc.net/posts/2015/loadview-vs-viewdidload/
To conclude, we can set up the view hierarchy in either loadView or
viewDidLoad, as long as we’re aware of when which method gets called.
The most important thing to remember is that if you override loadView,
you should set the view property, while if you override viewDidLoad,
you should only read the view property, which should have been already
set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64713564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular - Remove item from array on click of that item I'm learning Angular (v6 to be specific), and trying to build a simple to do list.
I'm able to add items to an array and display in a list but cannot figure out how to delete specific items on click of that item.
Current code deletes the entire array on click. Here's my code:
app.component.html
<h1>To Do List</h1>
<label for="">What do you need to to?</label>
<input type="text" [(ngModel)]="listItem">
<br>
<button (click)="addToList()">Add</button>
<hr>
<ul>
<li *ngFor="let toDo of toDoList" (click)="removeFromList($event)">{{ toDo }}</li>
</ul>
app.component.ts
export class AppComponent {
title = 'to-do-list-app';
listItem = '';
toDoList = [];
addToList() {
this.toDoList.push(this.listItem);
}
removeFromList(addedItem) {
this.toDoList.splice(addedItem);
}
A: Pass the item index to splice and specify that one item is to be removed:
<li *ngFor="let toDo of toDoList; let i = index" (click)="toDoList.splice(i, 1)">
See this stackblitz for a demo.
A: On your click function send the object you are removing:
<li *ngFor="let toDo of toDoList" (click)="removeFromList(toDo)">{{ toDo }}</li>
And in your function, find the index of the element, and then use splice to remove it
removeFromList(addedItem) {
var index = this.toDoList.indexOf(addedItem);
this.toDoList.splice(index, 1); // Removes one element, starting from index
}
A: Splice will remove the item from the array by index (and how many items you want to remove), not by value.
To work with arrays and collections, I would suggest to use https://underscorejs.org/ I know it may be an overkill for this problem, but will be useful for more complex scenarios.
You can add the library to your angular project by running the following command:
npm i underscore --save
You may want to also add the typings by running:
npm i @types/underscore --save-dev
Your app.component.ts would then look like
import { Component } from '@angular/core';
import * as _ from 'underscore';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'to-do-list-app';
listItem = '';
toDoList = [];
addToList() {
this.toDoList.push(this.listItem);
}
removeFromList(addedItem) {
this.toDoList = _.without(this.toDoList, addedItem);
}
}
And your app.component.html will look like:
<h1>To Do List</h1>
<label for="">What do you need to to?</label>
<input type="text" [(ngModel)]="listItem">
<br>
<button (click)="addToList()">Add</button>
<hr>
<ul>
<li *ngFor="let toDo of toDoList" (click)="removeFromList(toDo)">{{ toDo }}</li>
</ul>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52042665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring Profiles odd behavior I am trying to figure out how to use Spring Profiles for testing. I think I do everything according to spring docs. And in the end I got results that I cannot explain Here is the listing of my program:
Here is the main config:
package com.test.profiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.util.HashMap;
import java.util.Map;
@Configuration
@ComponentScan("com.test.profiles")
public class MainConfig {
@Autowired
private String helloMsg;
@Autowired
private Map<String,String> profileDependentProps;
@Bean
@Profile("default")
public String helloMsg() {
return "Hello default";
}
@Bean
@Profile("default")
public Map<String,String> profileDependentProps() {
Map<String,String> props = new HashMap<>();
props.put("1", "default");
props.put("2", "default");
props.put("3", "default");
return props;
}
}
Test configuration:
package com.test.profiles;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.util.HashMap;
import java.util.Map;
@Configuration
@Profile("dev")
public class TestConfig {
@Bean
public String helloMsg() {
return "Hello dev";
}
@Bean
public Map<String,String> profileDependentProps() {
Map<String,String> props = new HashMap<>();
props.put("1", "dev");
props.put("2", "dev");
props.put("3", "dev");
return props;
}
}
And finally my test class:
package com.test.profiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import java.util.Map;
@ContextConfiguration(classes = MainConfig.class)
@ActiveProfiles("dev")
public class ProfileTester extends AbstractTestNGSpringContextTests {
@Autowired
private String string;
@Autowired
private Map<String,String> profileDependentProps;
@Test
public void profileTest() {
System.out.println("TEST: "+string);
for(Map.Entry<String,String> entry : profileDependentProps.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
And odd output:
[TestNG] Running:
C:\Users\nikopol\.IntelliJIdea13\system\temp-testng-customsuite.xml
15:36:34,893 INFO GenericApplicationContext:513 - Refreshing org.springframework.context.support.GenericApplicationContext@7ecdc69b: startup date [Mon Mar 10 15:36:34 EET 2014]; root of context hierarchy
TEST: Hello dev
helloMsg=Hello dev
===============================================
Custom suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
15:36:35,105 INFO GenericApplicationContext:873 - Closing org.springframework.context.support.GenericApplicationContext@7ecdc69b: startup date [Mon Mar 10 15:36:34 EET 2014]; root of context hierarchy
What's with this line? --- helloMsg=Hello dev
Where is my map?
A: By default when Spring encounters a auto wiring field of type Map<String, [type]> it will inject a map of beans of the specific [type]. In your case String. You will not get your configured map.
See: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation.
You are basically running into a corner case as you have a map with String as keys. To get your bean you will either have to put an @Qualifier("profileDependentProps") next to the @Autowired or use @Resource("profileDependentProps") instead of @Autowired.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22301878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to order by date django post view How can I order my posts from latest to oldest? I Use ordering = ['-date_posted'] for class based views. how can I do the exact thing for a function based view?
this is my view function:
def blog_view(request):
posts = Post.objects.all()
paginator = Paginator(posts, 3)
page = request.GET.get('page')
posts = paginator.get_page(page)
common_tags = Post.tags.most_common()[:]
context = {
'posts':posts,
'common_tags':common_tags,
}
return render(request, 'posts/blog.html', context)
A: you can do
posts = Post.objects.all().order_by('-date_posted')
or in your models add a meta class
class Meta:
ordering = ['-date_posted']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61250105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Merging Corresponding MySQL Records I have a MySQL table called "objecttable" that has the following structure and data in it. (The data is just a sequence, there is a whole lot more).
ID | Name | posX | posY | posZ |rotX | rotY | rotZ | rotW |
3562 | LODpmedhos1_LAe | 2062 | -1703 | 16 | 0 | 45 | 22 | 1 |
3559 | LODpmedhos5_LAe | 2021 | -1717 | 15 | 0 | 45 | 34 | 1 |
3561 | LODpmedhos3_LAe | 2021 | -1717 | 15 | 0 | 45 | 34 | 1 |
I want to figure out which records have the same posX, posY, posZ, rotX, rotY and rotZ values and insert them into a table called "matchtable", and in the end I want it to look like this (I have the table structure ready)
ID1 | Name | ID2 | Name |
3559 | LODpmedhos5_LAe | 3561 | LODpmedhos3_LAe|
I'd appreciate if someone could give me the correct SQL query for it. I don't have more than two matching coordinates and not all coordinates match.
Sorry if the table representations suck, I'll try to make a HTML table if necessary.
Thanks!
A: This query will do the trick, but the number of results might be a LOT more than required. For example, if there are 5 rows satisfying your query, then the results will be 20( = n*(n-1) ) in number.
SELECT ot.ID AS ID1, ot.Name AS Name1, ot2.ID AS ID2, ot2.Name AS Name
FROM objecttable ot
JOIN objecttable ot2
ON ot.ID > ot2.ID
AND ot.posX = ot2.posX
AND ot.posY = ot2.posY
AND ot.posZ = ot2.posZ
AND ot.rotX = ot2.rotX
AND ot.rotY = ot2.rotY
AND ot.rotZ = ot2.rotZ
EDIT
In reply to lserni's comment:
ON ot.ID <> ot2.ID
The above condition is there to remove the result like:
ID1 | Name | ID2 | Name |
3559 | LODpmedhos5_LAe | 3559 | LODpmedhos5_LAe|
A: try this:
-- insert into matchtable -- uncomment to insert the data
select alias1.Id,
alias1.Name,
alias2.Id
alias2.Name
from objecttable as alias1
join objecttable as alias2
on alias1.posx = alias2.posx
and alias1.posy = alias2.posy
and alias1.posz = alias2.posz
and alias1.roty = alias2.roty
and alias1.roty = alias2.roty
and alias1.rotz = alias2.rotz
and alias1.Id > alias2.Id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12552234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: send automated messages to various whatsApp users using this xpath to click send started not to work I used send automated messages to various whatsApp users using this xpath code to click on the send button.
navegador.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]').send_keys(Keys.SEND)
It recently stopped working saying that it can't find the xpath.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/footer/div[1]/div[2]/div/div[2]/button"} (Session info: chrome=91.0.4472.124)
I've tried updating the xpath as it seams to have changed to:
//*[@id="main"]/footer/div[1]/div[2]/div/div[2]/button
But I still get the same error message.
I've also seen one thread suggesting that the driver may not be set for the current page. If so, how do I fix that?
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=81.0.4044.138)
What am 'I missing?
Thanks in advance for any help on this mater.
A: Possibly your locator is not correct.
Also, the send element button appears with a short delay after the text is inserted into the message text area.
Try this:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located((By.XPATH, '//span[@data-testid="send"]'))).click()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68391730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lua/Wow: UseInventoryItem() issue My goal is to create a script that warns when you are disenchanting a piece you don't want. When disenchanting an item straight from inventory, I could use the UseInventoryItem() API. Since UseInventoryItem() seems to work only on inventory slot right click, I created this script, based on GetMouseFocus() API, that works with the original interface of the game: but if someone used an addon, would it still work?
Of course, better solutions are welcome
local mt = {
__index = {
isvalue = function(t, value)
local is = false
for k, entry in ipairs(t) do
if (entry == value) then
is = true
break
end
end
return is
end
}
};
local protected = { "item1", "item2", "item3", "etch." }; -- items I want to protect
setmetatable(protected, mt);
local disenchanting;
local antidisenchant = CreateFrame("Frame");
antidisenchant:RegisterEvent("UNIT_SPELLCAST_SENT");
antidisenchant:SetScript("OnEvent", function(self, event, ...)
if (event == "UNIT_SPELLCAST_SENT") then
if (arg2 == "Disenchant") then
disenchanting = true
end
end
end);
antidisenchant:SetScript("OnUpdate", function()
if GetMouseFocus() then -- GetMouseFocus() returns the frame that currently has mouse focus.
local TargetItemID = GetInventoryItemID("player",GetMouseFocus():GetID()) -- The IDs of each inventory slot frame have the same id as the slot (16 for main hand, 17 for off hand etc.).
if (TargetItemID) and (string.find(GetMouseFocus():GetName(),"Slot")) then -- Inventory slot frame are named like "CharacterMainHandSlot".
local name, link = GetItemInfo(TargetItemID)
if (disenchanting) and (protected:isvalue(name)) then
DEFAULT_CHAT_FRAME:AddMessage("WARNING! YOU'RE DISENCHANTING "..link,1,0,0)
end
end
end
end)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75264387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Groovy Template Engine rendering contents I'm trying to separate some contents in the body section of my layout.tpl. For instance, I have carousel slider in my index.tpl, but it's not necessary to include it inside the login.tpl. Moreover, I need to add another page specific contents too. So, layout.tpl, and index.tpl are like in the following:
layout.tpl
body {
headerContents()
div(class:'container') {
div(class:'row') {
div(class:'col-lg-12') {
content()
}
}
}
}
index.tpl
layout 'layouts/layout.tpl',
title:'Home',
headerContents: contents {
h1('Test Header')
}
content: contents {
h1('Test Content')
}
But h1('Test Content) cannot be rendered. I checked the docs but I couldn't find anything about how to render two different contents. Does template engine support to do this or not?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25102967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How is gRPC used to enhance Microservice interaction in PHP? I'm studying gRPC and noticed they assist in building quality microservice interactions.
Currently I use RESTful requests to interact between services with typical tools like Guzzle etc.
How does gRPC improve the way Microservices would interact with each-other?
A: gRPC offers several benefits over REST (and also some tradeoffs).
The three primary benefits are:
*
*Protocol Buffers are efficient. Because both sides already have the protobuf definitions, only the data needs to be transferred, not the structure. In contrast, for some JSON payloads, the names of the fields can make the payload significantly larger than just the data. Also, protobuf has a very compact representation "on the wire". Finally, you don't have the overhead of the HTTP headers for every request. (Again, for some smaller requests, the headers could be significantly larger than the request body itself.)
*gRPC can be bidirectional. gRPC services can have "streams" of data which can go both directions. HTTP must always have a request and response matched together.
*gRPC tries to make you think about version compatibility. Protocol Buffers are specifically designed to help you make sure you maintain backwards compatibility as your data structures change. If done properly, this can make future upgrades easier to implement.
With all those upsides, why not use gRPC for everything?
In my view, the main downside of gRPC is that it requires more tooling. Just about any programming language can handle HTTP and there are many debugging tools, but for gRPC you have to compile your .proto files for each language and share them. There also aren't as many testing tools.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71610388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to pass a string from VBA (Excel) to my COM object I am experimenting with creating a COM interface for my application in order to allow eg. VBA to drive certain parts of my application.
I have my COM library up and running and installed, even to the part where a routine called in Excel can be debugged in the Delphi IDE.
Here's the VBA code that I activate from Excel using a button:
Sub TestAMQMOLE_OpenProject()
Dim vConnection As String
Dim vAMQM As Object
Dim vAMProject As Object
vConnection = "$(MYSRC)\LCCAMQM38\UnitTestData\AnalyseSortingAndGrouping"
Set vAMQM = CreateObject("LCCAMQM_AX.LCCAMQM_Application")
vAMQM.Connect
Set vAMQMProject = vAMQM.OpenProject(vConnection) 'This parameter does not get through
Set vAMQMProject.Active = True
Set vAMQMProject = Nothing
vAMQM.Disconnect
Set vAMQM = Nothing
End Sub
And the part in Delphi handling it looks like this:
function TLCCAMQM_Application.OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project;
begin
try
Result:=TLCCAMQM_Project.Create(aFolderOrAlias); // wrapper om TdmAMEditBase
except
SHowMessage(ExceptionToString(ExceptObject,ExceptAddr));
end;
end;
Where the code fails because the aFolderOrAlias parameter string is empty. I added the exception handler in order to debug outside the Delphi IDE. when debugging inside the IDE, the parameter string indeed appears as empty.
I have also tried to pass the parameter as a Variant, or const Variant (and adjusting the type library accordingly), but in that case I get a VT_RECORD variant type (0x0024) which does not make any sense to me.
Here is what the interface definition of the type library looks like.
....
[
uuid(EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5),
helpstring("Dispatch interface for LCCAMQM_Application Object"),
dual,
oleautomation
]
interface ILCCAMQM_Application: IDispatch
{
[id(0x000000C9)]
int _stdcall Connect(void);
[id(0x000000CA)]
int _stdcall Disconnect(void);
[id(0x000000CB)]
ILCCAMQM_Project* _stdcall OpenProject([in] BSTR aFolderOrAlias);
[propget, id(0x000000CC)]
HRESULT _stdcall Connected([out, retval] VARIANT_BOOL* Value);
};
[
uuid(590DBF46-76C9-4877-8F47-5A926AFF389F),
helpstring("LCCAMQM_Application Object")
]
coclass LCCAMQM_Application
{
[default] interface ILCCAMQM_Application;
};
....
I am fairly sure there must be a way to pass strings from VBA to COM objects. But after fiddling around for several hours I am lost :s.
A: As it turned out, ComIntern and Remy were right. I had completely misunderstood the whole stdcall and safecall interfaces.
The .ridl file now looks like this:
....
interface ILCCAMQM_Application: IDispatch
{
[id(0x000000C9)]
int _stdcall Connect(void);
[id(0x000000CA)]
int _stdcall Disconnect(void);
[propget, id(0x000000CC)]
HRESULT _stdcall Connected([out, retval] VARIANT_BOOL* Value);
[id(0x000000CB)]
HRESULT _stdcall OpenProject([in] BSTR aFolderOrAlias, [out, retval] ILCCAMQM_Project** Value);
};
....
And the generated ...TLB.pas file looks like this:
....
// *********************************************************************//
// Interface: ILCCAMQM_Application
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
ILCCAMQM_Application = interface(IDispatch)
['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
function Connect: SYSINT; stdcall;
function Disconnect: SYSINT; stdcall;
function Get_Connected: WordBool; safecall;
function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; safecall;
property Connected: WordBool read Get_Connected;
end;
// *********************************************************************//
// DispIntf: ILCCAMQM_ApplicationDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
ILCCAMQM_ApplicationDisp = dispinterface
['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
function Connect: SYSINT; dispid 201;
function Disconnect: SYSINT; dispid 202;
property Connected: WordBool readonly dispid 204;
function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; dispid 203;
end;
....
And the OpenProject now works from my internal unit test (written in delphi) as well as from Excel-VBA.
Now I am struggling with properties to set and get through Excel VBA as well as through an OleVariant in delphi. But I will have to put that in another Q.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52080187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Table with an array, return hash I have an array ["1","1","a","b","y"] and table1:
table1
POSITION NAME VALUE CODE
1 Animal Dog 1
1 Animal Cat 2
1 Animal Bird 3
2 Place USA 1
2 Place Other 2
3 Color Red a
3 Color Blue b
3 Color Orange c
4 Age Young a
4 Age Middle b
4 Age Old c
5 Alive Yes y
5 Alive No n
For each element in the array, I would like to find a matching POSITION-CODE combination in table1, where POSITION is the index of the element (base 1) and CODE is the element in the array. Then, I want to return a hash that contains the corresponding NAME and VALUE for the matches as a key and its value. The output would be:
{"Animal" => "Dog", "Place" => "USA", "Color" => "Red", "Age" => "Middle", "Alive" => "Yes"}
How would I go about this?
A: I assume you want to map several codes arrays against the same table. Suppose you first read the table into an array:
a = [["1", "Animal", "Dog", "1"],
["1", "Animal", "Cat", "2"],
["1", "Animal", "Bird", "3"],
["2", "Place", "USA", "1"],
["2", "Place", "Other", "2"],
["3", "Color", "Red", "a"],
["3", "Color", "Blue", "b"],
["3", "Color", "Orange", "c"],
["4", "Age", "Young", "a"],
["4", "Age", "Middle", "b"],
["4", "Age", "Old", "c"],
["5", "Alive", "Yes", "y"],
["5", "Alive", "No", "n"]]
and
codes = ["1","1","a","b","y"]
Then you could do this:
codes.zip(a.chunk { |a| a.first }).map { |l,(_,b)|
b.find { |c| c.last == l}[1...-1] }.to_h
#=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
# "Age"=>"Middle", "Alive"=>"Yes"}
The steps:
enum0 = a.chunk { |a| a.first }
#=> #<Enumerator:
# #<Enumerator::Generator:0x007f8d6a0269b8>:each>
To see the contents of the enumerator,
enum0.to_a
#=> [["1", [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
# ["1", "Animal", "Bird", "3"]]],
# ["2", [["2", "Place", "USA", "1"], ["2", "Place", "Other", "2"]]],
# ["3", [["3", "Color", "Red", "a"], ["3", "Color", "Blue", "b"],
["3", "Color", "Orange", "c"]]],
# ["4", [["4", "Age", "Young", "a"], ["4", "Age", "Middle", "b"],
# ["4", "Age", "Old", "c"]]],
# ["5", [["5", "Alive", "Yes", "y"], ["5", "Alive", "No", "n"]]]]
p = codes.zip(enum0)
#=> [["1", ["1", [["1", "Animal", "Dog", "1"],
# ["1", "Animal", "Cat", "2"],
# ["1", "Animal", "Bird", "3"]]]],
# ["1", ["2", [["2", "Place", "USA", "1"],
# ["2", "Place", "Other", "2"]]]],
# ["a", ["3", [["3", "Color", "Red", "a"],
# ["3", "Color", "Blue", "b"],
# ["3", "Color", "Orange", "c"]]]],
# ["b", ["4", [["4", "Age", "Young", "a"],
# ["4", "Age", "Middle", "b"],
# ["4", "Age", "Old", "c"]]]],
# ["y", ["5", [["5", "Alive", "Yes", "y"],
# ["5", "Alive", "No", "n"]]]]]
l,(_,b) = enum1.next
l #=> "1"
b #=> [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
# ["1", "Animal", "Bird", "3"]]
enum1 = b.find
#=> #<Enumerator: [["1", "Animal", "Dog", "1"],
# ["1", "Animal", "Cat", "2"],
# ["1", "Animal", "Bird", "3"]]:find>
c = enum1.next
#=> ["1", "Animal", "Dog", "1"]
c.last == l
#=> true
so enum1 returns
d = ["1", "Animal", "Dog", "1"]
e = d[1...-1]
#=> ["Animal", "Dog"]
So the first element of x.zip(y) is mapped to ["Animal", "Dog"].
After performing the same operations for each of the other elements of enum1, x.zip(y) equals:
f = [["Animal", "Dog"], ["Place", "USA"], ["Color","Red"],
["Age", "Middle"], ["Alive", "Yes"]]
The final steps is
f.to_h
#=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
# "Age"=>"Middle", "Alive"=>"Yes"}
or for < v2.0
Hash[f]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29239926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Oracle 'after create' trigger to grant privileges I have an 'after create on database' trigger to provide select access on newly created tables within specific schemas to different Oracle roles.
If I execute a create table ... as select statement and then query the new table in the same block of code within TOAD or a different UI I encounter an error, but it works if I run the commands separately:
create table schema1.table1 as select * from schema2.table2 where rownum < 2;
select count(*) from schema1.table1;
If I execute them as one block of code I get:
ORA-01031: insufficient privileges
If I execute them individually, I don't get an error and am able to obtain the correct count.
Sample snippet of AFTER CREATE trigger
CREATE OR REPLACE TRIGGER TGR_DATABASE_AUDIT AFTER
CREATE OR DROP OR ALTER ON Database
DECLARE
vOS_User VARCHAR2(30);
vTerminal VARCHAR2(30);
vMachine VARCHAR2(30);
vSession_User VARCHAR2(30);
vSession_Id INTEGER;
l_jobno NUMBER;
BEGIN
SELECT sys_context('USERENV', 'SESSIONID'),
sys_context('USERENV', 'OS_USER'),
sys_context('USERENV', 'TERMINAL'),
sys_context('USERENV', 'HOST'),
sys_context('USERENV', 'SESSION_USER')
INTO vSession_Id,
vOS_User,
vTerminal,
vMachine,
vSession_User
FROM Dual;
insert into schema3.event_table VALUES (vSession_Id, SYSDATE,
vSession_User, vOS_User, vMachine, vTerminal, ora_sysevent,
ora_dict_obj_type,ora_dict_obj_owner,ora_dict_obj_name);
IF ora_sysevent = 'CREATE' THEN
IF (ora_dict_obj_owner = 'SCHEMA1') THEN
IF DICTIONARY_OBJ_TYPE = 'TABLE' THEN
dbms_job.submit(l_jobno,'sys.execute_app_ddl(''GRANT SELECT
ON '||ora_dict_obj_owner||'.'||ora_dict_obj_name||' TO
Role1,Role2'');');
END IF;
END IF;
END IF;
END;
A: Jobs are asynchronous. Your code is not.
Ignoring for the moment the fact that if you're dynamically granting privileges that something in the world is creating new tables live in production without going through a change control process (at which point a human reviewer would ensure that appropriate grants were included) which implies that you have a much bigger problem...
When you run the CREATE TABLE statement, the trigger fires and a job is scheduled to run. That job runs in a separate session and can't start until your CREATE TABLE statement issues its final implicit commit and returns control to the first session. Best case, that job runs a second or two after the CREATE TABLE statement completes. But it could be longer depending on how many background jobs are allowed to run simultaneously, what other jobs are running, how busy Oracle is, etc.
The simplest approach would be to add a dbms_lock.sleep call between the CREATE TABLE and the SELECT that waits a reasonable amount of time to give the background job time to run. That's trivial to code (and useful to validate that this is, in fact, the only problem you have) but it's not foolproof. Even if you put in a delay that's "long enough" for testing, you might encounter a longer delay in the future. The more complicated approach would be to query dba_jobs, look to see if there is a job there related to the table you just created, and sleep if there is in a loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32356401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: take minus(-) sign number from sting and use in in different procedure I have variable
DECLARE @Routs NVARCHAR(1024)
@i int
SET @Routs = N'6,4,-5,8'
I need to extract any number from this sting, where it have minus sign before it (-5 in example)
and use it as input parameter with out (-) sing for example @i in different stored procedure.
A: Pass in you're @Routs parameter to a table valued function that will split the list into a table and then loop through the table and if the value is a negative number execute stored procedure or whatever you want or do nothing if its not negative.
--table function to split parameter by comma
ALTER FUNCTION [dbo].[SplitListOfInts] (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
if len(rtrim(@list)) > 0
begin
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
end
RETURN
END
-- stored procedure that calls that split function and uses @routs parameter
CREATE TABLE #values(nbrValue int)
INSERT INTO #values(nbrValue
EXEC [dbo].[SplitListOfInts] @routs
--if you don't care about non-negatives delete them here
DELETE FROM #values
where nbrValue >= 0
DECLARE @i int
DECLARE @countrows = (SELECT COUNT(nbrValue) FROM #values)
WHILE @countrows >0
SET @i = (SELECT TOP 1 nbrValue FROM #values)
...do what you want
DELETE FROM #values where nbrValue=@i
set @countrows = (SELECT COUNT(nbrValue) FROM #values)
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27232587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Mock lodash .isEqual Nodejs Jest Framework Super Test I am bit stuck testing lodash library lodash library using jest and super test
A.routes.js
import express from 'express';
const router = express.Router();
const _ = require('lodash');
router.post('/', async (req, res, next) => {
try {
let data = req.body
if(!_.isEqual(data,{"hello":"hello"}){
console.log('Not Equal') // This line is not getting covered in Code Coverage
}
}.catch(e=>{
console.log(e);
})
});
export default router;
A.route.test.js
import a from 'A.route'
import express from 'express';
import supertest from 'supertest';
let _ = require('lodash');
_.isEqual = jest.fn();
describe('API Calls', () => {
const app = express();
let request;
beforeAll(() => {
request = supertest(app);
});
beforeEach(()=>{
jest.resetModules();
});
test('Successful call to post /', async () => {
const body= {
"Hello": "Not Hello"
};
_.isEqual.mockResolvedValueOnce(false);
await request.post('/')
.set('Content-Type', 'application/json')
.set('Authorization', 'authToken')
.send(body);
});
});
Code coverage is not able to cover console.log('Not Equal');I tried with _.isEqual.mockImplementation (()=>return false); also tried with _.isEqual.mockReturnValueOnce(false)
A: You should test the behaviour of this API. This means you should care about the response rather than the implementation details. You should pass in an input, such as req.body, to assert whether the result is in line with your expectations.
Since your code cannot be executed, I will arbitrarily add some code to demonstrate
E.g.
a.router.js:
import express from 'express';
const router = express.Router();
const _ = require('lodash');
router.use(express.json());
router.post('/', async (req, res, next) => {
try {
let data = req.body;
console.log('data: ', data);
if (!_.isEqual(data, { hello: 'hello' })) {
res.send('Not Equal');
} else {
throw new Error('Equal');
}
} catch (e) {
res.send(`Error: ${e.message}`);
}
});
export default router;
a.router.test.js:
import a from './a.router';
import express from 'express';
import supertest from 'supertest';
describe('API Calls', () => {
const app = express();
let request;
beforeAll(() => {
app.use(a);
request = supertest(app);
});
test('Successful call to post /', async () => {
const body = {
Hello: 'Not Hello',
};
const res = await request
.post('/')
.set('Content-Type', 'application/json')
.set('Authorization', 'authToken')
.send(body);
expect(res.text).toEqual('Not Equal');
});
test('should handle error', async () => {
const body = {
hello: 'hello',
};
const res = await request
.post('/')
.set('Content-Type', 'application/json')
.set('Authorization', 'authToken')
.send(body);
expect(res.text).toEqual('Error: Equal');
});
});
test result:
PASS examples/67536129/a.router.test.js (8.606 s)
API Calls
✓ Successful call to post / (48 ms)
✓ should handle error (5 ms)
console.log
data: { Hello: 'Not Hello' }
at examples/67536129/a.router.js:9:13
console.log
data: { hello: 'hello' }
at examples/67536129/a.router.js:9:13
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
a.router.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.424 s
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67536129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamicly adding paramteters to an ajax call based on a variables state I have an ajax call that has a list of parameters that it needs to pass to its data object. But this list changes based on a certain category. So I'm trying to find a way to filter through the ones I need and the ones I don't need.
$.ajax({
url:'......',
type:'post',
dataType:'json',
data: {
'api': 'myApilist',
'address' : 'someaddress',
'callTime' : _this.get('calltime'),
'id1' : _this.get('id1'),
'id2' : _this.get('id2'),
'type' : _this.get('type'),
'options': _this.get("options"),
'mode' : _this.get('mode'),
'time' : _this.get('time')
'method' : 'POST'
},
Sometimes id1 and id2 are not needed based on a state I have setup. So if the state="time" then the id1 and id2 don not need to be part of the data list. And if the state="id" then both ids need to be in there.
I was trying to use the filter loops in _underscore to try and filter out these options based on my state but it didn't work as I don't understand them correctly. How would I go about this.
_this.get("options") is referring to a Backbone model.
A: You have to build your data string before you pass it in the ajax call. This is one way you can do:
var dynData = new Object();
dynData.api = <value>;
dynData.address = <value>;
Looks static as of now. Now based on your 'state', you can add properties to the javascript object on the fly using the following:
dynData["newProperty"] = <value>;
Now using JSON and json2.js, you can create your JSON string using:
data:JSON.stringify(dynData);
Mark as answer if this worked :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7989807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP - UTF8 problem with German characters I'm at my wits end with this one, then I remember stack overflow.
I have a site, http://bridgeserver3.co.uk/disklavier/de/ , the language is stored in a simple PHP file which looks like..
$translations["welcome_text_3"]="Zum Lieferumfang eines jeden Disklaviers gehren bereits zahlreiche Lieder und das Angebot lsst sich jederzeit erweitern. Unsere neuen Modelle warten sowohl mit akustischen als auch mit digitalen Errungenschaften auf, darunter die Wiedergabe von Audio- und MIDI-CDs sowie die revolutionre ãPianoSmartªÓ-Funktion fr die Synchronisation Ihrer Klavieraufzeichnungen mit handelsblichen Audio-CDs. Und wenn Sie schon eine Weile davon trumen, eines Tages zumindest passabel Klavier spielen zu knnen, hilft Ihnen die neue ãSmartKeyªÓ-Technologie beim Einstudieren Ihrer ersten Stcke und versieht Ihr Spiel sogar mit professionellen Verzierungen.";
(The characters show up perfectly in the file, but not on SO).
This text was exported from an excel spreadsheet and the flat file created manually.
The page encoding is UTF8, and I've added:
header("Content-type: text/html; charset=UTF-8");
to the php file, yet when I echo out the string it lose the German characters.
Can anyone offer any tips?
James
A: I found the problem...
Excel exported the text with Windows encoding, so it looked correct even in TextMate on my mac. When I reopen with UTF8 encoding the problem was visible in the translations file.
To resolve I used EditPadPro on a PC to convert to UTF8.
Phew.
A: Maybe you could try adding this inside your <head> tag?
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
A: I use Coda but I think textmate has to offer some option like Text->Encoding->Unicode UTF-8, activate it and then your file will be encoded properly and then save it.
Anyway if you are going to put some forms and you are not sure the people is using the correct encoding mode you'll have the same problem.
Use something like this:
<?php
$not_utf8 = "An invalid string"; //Put here the bad text for testing
$not_utf8 = mb_convert_encoding($not_utf8, 'UTF-8', mb_detect_encoding($not_utf8));
echo htmlspecialchars($not_utf8, ENT_QUOTES, 'UTF-8'); //The output should be ok, see the source code generated and search for the correct html entities for these special chars
?>
Hope this help you!
Luis.
A:
The page encoding is UTF8, and I've added:
Probably not. Make sure that the php file is actually saved with utf-8 encoding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1757345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to assign names to dynamically generated text boxes and retrieve their values? I have dynamically generated textboxes. I want to assign names and id to the textboxes and also retrieve the values of dynamically generated textboxes to insert into database. How can it be done?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<select id="sel2" multiple>
<option value="first">first option</option>
<option value="second">sec option</option>
<option value="third">third option</option>
<option value="fourth">fourth option</option>
<option value="fifth">fifth option</option>
<option value="sixth">six option</option>
</select>
<table id="tab2">
<tbody>
</tbody>
</table>
<button id="add" value="Add">Add</button>
<script>
$(document).ready(function()
{
$("#add").click(function()
{
var selectval = $('#sel2').val();
var len = selectval.length;
for(var i=0; i < len; i++){
$("#tab2 tbody").append("<tr><td>"+selectval[i]+"</td><td><input type='text'</td></tr>");
}
});
});
</script>
A: Try like below , It will help you...
$("#tab2 tbody").append("<tr><td>"+selectval[i]+"</td><td><input type='text' id='text" + i + "' /></td></tr>");
It will generate Id like text0, text1, text2...
To Get the value from the Text box add the below codes and try it...
Fiddle Example : http://jsfiddle.net/RDz5M/4/
HTML :
<button id="Get" value="Get">Get</button>
JQuery :
$("#Get").click(function(){
$('#tab2 tr').each(function(){
$("#divResult").html($("#divResult").html() + ($(this).find("input[id^='text']").val()) + "<br>")
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15438746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Massive inserts kill arangod (well, almost) I was wondering of anyone has ever encountered this:
When inserting documents via AQL, I can easily kill my arango server. For example
FOR i IN 1 .. 10
FOR u IN users
INSERT {
_from: u._id,
_to: CONCAT("posts/",CEIL(RAND()*2000)),
displayDate: CEIL(RAND()*100000000)
} INTO canSee
(where users contains 500000 entries), the following happens
*
*canSee becomes completely locked (also no more reads)
*memory consumption goes up
*arangosh or web console becomes unresponsive
*fails [ArangoError 2001: Could not connect]
*server is still running, accessing collection gives timeouts
*it takes around 5-10 minutes until the server recovers and I can access the collection again
*access to any other collection works fine
So ok, I'm creating a lot of entries and AQL might be implemented in a way that it does this in bulk. When doing the writes via db.save method it works but is much slower.
Also I suspect this might have to do with write-ahead cache filling up.
But still, is there a way I can fix this? Writing a lot of entries to a database should not necessarily kill it.
Logs say
DEBUG [./lib/GeneralServer/GeneralServerDispatcher.h:411] shutdownHandler called, but no handler is known for task
DEBUG [arangod/VocBase/datafile.cpp:949] created datafile '/usr/local/var/lib/arangodb/journals/logfile-6623368699310.db' of size 33554432 and page-size 4096
DEBUG [arangod/Wal/CollectorThread.cpp:1305] closing full journal '/usr/local/var/lib/arangodb/databases/database-120933/collection-4262707447412/journal-6558669721243.db'
bests
A: The above query will insert 5M documents into ArangoDB in a single transaction. This will take a while to complete, and while the transaction is still ongoing, it will hold lots of (potentially needed) rollback data in memory.
Additionally, the above query will first build up all the documents to insert in memory, and once that's done, will start inserting them. Building all the documents will also consume a lot of memory. When executing this query, you will see the memory usage steadily increasing until at some point the disk writes will kick in when the actual inserts start.
There are at least two ways for improving this:
*
*it might be beneficial to split the query into multiple, smaller transactions. Each transaction then won't be as big as the original one, and will not block that many system resources while ongoing.
*for the query above, it technically isn't necessary to build up all documents to insert in memory first, and only after that insert them all. Instead, documents read from users could be inserted into canSee as they arrive. This won't speed up the query, but it will significantly lower memory consumption during query execution for result sets as big as above. It will also lead to the writes starting immediately, and thus write-ahead log collection starting earlier. Not all queries are eligible for this optimization, but some (including the above) are. I worked on a mechanism today that detects eligible queries and executes them this way. The change was pushed into the devel branch today, and will be available with ArangoDB 2.5.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28322579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: smartfield annotation - valuehelp dropdown I have a value help field and want to see only descriptions (not codes) in the dropdown. After selection, want to store the code in another field which would be in hidden mode. For this, I have defined the following annotation:
<Annotations Target="Metadata.CallReport/DivisionText">
<Annotation Term="Common.ValueList">
<Record Type="Common.ValueListType">
<PropertyValue Property="CollectionPath" String="CustomizingDivisionSet" />
<PropertyValue Property="Parameters">
<Collection>
<Record Type="Common.ValueListParameterOut">
<PropertyValue Property="LocalDataProperty" PropertyPath="DivisionText" />
<PropertyValue Property="ValueListProperty" String="Text" />
</Record>
<Record Type="Common.ValueListParameterOut">
<PropertyValue Property="LocalDataProperty" PropertyPath="Division" />
<PropertyValue Property="ValueListProperty" String="Value" />
</Record>
</Collection>
</PropertyValue>
<PropertyValue Property="SearchSupported" Bool="false" />
</Record>
</Annotation>
</Annotations>
And the view definition..
<!-- ... -->
<smartField:SmartField textLabel="Division" value="{DivisionText}">
<smartField:configuration>
<smartField:Configuration controlType="dropDownList" displayBehaviour="descriptionOnly" />
</smartField:configuration>
</smartField:SmartField>
<!-- ... -->
Everything works fine; the code for the description I have selected is copied to Division field. However, when I change this dropdown field, the selection works, but the code does not get copied to Division field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57980346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iOS location icon everyone. I don't know whether you used app name Moves or not. If not,you can to download from app store. And you can find a issue, that display gps icon in status bar always(even though app was killed). At "Setting-privacy-location service",if you turn off the app,icon disappear. Turn on again, icon purple display. Why purple display,app is updating location?
A: If an app uses, for example, significant change service, the icon stays on even if the app is killed (because with significant change service, the app will be automatically re-awaken when iOS determines that a significant change has taken place; i.e. the iOS is effectively still tracking your location on behalf of the app, even though the app has been manually terminated). This is the documented behavior of significant change service, which, while less accurate than can be rendered by standard location services, continues tracking you even after the app has been terminated. The purple icon of location services won't be turned off until the app explicitly disables significant change service, or the app has been uninstalled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18179394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Possible to retrieve selected children list from database only by using JPA/Hibernate-Annotation? Guess this might be a difficult one. Well, at least for me. I need some help with JPA/Hibernate-Annotations and I was wondering, if there is a way to solve my problem. Unfortunately, my own skills seem too limited to solve that problem by myself. That's why I'm hoping to find anyone here who might have a good grasp on jpa-annotations and relational databases (here: oracle).
Task:
I have three tables (see attached image! Please don't change this part, since the tables aren't supposed to be created! They already exist with exactly these names, may not be changed and the primary key + foreign key part is just to provide more information about these already existing tables that I uploaded here as an image! Thank you.):
CONSTANT (PRIMARY KEY CONSTANT(ID) + FOREIGN KEY (PARENT_CONSTANT_ID) REFERENCES CONSTANT(ID)),
COUNTRY (PRIMARY KEY COUNTRY(ID)),
COUNTRY_TO_CONSTANT (PRIMARY KEY COUNTRY_TO_CONSTANT(COUNTRY_ID, CONSTANT_ID))
as shown here: Tables-Image
Java-Beans look like that:
Constant.java
@Id
@Column(name = "ID")
private Integer id;
@Basic
@Column(name = "CODE")
private String code;
@Basic
@Column(name = "SORT_KEY")
private int sortKey;
@ManyToOne
@JoinColumn(name = "CONSTANT_TYPE_ID", referencedColumnName = "ID")
private ConstantType constantType;
@ManyToOne
@JoinColumn(name = "parent_constant_id", referencedColumnName = "ID")
private Constant parent;
@OneToMany(mappedBy = "parent", targetEntity = Constant.class)
private List children;
...
public Collection<Constant> getChildren() {
return children;
}
CountryToConstant.java
@Id
@Basic
@Column( name = "COUNTRY_ID" )
private Integer countryID;
@Id
@Basic
@Column( name = "CONSTANT_ID" )
private Integer constantID;
Country.java
@Id
@Column( name = "ID" )
@SequenceGenerator( name = "CountrySequence", sequenceName = "COUNTRY_ID_SEQ" )
@GeneratedValue( generator = "CountrySequence" )
private Integer id;
@Basic
@Column( name = "CODE" )
private String code;
@Basic
@Column( name = "NAME" )
private String name;
@Basic
@Column( name = "LANGUAGE_CODES" )
private String languageCodes;
I left out all getters + setters for brevity except for the constant.java-getter of the 'children'-attribute, since this is the only getter needed for this issue. To make it more difficult: The structure of the java-beans shown above may not be changed, but is allowed to be expanded. This is due to not destroying the already existing (very complex) programm structure.
private List children (Constant.java) is mapped by the attribute private Constant parent. Let's assume that by the other program logic a list with 'parent' CONSTANT ids (e.g. id = {11, 12}) is used here to iterate through and handed over one after another to create 1 parent-object. As a result this will create one private List children after another. Therefore, the result of the example would be 2 separate children lists due to the iteration:
*
*parent-id 11 -> children-id-list: {111, 112, 113, 114, 115, 116}
*id 12 -> id-list: {121, 122, 123}) for each parent-object.
What I need to get instead is a specific list corresponding to the COUNTRY_TO_CONSTANT table, only by using annotations. For example: If the person uses a browser in Germany, the locale is set to de_DE resulting in the COUNTRY.id '1001'. And based (only) on the country code (not the locale), the result for the iteration example above (CONSTANT.id = {11, 12}) should be these two lists:
*
*parent-id 11 -> children-id-list: {111, 112, 113} (leaving out constant-id 114, 115, and 116)
*parent-id 12 -> children-id-list: {121} (leaving out constant-id 122, and 123)
Idea is that depending on the country code and the CONSTANT.IDs put in the table COUNTRY_TO_CONSTANT, every list is created individually corresponding to the related database entries.
Since private List children cannot be changed in definition, what I need is a second attribute (e.g. private List children2) that works exactly like private List children with the only difference that only the country related children (see COUNTRY_TO_CONSTANT table) should be mapped by private Constant parent.
I was thinking about something like:
@OneToMany(mappedBy = "parent", targetEntity = Constant.class)
//Any annotation to get what I need.
private List children2
or maybe:
@ManyToMany(mappedBy = "children", targetEntity = Constant.class)
//Any annotation to get what I need.
private Set children2
Is that even possible to achieve just by using annotations?
Hope, things are clearly explained so far. If not, what kind of workaround could I use here? If any info is missing, please let me know.
Thanks a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65674232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: One site with 2 different physical paths (2 different subfolders) is it possible to that I can configure a site in IIS Manager with two different physical paths (2 subfolders)?
Thank you ;-)
A: No, you can only specify one path for the site, that is the path for loading the site's default document and configuration file (web.config) etc. But you can add multiple virtual directory for the website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21409437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSWindowFlipper build error I am trying to use Mizage's window flipper library in my Mac app.
When I tried to build it, the following error occurs:
Undefined symbols for architecture x86_64:
"_kCAGravityCenter", referenced from:
-[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DMakeRotation", referenced from:
-[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_kCAMediaTimingFunctionEaseInEaseOut", referenced from:
-[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DIdentity", referenced from:
-[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DRotate", referenced from:
-[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_OBJC_CLASS_$_CALayer", referenced from:
objc-class-ref in NSWindowFlipper.o
"_OBJC_CLASS_$_CABasicAnimation", referenced from:
objc-class-ref in NSWindowFlipper.o
"_OBJC_CLASS_$_CAMediaTimingFunction", referenced from:
objc-class-ref in NSWindowFlipper.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
My base SDK is 10.7 and have ARC enabled. I am new to Cocoa and have not seen this kind of error before. Can someone suggest what's the problem here and possibly how to resolve it? Thanks.
A: You need to link with the QuartzCore framework.
Linking to a Library or Framework
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7957324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RegEx multiple steps in ruby Given the string below:
"oxcCFC/video.mp4 "GET /accounts/6/videos/xboxcCFC/video.mp4 HTTP/1.1" 206 - 2 697898511 56 56 "-""
How would I create a regular expression that first finds "HTTP, then finds "-", and then captures the next indiviual number or consecutive numbers that occurs in the sequence?
I'm trying to use rubular but struggling big time.
A: Not a lot to go on, but I think it should be something like this:
/^.*\s+HTTP.*\s+-\s+(\d+)\s+/
A backreference will then hold the value you're after.
A: I'd see if you can use the apachelogregex gem... http://rubydoc.info/gems/apachelogregex/0.1.0/frames
A: Short answer: /HTTP[^-]*-([\d\s]+)/
then, call split on the result.
This regexp translates to:
"HTTP", followed by any number of non-hyphen characters, followed by a hyphen, followed by the largest string consisting only of digits and spaces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13637269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why do I get this NullReferenceException C# I've been working in some codes for an application to manage connected users and Equipments via Active directory queries.
Then I get this error "NullReferenceException was unhandled" for about a week, working with the code this is the only thing stopping the application now.
And this is the code of the background worked I used:
private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)
{
try
{
e.Result = "";
int val = 6000;
for (int a = 1; a <= val; a++)
{
counter.Text = Convert.ToString(a);
if (txtWorkGroupName.Text == "") return;
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add(new DataColumn("ComputerName", typeof(String))); //0
dt.Columns.Add(new DataColumn("IP", typeof(String))); //1
dt.Columns.Add(new DataColumn("MAC", typeof(String))); //2
dt.Columns.Add(new DataColumn("Descubierto", typeof(String))); //3
//int i = 0;
try
{
// Datos del grupo WinNT://&&&&(Nombre del grupo de trabajo)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + txtWorkGroupName.Text + "");
DomainEntry.Children.SchemaFilter.Add("Computer");
///*************************************************
/// Interacting with pc's in the domain
///*************************************************
foreach (DirectoryEntry machine in DomainEntry.Children)
{
string strMachineName = machine.Name;
string strMACAddress = "";
IPAddress IPAddress;
DateTime discovered;
try
{
IPAddress = getIPByName(machine.Name);
}
catch
{
continue;
}//try/catch
///*************************************************
/// Get Mac
///*************************************************
strMACAddress = getMACAddress(IPAddress);
discovered = DateTime.Now;
///*************************************************
/// Add lines in the grid
///*************************************************
DataRow dr = dt.NewRow();
dr[0] = machine.Name;
dr[1] = IPAddress;
dr[2] = strMACAddress;
dr[3] = Convert.ToString(discovered);
dt.Rows.Add(dr);
///*************************************************
/// SETTING DATASOURCE
///*************************************************
dgvComputers1.DataSource = dt;
Thread.Sleep(2000);
}//foreach loop
catch (Exception ex)
{
{
MessageBox.Show(ex.Message);
}
}
if (backgroundWorker2.CancellationPending)
{
e.Cancel = true;
return;
}
}
}
catch (NullReferenceException ex)
{
MessageBox.Show("error:" + ex);
}
catch (NoNullAllowedException ex)
{
MessageBox.Show("error:" + ex);
}
catch (AccessViolationException ex)
{
MessageBox.Show("error:" + ex);
}
}
This is the exception details, sorry that they are in Spanish.
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="System.Windows.Forms"
StackTrace:
en System.Windows.Forms.DataGridViewRowHeaderCell.PaintPrivate(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates dataGridViewElementState, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, Boolean computeContentBounds, Boolean computeErrorIconBounds, Boolean paint)
en System.Windows.Forms.DataGridViewRowHeaderCell.Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, Object value, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
en System.Windows.Forms.DataGridViewCell.PaintWork(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
en System.Windows.Forms.DataGridViewRow.PaintHeader(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow, DataGridViewPaintParts paintParts)
en System.Windows.Forms.DataGridViewRow.Paint(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow)
en System.Windows.Forms.DataGridView.PaintRows(Graphics g, Rectangle boundingRect, Rectangle clipRect, Boolean singleHorizontalBorderAdded)
en System.Windows.Forms.DataGridView.PaintGrid(Graphics g, Rectangle gridBounds, Rectangle clipRect, Boolean singleVerticalBorderAdded, Boolean singleHorizontalBorderAdded)
en System.Windows.Forms.DataGridView.OnPaint(PaintEventArgs e)
en System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
en System.Windows.Forms.Control.WmPaint(Message& m)
en System.Windows.Forms.Control.WndProc(Message& m)
en System.Windows.Forms.DataGridView.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
en System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods. IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.Run(Form mainForm)
en NetworkScanner.Program.Main() en C:\Project Sigma 6\New Power move\discover\Program.cs:línea 17
en System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
en System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
en System.Threading.ThreadHelper.ThreadStart_Context(Object state)
en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
en System.Threading.ThreadHelper.ThreadStart()
A: It's a multithreading issue. At some point you're trying to change the datasource of your datagrid at the exact same time it's painting itself on screen.
dgvComputers1.DataSource = dt;
Try replacing that by:
this.Invoke(delegate(DataTable table)
{
dgvComputers1.DataSource = table;
}, dt);
A: Have you tried this?
dr[1] = IPAddress ?? "(unknown)";
A: Try putting a breakpoint in (if you are using Visual Studio) and checking each line and see where the error occurs.
Then, after getting to the line, check in the watch window to see what is null.
Then go: if(nullThing == null) return; before the line where the error occurs, of course, you shouldn't always do this, but find out WHY it is null, and sort it out.
That should do the job.
A: Check this out:
`private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)
Delete that
`
It should be:
private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8621350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: netlify-function Netlify functions is one of the services offered in the Netlify platform.
It uses AWS's serverless Lambda functions, but allows users to access them without an AWS account, and with management of the functions all done by Netlify. Netlify functions can be built with either JavaScript or Go.
Learn more about Netlify Functions and their abilities here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62924371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to select columns from another dataframe , where these columns are list of value of column in different dataframe I am using spark-sql 2.3.1v with java8.
I have data frame like below
val df_data = Seq(
("G1","I1","col1_r1", "col2_r1","col3_r1"),
("G1","I2","col1_r2", "col2_r2","col3_r3")
).toDF("group","industry_id","col1","col2","col3")
.withColumn("group", $"group".cast(StringType))
.withColumn("industry_id", $"industry_id".cast(StringType))
.withColumn("col1", $"col1".cast(StringType))
.withColumn("col2", $"col2".cast(StringType))
.withColumn("col3", $"col3".cast(StringType))
+-----+-----------+-------+-------+-------+
|group|industry_id| col1| col2| col3|
+-----+-----------+-------+-------+-------+
| G1| I1|col1_r1|col2_r1|col3_r1|
| G1| I2|col1_r2|col2_r2|col3_r3|
+-----+-----------+-------+-------+-------+
val df_cols = Seq(
("1", "usa", Seq("col1","col2","col3")),
("2", "ind", Seq("col1","col2"))
).toDF("id","name","list_of_colums")
.withColumn("id", $"id".cast(IntegerType))
.withColumn("name", $"name".cast(StringType))
+---+----+------------------+
| id|name| list_of_colums|
+---+----+------------------+
| 1| usa|[col1, col2, col3]|
| 2| ind| [col1, col2]|
+---+----+------------------+
Question :
As shown above I have columns information in "df_cols" dataframe.
And all the data in the "df_data" dataframe.
how can I select columns dynamically from "df_data" to the given id of "df_cols" ??
A: Initial question:
val columns = df_cols
.where("id = 2")
.select("list_of_colums")
.rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0)
val df_data_result = df_data.select(columns(0), columns.tail: _*)
+-------+-------+
| col1| col2|
+-------+-------+
|col1_r1|col2_r1|
|col1_r2|col2_r2|
+-------+-------+
Updated question:
1) We may just use 2 lists: static columns + dynamic ones
2) I think that "rdd" is ok in this code. I don't know how to update to "Dataframe" only, unfortunately.
val staticColumns = Seq[String]("group", "industry_id")
val dynamicColumns = df_cols
.where("id = 2")
.select("list_of_colums")
.rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0)
val columns: Seq[String] = staticColumns ++ dynamicColumns
val df_data_result = df_data.select(columns(0), columns.tail: _*)
+-----+-----------+-------+-------+
|group|industry_id| col1| col2|
+-----+-----------+-------+-------+
| G1| I1|col1_r1|col2_r1|
| G1| I2|col1_r2|col2_r2|
+-----+-----------+-------+-------+
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60830256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open a new tab in a browser with the response to an ASP request It's a bit complicated this one... Lets say I have a listing of PDF files displayed in the user's browser. Each filename is a link pointing not to the file, but to an ASP page, say
<--a href="viewfile.asp?file=somefile.pdf">somefile.pdf</a>
I want viewfile.asp to fetch the file (I've done that bit OK) but I then want the file to be loaded by the browser as if the user had opened the PDF file directly. And I want it to open in a new tab or browser window.
here's (simplified) viewfile.asp:
<%
var FileID = Request.querystring ("file") ;
var ResponseBody = MyGETRequest (SomeURL + FileID) ;
if (MyHTTPResult == 200)
{
if (ExtractFileExt (FileID).toLowerCase = "pdf")
{
?????? // return file contents in new browser tab
}
....
%>
A: As Daniel points out you can control whether to open in a new window but not a new tab. If the user has configured their browser so that new windows should open in new tabs (like I do) then you're golden. If not it will open in a new window. You can't control tabs.
A: I would do this.
<a href="viewfile.asp?file=somefile.pdf" target="_blank">somefile.pdf</a>
That way this opens in a new window/tab. Any server side language does not have control of the browser.
To serve it as a PDF, call
<% response.ContentType="application/pdf" %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2717943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Writing from System.out.println to a file I've replaced many strings and outputted the result and now am trying to write those lines into a text file. Here's what I did. I created a new file:
File newfile = new File("/Users/Bill/Desktop/newfile.txt");
if (newfile.exists()) {
System.out.println("File exists");
} else {
newfile.createNewFile();
System.out.println("New file created");
}
And then I tried to write to the created file the result of System.out.println(lines[i]);
try {
WriteToFile newFile = new WriteToFile(newfile, true);
newFile.write(lines[i]);
// lines[i] is what I used to print out System.out.println(lines[i])
}
catch (IOException e) {
System.out.println("Error.");
}
I'm not getting what I'm expecting, though. Any suggestions?
WRITETOFILE:
public class WriteToFile {
private String path;
private boolean append = false;
public WriteToFile(String filename) {
path=filename;
}
public WriteToFile(String filename, boolean appendfile){
path=filename;
append=appendfile;
}
public void write(String text) throws IOException {
FileWriter filewrite = new FileWriter(path, append);
PrintWriter print = new PrintWriter(filewrite);
print.printf("%s" + "%n", text);
print.close();
}
}
A: Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter.
On the calling side, do this:
WriteToFile writer = new WriteToFile(filename);
try {
// writer.write(...);
} finally {
writer.close();
}
By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early.
A: Look at the 2nd argument of the FileWriter constructor in your code.
FileWriter filewrite = new FileWriter(path, append);
See, it says "append". Guess what it does. Read the documentation if you're unsure.
Now, look how you initialized append.
private boolean append = false;
This code is fully behaving as expected. It's just a developer's fault. Fix it :)
A: Just set fileName on System using the method
System.setOut(fileName);
Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6092305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to convert 32-bit tiff to 16-bit png? Grayscale displacement texture I need to convert 32bit tif to 16bit, but preserve all range of details.
I've tried convert -normalize, convert -depth 16, convert -depth 16 -normalize and it just gets rid of all the details and part of the texture is just black.
The image I got is here, displacement texture of the moon
Image:
Filename: ldem_64.tif
Format: TIFF (Tagged Image File Format)
Mime type: image/tiff
Class: DirectClass
Geometry: 23040x11520+0+0
Resolution: 100x100
Print size: 230.4x115.2
Units: PixelsPerInch
Colorspace: Gray
Type: Grayscale
Endianness: LSB
Depth: 32/16-bit
Channel depth:
Gray: 16-bit
Channel statistics:
Pixels: 265420800
Gray:
min: -597319 (-9.1145)
max: 704960 (10.757)
mean: -34039.6 (-0.519411)
median: -52133.1 (-0.7955)
standard deviation: 144682 (2.2077)
kurtosis: 0.855997
skewness: 0.540128
entropy: 0.244393
Rendering intent: Undefined
Gamma: 0.454545
Matte color: grey74
Background color: white
Border color: srgb(223,223,223)
Transparent color: none
Interlace: None
Intensity: Undefined
Compose: Over
Page geometry: 23040x11520+0+0
Dispose: Undefined
Iterations: 0
Compression: None
Orientation: TopLeft
Properties:
comment: IDL TIFF file
date:create: 2019-06-05T20:21:05+00:00
date:modify: 2019-06-05T20:21:05+00:00
date:timestamp: 2022-11-24T22:57:25+00:00
quantum:format: floating-point
signature: cb63f78e418cec4a32935a7eeb388c3dc541bf2ed95d46de2d35e70c2e3ad805
tiff:alpha: unspecified
tiff:document: ldem_64.tif
tiff:endian: lsb
tiff:photometric: min-is-black
tiff:rows-per-strip: 1
tiff:software: IDL 8.7.2, Harris Geospatial Solutions, Inc.
tiff:timestamp: 2019:05:20 12:47:07
Artifacts:
verbose: true
Tainted: False
Filesize: 1012.59MiB
Number pixels: 265.421M
Pixel cache type: Memory
Pixels per second: 59.0163MP
User time: 3.672u
Elapsed time: 0:05.497
Version: ImageMagick 7.1.0-52 Q16-HDRI x64 04ee6ce:20221106 https://imagemagick.org
aodhasdoashdoasd cannot post the question cuz alot of "code"
A: I am not sure what you want, but perhaps just -auto-level in Imagemagick.
Input:
I downloaded a smaller version, ldem_4.tif (1440x720) and using IM 7 (which you need for the HDRI compile since your image is outside the normal range of 16-bit integers).
magick ldem_4.tif -auto-level x.png
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74567005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: ruby on rails: solid method to change logged in client's browser location on time X even when they reload pages? Im in the need of changing a client's browser location on a certain time X. It has to be solid even if a user reloads page it should redirect to location X
Below is my current (imperfect) implementation of this:
Im in the need to a way to make this solution solid OR an alternative solution if that would fit better. ITs to complex to share code snippets so I would like to reframe from that and discuss the concept instead and discuss how to code wise implement the missing gaps to keep this question overseen able.
Current solution:
*
*Im currently using redis and faye to send data to a subscribed channel (at the client) at time X
*This means that a jquery event (redirect of url ) will be triggered when the redis background scheduler pushes/sends this data at a certain time X ( which is always in future)
The problem is this is not solid, since on a page reload the pushed/send data is never received and rendered useless.
Even if it would be possible to save the last 10 sends/pushes in lets call it a "history" one could read it but say a user drops connection the excecution of this data would be useless since it will be to late and not in time.
*How could I overcome this problem? I prefer to keep the load server side and not use a client polling the server every 1 seconds to check if there is data received. that would not scale at all and would become a big problem if usage of the app grows.*
What ideas on this concept to make it solid or use another method to get a solid implementation of this idea? any comments ideas suggestions welcome thanks in advanche!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11354355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: multiply form values from form array with JS I have html form with arrays:
<form method="post" id="formaa" name="form">
<div id="fields">
<div id="divas1" class="row">
<a href="#" id="did1" onClick="d(this);"><img src="d.jpg" /></a><a href="#" id="uid1" onClick="u(this);">
<img src="u.jpg" /></a><input type="text" name="ite[]" id="item" /><input type="text" name="q[]" id="quantity" class="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" class="kaina" onkeyup="update();"/><input type="text" name="sum[]" id="suma" size="10" disabled="disabled"/></div>
</div>
<br />
<input type="button" name="nw" id="new" value="ADD" onClick="naujas('laukeliai');" /><br />
Total: <input type="text" name="sumaa[]" id="suma" size="10" disabled="disabled"/>
</form>
Each time I push forms ADD button, inside the <div id="fields"> is included new div block <div id=divas(i++)> I need multiply qp[] and pr[] values and dynamicaly add to sum field, need do multiply price and quantity of each product seperately and get final each product price (not all products total).
first tried to get all values and filter these two, but couldnt figure out...
var form = document.getElementsByName('form')[0];
var inputs = form.getElementsByTagName('input');
for (var i = 0, j = inputs.length; i < j; i++) {
var element = inputs[i];
alert(element.value);
}
How to extract from this array only needed values and multiply? Thanks for advices.
A: you can read form array in way as below
frmRefer = document.getElementByTagName("form")[0];
for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){
alert(frmRefer.elements["ite[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){
alert(frmRefer.elements["quant[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){
alert(frmRefer.elements["pr[]"][i].value );
}
A: Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as:
<form id="example_form">
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<!-- ... many more rows -->
<input type="text" disabled id="sum" name="sum"></input>
</form>
Use jQuery to make field access easier. Using JQuery, you would use the following JS:
function update() {
var total = 0;
$("#example_form div.row").each(function(i,o){
total += $(o).find(".quant").val() *
$(o).find(".price").val();
});
$("#example_form #sum").val(total);
}
This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like
$("#example_form div.row input").change(update);
Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11434357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Quicksort with Lists in C++ I am working on a comparison for how different data structures effect the performance of an algorithm. I am trying to get the "List" data structure to work with Quicksort. When I try to run it however, my application crashes and gives me the error "list iterator not derefencable". Anyone know what could be going wrong? It is quite possible that there is some kind of iteration problem, because I am very unfamiliar with it.
void quickSortList(List& arr, int left, int right, int trialnr)
{// prepare iterators
list<int>::iterator i = arr.begin();
while(*i != left)
{
i++;
}
list<int>::iterator j = arr.end();
while (*j != right)
{
j--;
}
int pivot = *i + *j / 2;
// inititate partitioning while the values on both left and right are not equal
while (*i <= *j)
{
while (*i < pivot)
{
i++;
}
while (*j > pivot)
{
j--;
}
if (*i <= *j)
{
// while partitioning is in process, swap the corresponding arrays
swap(i, j);
i++;
j--;
}
}
// repeat the process until the array is sorted
if (left < *j)
{
quickSortList(arr, left, right, trialnr);
}
if (*i < right)
{
quickSortList(arr, left, right, trialnr);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40960871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding a NEXT button to an iPad UISplitViewControl Simple question (yeah right!). I want to add a "NEXT" button on the detail pages of my UISplitViewController for my iPad project. If clicked, it would be another way of advancing to the next page in the list of pages. As a bonus, I want to highlight the correct row that in the root view that corresponds with the new view you land on.
Any general guidance and suggestions on where to go would be AWESOME!
UPDATE: Thanks to Anna's Suggestion below, here is the code I used to pull all this together. IT WORKS GREAT. Thanks Anna.
On the details page I included this:
- (IBAction)goToNext{
NSLog(@"Going to Next from Welcome");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"NextPageRequested" object:nil];
}
On the RootViewController page I did:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(moveOnToNextPage:)
name:@"NextPageRequested" object:nil];
}
And Finally later in the RootViewController:
#pragma mark -
#pragma mark The NEXT Button
// This is the Code used for the Big NEXT button. basically a Notification Center listener is set up in the view did load and when triggered by any of the buttons, this
// function is called. Here, I do 3 things: 1. advance the highlighted cell of the master table view. 2. call the didSelectRowAtIndexPath function of the table to
// advance to the next page. and 3. Exchange the "dash" icon with the "check" icon.
-(void)moveOnToNextPage:(NSNotification*)notifications {
NSIndexPath* selection = [self.tableView indexPathForSelectedRow]; // grab the row path of the currently highlighted item
// Change the icon in the current row:
NSString *checkImage = [[NSBundle mainBundle] pathForResource:@"checkGreen" ofType:@"png"];
UIImage *checkMark = [[[UIImage alloc] initWithContentsOfFile:checkImage] autorelease]; // Grab the checkmark image.
if (selection) {
NSLog(@"not nil");
UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[self.tableView indexPathForSelectedRow]];
// cell1.accessoryType = UITableViewCellAccessoryCheckmark; // this is yet another way to add the checkmar, but for now, I will use Mine.
cell1.imageView.image = checkMark; // now set the icon
} else {
NSLog(@"must be nil");
NSUInteger indexArrBlank[] = {0,0}; // now throw this back into the integer set
NSIndexPath *blankSet = [NSIndexPath indexPathWithIndexes:indexArrBlank length:2]; // create a new index path
UITableViewCell *cell0 = [self.tableView cellForRowAtIndexPath:blankSet];
// cell1.accessoryType = UITableViewCellAccessoryCheckmark; // this is yet another way to add the checkmar, but for now, I will use Mine.
cell0.imageView.image = checkMark; // now set the icon
}
// Highlight the new Row
int nextSelection = selection.row +1; // grab the int value of the row (cuz it actually has both the section and the row {section, row}) and add 1
NSUInteger indexArr[] = {0,nextSelection}; // now throw this back into the integer set
NSIndexPath *indexSet = [NSIndexPath indexPathWithIndexes:indexArr length:2]; // create a new index path
[self.tableView selectRowAtIndexPath:indexSet animated:YES scrollPosition:UITableViewScrollPositionTop]; // tell the table to highlight the new row
// Move to the new View
UITableView *newTableView = self.tableView; // create a pointer to a new table View
[self tableView:newTableView didSelectRowAtIndexPath:indexSet]; // call the didSelectRowAtIndexPath function
//[newTableView autorelease]; //let the new tableView go. ok. this crashes it, so no releasing for now.
}
A: One way to implement this is using NSNotificationCenter.
The root view controller, in viewDidLoad, would call addObserver:selector:name:object: to make itself an observer for a notification named, say, @"NextPageRequested".
The button(s) on the detail view(s), when tapped, would call postNotificationName:object: to request the root view controller to go to the next page.
In the root view controller, the notification handler method would (assuming the root view controller is a UITableView):
*
*get the current index path using UITableView's indexPathForSelectedRow
*calculate the next index path
*call selectRowAtIndexPath:animated:scrollPosition: to highlight that row
*call the code needed to actually change the page (possibly by calling tableView:didSelectRowAtIndexPath: directly)
A: Give your detailviewcontroller a parent navigationcontroller and add your next button to the navbar via the navigation item. Pressing Next will trigger a pushviewcontroller to the nav-stack.
Or add a top-toolbar to your current view controller and put the button there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5797917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Camera photo selection not working in Swift Why isn't the second function being called when the user takes the photo and clicks the use photo button? The view gets dismissed, but the print statement doesn't work and the function isn't called.
@IBAction func openCamera(_ sender: UIBarButtonItem)
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
print("made it")
createImage(image: image)
self.dismiss(animated: true, completion: nil);
}
A: Using Swift 3, here's what I have. My code is meant to have (1) a select view controller, which uses the UIImagePickerController to either use the camera or select from the camera roll, then (2) sequel to an edit view controller I stripped out the code for the buttons, as I'm not using IB.
class SelectViewController: UIViewController {
// selection and pass to editor
let picker = ImagePickerController()
var image = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
extension SelectViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Camera App
func openCameraApp() {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,
animated: true,
completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
// MARK: Photos Albums
func showImagePicker() {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
present(picker,
animated: true,
completion: nil)
picker.popoverPresentationController?.sourceView = self.view
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
self.performSegue(withIdentifier: "ShowEditView", sender: self)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: false, completion: nil)
}
// MARK: Seque to EditViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowEditView" {
if let vc = segue.destination as? EditViewController {
vc.image = image
}
}
}
}
If you aren't segueing to another VC, remove the .performSegue call and the code below the the final MARK: notation. (The camera/selected image is in the image var.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41750808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is Paramiko raising EOFError() when the SFTP object is stored in a dictionary? I'm having trouble with an application I'm writing that downloads and uploads files to and from other boxes via SSH. The issue I'm experiencing is that I can get (download) files just fine but when I try to put (upload) them onto another server I get an EOFError() exception. When I looked at _write_all() in paramiko\sftp.py it seemed like the error was caused when it couldn't write any data to the stream? I have no network programming experience so if someone knows what it's trying to do and could communicate that to me I'd appreciate it.
I wrote a simplified version of the function that handles my connections as ssh(). runCommand() shows how the upload is failing in my application while simpleTest() shows how sftp put does work, but I can't see any difference between runCommand() and simpleTest() other than how my SFTP objects are being stored. One is stored in a dictionary and the other by itself. It seems like if the dictionary was the problem that downloading files wouldn't work but that is not the case.
Does anyone know what could cause this behavior or could recommend another way to manage my connections if this way is causing problems?
I'm using Python 2.7 with Paramiko 1.7.6. I've tested this code on both Linux and Windows and got the same results.
EDIT: code included now.
import os
import paramiko
class ManageSSH:
"""Manages ssh connections."""
def __init__(self):
self.hosts = {"testbox": ['testbox', 'test', 'test']}
self.sshConnections = {}
self.sftpConnections = {}
self.localfile = "C:\\testfile"
self.remotefile = "/tmp/tempfile"
self.fetchedfile = "C:\\tempdl"
def ssh(self):
"""Manages ssh connections."""
for host in self.hosts.keys():
try:
self.sshConnections[host]
print "ssh connection is already open for %s" % host
except KeyError, e: # if no ssh connection for the host exists then open one
# open ssh connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2])
self.sshConnections[host] = ssh
print "ssh connection to %s opened" % host
try:
self.sftpConnections[host]
print "sftp connection is already open for %s" % host
except KeyError, e:
# open sftp connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2])
self.sftpConnections[host] = ssh.open_sftp()
print "sftp connection to %s opened" % host
def runCommand(self):
"""run commands and return output"""
for host in self.hosts:
command = "if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi"
stdin, stdout, stderr = self.sshConnections[host].exec_command(command)
print "%s executed on %s" % (command, host)
print "returned %s" % stdout.read()
self.sftpConnections.get(self.remotefile, self.fetchedfile)
print "downloaded %s from %s" % (self.remotefile, host)
self.sftpConnections[host].put(self.localfile, self.remotefile)
print "uploaded %s to %s" % (self.localfile, host)
self.sftpConnections[host].close()
self.sshConnections[host].close()
def simpleTest(self):
host = "testbox"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, 22, 'test', 'test')
sftp = ssh.open_sftp()
print "sftp connection to %s opened" % host
sftp.get(self.remotefile, self.fetchedfile)
print "downloaded %s from %s" % (self.localfile, host)
sftp.put(self.localfile, self.remotefile)
print "uploaded %s to %s" % (self.localfile, host)
sftp.close()
if __name__ == "__main__":
test = ManageSSH()
print "running test that works"
test.simpleTest()
print "running test that fails"
test.ssh()
test.runCommand()
output:
running test that works
sftp connection to testbox opened
downloaded C:\testfile from testbox
uploaded C:\testfile to testbox
running test that fails
ssh connection to testbox opened
sftp connection to testbox opened
if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi executed on testbox
returned 1
downloaded /tmp/tempfile from testbox
Traceback (most recent call last):
File "paramikotest.py", line 71, in <module>
test.runCommand()
File "paramikotest.py", line 47, in runCommand
self.sftpConnections[host].put(self.localfile, self.remotefile)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 561, in put
fr = self.file(remotepath, 'wb')
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 245, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 627, in _request
num = self._async_request(type(None), t, *arg)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 649, in _async_request
self._send_packet(t, str(msg))
File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 172, in _send_packet
self._write_all(out)
File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 138, in _write_all
raise EOFError()
EOFError
A: I was able to resolve my issue. I was supposed to be using Paramiko.Transport and then creating the SFTPClient with paramiko.SFTPClient.from_transport(t) instead of using open_sftp() from SSHClient().
The following code works:
t = paramiko.Transport((host, 22))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
A: as i see it, with ssh=SSHClient() you create an SSHClient-Object, and then with sftp=ssh.open_sftp() you create an sftp-object. while you only want to use the sftp, you store the ssh in a local variable, which then gets gc'd, but, if the ssh is gc'd, the sftp magically stops working. don't know why, but try to store the ssh for the time your sftp lives.
A: After reading your edit I think the problem is here
stdin, stdout, stderr = self.sshConnections[host].exec_command(command)
this line apparently disconnect the ftp thing
EDITED
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5342350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: I need an example on how to use the function create created by the RESTful from entity class I need an example on how to use the function create created by the RESTful from entity class
My entity class (Countries) :
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
*
* @author oracle
*/
@Entity
@Table(name = "COUNTRIES")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Countries.findAll", query = "SELECT c FROM Countries c"),
@NamedQuery(name = "Countries.findByCountryId", query = "SELECT c FROM Countries c WHERE c.countryId = :countryId"),
@NamedQuery(name = "Countries.findByCountryName", query = "SELECT c FROM Countries c WHERE c.countryName = :countryName")})
public class Countries implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2)
@Column(name = "COUNTRY_ID")
private String countryId;
@Size(max = 40)
@Column(name = "COUNTRY_NAME")
private String countryName;
static SessionFactory sessionFactory ;
public Countries() {
}
public Countries(String countryId) {
this.countryId = countryId;
}
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
@Override
public int hashCode() {
int hash = 0;
hash += (countryId != null ? countryId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Countries)) {
return false;
}
Countries other = (Countries) object;
if ((this.countryId == null && other.countryId != null) || (this.countryId != null && !this.countryId.equals(other.countryId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.Countries[ countryId=" + countryId + " ]";
}
My CountriesFacadeREST contains the create function :
@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Countries entity) {
super.create(entity);
}
the client code is from an android application :
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://192.168.0.104:8080/wsDatabase/webresources/entities.countries/create");
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
BTW : the client code is working and tested on other web services but I need to let it work on a "create web service "
A: Try to change your HttpGet with HttpPost since your rest service answer to a POST request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29086388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to count the number of date-specific newly data entered on an increasing range from row x? I need formulas that do these things for me automatically
*
*Count and display the number of new pieces of data added to the spreadsheet =TODAY()
*On a separate sheet, list the number of new pieces of data added to the main sheet each day
*Count the average number of pieces of content added to the spreadsheet in a given month
The challenge for me here is that every new data is being inserted on the top row of the spreadsheet just below the header so the start of the range changes every time. Is there a way to permanently include in the range all the newly inserted rows below the header? Here's the link to the spreadsheet
A: use in cell H1:
={COUNTIF(INDIRECT("D4:D"), TODAY());ARRAYFORMULA(COUNTIFS(
INDIRECT("B4:B"), "content", MONTH(
INDIRECT("D4:D")), MONTH(TODAY()))/COUNTIFS(MONTH(
INDIRECT("D4:D")), MONTH(TODAY())))}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65707281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Iterating over listed data frames within a piped purrr anonymous function call Using purrr::map and the magrittr pipe, I am trying generate a new column with values equal to a substring of the existing column.
I can illustrate what I'm trying to do with the following toy dataset:
library(tidyverse)
library(purrr)
test <- list(tibble(geoid_1970 = c(123, 456),
name_1970 = c("here", "there"),
pop_1970 = c(1, 2)),
tibble(geoid_1980 = c(234, 567),
name_1980 = c("here", "there"),
pop_1970 = c(3, 4))
)
Within each listed data frame, I want a column equal to the relevant year. Without iterating, the code I have is:
data <- map(test, ~ .x %>% mutate(year = as.integer(str_sub(names(test[[1]][1]), -4))))
Of course, this returns a year of 1970 in both listed data frames, which I don't want. (I want 1970 in the first and 1980 in the second.)
In addition, it's not piped, and my attempt to pipe it throws an error:
data <- test %>% map(~ .x %>% mutate(year = as.integer(str_sub(names(.x[[1]][1]), -4))))
# > Error: Problem with `mutate()` input `year`.
# > x Input `year` can't be recycled to size 2.
# > ℹ Input `year` is `as.integer(str_sub(names(.x[[1]][1]), -4))`.
# > ℹ Input `year` must be size 2 or 1, not 0.
How can I iterate over each listed data frame using the pipe?
A: Try:
test %>% map(~.x %>% mutate(year = as.integer(str_sub(names(.x[1]), -4))))
[[1]]
# A tibble: 2 x 4
geoid_1970 name_1970 pop_1970 year
<dbl> <chr> <dbl> <int>
1 123 here 1 1970
2 456 there 2 1970
[[2]]
# A tibble: 2 x 4
geoid_1980 name_1980 pop_1970 year
<dbl> <chr> <dbl> <int>
1 234 here 3 1980
2 567 there 4 1980
A: We can get the 'year' with parse_number
library(dplyr)
library(purrr)
map(test, ~ .x %>%
mutate(year = readr::parse_number(names(.)[1])))
-output
#[[1]]
# A tibble: 2 x 4
# geoid_1970 name_1970 pop_1970 year
# <dbl> <chr> <dbl> <dbl>
#1 123 here 1 1970
#2 456 there 2 1970
#[[2]]
# A tibble: 2 x 4
# geoid_1980 name_1980 pop_1970 year
# <dbl> <chr> <dbl> <dbl>
#1 234 here 3 1980
#2 567 there 4 1980
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67143140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How OR Xor And blocks of memory We have two bitmap such as bitmap1,bitmap2.both initialized with malloc(same parameters). Bitmap1 is assigned such as 0010 0110 and bitmap2 is assigned with 1000 0001. How we do OR operation between bitmaps to make 1010 0111. On the other hand, we want to set bits of bitmap1 that are 1 in corresponding entry in bit2.
We don't want to use some approaches such as:
for(i=0;i<n;i++) bitmap1[i] ||= bitmap2[i];
Because these approaches are slower than some functions (e.g. memset,memcpy).
Any guidance would be useful.
Programming language is C/C++
A: You can directly use the bitwise or and xor commands.
or_result = bitmap1 | bitmap2
xor_result = bitmap1 ^ bitmap2
If this will not work because of how you've defined your bitmap1 and bitmap2 (which is unclear, is it a struct or an int or a char or something less useful like an array or something strange like a class with an operator[] defined? We need more information) then you'll probably have to change how you're storing your data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11362181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Error when used consolidate node package I tried to used consolidate package with gulp to build the MEAN stack app. But I don't know why when I run npm install, then gulp browserify, it always threw a lot of exceptions like
Browserify Error { [Error: Cannot find module 'hogan.js' from '<my project path>\node_modules\consolidate\lib']
stream:
{ _readableState:
{ highWaterMark: 16,
buffer: [],
length: 0,
pipes: [Object],
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
objectMode: true,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: false },
readable: true,
domain: null,
_events:
{ end: [Object],
error: [Object],
data: [Function: ondata],
_mutate: [Object] },
_maxListeners: undefined,
_writableState:
{ highWaterMark: 16,
objectMode: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
pendingcb: 0,
prefinished: true,
errorEmitted: false },
writable: true,
allowHalfOpen: true,
_options: { objectMode: true },
_wrapOptions: { objectMode: true },
_streams: [ [Object], [Object] ],
length: 2,
label: 'deps' } }
[16:01:17] Browserify Error { [Error: Cannot find module 'handlebars' from '<my project path>\node_modules\consolidate\lib']
stream:
{ _readableState:
{ highWaterMark: 16,
buffer: [],
length: 0,
pipes: [Object],
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
objectMode: true,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: false },
readable: true,
domain: null,
_events:
{ end: [Object],
error: [Object],
data: [Function: ondata],
_mutate: [Object] },
_maxListeners: undefined,
_writableState:
{ highWaterMark: 16,
objectMode: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
pendingcb: 0,
prefinished: true,
errorEmitted: false },
writable: true,
allowHalfOpen: true,
_options: { objectMode: true },
_wrapOptions: { objectMode: true },
_streams: [ [Object], [Object] ],
length: 2,
label: 'deps' } }
[16:01:17] Browserify Error { [Error: Cannot find module 'underscore' from '<my project path>\node_modules\consolidate\lib']
I guess that something wrong in consolidate package, because it did not install package recursively. My consolidate version that I used is 0.12.1. Anyone can help me?
A: Consolidate does not contain any template engine. You should install them on your level.
I guess you are using hogan templates, so you need to install it. Run this in your project root
npm install hogan.js --save
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30369262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Andropid SDK 20 - Can't open more than one avd I have just updated to Android SDK Tools 20 and SDK Platform-Tools 12.
Now I find that, for some reason, I can't open more than one AVD at the same time.
Anyone else found this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11345254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to access a function which is not global and it exist in another js file? I have the following js files and I want to access one function from another function but I call it in another js file. I receive this error when I call it Uncaught ReferenceError: vidPause is not defined.
(function($) {
$.fn.controlls = function(opt) {
......
function init() {
.....
}
function vidPause(e){
e.stopPropagation();
$.fn.controlls.toggleBarPlayingButtons('pause');
video.pause();
}
.....
From this js file I want to call vidPause in the following function in another js file
function myFunction(e) {
if (video) {
$('video').controlls(vidPause());
A: This issue is scope.
init() and vidPause() are private to the (function($) { call. They will not be directly accessible the way you are trying to access them.
Many jquery plugins use text (not my preference, but that's how they work), eg $.dialog("open"), so you could do something like that (not sure if opt is meant to mean action, so update accordingly) :
(function($) {
$.fn.controlls = function(action, opt) {
switch (action) {
case "pause":
vidPause(opt);
break;
...
usage
$('video').controlls("pause");
It might be possible to add the methods as if using namespaces, but I've not seen this in plugins so depends on what you are doing with your plugin (ie releasing it) whether you want to be consistent, eg:
(function($) {
$.fn.controlls = {};
$.fn.controlls.pause = function(opt) {
video.pause();
...
usage
$('video').controlls.pause()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33628251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I map the result set of query to a different entity other than table I am trying to fetch data from db and mapping it to different entity but I get
java.lang.IllegalArgumentException: java.lang.ArrayIndexOutOfBoundsException: 0
My Table looks like
@Entity
@Table(name = "Student")
@NamedNativeQueries({
@NamedNativeQuery(name = "findAll", query = "Select a.student_id as id, a.student_code as code from Student a")
})
public class Student {
@Id
private Long student_id;
private String student_code;
private String student_user_id;
private String student_first_name;
//Some other fields, getters and setters
}
My BO Looks like
@Entity
public class Generic{
@Id
private Long id;
private String code;
private String user_id;
//getters and setters
}
My DAO call class something like this
Query query = entityManager.createNamedQuery("findAll", Generic.class);
query.getResultList();
I get exception on
entityManager.createNamedQuery("findAll", Generic.class);
This is the stack trace I have
Caused by: java.lang.IllegalArgumentException: java.lang.ArrayIndexOutOfBoundsException: 0
at org.hibernate.internal.AbstractSharedSessionContract.buildQueryFromName(AbstractSharedSessionContract.java:774)
at org.hibernate.internal.AbstractSharedSessionContract.createNamedQuery(AbstractSharedSessionContract.java:869)
at org.hibernate.internal.AbstractSessionImpl.createNamedQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:301)
at com.sun.proxy.$Proxy157.createNamedQuery(Unknown Source)
A:
I am trying to fetch data from db and mapping it to a different entity
but I get ArrayIndexOutOfBoundsException
But in the following line, you are not doing that, you are trying to get the list of Student entity list. And what's your different Entity here?
entityManager.createNamedQuery("findAll", Student.class);
But as you provided another entity Generic, I assume you want your data to be loaded in that. There are different possible solutions to this problem. Lets figure out.
Using the SELECT NEW keywords
Update your Native query to this
@NamedNativeQueries({
@NamedNativeQuery(name = "Student.findAll", query = "SELECT NEW Generic(a.student_id, a.student_code) FROM Student a")
})
You have to define a Constructor in the Generic class as well that qualifies this call
public void Generic(Long id, String code) {
this.id = id;
this.code = code;
}
And update the query execution in DAO as
List<Generic> results = em.createNamedQuery("Student.findAll" , Generic.class).getResultList();
Note: You may have to place the fully qualified path for the Generic class in the Query for this
Construct from List<Object[]>
Alternatively the straight forward and simplest solution would fetch the result list as a list of Object[] and populate to any new Object you want.
List<Object[]> list = em.createQuery("SELECT s.student_id, s.student_code FROM Student s")
.getResultList();
for (Object[] obj : list){
Generic generic = new Generic();
generic.setId(((BigDecimal)obj[0]).longValue());
generic.setCode((String)obj[1]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59942606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: C# Multi-threading logical error I am new to multi-threading, but I don't know what's wrong with my code:
public int k;
private void button2_Click(object sender, EventArgs e)
{
k = 10;
ThreadPool.SetMinThreads(2, 6);
ThreadPool.SetMaxThreads(2, 6);
ThreadPool.QueueUserWorkItem(aki);
ThreadPool.QueueUserWorkItem(aki);
}
public void aki(object ab)
{
do
{
this.SetText1(textBox1.Text +
" thread " + Thread.CurrentThread.GetHashCode() +
" valu= " + k + Environment.NewLine);
k--;
} while (k > 0);
if (k < 0) Thread.CurrentThread.Abort();
}
For the above, I am getting the following output:
thread 11 valu= 10
thread 11 valu= 8
thread 11 valu= 6
thread 11 valu= 4
thread 11 valu= 2
thread 10 valu= 0
I am expecting an output in 10,9,8,7,6,5,4,3,2,1,0
Please guide me on what is wrong with this.
I am trying to run two threads at a time.
What to do?
EDIT: After rohit's answer, I tried this but i got the following output:
thread 11 valu= 10
thread 12 valu= 9
thread 12 valu= 8
thread 11 valu= 7
thread 11 valu= 6
thread 6 valu= 7
thread 6 valu= 6
thread 6 valu= 5
thread 13 valu= 3
thread 14 valu= 2
thread 14 valu= 1
In this run, 7 and 6 are repeating twice.
A: Problem here is both thread working on same instance variable k of your class.
So, when one thread modifies the value, it gets reflected in other thread.
The output will always be indeterministic. Like i got this output -
thread 18 valu= 10
thread 21 valu= 10
thread 18 valu= 9
thread 18 valu= 7
thread 18 valu= 6
thread 18 valu= 5
thread 18 valu= 4
thread 18 valu= 3
thread 18 valu= 2
thread 18 valu= 1
thread 21 valu= 8
You should used local variable inside aki method -
public void aki(object ab)
{
int k = 10; // <---- HERE
do
{
this.SetText1(textBox1.Text +
" thread " + Thread.CurrentThread.GetHashCode() +
" valu= " + k + Environment.NewLine);
k--;
} while (k >= 0); // It should be less than and equal to 0 to print 0.
if (k < 0) Thread.CurrentThread.Abort();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17895851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Post serialized form data with ajax I have this form
<div class="tab-pane" id="trade">
<br/>
<div class="well">There are currently a total of <b>$traders traders</b> and this session has a total of <b>Ksh $total</b> you can earn this very minute.</div>
<form class="form-horizontal" name="trade">
<br/>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Telephone Number:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="email" placeholder="Enter Telephone Number" name="telephone" required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Id Number:</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="email" placeholder="Enter Id Number" name="nid" required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Amount:</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="email" placeholder="Enter Amount" name="amount" required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Direction:</label>
<div class="col-sm-10">
<select class="form-control" name="direction"><option value="up">Up</option><option value="down">Down</option></select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</div>
</form>
</div>
I have this as my jquery
$(document).ready(function(){
var datastring = $("#trade").serialize();
$.ajax({
type: "POST",
url: "http://localhost/lords/trade.php",
data: datastring,
dataType: "json",
success: function(data) {
alert(data);
},
error: function() {
}
});
});
However, i am not stopping default and the form reloads and no data is posted.
I have tried this
var frm = $('#trade');
frm.submit(function (ev) {
$.ajax({
type: 'post',
url: 'http://localhost/lords/trade.php',
data: frm.serialize(),
success: function (data) {
alert(data);
}
});
ev.preventDefault();
});
But this does not post data. I am using jquery 3.3.1
This is the fiddle https://jsfiddle.net/e3zc1gpb/3/
A: add id="name" on form tag,
or change
var frm = $('#trade');
to
var frm = $('form[name="trade"]')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53202808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bus Error when using recursion So, I'm using recursion and going through an array named code which contains integers and a value is computed after
traversing through the array. But I don't know for what reason this is giving a BUS ERROR : 10.
I even tried manually going through the array and everything seems fine, array is sufficiently big.
//change to bits/stdc++.h
#include "stdc++.h"
#define MAX 5001
typedef unsigned long long ull;
typedef long long ll;
using namespace std;
int code[MAX];
int co_code;
ull rec(int i, int j, int k){
if(k==j-1)
return 0;
if(i==j-1)
return (rec(k+2, j, k+2));
int temp = code[i]*10 + code[i+1];
if(temp<=26)
return (1 + rec(i+1, j, k));
else
return (rec(i+1, j, k));
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
while(1){
memset(code, 0, sizeof(code[0])*MAX);
string str;
cin>>str;
size_t size = str.length();
co_code = 0;
while(co_code!= size){
code[co_code] = str[co_code] - '0';
co_code++;
}
if(code[0] == 0)
break;
cout<<rec(0, co_code-1, 0) + 1;
}
return 0;
}
A: The error is in accessing the array outside the size given by co_code,
so it can be fixed by changing the if condition.
Corrected : -
if(k>=j-1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51900731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot read properties of this object values of parent component to child component function in angular I'm calling a function declared in parent component in the child component in the form of callback.
Parent Component
translation-editor.component.ts
export class TranslationEditorComponent implements OnInit {
textGuid: string = this.actRoute.snapshot.params['textGuid'];
editDataset: any;
currentTopBarConfig: any;
summaryTopbarConfig = [
{
"label": "Save Text",
"function": this.save, //see save function below
},
{
"label": "Delete Text",
"function": this.delete,
}
];
constructor(
private translationService:TranslationService,
public actRoute: ActivatedRoute,
) {
}
ngOnInit(): void {
this.loadDataToEdit();
}
loadDataToEdit(){
this.translationService.getTextById(this.textGuid).subscribe(res => {
this.editDataset = res;
})
this.currentTopBarConfig = this.summaryTopbarConfig;
}
save(){
console.log("this.textGuid",this.textGuid);
if(this.textGuid){
this.translationService.updateText(this.textGuid, this.editDataset).subscribe((res:any)=>{
console.log(res);
});
}
}
delete(){
console.log("delete code lies here");
}
}
translation-editor.component.html
<topbar [config]="currentTopBarConfig"></topbar>
<form [ngClass]="{'hidden':currentTab!=='summary'}" >
<fieldset>
<legend>Field</legend>
<ul *ngIf="editDataset">
<ng-container *ngFor="let key of objectKeys(editDataset)" >
<li *ngIf="key === 'textGuid' || key === 'strongName' || key === 'container'">
<label class="grid-input-group">
<input type="text" value="{{editDataset[key]}}" readonly>
<span class="label">{{key}}</span>
</label>
</li>
</ng-container>
</ul>
</fieldset>
</form>
I'm calling the save function in the below component as a callback to initiateFunction() function.
Child Component
topbar.component.html
<ul class="sidebar-items">
<ng-container *ngFor="let btn of config">
<li>
<button
(click)="initiateFunction(btn.function)"
<span class="label" >{{btn.label}}</span>
</button>
</li>
</ng-container>
</ul>
topbar.component.ts
export class TopbarComponent implements OnInit {
@Input() config: any[] | undefined;
constructor(private location: Location) { }
ngOnInit(): void {
}
initiateFunction(fnct:any){
fnct();
}
}
Here when function is executed I'm getting an error:
ERROR TypeError: Cannot read properties of undefined (reading 'textGuid')
Where I'm not able access the this.textGuid.
Please give me suggestions on how to solve this.
A: I think the issue is caused because the save() function isn't bound to the correct object, so instead you can use Angular component interaction features. You can use @Output decorator and emit an event that will be handled by parent component.
First, update your TopbarComponent to add that event:
topbar.component.ts
export class TopbarComponent implements OnInit {
@Input() config: any[] | undefined;
@Output() save: EventEmitter<any> = new EventEmitter();
constructor(private location: Location) {}
ngOnInit(): void {}
onSave() {
this.save.emit();
//fnct();
}
}
topbar.component.html there was a typo on in button start tag >
<ul class="sidebar-items">
<ng-container *ngFor="let btn of config">
<li>
<button
(click)="onSave()">
<span class="label" >{{btn.label}}</span>
</button>
</li>
</ng-container>
</ul>
Next, update the TranslationEditorComponent component to bind to that event:
translation-editor.component.html
<topbar [config]="currentTopBarConfig" (save)="save()"></topbar>
You can do the same for other types of events like delete or update. Refer to Angular docs for more details about components interaction and sharing data https://angular.io/guide/inputs-outputs
A: Your this context has been changed when you call fnct();. In order to pass the this context to the function you can use javascript bind method.
So you just need to change the config property:
summaryTopbarConfig = [
{
"label": "Save Text",
"function": this.save.bind(this), //bind current context
}
];
Read more about bind: https://www.w3schools.com/js/js_function_bind.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73334914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Test a simple function in jasmine karma - Angular Basically i have this function
function getDP() {
if (someFunctionOutsideAngular()) {
var str = vm.dp;
var selectedDate = '';
if (vm.dp == null) {
selectedDate = new Date();
} else {
selectedDate = vm.dp;
}
var options = {
date: selectedDate,
mode: 'date'
};
function onSuccess(date) {
vm.dt = new Date(date);
}
function onError(error) { // Android only
console.log('Error: ' + error);
}
datePicker.show(options, onSuccess, onError);
} else {
return false;
}
}
I'm writing Unit test for this function. This is what i have written till now.
(function(){
describe('test', function(){
var sut,
dataContext,
$q,
deferred,
$location;
beforeEach(module('app'));
beforeEach(inject(function(_$controller_, _dataContext_, _$q_,$location) {
inject(function($injector) {
sut = contFactory("mods", { $scope: $scope });
});
}));
describe('Definition tests', function(){
it('Should define the controller', function(){
expect(sut).toBeDefined();
});
var testCases = ['getDatePicker'];
_.forEach(testCases, function(testCase){
it(testCase + ' should be defined', function(){
expect(sut[testCase]).toBeDefined();
})
});
});
describe('and calling the getDatePicker function', function () {
it('and should define getDatePicker',function(){
expect(sut.getDatePicker).toBeDefined();
});
var lastCalibration;
it('return null lastCalibration', function(){
lastCalibration = sut.lastCalibration(null);
});
it('return true for lastCalibration', function(){
});
});
I'm stuck here.. i need to check if else condition, success, and onError.. i have declared varialble.. and stuck if i have to do spyOn. How to write condition for these?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44174186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: django model's inheritance I want to have two registration type. for example : employee and employer type. i want two different form.
i override AbstractUser and after i use this class (inheritance)
class User(AbstractUser):
age=models.BooleanField(default=True)
class employee(User):
is_employee=models.BooleanField(default=True)
ser=models.BooleanField()
sag=models.CharField(max_length=1)
class Meta:
verbose_name="employee"
class employer(User):
is_employer=models.BooleanField(default=True)
address=models.CharField(max_length=100)
but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User
A: I think it depends on the state of the User table - the way you have it now there will be a User table and a Employee table and a One to One relationship.
If you want it so that both the Employee and Employer Table includes an 'age' attribute you have to make the User table abstract.
https://docs.djangoproject.com/en/3.1/topics/db/models/#model-inheritance
The way to do this is :
class User(AbstractUser):
class Meta:
abstract = True
age=models.BooleanField(default=True)
Even though you have inherited from Abstract User, I wouldn't assume that the Meta settings are inherited.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66917570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Weird matrix array behavior in C I have some piece of code which I used for making some zeros on Matrix Array to 1 and printing it. I am making 4 0s to 1 in first while, but it says there are 5 1s on the array on second loop. Could not figure it out. Can you explain what is wrong in my code. Thanks for your time
#include <stdio.h>
main(){
int n;
printf("Desenin buyuklugunu giriniz: ");
scanf("%d",&n);
int satirlar[n][n]= {0};
int i=0, j=n-1;
while(i<(n/2) && j>n/2) {
satirlar[i][j] = 1;
i++;
j--;
}
for(int i=0; i< n; i++) {
for(int j=0; j< n; j++) {
if(satirlar[i][j] == 1) {
printf("*");
}
else printf("k");
}
printf("\n");
}
}
I Print "k" for seeing how many times loop worked.
I get an output like this.
kkkk
kkkkk
A: You have not shown a complete program, so we have to guess at what your program actually is. It appears you declared int arr[9][9]; inside a function. In that case, it is not initialized, and the values of its elements are indeterminate. They might be zeros. They might not. They might even change from use to use.
To initialize the array, change the definition to int arr[9][9] = { 0 };.
If the array is defined as a variable-length array, then write a loop to set the entire array to zeros immediately after the definition:
…
int array[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
arr[i][j] = 0;
Or write a loop to both set chosen elements to 1 and others to 0:
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
arr[i][j] = i == j && i < n/2 ? 1 : 0;
In the existing loop test, i<(n/2) & j>n/2 happens to work, but the conventional way to express this in C would be i < n/2 && j > n/2, because '&&is for the Boolean AND of two expressions, while&is for the bitwise AND of two integers. Additionally, there seems to be little point in testing bothiandj`. As the loop is written, testing just one of them will suffice to control the loop, unless you are intending the loop to handle non-square matrices in future code revisions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60459243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Validating the data entered in numeric input in RShiny I am developing the Shiny app in which if the user enters non-numeric characters, the value should be changed to the value mentioned in updateNumericInput().
Here is my Rcode
library(shiny)
ui <- fluidPage (
numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)
server <- function(input, output, session) {
observeEvent(input$current, {
updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
if(!(is.null(input$current) || is.na(input$current))){
if(input$current < 40){
40
}else if(input$current > 80){
80
} else{
return (isolate(input$current))
}
}
})
)
})
}
shinyApp(ui=ui, server = server)
Can anyone help me with this code?
A: Something like this?
library(shiny)
ui <- fluidPage (
numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)
server <- function(input, output, session) {
observeEvent(input$current, {
updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
else if(!(is.null(input$current) || is.na(input$current))){
if(input$current < 40){
40
}else if(input$current > 80){
80
} else{
return (isolate(input$current))
}
}
else{40}
})
)
})
}
shinyApp(ui=ui, server = server)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46703166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Displaying child records based on parent id from URL I have one model Dataset and another one called DatasetReview, where DatasetReview has a foreign key connection to Dataset. I would like to display all of the DatasetReview models that are tied to a specific Dataset in a separate page.
I can currently view each Dataset like so: http://127.0.0.1:8000/dataset/3/ and would like to see all of the DatasetReview models for Dataset 3 like so: http://127.0.0.1:8000/dataset/3/reviews But I am unsure how to set this up.
I am not sure how to phrase this question well so I had difficulty finding other posts discussing how to do something like this. Here is my code:
urls.py:
from django.urls import path
from .views import (
DatasetListView,
DatasetDetailView,
DatasetCreateView,
DatasetUpdateView,
DatasetDeleteView,
DatasetReviewsView
)
from . import views
urlpatterns = [
path('', DatasetListView.as_view(), name='argo-home'),
path('dataset/<int:pk>/', DatasetDetailView.as_view(), name='dataset-detail'),
path('dataset/new/', DatasetCreateView.as_view(), name='dataset-create'),
path('dataset/<int:pk>/update', DatasetUpdateView.as_view(), name='dataset-update'),
path('dataset/<int:pk>/delete', DatasetDeleteView.as_view(), name='dataset-delete'),
path('dataset/<int:pk>/reviews', DatasetReviewsView.as_view(), name='dataset-review'),
path('about/', views.about, name='argo-about'),
]
views.py:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Dataset, DatasetReview
def home(request):
context = {
'datasets' : Dataset.objects.all(),
}
return render(request, 'argo/home.html', context)
class DatasetListView(ListView):
model = Dataset
template_name = 'argo/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'datasets'
ordering = ['-date_posted']
class DatasetDetailView(DetailView):
model = Dataset
class DatasetCreateView(LoginRequiredMixin, CreateView):
model = Dataset
fields = ['title', 'description', 'access']
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.affiliation = self.request.user.affiliation
return super().form_valid(form)
class DatasetUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Dataset
fields = ['title', 'description']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
Dataset = self.get_object()
if self.request.user == Dataset.author:
return True
return False
class DatasetDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Dataset
success_url = '/'
def test_func(self):
dataset = self.get_object()
if self.request.user == dataset.author:
return True
return False
class DatasetReviewsView(DetailView):
model = DatasetReview
success_url = '/'
def test_func(self):
datasetReview = self.get_object()
if self.request.user == datasetReview.author:
return True
return False
def about(request):
return render(request, 'argo/about.html', {'title': 'About'})
models.py:
from django.db import models
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from django.urls import reverse
from users.models import User, Affiliation
# from django.contrib.auth.models import User
class Dataset(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
affiliation = models.ForeignKey(Affiliation, on_delete=models.CASCADE, related_name='posted_datasets')
access = models.ManyToManyField(Affiliation, related_name='available_datasets')
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('dataset-detail', kwargs={'pk' : self.pk})
class DatasetReview(models.Model):
dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE, related_name='reviews_obj')
reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviews')
comments = models.TextField()
rating = models.FloatField(
default=3.0,
validators=[MaxValueValidator(5.0), MinValueValidator(1.0)]
)
def __str__(self):
return self.dataset.title + ' review by ' + self.reviewer.username
def get_absolute_url(self):
return reverse('dataset-review', kwargs={'rpk' : self.pk})
admin.py:
from django.contrib import admin
from .models import Dataset, DatasetReview
admin.site.register(Dataset)
admin.site.register(DatasetReview)
Any tips would be super helpful, very new to django.
A: Figured this out.
The key is within class DatasetReviewsView(DetailView) in views.py. I first needed to change this inheritance to a ListView to enable what I was looking for.
Next, I just needed to provide context for what I wanted to show in my html page. This is easily done by overriding the get_context_data function, which provides the context data for templates displaying this class based view.
It makes it very easy to leverage python to provide the information I want. I could query the id of the dataset I was looking at with id = self.kwargs['pk'] (which must be included in the function parameters for get_context_data), and then I could just filter all reviews to just those with a dataset matching this id. Within the html I could then iterate over the variable num_reviews.
There is some other code that averages all the ratings to provide an overall rating as well.
class DatasetReviewsView(ListView):
model = DatasetReview
context_object_name = 'reviews'
success_url = '/'
def get_context_data(self, **kwargs):
id = self.kwargs['pk']
context = super(DatasetReviewsView, self).get_context_data(**kwargs)
context['id'] = id
context['name'] = Dataset.objects.get(pk=id).title
context['num_reviews'] = len(DatasetReview.objects.filter(dataset=id))
tot = 0
for review in DatasetReview.objects.filter(dataset=id):
tot += review.rating
context['avg_rating'] = tot / context['num_reviews']
return context
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72176800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to redirect users and integrate whmcs bridge using htaccess? I have a wordpress blog and whmcs client area. For bridging whmcs and wordpress I have used the whmcs-bridge plugin. It allows me to access the whmcs area using the url,
/client-area?ccce=cart for page /clients/cart.php
/clients/cart.php --> /client-area?ccce=cart
Thus, all the pages within the clients/ folder are redirected to the /client-area page with argument (without the extenstion ,.php)
How can I do that using htaccess?
Presently I have this,
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32547240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to clip children in qml? I have webView element that display google maps page. I need to show only map, without search input and other content. I have no idea except something like this:
Rectangle {
x: 0
y: 51
height: 549
//something like android clipChildren property
WebView {
id: mapView
x:0
y: -51
width: 800
height: 600
url: ""
onUrlChanged: {
mapView.reload()
}
}
}
but I don't know property that can do it.
A: Maybe use the clip: true; property which is present on every item in QtQuick ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17105087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are C standard library structures compatible between compilers and library versions on macOS or Linux? My host application took over the ownership of e.g. a FILE object which came from a dynamic library. Can I call fclose() on this object safely even though my host application and the dynamic library are compiled with different versions of clang / gcc?
Background
On Windows (with different VS runtimes) it would be illegal and I have to first extract the fclose() function from the runtime library which is used by the dynamic library since all runtimes have their own pools and internal structures for file or memory objects.
An illustration for the situation in Windows would look like this:
Does this restriction apply for Linux and macOS as well?
A: The issue is not whether your application and the dynamic libraries were compiled with different versions of clang and/or gcc. The issue is whether, ultimately, there's one underlying C library that manipulates one kind of FILE * object and has one, compatible implementation of fclose().
Under MacOS and Linux, at least, the answer to all these questions is likely to be "yes". In my experience it's hard to get two different, incompatible C libraries into the mix; you'd have to really work at it.
Addendum: I suppose I should admit, however, that my experience may be getting dated. In my experience, on any Unix-like system, there's exactly one C library, generally /lib/libc.{a,so}. But I gather that "modern" compilers are tending to access their own compiler- and version-specific libraries off in special places, meaning that the scenario you're worried about could be a problem. To me, it seems, this way lies madness, but then again, it seems that more and more of the world seems to be embracing dependency hell, rather than trying to eliminate it.
A: It is not generally safe to use a library designed for one compiler with code compiled by a different compiler. A compiler may generate code that implements the nominal functions in the standard library using internal routines or interfaces, and those routines or interfaces may be different or missing in the library designed for another compiler.
Nor is it safe to take any pointer to some internal data structure from one library and use it with another library.
If the sources are just compiled with different versions of one compiler (e.g., clang 73 and clang 89), not different compilers (e.g., Apple clang versus GCC), the compiler might offer some guarantee about library compatibility. You would have to check its documentation. Or, if the compiler is intended to use the library provided with the operating system, that could work. Again, you would have to check its documentation.
A: On Linux, if both your code and the other library dynamically link to the same library (such as libc.so.6), both will get the same version and implementation of that library at runtime. You can check which libraries a given dynamic library links to with ldd.
If you were linking to a library that statically linked in a supporting library, you would need to be careful to pass any structures to or from it against the same version of the library. But this is more likely to come up in practice with libc++ and libstdc++ than with libc.
So, don't statically link your library to another and then pass a data structure that requires client code to separately link to the same library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48389080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: SQL multiple start dates to end date I have a table with the following format (which I cannot change)
ClientID | RefAd1 | Cluster Start Date | Cluster End Date
100001 | R1234 | 2014-11-01 |
100001 | R1234 | 2014-11-10 |
100001 | R1234 | 2014-11-20 |
What I would like to come out with is:
ClientID | RefAd1 | Cluster Start Date | Cluster End Date
100001 | R1234 | 2014-11-01 | 2014-11-10
100001 | R1234 | 2014-11-10 | 2014-11-20
100001 | R1234 | 2014-11-20 | NULL
I've searched on here, and had many attempts myself, but just can't get it working.
I can't update the source table (or add another table into the database) so I'm going to do this in a view (which I can save)
Any help would be gratefully appreciated, been going round in circles with this for a day and a bit now!
A: Use Self join to get next record
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
FROM YOURTABLE
)
SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1
*
*Click here to view result
EDIT :
To update the table, you can use the below query
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date]
*
*Click here to view result
EDIT 2 :
If you want this to be done for ClientId and RefAd1.
;WITH CTE AS
(
-- Get current date and next date for each type of ClientId and RefAd1
SELECT ROW_NUMBER() OVER(PARTITION BY ClientID,RefAd1 ORDER BY [Cluster Start Date])RNO,*
FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 AND C1.ClientID=C2.ClientID AND C1.RefAd1=C2.RefAd1
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date] AND TAB.ClientID=#TEMP.ClientID AND TAB.RefAd1=#TEMP.RefAd1
*
*Click here to view result
If you want to do it only for ClientId, remove the conditions for RefAd1
A: Here is the script if you just want the view you described:
CREATE VIEW v_name as
SELECT
ClientId,
RefAd1,
[Cluster Start Date],
( SELECT
min([Cluster Start Date])
FROM yourTable
WHERE
t.[Cluster Start Date] < [Cluster Start Date]
) as [Cluster End Date]
FROM yourtable t
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28191139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to pass state values from a component into another child component that contains param settings? I have a basic component that goes out and gets user info via axios and then sets the users state. But in the component, I have another nested component that is a form type component that sets placeholders, defaultValue, etc.
This is the lifecyle method that gets the data and sets state:
componentDidMount() {
axios.get('https://niftyURLforGettingData')
.then(response => {
console.log(response.data);
const users = response.data;
this.setState({ users });
})
.catch(error => {
console.log(error);
});
}
Nested within this component is my form component:
<FormInputs
ncols={["col-md-5", "col-md-3", "col-md-4"]}
properties={[
{
defaultValue: "I NEED VALUE HERE: this.state.users.id",
}
/>
if I use just:
{this.state.users.id} outside the component it works... but inside form...nothing.
I am quite sure I have to pass the state into this component... but can't quite get it.
A: I am pretty sure it doesn't work because users is undefined when your component renders for the first time.
Try to initialize that variable in the state doing something like this:
state = {
users: {}
}
and then use a fallback since id will also be undefined doing this:
<FormInputs
ncols={["col-md-5", "col-md-3", "col-md-4"]}
properties={[
{
defaultValue: this.state.users.id || "Fallback Value", // this will render "Fallback value" if users.id is undefined
}
/>
If this is not the case please share more information about your situation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62866302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Did a stopwatch using time libraries, it worked as expected, but it returns none also I'm new to python, so I was following a few tutorials to understand how to do something I liked to do. A stopwatch returning not only the time passed but also the time it started and finished. My plan started creating two variables with time.time, one for the start and another for the finish. So I subtracted the final time minus the start, and get time lapsed. Then I added two more variables, one for the time the program stopped counting, and another for the time it started. For the finish time it was easy, just used dateTime.now(), and for the time start I decided timeDelta might be usefull, so I did subtracted current time minus time lapsed, and get time started. It worked as expected as I said in the title, except for a little detail, which is also returning a None value apart of my time lapsed, so I'm not quite sure why being new to Python and being all I know from tutorials that don't explained these things. If you could give me any sort of explanation it'll help a lot!
import time
from datetime import datetime, timedelta
time_ended=datetime.now()
def time_convert(sec):
mins = sec // 60
sec = sec % 60
hours = mins // 60
mins = mins % 60
print("Time Lapsed = {0}:{1}:{2}".format(int(hours),int(mins),sec))
input("Press Enter to start")
start_time = time.time()
input("Press Enter to stop")
end_time = time.time()
time_lapsed = end_time - start_time
time_started=timedelta(((time_lapsed/24)/60)/60)
print("Time started: ",time_ended-time_started)
print(time_convert(time_lapsed))
print("Time finished: ",time_ended)
This is what happen after running the program
Press Enter to start
Press Enter to stop
Time started: 2022-06-08 14:01:20.396229
Time Lapsed = 0:0:53.04069781303406
None
Time finished: 2022-06-08 14:02:13.436927
BTW, I did try to delete the first "import time" but it brokes my code, and trying to do something like putting at the end of the second line a ",time" deleting the first line again, it doesn't work neither.
A: print(time_convert(time_lapsed))
Is your problem.
The tine_convert method doesn't return anything. So by encapsulating the function in a print function it just prints none.
Try returning a string in the end of your method like:
Return "test"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72550990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nested query to reference field from parent query Simplified example:
select
ticket_id,
`number` as 'ticket number',
(SELECT count(*) from ost_thread_entry join ost_thread on ost_thread_entry.thread_id = ost_thread.id where ost_thread.object_id = 1234) as 'number of posts in ticket'
from
ost_ticket
I need to reference the value from ticket_id instead of 1234
A: You may use table aliases here:
SELECT
ticket_id,
number AS `ticket number`,
(SELECT COUNT(*)
FROM ost_thread_entry ote
INNER JOIN ost_thread ot ON ote.thread_id = ot.id
WHERE ot.object_id = t.ticket_id) AS `number of posts in ticket`
FROM ost_ticket t;
Note that you might also be able to write your query without the correlated subquery, instead using joins:
SELECT
t.ticket_id,
t.number AS `ticket number`,
COUNT(ote.thread_id) AS `number of posts in ticket`
FROM ost_ticket t
LEFT JOIN ost_thread ot ON ot.object_id = t.ticket_id
LEFT JOIN ost_thread_entry ote ON ote.thread_id = ot.id
GROUP BY
t.ticket_id,
t.number;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71795285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why am I getting a NoMethodError when calling an instance method from global scope? I have searched around for the answer to this and I can see a lot of similar problems but I still do not understand what I am doing wrong here. I have declared a Ruby class and attempted to new it and then call some instance methods on the instance, so why do I get the NoMethodError on my start method?
class MyClass
def initialize
self.class.reset
end
def self.reset
...
end
def self.start(port)
...
end
end
test = MyClass.new
test.start '8082' <- here <- undefined method `start' for #<MyClass:0x2f494b0> (NoMethodError)
As you can see I am a Ruby noob. Any help would be appreciated. I can change my class structure but I would really like to understand what I am doing wrong here.
A: here start is a class method.
By your current approach, you can use it in the following way
MyClass.start '8080'
But if you want to use it on instance of class then use the following code
class MyClass
def initialize
self.class.reset
end
def self.reset
...
end
def start(port)
...
end
end
test = MyClass.new
test.start '8080'
A: You are using start as a Class variable, the method names preceded with self-keyword make those methods as Class methods. So if you really want to not change your class then you should call it like this:
MyClass.start '8080'
Else you can remove the self from your reset and start methods and make them as Instance methods and use them as:
test = MyClass.new
test.start '8082'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46271427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing 'this' to prototype function nested function what's the best style to pass 'this.dayNames' and use it within the nested function (createCalendar())?
function DateNames()
{
this.dayNames = ["Su", "M", "T", "W", "Th", "F", "S"];
}
DateNames.prototype.render = function(date)
{
console.log(date);
createCalendar()
function createCalendar()
{
console.log(this.dayNames);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73359913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to read response from server using Socket.IO client in Swift I am trying to connect to my Socket.io server (Node/Express) from an iOS client.
Here is the code for the server (JS):
// Server Code
io.on('connection', (socket) => {
console.log('user connected');
})
And here is my client code (Swift):
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Testing Socket.io
let manager = SocketManager(socketURL: URL(string: "http://<my ip address>:3001")!, config: [.log(true), .compress])
let socket = manager.defaultSocket
socket.on("connection") {data, ack in
print("EG socket connected")
}
socket.connect()
}
I am expecting the Swift console to print "EG socket connected." Instead this is what I recieve:
2021-07-09 22:02:16.481690-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Adding handler for event: connection
2021-07-09 22:02:16.482397-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-07-09 22:02:16.482630-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Joining namespace /
2021-07-09 22:02:16.482906-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2021-07-09 22:02:16.483073-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Adding engine
2021-07-09 22:02:16.484655-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Manager is being released
2021-07-09 22:02:16.484700-0400 Skull-King iOS Client[62477:10032656] LOG SocketEngine: Starting engine. Server: http://<my ip address>:3001
2021-07-09 22:02:16.484879-0400 Skull-King iOS Client[62477:10032656] LOG SocketEngine: Handshaking
2021-07-09 22:02:16.484923-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Client is being released
2021-07-09 22:02:16.487428-0400 Skull-King iOS Client[62477:10032656] LOG SocketEnginePolling: Doing polling GET http://192.168.1.220:3001/socket.io/?transport=polling&b64=1&EIO=4
2021-07-09 22:02:16.653389-0400 Skull-King iOS Client[62477:10032658] LOG SocketEnginePolling: Got polling response
2021-07-09 22:02:16.653593-0400 Skull-King iOS Client[62477:10032658] LOG SocketEnginePolling: Got poll message: 0{"sid":"BateC4jf7tW2ET39AAAF","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
2021-07-09 22:02:16.654032-0400 Skull-King iOS Client[62477:10032658] LOG SocketEngine: Got message: 0{"sid":"BateC4jf7tW2ET39AAAF","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
2021-07-09 22:02:16.656761-0400 Skull-King iOS Client[62477:10032655] LOG SocketEngine: Engine is being released
Am I missing a step?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68324189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why show all data from mysql databese if I hit saarch button by keep search field blank and need extra one HTML button for all Entries.? When i keep search field blank and hit on search button, then show all results from mysql database, Why.... here is my php code....
I want to create it, when i keep search field blank and click search button... have to show error "no search result" and want to create disallowed white spacing search and need extra one HTML button for all Entries. By one click so that i get all entries......
please help me....
<?php
$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');
if(isset($_POST['button'])){ //trigger button click
$search=$_POST['search'];
$query=mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
echo "<tbody>";
echo "<tr>";
echo "<td data-label='Student ID'>".$row['student_id']."</td>";
echo "<td data-label='Name' style='font-weight:bold;' >".$row['name']."</td>";
echo "<td data-label='Mobile No'>"."<a href='tel:".$row['phone']."'>".$row['phone']."</a>"."</td>";
echo "<td data-label='Blood' style='color:red; font-weight:bold;' >".$row['blood']."</td>";
echo "<td data-label='Email'>"."<a href='mailto:".$row['email']."'>".$row['email']."</a>"."</td>";
echo "<td data-label='District'>".$row['district']."</td>";
echo "</tr>";
echo "</tbody>";
}
}else{
echo "<div class='error-text'>No results</div><br><br>";
}
}else{ //while not in use of search returns all the values
$query=mysql_query("select * from iconic19");
while ($row = mysql_fetch_array($query)) {
}
}
mysql_close();
?>
Its Html Code
<form id="nbc-searchblue1" method="post" enctype="multipart/form-data" autocomplete="off">
<input id='wc-searchblueinput1' placeholder="Search Iconic..." name="search" type="search" autofocus>
<br>
<input id='nbc-searchbluesubmit1' value="Search" type="submit" name="button">
<div class="view-all"> <a href="script.php">Show all</a></div>
</form>
Its css Code..
.view-all a {
background: red;
padding: 10px;
border-radius: 4px;
color: #fff;
text-decoration: none;
}
A: Just check if $_POST['search'] is blank then display your message else execute your query.
A: <?php
$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');
if(isset($_POST['button'])){ //trigger button click
$numRows = 0;
if(!empty($_POST['search'])) {
$search = mysql_real_escape_string($_POST['search']);
$query = mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");
$numRows = (int)mysql_num_rows($query);
}
if ($numRows > 0) {
while ($row = mysql_fetch_array($query)) {
echo "<tbody>";
echo "<tr>";
echo "<td data-label='Student ID'>".$row['student_id']."</td>";
echo "<td data-label='Name' style='font-weight:bold;' >".$row['name']."</td>";
echo "<td data-label='Mobile No'>"."<a href='tel:".$row['phone']."'>".$row['phone']."</a>"."</td>";
echo "<td data-label='Blood' style='color:red; font-weight:bold;' >".$row['blood']."</td>";
echo "<td data-label='Email'>"."<a href='mailto:".$row['email']."'>".$row['email']."</a>"."</td>";
echo "<td data-label='District'>".$row['district']."</td>";
echo "</tr>";
echo "</tbody>";
}
} else {
echo "<div class='error-text'>No results</div><br><br>";
}
} else { //while not in use of search returns all the values
$query = mysql_query("select * from iconic19");
while ($row = mysql_fetch_array($query)) {
}
}
mysql_close();
?>
What I have done was creating a new variable $numRows with a default value of 0. If your search is empty there is no query to the database. I escaped your $search variable.
BTW: Please change to mysqli, the mysql extension is no longer supported in newer php versions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55080963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TFX - How to inspect records from CsvExampleGen Question
How to inspect the data loaded into TFX CsvExampleGen?
CSV
Top 3 rows from the california_housing_train.csv looks below.
longitude
latitude
housing_median_age
total_rooms
total_bedrooms
population
households
median_income
median_house_value
-122.05
37.37
27
3885
661
1537
606
6.6085
344700
-118.3
34.26
43
1510
310
809
277
3.599
176500
-117.81
33.78
27
3589
507
1484
495
5.7934
270500
CsvExampleGen
The CSV is loaded into CsvExampleGen. In my understanding, XXXExampleGen is to generate tf.Record instances, hence I wonder if there is a way to iterate through the records from CsvExampleGen.
from tfx.components import (
CsvExampleGen
)
housing = CsvExampleGen("sample_data/california_housing_train.csv")
housing
----------
CsvExampleGen(
spec: <tfx.types.standard_component_specs.FileBasedExampleGenSpec object at 0x7fcd90435450>,
executor_spec: <tfx.dsl.components.base.executor_spec.BeamExecutorSpec object at 0x7fcd90435850>,
driver_class: <class 'tfx.components.example_gen.driver.FileBasedDriver'>,
component_id: CsvExampleGen,
inputs: {},
outputs: {
'examples': OutputChannel(artifact_type=Examples,
producer_component_id=CsvExampleGen,
output_key=examples,
additional_properties={},
additional_custom_properties={})
}
)
Experiment
for record in housing.outputs['examples']:
print(record)
TypeError Traceback (most recent call last)
in
----> 1 for record in housing.outputs['examples']:
2 print(record)
TypeError: 'OutputChannel' object is not iterable
A: Have you got a chance to take a look at this section in tutorials, which explains how to display the artifacts of ExampleGen component? You can modify the code below (Source: TFX Tutorial) to achieve the same.
# Get the URI of the output artifact representing the training examples, which is a directory
train_uri = os.path.join(example_gen.outputs['examples'].get()[0].uri, 'Split-train')
# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
for name in os.listdir(train_uri)]
# Create a `TFRecordDataset` to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")
# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
serialized_example = tfrecord.numpy()
example = tf.train.Example()
example.ParseFromString(serialized_example)
pp.pprint(example)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72007159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for render event in delegateEvents in Backbone.View I have one question about Backbone.View and its delegateEvents. You can read in docs here about extend method. Using this method, you can "override the render function, specify your declarative events" etc.
I have a question about declarative events or delegateEvents (not sure how should I call it). They are described here. And here is an example:
var DocumentView = Backbone.View.extend({
events: {
"dblclick" : "open",
"click .icon.doc" : "select",
"contextmenu .icon.doc" : "showMenu",
"click .show_notes" : "toggleNotes",
"click .title .lock" : "editAccessLevel",
"mouseover .title .date" : "showTooltip"
},
open: function() {
window.open(this.model.get("viewer_url"));
},
select: function() {
this.model.set({selected: true});
},
...
});
As you can see, you can add different events on specific objects in template DOM. Like click or mouseover. So, having this template:
<foo></foo>
{#myplayers}
<player class="normal" value="{player}" style="{style}"></player>
{/myplayers}
You can add different click event on every single player, like this:
events: {
'click player': 'playerClick'
},
playerClick: function( e ) {
var playerValue = e.currentTarget.getAttribute( 'value' );
// HERE: e.currentTarget I've particular player
}
My question: Can I declare render event in similar way as click event? I want to catch event when single player (not the whole list) is rendered. I need to get e.currentTarget there and change its css a little bit.
I'm looking for something like this:
events: {
'render player': 'playerRendered'
},
playerRendered: function( e ) {
var playerValue = e.currentTarget.getAttribute( 'value' );
// HERE: e.currentTarget I've particular player
}
How can I do this? Because render in delegateEvents, doesn't work:/
A: Maybe in the initialize function within your view you can have a listenTo with the render. Something like that:
var view = Backbone.View.extend({
className: 'list-container',
template: _.template($('#my-template').html()),
initialize: function () {
this.listenTo(this, 'render', function () {
console.info('actions');
});
},
render: function() {
this.$el.html(this.template(this));
return this;
},
});
And then:
var myView = new view();
myView.render();
myView.trigger('render');
$('#container').html(myView.el);
A: var View = Backbone.View.extend({
events: {
'render .myselector': 'playerRendered'
},
playerRendered: function( e ) {
console.log("arguments");
var playerValue = e.currentTarget.getAttribute( 'value' );
// HERE: e.currentTarget I've particular player
},
render:function(){
console.log("render");
this.$el.html("<div class='myselector'></div>");
}
});
var view = new View();
view.render();
and you can trigger with Jquery trigger
this.$(".myselector").trigger("render");
or outside your view
view.$(".myselector").trigger("render");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33662044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I just shifted my databases to a sql server 2008 cluster connected to a SAN and its started giving me the following errors SQL Server has encountered 1 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [T:\MSSQL\DATA\%file_name%] in database [%DB_name%] (2). The OS file handle is 0×00000838. The offset of the latest long I/O is: 0×000000ebdc0000
Has anyone encountered and solved this?
A: Please see this - you may have IO issues - and physical drive issues
http://blogs.msdn.com/chrissk/archive/2008/06/19/i-o-requests-taking-longer-than-15-seconds-to-complete-on-file.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1288283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Synchronized SELECT to web sql I have need for executing SELECT statement to my web sql table and based on response use result or make AJAX call to obtain results.
It is possible to make synchronized ?
I have function like this:
getFile : function( fileName ) {
var me = this;
me.db.transaction( function( tx ) {
tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError );
} );
// somehow return results as empty array or array with object
// I know results need to be transformed
},
and later in code want to do something like this:
var r = getFile( name );
if ( r.length > 0 ) {
// use it
}
else {
// make AJAX call and store it
}
A: The simplest way would be to create a function with the code you want to execute after the execution of the request, and pass this function in parameter of the getfile function :
getFile : function( fileName, success ) {
var me = this;
me.db.transaction( function( tx ) {
tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError );
},
success
);
// somehow return results as empty array or array with object
// I know results need to be transformed
});
var r = getFile(
name,
function() {
var r = getFile( name );
if ( r.length > 0 ) {
// use it
}
else {
// make AJAX call and store it
}
}
);
Otherwise, the best way to perform is to use Promises to resolve asynchronous issues but you'll have to use a library like JQuery.
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23664156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I 'monkey patch' or override User.is_authenticated()? Creates issues with using django-lazysignup I installed django-lazysignup and am facing the challenge now of User.is_authenticated() returning True, for what are not actually authenticated users, but instead lazy-signup users. I can update any checks for User.is_authenticated() in my code with my own function. However, other packages like django-allauth, check this method to decide whether a user is already signed-in, and redirect from attempts to reach the login page.
class RedirectAuthenticatedUserMixin(object):
def dispatch(self, request, *args, **kwargs):
self.request = request
if request.user.is_authenticated():
redirect_to = self.get_authenticated_redirect_url()
response = HttpResponseRedirect(redirect_to)
return _ajax_response(request, response)
...
Are there any recommendations that don't require replacing is_authenticated() in every package that I include? Seems most of them expect it to function a particular way, and django-lazysignup turns that on its head. Could I monkey patch the User model with a new is_authenticated() method? If it's possible, where would I do this so that it's attached to the page request?
A: django-lazysignup, which you are using, allows you to deliver a custom LazyUser class (here). All you need to do is to write a subclass of lazysignup.models.LazyUser with defined is_authenticated method and set it as settings.LAZYSIGNUP_USER_MODEL.
But this is not the end of your troubles. Lots of django apps
assume that authenticated user has some properties. Mainly, is_staff, is_superuser, permissions, groups. First and foremost, django.contrib.admin needs them to check if it can let the user in and what to show him. Look how django.contrib.auth.models.AnonymousUser mocks them and copy it. Remark: look how AnonymousUser is not subclassing any user class nor db.Model. Supplied user class only needs to quack.
A: Ended up just having to replace all calls to User.is_authenticated().
To prevent django-allauth from redirecting lazy-users from the login page, this ended up looking something like this:
from allauth.account.views import AjaxCapableProcessFormViewMixin
def _ajax_response(request, response, form=None):
if request.is_ajax():
if (isinstance(response, HttpResponseRedirect)
or isinstance(response, HttpResponsePermanentRedirect)):
redirect_to = response['Location']
else:
redirect_to = None
response = get_adapter().ajax_response(request,
response,
form=form,
redirect_to=redirect_to)
return response
class RedirectUserWithAccountMixin(object):
def dispatch(self, request, *args, **kwargs):
self.request = request
if user_has_account(request.user):
redirect_to = self.get_authenticated_redirect_url()
response = HttpResponseRedirect(redirect_to)
return _ajax_response(request, response)
else:
response = super(RedirectUserWithAccountMixin,
self).dispatch(request,
*args,
**kwargs)
return response
def get_authenticated_redirect_url(self):
redirect_field_name = self.redirect_field_name
return get_login_redirect_url(self.request,
url=self.get_success_url(),
redirect_field_name=redirect_field_name)
class LoginView(RedirectUserWithAccountMixin,
AjaxCapableProcessFormViewMixin,
FormView):
...
Where user_has_account() was my own method for checking whether the user was actually signed in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31256174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where is page social_django.views.auth? I'm trying to make auth with google. But get
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/account/login/google/
Raised by: social_django.views.auth
Backend not found
settings.py
INSTALLED_APPS = [
...,
'social_django',
]
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...'
SOCIAL_AUTH_URL_NAMESPACE = 'social'
urls.py(root)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('books.urls')),
path('account/', include('account.urls')),
path('comments/', include('django_comments.urls')),
path('account/', include('social_django.urls', namespace='social'))
]
login.html
<a href="{% url "social:begin" "google" %}">Login with Google</a>
I did migrations for social_django
A: Instead of using :
<a href="{% url "social:begin" "**google**" %}">
Login with Google
</a>
Use:
< a href="{% url 'social:begin' '**google-oauth2**' %}?next={{ request.path }}">
Login with Google
</a>
Source : official documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66387498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Predict Values by using neural net in R I'm new in using R, but the more I get in thouch with, the more I like it.
Howver, I try to utilze R for artificial neural networks.
My input data is a csv-Table with measured soil properties.
Phosphorus, pH, clay content, silt content and so on.
The objective is to train an neural network with neuralnet and predict Phosphorus (P) by using measured pH, clay content, silt content and so on.
Actually my following script works to train a net, but I don't know, if the script really predicts P by computing the test-dataset with the explaining variables.
Code is below.
library(neuralnet)
getwd("F:/Dropbox/Agrar/Fernerkundung_Agrar/ANN_Test/")
setwd("F:/Dropbox/Agrar/Fernerkundung_Agrar/ANN_Test/")
library(gdata)
# This is a script to train a neural net and test it afterward.
# Objectives are to extimate Phosphorus-Contents in Soil from other variables
# Again. Targetparameter is P (Phosphorus) which has to be estimated from pH, ECa (Soil apparent electrical conductivity) (and later other input variables)
# Traininginput is a CSV-File with measured varaiables P, pH, ECa [here called EC2509 because it was measured in September 25th]
traininginput = read.csv("in.csv", header = TRUE, sep = ";", dec = ".")
#Train the neural network
#Going to have 3 hidden layers -> thumb rule input + output variables
#Threshold is a numeric value specifying the threshold for the partial derivatives of the error function as stopping criteria.
# All later considerd parameters are P~ + PH + clay_A + silt_A + sand_A + LS + A_ABAG + TWI + EC2509
# First let's try P and two variables
net.Phos <- neuralnet(P~PH,traininginput, hidden=3, threshold=0.01, rep = 100) # stepmax = 1000000 will be included later
print(net.Phos)
write.table(net.Phos,"ann_setup.txt", header = TRUE, sep = " ", dec = ".")
#Plot the neural network
png(filename="ANN.png")
pdf(filename="ANN.pdf")
plot(net.Phos)
dev.off()
#Test the neural network: Testdata contains measured variables P, pH, ECa and others. Exactly the same setup than input
testdata = read.csv("testann.csv", header = TRUE, sep = ";", dec = ".")
head(testdata)
net.test <- compute(net.Phos, testdata$PH) #Run them through the neural network
#Lets see what properties net.sqrt has
ls(net.Phos)
write.table(net.Phos,"ann_properties.txt", header = TRUE, sep = ",", dec = ".")
#Lets see the test results
print(net.test$neurons[[1]])
print(net.test$net.test)
#Lets display a better version of the results
cleanoutput <- cbind(testdata$PH,testdata$P,
as.data.frame(net.results$net.result[,1]))
colnames(cleanoutput) <- c("PH","Expected P","Neural Net P")
print(cleanoutput)
write.csv(Cleanout,"ann_setup.csv", header = TRUE, sep = " ", dec = ".")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28083740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Use ONVIF Client Test Tool simulator for Profile T I am trying to do the ONVIF Client certification. For HTTPS streaming, I need to use the profile T simulator that is included with the Client Test Tool. As I understand it, the simulator should behave like an ONVIF camera (or some functionalities of a camera), but it doesn't. I can't even use the command getStreamUri(), because the media service doesn't work.
Has anyone had a similar experience? Or is there another way to use the simulator?
CTT version is 22.06 rev 4624
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73803979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: check facebook session onload Below I am trying to check the session of facebook on page load. And want to show different content on page as per login status. What's wrong?
I want first two check the user connection status. Then only appropriate content to be shown on the page.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
</head>
<body>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '1781292862', // App ID from the app dashboard
// channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
window.onload(){
FB.init({
appId : '178812862', // Your FB app ID from www.facebook.com/developers/
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("yes");
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
}
});
</script>
</body>
</html>
A: Try this
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
id= response.id;
if(id==undefined)
{
alert('I am logged out');
}
else
{
alert('I am logged in');
}
})
}
});
A: First, you'll want to use response.status instead of response.session. And since the status is going to be string either way ("connected", "not_authorized", or "unknown"), you'll want to set up your if statements accordingly. The following example is from https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
Let me know if that makes sense, or if you have any questions :)
Update
Your script is still missing the little closure that loads the facebook sdk into your document (which is why you're getting the error that FB is not defined). Try replacing your whole script block with the following:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 1343434343, // Your FB app ID from www.facebook.com/developers/
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("yes");
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
(^That last part is what loads the facebook sdk.) Try it out and let me know how it goes :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18865794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sending data from Arduino to MIT app Inventor 2 via bluetooth I have an Arduino Uno microprocessor connected with a temperature sensor, I am able to print the temperature on the Serial Monitor successfully.
The idea is, I wanna dump the value of the temperature into a label sitting on MIT app inventor 2 project via Bluetooth. Anybody has an idea how to do that?
What should I add to the following code to be able to send the data via Arduino.
const int dataPin = 8;
int temperature = -1;
int humidity = -1;
void setup() {
Serial.begin(115200);
}
int readDHT11(){
uint8_t recvBuffer[5];
uint8_t cnt = 7;
uint8_t idx = 0;
for(int i = 0; i<5; i++){
recvBuffer[i] = 0;
}
pinMode(dataPin, OUTPUT);
digitalWrite(dataPin, LOW);
delay(18);
digitalWrite(dataPin, HIGH);
delayMicroseconds(40);
pinMode(dataPin, INPUT);
pulseIn(dataPin, HIGH);
unsigned int timeout = 10000;
for(int i = 0; i<40; i++){
timeout = 10000;
while(digitalRead(dataPin) == LOW){
if(timeout == 0) return -1;
timeout--;
}
unsigned long t = micros();
timeout = 10000;
while(digitalRead(dataPin) == HIGH){
if(timeout == 0) return -1;
timeout--;
}
if ((micros() - t) > 40) recvBuffer[idx] |= (1 << cnt);
if(cnt ==0){
cnt = 7;
idx++;
}else{
cnt--;
}
}
humidity = recvBuffer[0];
temperature = recvBuffer[2];
uint8_t sum = recvBuffer[0] + recvBuffer[2];
if(recvBuffer[4] != sum) return -2;
return 0;
}
void loop() {
int ret = readDHT11();
if(ret!=0) Serial.println(ret);
Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t");
Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" C\n");
delay(500);
}
Thanks!!
A: Take a look here. This tutorial was really helpful for me when I was a beginner. Hope that it will helps you too!
Good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31460679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.