date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/15
| 1,352 | 5,119 |
<issue_start>username_0: I have a Activity indicator to inform user wait to login in webservice, but just show a circle rouding, I want set a text together like "Login, Wait..."
```
@IBOutlet weak var waitView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.waitView.startAnimating()
self.waitView.hidesWhenStopped = true
OdooAuth.init( successBlock: {
result in
self.waitView.stopAnimating()
print("Auth Success: \(result)")
}, failureBlock: {
result in
self.waitView.stopAnimating()
print("Auth Error: \(result)")
})
}
```<issue_comment>username_1: you can use like that:
```
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
let viewForActivityIndicator = UIView()
let view: UIView
let loadingTextLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.showActivityIndicator()
OdooAuth.init( successBlock: {
result in
self.stopActivityIndicator()
print("Auth Success: \(result)")
}, failureBlock: {
result in
self.stopActivityIndicator()
print("Auth Error: \(result)")
})
}
func showActivityIndicator() {
viewForActivityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)
viewForActivityIndicator.backgroundColor = UIColor.white
view.addSubview(viewForActivityIndicator)
activityIndicatorView.center = CGPoint(x: self.view.frame.size.width / 2.0, y: self.view.frame.size.height / 2.0)
loadingTextLabel.textColor = UIColor.black
loadingTextLabel.text = "LOADING"
loadingTextLabel.font = UIFont(name: "Avenir Light", size: 10)
loadingTextLabel.sizeToFit()
loadingTextLabel.center = CGPoint(x: activityIndicatorView.center.x, y: activityIndicatorView.center.y + 30)
viewForActivityIndicator.addSubview(loadingTextLabel)
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.activityIndicatorViewStyle = .gray
viewForActivityIndicator.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
}
func stopActivityIndicator() {
viewForActivityIndicator.removeFromSuperview()
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
}
```
Upvotes: 2 <issue_comment>username_2: For Swift 5
Indicator with label inside WKWebview
```
var strLabel = UILabel()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
let loadingTextLabel = UILabel()
@IBOutlet var indicator: UIActivityIndicatorView!
@IBOutlet var webView: WKWebView!
var refController:UIRefreshControl = UIRefreshControl()
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self
webView.uiDelegate = self as? WKUIDelegate
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
webView.allowsBackForwardNavigationGestures = true
webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
setBackground()
}
func setBackground() {
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
func showActivityIndicator(show: Bool) {
if show {
strLabel = UILabel(frame: CGRect(x: 55, y: 0, width: 400, height: 66))
strLabel.text = "Please Wait. Checking Internet Connection..."
strLabel.font = UIFont(name: "Avenir Light", size: 12)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 300, height: 66)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(style: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 66, height: 66)
indicator.startAnimating()
effectView.contentView.addSubview(indicator)
effectView.contentView.addSubview(strLabel)
indicator.transform = CGAffineTransform(scaleX: 1.4, y: 1.4);
effectView.center = webView.center
view.addSubview(effectView)
} else {
strLabel.removeFromSuperview()
effectView.removeFromSuperview()
indicator.removeFromSuperview()
indicator.stopAnimating()
}
}
```
[](https://i.stack.imgur.com/XSCJY.png)
Upvotes: 0
|
2018/03/15
| 1,529 | 5,778 |
<issue_start>username_0: Looking to return each occurrence (product) found in `name` where `name` is comma separated, e.g. `[woo_products_by_name name="shoe,shirt"]` If I do not `explode` `name` then nothing is returned as only `shoe,shirt` is seen. If `explode` is used then the query is not selective and it appears that all products are returned. If only `'name' => $name` is used and one verse two products as described above are specified, then the query works as expected. Would like to return a match for each item so in this example, to products would be returned.
```
function woo_products_by_name_shortcode( $atts, $content = null ) {
// Get attribuets
extract(shortcode_atts(array(
'name' => ''
), $atts));
//$name = explode(",", $atts['name']);
ob_start();
// Define Query Arguments
$loop = new WP_Query( array(
'post_type' => 'product',
'posts_per_page' => 10,
'name' => explode(",",$name)
));
// Get products number
$product_count = $loop->post_count;
echo '
```
'; print_r($loop->posts); echo '
```
';
return ob_get_clean();
}
add_shortcode("woo_products_by_name", "woo_products_by_name_shortcode");
```<issue_comment>username_1: you can use like that:
```
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
let viewForActivityIndicator = UIView()
let view: UIView
let loadingTextLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.showActivityIndicator()
OdooAuth.init( successBlock: {
result in
self.stopActivityIndicator()
print("Auth Success: \(result)")
}, failureBlock: {
result in
self.stopActivityIndicator()
print("Auth Error: \(result)")
})
}
func showActivityIndicator() {
viewForActivityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)
viewForActivityIndicator.backgroundColor = UIColor.white
view.addSubview(viewForActivityIndicator)
activityIndicatorView.center = CGPoint(x: self.view.frame.size.width / 2.0, y: self.view.frame.size.height / 2.0)
loadingTextLabel.textColor = UIColor.black
loadingTextLabel.text = "LOADING"
loadingTextLabel.font = UIFont(name: "Avenir Light", size: 10)
loadingTextLabel.sizeToFit()
loadingTextLabel.center = CGPoint(x: activityIndicatorView.center.x, y: activityIndicatorView.center.y + 30)
viewForActivityIndicator.addSubview(loadingTextLabel)
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.activityIndicatorViewStyle = .gray
viewForActivityIndicator.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
}
func stopActivityIndicator() {
viewForActivityIndicator.removeFromSuperview()
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
}
```
Upvotes: 2 <issue_comment>username_2: For Swift 5
Indicator with label inside WKWebview
```
var strLabel = UILabel()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
let loadingTextLabel = UILabel()
@IBOutlet var indicator: UIActivityIndicatorView!
@IBOutlet var webView: WKWebView!
var refController:UIRefreshControl = UIRefreshControl()
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self
webView.uiDelegate = self as? WKUIDelegate
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
webView.allowsBackForwardNavigationGestures = true
webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
setBackground()
}
func setBackground() {
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
func showActivityIndicator(show: Bool) {
if show {
strLabel = UILabel(frame: CGRect(x: 55, y: 0, width: 400, height: 66))
strLabel.text = "Please Wait. Checking Internet Connection..."
strLabel.font = UIFont(name: "Avenir Light", size: 12)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 300, height: 66)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(style: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 66, height: 66)
indicator.startAnimating()
effectView.contentView.addSubview(indicator)
effectView.contentView.addSubview(strLabel)
indicator.transform = CGAffineTransform(scaleX: 1.4, y: 1.4);
effectView.center = webView.center
view.addSubview(effectView)
} else {
strLabel.removeFromSuperview()
effectView.removeFromSuperview()
indicator.removeFromSuperview()
indicator.stopAnimating()
}
}
```
[](https://i.stack.imgur.com/XSCJY.png)
Upvotes: 0
|
2018/03/15
| 1,680 | 3,986 |
<issue_start>username_0: I'm trying to parse a list of dates so say I have the following data:
```
2012-02-19 10:06:29.287
2012-02-19 10:06:29.900
2014-01-21 15:21:11.114
2015-04-22 01:11:50.233
2015-04-22 01:11:55.921
2015-04-22 01:12:12.144
2017-12-18 12:01:01.762
```
I want to then be left with the following list:
```
2012-02-19 10:06:29.900
2014-01-21 15:21:11.114
2015-04-22 01:12:12.144
2017-12-18 12:01:01.762
```
Where any dates that are within 1 minute of each other, all are removed except the most recent date. With fluent syntax LINQ if possible.
So in the above example we have 2 dates that fit that criteria:
```
2012-02-19 10:06:29.287
2012-02-19 10:06:29.900
```
Are within 1 minute of each other, so the first entry is removed so only the most recent is left.
```
2015-04-22 01:11:50.233
2015-04-22 01:11:55.921
2015-04-22 01:12:12.144
```
Has 3 within a minute of each other, so the first two should be removed and left with only the last.<issue_comment>username_1: Using a few extension methods, you can do this in LINQ, though it isn't ideal.
The first is a variation of the APL scan operator, which is similar to `Aggregate`, but returns the intermediate results computed from the previous and current values.
```
public static IEnumerable> ScanPair(this IEnumerable src, TKey seedKey, Func, T, TKey> combine) {
using (var srce = src.GetEnumerator()) {
if (srce.MoveNext()) {
var prevkv = new KeyValuePair(seedKey, srce.Current);
while (srce.MoveNext()) {
yield return prevkv;
prevkv = new KeyValuePair(combine(prevkv, srce.Current), srce.Current);
}
yield return prevkv;
}
}
}
```
The second is another APL operator implementation, this time of the compress operator, which uses a boolean vector to select elements.
```
public static IEnumerable Compress(this IEnumerable bv, IEnumerable src) {
using (var srce = src.GetEnumerator()) {
foreach (var b in bv) {
srce.MoveNext();
if (b)
yield return srce.Current;
}
}
}
```
The third lets you concatenate values to a sequence:
```
public static IEnumerable Append(this IEnumerable rest, params T[] last) => rest.Concat(last);
```
Now you can process the list:
```
var ans = src.Scan((prev, cur) => (cur-prev).TotalSeconds > 60) // find times over a minute apart
.Append(true) // always keep the last time
.Compress(src); // keep the DateTimes that are okay
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
var data = new List
{
new DateTime(2012, 02, 19, 10, 06, 29, 287), new DateTime(2012, 02, 19, 10, 06, 29, 900) ,
new DateTime(2014, 01, 21, 15, 21, 11, 114) ,
new DateTime(2015, 04, 22, 01, 11, 50, 233),
new DateTime(2015, 04, 22, 01, 11, 55, 921),
new DateTime(2015, 04, 22, 01, 12, 12, 144),
new DateTime(2017, 12, 18, 12, 01, 01, 762)
};
var dataFIltered = data.Select(c => new DateTime(c.Year,c.Month,c.Minute)).Distinct().ToList();
```
Upvotes: 0 <issue_comment>username_3: Here's a small example I wrote up in a console program.. It involves two lists, but gets the job done:
```
static void Main(string[] args)
{
List times = new List();
times.Add(new DateTime(2012, 02, 19, 10, 06, 29));
times.Add(new DateTime(2012, 02, 19, 10, 06, 29));
times.Add(new DateTime(2014, 01, 21, 15, 21, 11));
times.Add(new DateTime(2015, 04, 22, 01, 11, 50));
times.Add(new DateTime(2015, 04, 22, 01, 11, 55));
times.Add(new DateTime(2015, 04, 22, 01, 12, 12));
times.Add(new DateTime(2017, 12, 18, 12, 01, 01));
List TheList = new List();
DateTime min = times.OrderBy(c => c.Date).ThenBy(c => c.TimeOfDay).FirstOrDefault();
while (times.Where(t => t <= min.AddMinutes(1)).Any())
{
TheList.Add(min);
Remove(times, min);
min = times.OrderBy(c => c.Date).ThenBy(c => c.TimeOfDay).FirstOrDefault();
}
foreach (DateTime t in TheList)
Console.WriteLine(t);
Console.ReadKey();
}
static void Remove(List times, DateTime min)
{
times.RemoveAll(t => t <= min.AddMinutes(1));
}
```
Upvotes: 0
|
2018/03/15
| 1,940 | 5,489 |
<issue_start>username_0: I'm importing some OSM data from [Trimble](https://data.trimble.com/market/provider/OpenStreetMap.html) into a PostGIS database to process it as part of a Django app. This works fine for points and lines but I'm struggling with the polygons.
The import appears to work fine:
```
shp2pgsql -d -I aeroway_polygon_polygon.shp aeroway_polygon | psql
```
Django InspectDB interprets the data in a sensible manner:
```
./manage.py inspectdb > models.py
```
models.py contents:
```
class AerowayPolygon(models.Model):
gid = models.AutoField(primary_key=True)
id = models.FloatField(blank=True, null=True)
osm_id = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True)
z_order = models.FloatField(blank=True, null=True)
aeroway = models.CharField(max_length=80, blank=True, null=True)
name = models.CharField(max_length=80, blank=True, null=True)
name_en = models.CharField(db_column='name:en', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters.
operator = models.CharField(max_length=80, blank=True, null=True)
ref = models.CharField(max_length=80, blank=True, null=True)
faa = models.CharField(max_length=80, blank=True, null=True)
iata = models.CharField(max_length=80, blank=True, null=True)
icao = models.CharField(max_length=80, blank=True, null=True)
website = models.CharField(max_length=80, blank=True, null=True)
contact_we = models.CharField(db_column='contact:we', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters.
phone = models.CharField(max_length=80, blank=True, null=True)
contact_ph = models.CharField(db_column='contact:ph', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters.
ele = models.CharField(max_length=80, blank=True, null=True)
tower_type = models.CharField(db_column='tower:type', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters.
geom = models.MultiPolygonField(srid=0, dim=4, blank=True, null=True)
class Meta:
managed = False
db_table = 'aeroway_polygon'
```
Any attempt to access objects from the database cause GEOS to complain about a LinearRing.
```
>>> from data.models import AerowayPolygon
>>> AerowayPolygon.objects.all()[0]
GEOS_ERROR: IllegalArgumentException: Points of LinearRing do not form a closed linestring
```
The error is not wrong, the points don't close the LineString. But I'm confused as I think the type should be a MultiPolygon and should, therefore, work fine. What gives?
---
I dug a little deeper by manually trying to take geometries from PostGIS.
As a well-known binary hex string, I get the same behaviour:
```
>>> from django.contrib.gis.geos import GEOSGeometry
>>> wkb ='01060000C00100000001030000C0020000008E0000000064931E4F47DDBF4020B11AB5BC49400000000000000000FFFFFFFFFFFFEFFF006493B23347DDBF442075F9B7BC494 ... 003C9368871FDDBF4020B193B4BC49400000000000000000FFFFFFFFFFFFEFFF'
>>> GEOSGeometry(wkb)
GEOS_ERROR: IllegalArgumentException: Points of LinearRing do not form a closed linestring
```
However, if I pre-convert to well known text using ST\_AsEWKT, all appears well:
```
>>> wkt = 'MULTIPOLYGON(((-0.45747735963738 51.4742768635629 0 -1.79769313486232e+308,-0.457470821752906 51.474364454451 0 -1.79769313486232e+308, ... ,-0.455049373745112 51.4742607703088 0 -1.79769313486232e+308)))'
>>> GEOSGeometry(wkt)
```<issue_comment>username_1: Each polygon of a MultiPolygon should still form a closed linestring. Your data is probably malformed or corrupted.
You can try to fix this by using [ST\_MakeValid](http://postgis.refractions.net/docs/ST_MakeValid.html).
```sql
UPDATE aeroway_polygon
SET geom = ST_Multi(ST_CollectionExtract(ST_Makevalid(geom), 3))
WHERE ST_IsValid(geom) = false;
```
Note that I didn't test this query, I found it [here on gis.stackexchange](https://gis.stackexchange.com/questions/165151/postgis-update-multipolygon-with-st-makevalid-gives-error).
Upvotes: 2 <issue_comment>username_2: `Polygons` by definition are closed geometries, which means that the first and last `Point` must be the same exact `Point`.
For `Multipolygons` the same principle exists, hence every `Polygon` of a `Multipolygon` must be closed and there must not be "free" edges inside the geometry.
If you check your dataset you will find that some of those `LineStrings` are not closing.
@AntoinePinsard gives a good PostGIS solution.
In GeoDjango version >= 1.10, [`MakeValid`](https://docs.djangoproject.com/en/stable/ref/contrib/gis/functions/#makevalid) exists as a database function and we can use it on queries:
```
AerowayPolygon.objects.all().update(geom=MakeValid('geom'))
```
If your Django version < 1.10, I have a set of answers on how to create a custom database function and use it as in the example above:
* [How to make/use a custom database function in Django](https://stackoverflow.com/questions/46689979/how-to-make-use-a-custom-database-function-in-django)
* [Equivalent of PostGIS ST\_MakeValid in Django GEOS](https://stackoverflow.com/questions/45631855/equivalent-of-postgis-st-makevalid-in-django-geos/45633779#45633779):
>
>
> ```
> from django.contrib.gis.db.models.functions import GeoFunc
>
> class MyMakeValid(GeoFunc):
> function='ST_MakeValid'
>
> AerowayPolygon.objects.all().update(geom=MyMakeValid('geom'))
>
> ```
>
>
Upvotes: 1
|
2018/03/15
| 706 | 2,489 |
<issue_start>username_0: I have a Javascript function that looks like this:
```
sendData: function(event) {
///my code////
},
```
I need to call this function somewhere in my page in an setInterval function.
So i tried this:
```
function myTimeoutFunction()
{
sendData();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 3000);
```
But this doesn't seem to fire up the function!
I also tried this way with no result:
```
function myTimeoutFunction()
{
this.sendData();
}
```
Could someone please advice on this issue?
Thanks in advance.<issue_comment>username_1: sendData seems to be a part of an object such as below
```
object = {
sendData: function() {
}
}
```
then you should call it like this.
```
object.sendData();
```
Let me know if this helps.
Upvotes: 2 <issue_comment>username_2: Your syntax:
```
sendData: function(event) {
///my code////
},
```
Implies that your code is part of a larger, `Object` structure, similar to this:
```
var myObj = {
sendData: function(event) {
///my code////
},
somethingElse: true
}
```
That being the case, how you call the function will depend on from where you are trying to call it:
If you are trying to call the function from inside of the object structure, you can access the function with the `this` keyword as long as the object has been instantiated:
```js
var myObj = {
sendData: function(event) {
console.log("Hello!");
},
runSendData: function(){
// As long as you are inside of the same object structure
// as the function you wish to invoke, you can use "this"
this.sendData();
}
}
myObj.runSendData();
```
If you are trying to call the function from outside of the object structure, you'll have to access your function as a method of the object it is defined within:
```js
var myObj = {
sendData: function(event) {
console.log("Hello!");
},
somethingElse: true
}
myObj.sendData();
```
If your goal is to just be able to call the function, independent of anything else, then you need to create it as "function declaration", which happens outside of an object:
```js
function sendData(){
console.log("Hello");
}
// Now you can invoke the function as long as it has been already read into memory
sendData();
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: ```
var sendData = function(params) {
//Code
}
```
You can call your function with;
```
sendData(params);
```
Upvotes: -1
|
2018/03/15
| 818 | 2,839 |
<issue_start>username_0: I am very new to jenkins, but I have searched for an answer for this a couple of days now. I run jenkins on localhost:8080. I have written a program in Java which uses gradle to deploy to Google App Engine cloud. Now I wanted to use Jenkins to build my program in GIT. Building the program with gradle is fine. When I run
>
> ./gradlew appengineDeploy
>
>
>
in Execute Shell I get following:
>
> FAILURE: Build failed with an exception.
>
>
> * What went wrong:
>
>
> Execution failed for task ':appengineDeploy'.
>
>
> The Google Cloud SDK could not be found in the customary locations and no path was provided.
>
>
> * Try:
>
>
> Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
>
>
> BUILD FAILED
>
>
> Total time: 9.571 secs
>
>
> Build step 'Execute shell' marked build as failure
> Finished: FAILURE
>
>
>
When I run the code locally, without Jenkins, The Google Cloud SDk is found under:
>
> /Users/marioyoussef/Desktop/google-cloud-sdk
>
>
>
And it works perfect, but I have no idea how to load it to jenkins when executing ./gradlew appengineDeploy.<issue_comment>username_1: Adding the following to the module's `build.gradle` might help:
```
appengine.tools.cloudSdkHome="/Users/marioyoussef/Desktop/google-cloud-sdk"
```
See <https://cloud.google.com/appengine/docs/flexible/java/gradle-reference#global_properties>:
>
> Optional property to configure the location of the Google Cloud SDK. Typically the plugin finds this in the Cloud SDK when it is installed with **gcloud components install app-engine-java**.
>
>
>
Upvotes: 3 <issue_comment>username_2: There are two ways to tackle the issue.
1. Add a symlink/shortcut for Google Cloud SDK
The cloud plugin in IDE searches for SDK in some custom locations such as `$HOME/google-cloud-sdk`. So you can add a symlink in this directory and point it to actual installed location.
In your case a shortcut in `/Users/marioyoussef` named **`google-cloud-sdk`** and point it to `/Users/marioyoussef/Desktop/google-cloud-sdk`
2. Add a cloudSdkHome property in **build.gradle**, but this can be troublesome if you share it with others as the might have it on a different location. For that, you can just mention it in README for others to change it.
Just add this line in app's build.gradle
`appengine.tools.cloudSdkHome="/Users/marioyoussef/Desktop/google-cloud-sdk"`
Source: [GitHub Issues](https://github.com/GoogleCloudPlatform/appengine-plugins-core/issues/416#issuecomment-350181571)
Upvotes: 3 <issue_comment>username_3: The cloud tries to find the Google Cloud sdk in a set of predefined directories. If it does not find it, it throws an error.
What helped me was this:
**Adding a shortcut to the home directory solved my problem.**
Upvotes: 0
|
2018/03/15
| 372 | 1,147 |
<issue_start>username_0: Below is example code:
```
List1 = [['a'], ['b'], ['c']]
range_value = len(List1) * 2
for x in range(0, range_value):
if x == 0 or x == 1:
for y in List1[1]:
print y
if x == 2 or x == 3:
for y in List1[2]
if x == 4 or x == 5:
for y in List1[2]
```
This is manual steps defineing if statement in case I have big values like 100 or 1000. Its difficult, Please help me with any logic for this. first two values should use List[1] and next two values List[2] and so on.<issue_comment>username_1: I think you're looking for:
```
for y in List1[x//2]
```
It's a bit hard to tell, since you started at index 1 instead of index 0, but apparently want to use every element of the list. You may need `[x//2 + 1]`.
Another possible enhancement is to double-step your outer loop:
```
for x in range(0, range_value, 2):
```
Upvotes: 0 <issue_comment>username_2: Use a third loop:
```
for x in List1:
for _ in [0,1]:
for y in x:
...
```
This iterates over each element of `List1` twice, as in the original code, without explicit index wrangling.
Upvotes: 1
|
2018/03/15
| 2,413 | 8,438 |
<issue_start>username_0: In angular 5 I am getting the images for hotelgallery from mongodb through my service. So basically the data what I am getting is like this
```
{
fieldname: "hotelgallery",
originalname: "e.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/",
encoding : "7bit",
filename : "1521139307413.jpg"
mimetype : "image/jpeg"
path : "public/1521139307413.jpg"
size : 66474
}
{
fieldname: "hotelgallery",
originalname: "e.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/",
encoding : "7bit",
filename : "1521139307413.jpg"
mimetype : "image/jpeg"
path : "public/1521139307413.jpg"
size : 66474
}
{
fieldname: "hotelgallery",
originalname: "j.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/",
encoding : "7bit",
filename : "1526753678390.jpg"
mimetype : "image/jpeg"
path : "public/1526753678390.jpg"
size : 66470
}
{
fieldname: "hotelgallery",
originalname: "k.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/",
encoding : "7bit",
filename : "7865456789413.jpg"
mimetype : "image/jpeg"
path : "public/7865456789413.jpg"
size : 66300
}
```
Now I want to again append those data to FormData but its not working.
The code what I have done so far
```
export class HotelEditComponent implements OnInit {
formData = new FormData();
ngOnInit() {
this.getOneHotel(this.route.snapshot.params['id']);
}
getOneHotel(id) {
this.http.get( this.apiUrl + '/api/hotel/' + id).subscribe(data => {
this.hotel = data;
this.appendImages(data['hotelimages']); //Here I am getting the data as mentioned here
});
}
public appendImages(imagedata) {
for (var i = 0; i < imagedata.length; i++) {
console.log(imagedata[i]);
this.formData.append('hotelgallery', imagedata[i], imagedata[i]['originalname']);
}
console.log(this.formData);
}
}
```
So can someone tell me how can I append the existing image data to FormData? Any help and suggestions will be really appreciable.
**UseCase for this:**
Actually I had used formData to upload images in angular. Now in the edit page the images are showing fine. But lets say a user edits some data and upload some images or remove some images. In that case I am getting the images from the database and again trying to upload them with formdata.
I have used [this](https://aberezkin.github.io/ng2-image-upload/#/demo) module and multer for nodejs to upload images with formData.<issue_comment>username_1: >
> So can someone tell me how can I append the existing image data to FormData? Any help and suggestions will be really appreciable.
>
>
>
Actually, this approach need more add script solution. for example
**1. Get Image Blob from server**
Since you return detail object of images, not with the blob. You need have a endpoint to return as blob. (or if return as data buffer then it transform to blob you can use [BlobUtil](https://github.com/nolanlawson/blob-util))
**2. Put Blob to append form data**
You need use blob to append in param 2 no a path, see [documentation](https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#Syntax).
>
> **name**
>
>
> The name of the field whose data is contained in value.
>
>
> **value**
>
>
> The field's value. This can be a USVString or Blob (including subclasses
> such as File).
>
>
> **filename Optional**
>
>
> The filename reported to the server
> (a USVString), when a Blob or File is passed as the second parameter.
> The default filename for Blob objects is "blob". The default filename
> for File objects is the file's filename.
>
>
>
That what you need, but that is **bad practice**.
Let's say, you have 30 images to edit, then you need request blob endpoint to get those images blob to appends. But user only want to update 1 image, wasting time to request image blob, right?
For **edit** image usually we don't need append to file form ().
Just show it as thumbnail to see what image uploaded and let file form empty.
What we do usually, thumbnail that image.
When user what to change, user put new image and replace old image with new want and update database.
if not, do nothing for image. ([YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it))
Upvotes: 2 <issue_comment>username_2: FormData's append is silently failing here. You need to attach the 'image' as a blob. See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/FormData/append).
```
formData.append('hotelgallery', new Blob([imagedata[i]], { type: "text/xml"}), imagedata[i]['originalname']);
```
Also, just printing formData won't show anything, instead try:
```
console.log(this.formData.getAll('hotelgallery'));
```
or
```
for (var value of this.formData.values()) {
console.log(value);
}
```
Upvotes: 0 <issue_comment>username_3: >
> But lets say a user edits some data and upload some images or remove
> some images. In that case I am getting the images from the database
> and again trying to upload them with formdata.
>
>
>
So, you can pass object to universal method and on result get `formData`. Object data even can contain nested objects.
```
static createFormData(object: Object, form?: FormData, namespace?: string): FormData {
const formData = form || new FormData();
for (let property in object) {
if (!object.hasOwnProperty(property) || object[property] === undefined) {
continue;
}
const formKey = namespace ? `${namespace}[${property}]` : property;
if (object[property] instanceof Date) {
formData.append(formKey, object[property].toISOString());
} else if (typeof object[property] === 'object' && !(object[property] instanceof File)) {
this.createFormData(object[property], formData, formKey);
}
else if (typeof object[property] === 'number') {
let numberStr = object[property].toString().replace('.', ',');
formData.append(formKey, numberStr);
}
else {
formData.append(formKey, object[property]);
}
}
return formData;
}
}
```
**In Component class:**
```
export class HotelEditComponent implements OnInit {
formData = new FormData();
hotel: any;
...
ngOnInit() {
this.getOneHotel(this.route.snapshot.params['id']);
}
getOneHotel(id) {
this.http.get( this.apiUrl + '/api/hotel/' + id).subscribe(data => {
this.hotel = data;
});
}
postToServer() {
// or even can pass full `this.hotel` object
// this.helperService.createFormData(this.hotel)
this.formData = this.helperService.createFormData(this.hotel['hotelimages'])
this.service.post(this.formData);
}
...
}
```
Upvotes: 0 <issue_comment>username_4: It looks like you are trying to append a JSON array, since formData.append can only accept a string or blob, try the JSON.stringify() method to convert your array into a JSON string. (untested)
e.g. I think you can replace
```
this.appendImages(data['hotelimages']);
```
with
```
this.formData.append('hotelgallery', JSON.stringify(data['hotelimages']));
```
Upvotes: 0 <issue_comment>username_5: This is more of a design issue right now, rather then a tech problem. You are asking about posting FormData again and you want to fetch the images data again for that.
Now let's look at your current design.
1. User uploads 3 images of 4MB size each
2. On your edit page you downloads each of these images. Cost=12MB
3. On the edit page user deletes 2 images and adds 2 images. Cost=12MB
4. So final cost of updating 2 images of 8MB is 24MB. Which is a lot
Now before figuring out how to do FormData, figure out the right design for your app.
Consider the `OLX` site which allows you to post ads and later edit them. When you edit and remove a image, they call a API for removing the image
[](https://i.stack.imgur.com/ODdtG.png)
The ideal design in my opinion would be below
* Submit all images in your create
* For edit create a add and remove endpoint for the image
Submitting text data again on a edit form is ok, but submitting the same images data again on a edit form is never ok. Reconsider your design
Upvotes: 0
|
2018/03/15
| 1,104 | 3,841 |
<issue_start>username_0: I'm attempting to learn Typescript and thought I should also make my webpack config in `.ts`. This is my `webpack.config.ts`:
```
import * as webpack from 'webpack';
import * as path from 'path';
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
export default config;
```
As well as my `package.json`:
```
"main": "index.js",
"scripts": {
"prebuild": "rimraf dist",
"build": "webpack --config devtools/webpack.config.ts --display-error-details",
"post-build": "webpack-dev-server --config devtools/webpack.config.ts --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^4.0.1",
"ts-node": "^5.0.1",
"typescript": "^2.7.2",
"webpack": "^4.1.1",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
}
}
```
The error I get when running npm run build is:
```
TS2307: Cannot find module 'path'
```
I have also tried requiring path, but then I get a different error saying it cant find module require.
What seems to be the issue?<issue_comment>username_1: Try using `require` syntax rather than `import` & change `webpack.config.ts` to the following code
webpack.config.ts
=================
```
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
```
And then run `npm run build`
Upvotes: -1 <issue_comment>username_2: First of all no need of `.ts` extension for webpack config file. Its just internal purpose for building the bundle. Use normal `.js` file.
Webpack is not ran by browser, its by `Node Js` which runs webpack module and make bundle as per config.
Now `Node Js` understand its own module system is which is `require`
So it would be like below: **require** in below is Node Js module importing syntax.
```
const webpack = require('webpack');
const path = require('path');
```
Upvotes: -1 <issue_comment>username_3: TypeScript needs typings for *any* module, except if that module is not written in TypeScript.
```bash
npm i @types/node -D
```
You may also need to add `"types": [ "node" ]` in your `tsconfig.json`.
Upvotes: 7 <issue_comment>username_4: Using
```
"types": ["node"]
```
in `tsconfig.json` as mentioned in the comments, solved the issue for me.
Upvotes: 3 <issue_comment>username_5: I had to do all this
1. [VS Code][Terminal] upgrade typescript: `npm i typescript/@latest -g`
2. [VS Code][Terminal] install node types: `npm i @types/node --save-dev`
3. [VS Code][tsconfig.json] add types: `"compilerOptions": {types:["node"]}`
4. [VS Code][Explorer] delete package-lock.json and node\_modules
5. [VS Code][Terminal] install: `npm install`
6. [VS Code] Restart VS Code
7. [VS Code][Terminal] test: `tsc`
Upvotes: 0 <issue_comment>username_6: In my case, I'm using a TypeScript monorepo and none of the solutions here worked for me. Adding `"typeRoots": ["../node_modules/@types"]` to the `compilerOptions` of the `tsconfig.json` file within a specific project worked for me. The IDE now also recognizes the type of `__dirname`
Upvotes: 0
|
2018/03/15
| 808 | 3,022 |
<issue_start>username_0: I have a number of microservices which needs a retry mechanism if connection with database fails.
This retry mechanism has to be triggered when SQLException and HibernateException occurs.
Passing a proper interceptor in @**Retryable** will work but this has to be incorporated in all the microservices.
Can we make a custom annotation similar to @**Retryable** like @**DatabaseRetryable** which will trigger retry on SQLException and HibernateException.
Usage of this annotation would be roughly as following
```
@DatabaseRetryable
void executeQuery()
{
//some code
}
```<issue_comment>username_1: Try using `require` syntax rather than `import` & change `webpack.config.ts` to the following code
webpack.config.ts
=================
```
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
```
And then run `npm run build`
Upvotes: -1 <issue_comment>username_2: First of all no need of `.ts` extension for webpack config file. Its just internal purpose for building the bundle. Use normal `.js` file.
Webpack is not ran by browser, its by `Node Js` which runs webpack module and make bundle as per config.
Now `Node Js` understand its own module system is which is `require`
So it would be like below: **require** in below is Node Js module importing syntax.
```
const webpack = require('webpack');
const path = require('path');
```
Upvotes: -1 <issue_comment>username_3: TypeScript needs typings for *any* module, except if that module is not written in TypeScript.
```bash
npm i @types/node -D
```
You may also need to add `"types": [ "node" ]` in your `tsconfig.json`.
Upvotes: 7 <issue_comment>username_4: Using
```
"types": ["node"]
```
in `tsconfig.json` as mentioned in the comments, solved the issue for me.
Upvotes: 3 <issue_comment>username_5: I had to do all this
1. [VS Code][Terminal] upgrade typescript: `npm i typescript/@latest -g`
2. [VS Code][Terminal] install node types: `npm i @types/node --save-dev`
3. [VS Code][tsconfig.json] add types: `"compilerOptions": {types:["node"]}`
4. [VS Code][Explorer] delete package-lock.json and node\_modules
5. [VS Code][Terminal] install: `npm install`
6. [VS Code] Restart VS Code
7. [VS Code][Terminal] test: `tsc`
Upvotes: 0 <issue_comment>username_6: In my case, I'm using a TypeScript monorepo and none of the solutions here worked for me. Adding `"typeRoots": ["../node_modules/@types"]` to the `compilerOptions` of the `tsconfig.json` file within a specific project worked for me. The IDE now also recognizes the type of `__dirname`
Upvotes: 0
|
2018/03/15
| 894 | 3,259 |
<issue_start>username_0: Disclaimer: I am not a tech guy, and my chosen profession is law. I know just enough to help my company create forms that can be filled out by using macros in Word.
I have gotten as far as completing the code and have it all working properly. However, I have realized that not all `TextBox`es will be filled out every single time. I want the unused `TextBox` to appear blank in the Word doc instead of having the place holders. Example of the code and issue is below.
```
If TextBox1.Value <> "" Then _
ActiveDocument.Range.Find.Execute _
FindText:="", ReplaceWith:=UCase(TextBox1.Value), Replace:=wdReplaceAll
```
Currently, if I do not fill out textbox 1, it will leave the place holder as on the Word doc. I want it to be just blank.
What do I need to add to make this work?
Does that make sense?<issue_comment>username_1: Try using `require` syntax rather than `import` & change `webpack.config.ts` to the following code
webpack.config.ts
=================
```
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
```
And then run `npm run build`
Upvotes: -1 <issue_comment>username_2: First of all no need of `.ts` extension for webpack config file. Its just internal purpose for building the bundle. Use normal `.js` file.
Webpack is not ran by browser, its by `Node Js` which runs webpack module and make bundle as per config.
Now `Node Js` understand its own module system is which is `require`
So it would be like below: **require** in below is Node Js module importing syntax.
```
const webpack = require('webpack');
const path = require('path');
```
Upvotes: -1 <issue_comment>username_3: TypeScript needs typings for *any* module, except if that module is not written in TypeScript.
```bash
npm i @types/node -D
```
You may also need to add `"types": [ "node" ]` in your `tsconfig.json`.
Upvotes: 7 <issue_comment>username_4: Using
```
"types": ["node"]
```
in `tsconfig.json` as mentioned in the comments, solved the issue for me.
Upvotes: 3 <issue_comment>username_5: I had to do all this
1. [VS Code][Terminal] upgrade typescript: `npm i typescript/@latest -g`
2. [VS Code][Terminal] install node types: `npm i @types/node --save-dev`
3. [VS Code][tsconfig.json] add types: `"compilerOptions": {types:["node"]}`
4. [VS Code][Explorer] delete package-lock.json and node\_modules
5. [VS Code][Terminal] install: `npm install`
6. [VS Code] Restart VS Code
7. [VS Code][Terminal] test: `tsc`
Upvotes: 0 <issue_comment>username_6: In my case, I'm using a TypeScript monorepo and none of the solutions here worked for me. Adding `"typeRoots": ["../node_modules/@types"]` to the `compilerOptions` of the `tsconfig.json` file within a specific project worked for me. The IDE now also recognizes the type of `__dirname`
Upvotes: 0
|
2018/03/15
| 754 | 2,709 |
<issue_start>username_0: Is it possible to create a custom assert based on a boolean value?
Something like this:
```
setUp(scn.inject(rampUsers(7) over (1 minutes))).protocols(httpProtocol).
assertions(
assert(/*method that returns boolean value*/),
/*other assertions*/
)
```
Thanks!<issue_comment>username_1: Try using `require` syntax rather than `import` & change `webpack.config.ts` to the following code
webpack.config.ts
=================
```
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
```
And then run `npm run build`
Upvotes: -1 <issue_comment>username_2: First of all no need of `.ts` extension for webpack config file. Its just internal purpose for building the bundle. Use normal `.js` file.
Webpack is not ran by browser, its by `Node Js` which runs webpack module and make bundle as per config.
Now `Node Js` understand its own module system is which is `require`
So it would be like below: **require** in below is Node Js module importing syntax.
```
const webpack = require('webpack');
const path = require('path');
```
Upvotes: -1 <issue_comment>username_3: TypeScript needs typings for *any* module, except if that module is not written in TypeScript.
```bash
npm i @types/node -D
```
You may also need to add `"types": [ "node" ]` in your `tsconfig.json`.
Upvotes: 7 <issue_comment>username_4: Using
```
"types": ["node"]
```
in `tsconfig.json` as mentioned in the comments, solved the issue for me.
Upvotes: 3 <issue_comment>username_5: I had to do all this
1. [VS Code][Terminal] upgrade typescript: `npm i typescript/@latest -g`
2. [VS Code][Terminal] install node types: `npm i @types/node --save-dev`
3. [VS Code][tsconfig.json] add types: `"compilerOptions": {types:["node"]}`
4. [VS Code][Explorer] delete package-lock.json and node\_modules
5. [VS Code][Terminal] install: `npm install`
6. [VS Code] Restart VS Code
7. [VS Code][Terminal] test: `tsc`
Upvotes: 0 <issue_comment>username_6: In my case, I'm using a TypeScript monorepo and none of the solutions here worked for me. Adding `"typeRoots": ["../node_modules/@types"]` to the `compilerOptions` of the `tsconfig.json` file within a specific project worked for me. The IDE now also recognizes the type of `__dirname`
Upvotes: 0
|
2018/03/15
| 483 | 1,981 |
<issue_start>username_0: I've already install pandas from either the terminal and add `pandas` in pycharm project interpreter. However, every time I run a program which uses `pandas` it keeps reminding me there's an error.
```
RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa
Traceback (most recent call last):
File "/Users/Rabbit/PycharmProjects/NLP/review2vector.py", line 7, in
from pandas import DataFrame
File "/Users/Rabbit/Library/Python/2.7/lib/python/site-packages/pandas/\_\_init\_\_.py", line 35, in
"the C extensions first.".format(module))
ImportError: C extension: numpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build\_ext --inplace --force' to build the C extensions first.
```
I also followed this question's answer [How to solve import error for pandas?](https://stackoverflow.com/questions/30761152/how-to-solve-import-error-for-pandas) But it does not work for me.<issue_comment>username_1: These issues can be easily avoided if you use a virtual environment to install and maintain your Python packages. Please refer to the link here for more information: [LINK](http://docs.python-guide.org/en/latest/dev/virtualenvs/)
Upvotes: 2 <issue_comment>username_2: The error message is telling you that numpy is not fully installed. There isn't enough information there to guess specifically what is wrong, but if I was troubleshooting I would use my package manager (pip probably) to uninstall and then re-install numpy and pandas. I would do numpy separately so that I could watch the messages. The numpy page says that they should have pre-compiled wheels available, so it just seems like a version mismatch.
Pycharm lets you install packages into a virtualenv easily and ensure that env is always activated when you open the pycharm terminal (great!) but it also makes it very hard to notice install errors.
Upvotes: 1
|
2018/03/15
| 454 | 1,968 |
<issue_start>username_0: I am using SharePoint Search API and referring link [SharePoint Search REST API overview](https://learn.microsoft.com/en-us/sharepoint/dev/general-development/sharepoint-search-rest-api-overview). I want to use property operators. Please refer 'Property operators that are supported in property restrictions' section in link [Keyword Query Language (KQL) syntax reference](https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference)
I am forming query as `http://server/_api/search/query?querytext='AmountCurrency > 10.50'&selectproperties='Title,Author'`
Similarly `http://server/_api/search/query?querytext='AmountNumber < 20.50'&selectproperties='Title,Author'`
In above queries AmountCurrency and AmountNumber are managed properties for Currency column and Number column respectively. But search api not returing any row. For me : and = operators are working fine. How to use greater than and less than operators in search API?<issue_comment>username_1: These issues can be easily avoided if you use a virtual environment to install and maintain your Python packages. Please refer to the link here for more information: [LINK](http://docs.python-guide.org/en/latest/dev/virtualenvs/)
Upvotes: 2 <issue_comment>username_2: The error message is telling you that numpy is not fully installed. There isn't enough information there to guess specifically what is wrong, but if I was troubleshooting I would use my package manager (pip probably) to uninstall and then re-install numpy and pandas. I would do numpy separately so that I could watch the messages. The numpy page says that they should have pre-compiled wheels available, so it just seems like a version mismatch.
Pycharm lets you install packages into a virtualenv easily and ensure that env is always activated when you open the pycharm terminal (great!) but it also makes it very hard to notice install errors.
Upvotes: 1
|
2018/03/15
| 1,302 | 3,581 |
<issue_start>username_0: Hi I am trying to calculate the average of previous 4 Tuesdays. I have daily sales data and I am trying to calculate what the average for previous 4 weeks were for the same weekday.
Attached is a snapshot of how my dataset looks like

Now for March 6, I would like to know what is the average for the previous 4 weeks were, (namely Feb 6, Feb 13, Feb 20 and Feb 27). This value needs to be assigned to Monthly Average column
I am using a PostGres DB.
Thanks<issue_comment>username_1: You can use window functions:
```
select t.*,
avg(dailycount) over (partition by seller_name, day
order by date
rows between 3 preceding and current row
) as avg_4_weeks
from t
where day = 'Tuesday';
```
This assumes that "previous 4 weeks" is the current date plus the previous three weeks. If it starts the week before, only the windowing clause needs to change:
```
select t.*,
avg(dailycount) over (partition by seller_name, day
order by date
rows between 4 preceding and 1 preceding
) as avg_4_weeks
from t
where day = 'Tuesday';
```
Upvotes: 1 <issue_comment>username_2: I decided to post my answer also, for anyone else searching. My answer will allow you to put in any date and get the average for the previous 4 weeks ( current day + previous 3 weeks matching the day).
[SQL Fiddle](http://sqlfiddle.com/#!15/4e448/1)
**PostgreSQL 9.3 Schema Setup**:
```
CREATE TABLE sales (sellerName varchar(10), dailyCount int, saleDay date) ;
INSERT INTO sales (sellerName, dailyCount, saleDay)
SELECT 'ABC',10,to_date('2018-03-15','YYYY-MM-DD') UNION ALL /* THIS ONE */
SELECT 'ABC',11,to_date('2018-03-14','YYYY-MM-DD') UNION ALL
SELECT 'ABC',12,to_date('2018-03-12','YYYY-MM-DD') UNION ALL
SELECT 'ABC',13,to_date('2018-03-11','YYYY-MM-DD') UNION ALL
SELECT 'ABC',14,to_date('2018-03-10','YYYY-MM-DD') UNION ALL
SELECT 'ABC',15,to_date('2018-03-09','YYYY-MM-DD') UNION ALL
SELECT 'ABC',16,to_date('2018-03-08','YYYY-MM-DD') UNION ALL /* THIS ONE */
SELECT 'ABC',17,to_date('2018-03-07','YYYY-MM-DD') UNION ALL
SELECT 'ABC',18,to_date('2018-03-06','YYYY-MM-DD') UNION ALL
SELECT 'ABC',19,to_date('2018-03-05','YYYY-MM-DD') UNION ALL
SELECT 'ABC',20,to_date('2018-03-04','YYYY-MM-DD') UNION ALL
SELECT 'ABC',21,to_date('2018-03-03','YYYY-MM-DD') UNION ALL
SELECT 'ABC',22,to_date('2018-03-02','YYYY-MM-DD') UNION ALL
SELECT 'ABC',23,to_date('2018-03-01','YYYY-MM-DD') UNION ALL /* THIS ONE */
SELECT 'ABC',24,to_date('2018-02-28','YYYY-MM-DD') UNION ALL
SELECT 'ABC',25,to_date('2018-02-22','YYYY-MM-DD') UNION ALL /* THIS ONE */
SELECT 'ABC',26,to_date('2018-02-15','YYYY-MM-DD') UNION ALL
SELECT 'ABC',27,to_date('2018-02-08','YYYY-MM-DD') UNION ALL
SELECT 'ABC',28,to_date('2018-02-01','YYYY-MM-DD')
;
```
**Now For The Query**:
```
WITH theDay AS (
SELECT to_date('2018-03-15','YYYY-MM-DD') AS inDate
)
SELECT AVG(dailyCount) AS totalCount /* 18.5 = (10(3/15)+16(3/8)+23(3/1)+25(2/22))/4 */
FROM sales
CROSS JOIN theDay
WHERE extract(dow from saleDay) = extract(dow from theDay.inDate)
AND saleDay <= theDay.inDate
AND saleDay >= theDay.inDate-INTERVAL '3 weeks' /* Since we want to include the entered
day, for the INTERVAL we need 1 less week than we want */
```
**[Results](http://sqlfiddle.com/#!15/4e448/1/0)**:
```
| totalcount |
|------------|
| 18.5 |
```
Upvotes: 0
|
2018/03/15
| 1,283 | 5,309 |
<issue_start>username_0: I'm creating an application which's architecture is *based* on [Uncle Bob's Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) concepts and [DDD](https://dddcommunity.org/book/evans_2003/). Note that it is *BASED* on DDD, so I gave myself the freedom to differ from strict DDD.
To create this application, I am using C# with .Net Standard 2.0
One of the principles of DDD relates to Value Objects. The definition for Value Objects, according to [Wikipedia](https://en.wikipedia.org/wiki/Domain-driven_design) is as follows:
>
> Value Object
>
>
> An object that contains attributes but has no conceptual identity. They should be treated as immutable.
>
>
> Example: When people exchange business cards, they generally do not distinguish between each unique card; they only are concerned about the information printed on the card. In this context, business cards are value object
>
>
>
Now, I want that my Value Objects does not allow their creation if some validation does not succeed. When it happens, an exception would be thrown during the instantiation. I really meant to throw an exception there, because the core of the architecture really does not expect any invalid data to reach that point.
Before going further on this question, to give you guys some more background, [here](https://web.archive.org/web/20180627192447/https://github.com/andremarcondesteixeira/A-Clean-Architecture-Proposal) is my architecture (NOTE: still incomplete):
[](https://i.stack.imgur.com/571Bn.png)
The rules I am following in this architecture is:
1. A layer can only know about its immediate innermost neighbor layer's interfaces
2. A layer cannot know anything about any outermost layer
3. All communications between layers MUST be done through interfaces
4. Each layer must be independently deployable
5. Each layer must be independently developable
To better understand the arrows in this diagram, I recommend reading those Stack Exchanges's questions:
[Explanation of the UML arrows](https://stackoverflow.com/questions/1874049/explanation-of-the-uml-arrows)
<https://softwareengineering.stackexchange.com/questions/61376/aggregation-vs-composition>
Now, the challenge I'm facing right now, is finding a good way to use the validators. I'm not satisfied with my architecture in this point. The problem is the following:
Since I can have thousands of Value Objects being instantiated at a given time, I don't want each instance of the Value Objects to have an instance method to perform the validation. I want the validation method to be static, since it's logic will be the same for every instance. Also, I want the validation logic to be available for the upper layer of the architecture to use to perform validations without trying to instantiating the Value Objects, thus causing an expensive exception to be thrown.
The problem is: C# *DOES NOT ALLOW* polymorphism with static methods, so I can't do something like:
```
internal interface IValueObject
{
T Value { get; }
static bool IsValid(T value);
}
```
How can I achieve this functionality without relying on static methods polymorphism and, at the same time, not wasting memory?<issue_comment>username_1: It's a good thing that you can think abstractly but you should generalize after you write some working code.
A general clean on-size-fit-all architecture DDD is a Mith. In fact DDD applies only to the Domain layer. That's the beauty of it, it's technology agnostic.
In my projects I don't even have a base class or an interface for Value objects, Entities or Aggregate roots. I don't need them. All the these building blocks are POPO (PHP).
In my opinion, a Clean architecture is the one that keeps the Domain layer technology agnostic, without dependencies to any external frameworks. The other layers could be almost anything.
Upvotes: 2 <issue_comment>username_2: I suggest you get rid of `IsValid()` and make your Value Objects self-checking, [always valid](http://codebetter.com/gregyoung/2009/05/22/always-valid/) objects. Making them immutable is recommended and will obviously help a lot in that regard. You only have to check the invariants once during creation.
**[Edit]**
You might need to treat that as a first pass of input validation instead of value object invariant enforcement. If there's a huge amount of unsafe data coming in that you want to turn into value objects, first handle it in a validation process in the outer layer - you can make all performance optimizations you need, implement error logic and coordinate VO creation there.
Upvotes: 1 [selected_answer]<issue_comment>username_3: In clean architecture all business logic goes into use case interactors. Validation rules are part of the business logic so should go into use case interactors as well.
In ur case I would suggest to put ur validation in interactors which take a "request model", validate the "parameters" and then return the respective value object(s) as (part of the) response model.
This way the validation logic is in the right layer and value objects are only created when validation succeeds - so no invalid value objects are created and no performance is wasted.
Upvotes: 0
|
2018/03/15
| 730 | 2,537 |
<issue_start>username_0: I want to merge/combine 2 arrays based on the same key/value pair.
To be more clear, what I'm searching for is kind of a join function known in MySQL. The first array should be "joined" by the second one, based on the ID, which is the key/value pair 'name'.
How can I do this?
**1. ARRAY**
```
[0] => Array
(
[name] => first
[logo] => url
[cat] => abc
)
[1] => Array
(
[name] => second
[logo] => url
[cat] => abc
)
```
**2. ARRAY**
```
[0] => Array
(
[name] => first
[menu] => true
[key] => value
)
```
**NEW ARRAY (Expexted Result):**
```
[0] => Array
(
[name] => first
[logo] => url
[cat] => abc
[menu] => true
[key] => value
)
```
As you an see, it's quite self-explaining. In this case, the 'name' key is like an ID (for both arrays).<issue_comment>username_1: If you reindex your second array by name first, it will be easier to get those values from it.
```
$second = array_column($second, null, 'name');
```
(It's okay to do this if 'name' is unique in the array. I assume that's the case since you said it's "like an ID". If 'name' isn't unique then you'll lose some rows when you reindex, because array keys have to be unique.)
Then iterate your first array and merge any corresponding values in the second array into the result.
```
foreach ($first as $key => $value) {
if (isset($second[$value['name']])) {
$result[$key] = array_merge($value, $second[$value['name']]);
}
}
```
This would be like an inner join in SQL, where the result would only include rows where the value exists in both tables. If you wanted it to work more like a left join, then you'd need to merge a set of empty values for the keys in the second array if a matching name value wasn't found there.
```
foreach ($first as $key => $value) {
if (isset($second[$value['name']])) {
$result[$key] = array_merge($value, $second[$value['name']]);
} else {
$result[$key] = array_merge($value, ['menu' => null, 'key' => null]);
}
}
```
[Working example at 3v4l.org.](https://3v4l.org/BImoP)
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this
```
$mergedArray = array_merge_recursive ($firstArray,$secondArray);
$newArray = [];
foreach( $mergedArray as $subArr ) {
$newArray = array_merge($subArr,$newArray);
}
```
Upvotes: 0
|
2018/03/15
| 489 | 1,598 |
<issue_start>username_0: I'm trying to use flex to align buttons on the same line : the button "Back" should be at the left and the button "Continue" at the right (end of the line).
```css
.footer {
display: flex;
}
.back {
align-content: flex-start;
}
.continue {
align-content: flex-end;
}
```
```html
Back
Continue
```
But this is not working, what I am missing ?<issue_comment>username_1: You can use [`justify-content: space-between;`](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) on the flex container to generate the desired layout:
```css
.footer {
display: flex;
justify-content: space-between;
}
.back {
}
.continue {
}
```
```html
Back
Continue
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: The `align-content` property, as well as `align-items` and `align-self`, position flex items along the *cross axis* of the flex container.
With `flex-direction: row` (the default setting in CSS), the cross axis is vertical. So in your code you're attempting to pin the items to the top and the bottom, not the left and right. (Note that the `flex-direction` default in React Native is `column`.)
For *main axis* alignment use the `justify-content` property.
More details here:
* [In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?](https://stackoverflow.com/q/32551291/3597276)
Upvotes: 2 <issue_comment>username_3: Use float to align buttons.
**HTML**
```
Back
Continue
```
**CSS**
```
.back {
float: left;
}
.continue {
float: right;
}
```
Upvotes: 2
|
2018/03/15
| 596 | 1,979 |
<issue_start>username_0: I'm trying to figure out how to add text boxes after hitting the "submit" button. I've tried everything I know, but I can't seem to get an outcome. I also want to make the max number of text boxes 25.
Here's some of the HTML:
```
Calculated Test Scores
======================
##### # of Students:
Submit
##### Scores:
Calculate
###### The average is:
```
And this is the JS:
```
$(function() {
$(".submit").click(function() {
for(var i=0; i < 26; i++)
$(".submit").append(arr[i])
});
$(".calculate").click(function() {
for(var i=0; i < arr.length; i++)
sum=sum + arr[i];
Average = sum/arr.length;
});
});
```<issue_comment>username_1: I am not sure what is arr but I simply added several inputs i.e. 25 into that. Here is
[jsfiddle](https://jsfiddle.net/8gv481L4/4/)
```
var arr = ['', '', '', '', '', '', '', '', '', '','','','','','','','','','','','','','','',''];
$(".submit").click(function() {
for(var i=0; i < 26; i++) {
$(".inputs").append(arr[i]);
}
});
$(".calculate").click(function() {
for(var i=0; i < arr.length; i++)
sum=sum + arr[i];
Average = sum/arr.length;
});
```
Let me know if this is something you are looking for.
Upvotes: 1 <issue_comment>username_2: Please see the working prototype (markup slightly modified):
```js
$(".submit").click(function() {
var newContent = "";
for (var i = 0; i < $("#scount").val(); i++)
newContent += "";
$(".dynamic_inputs").html(newContent);
});
$(".calculate").click(function() {
var sum = 0;
$(".dynamic_inputs input").each(function() {
sum = sum + parseInt($(this).val());
});
var avg = sum / $(".dynamic_inputs input").length;
$("h6").text("The average is: " + avg);
});
```
```html
Calculated Test Scores
======================
##### # of Students:
Submit
##### Scores:
---
Calculate
###### The average is:
```
Upvotes: 0
|
2018/03/15
| 1,564 | 6,440 |
<issue_start>username_0: ### What I want
I want my library to work with a range of versions of a NuGet package with breaking changes in API between the changes. I haven't investigated it further, but this path looks promising:
* Reference all versions of the library with different APIs by specifying [extern namespace aliases](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias).
* Create proxies for the needed classes, with flags/exceptions/whatever to tell what's actually supported.
* Choose the correct proxy at runtime depending on what version is actually loaded into the application.
* Code which depends on non-existent API won't be called, so everything should work fine.
While this may seem complicated, it has many benefits over a more straightforward approach of supporting every version in a separate assembly:
* Version of my library won't become a mess like 1.2.3-for-2.3.4-to-2.6.8. I don't even know how versioning is supposed to work in this case.
* NuGet users won't have to choose between several packages, one package fits all.
* Upgrading versions would be straightforward, won't require removing and adding my package.
### Problem
However, it's unclear whether it's possible at all. Even before getting to proxies and detecting current version, I'm stuck with the basics.
I can't even add multiple `PackageReference` nodes to my .csproj, only one reference actually works. There's a [workaround for adding extern aliases](https://github.com/NuGet/Home/issues/4989) which aren't supported by NuGet directly, but I can't get to that point because I can't get two references. And if I somehow get two, I won't be able to tell them apart.
### Questions
1. Can support for multiple versions be implemented this way, using extern namespace aliases and proxies?
2. If yes, how to add references to multiple versions of a NuGet package and use them in code?
3. If not, what is the correct approach then?
### Background
I'm working on CsConsoleFormat library for formatting Console output. I want to support all relevant versions of popular command-line packages directly, so that pretty command line help and stuff like this could be added with almost no coding, no matter what command line parsing library is used.
I guess declaring "I support only the latest version" is somewhat acceptable in my case, but I'd rather have wider support even if it's more complicated. Ideally, **I want a NuGet package which declares dependency on the lowest supported version, but supports everything up to the latest version**.
### Progress so far
I kinda got it to work, but with many issues. See [issue on GitHub NuGet Home](https://github.com/NuGet/Home/issues/6693) for more details.<issue_comment>username_1: NuGet only resolves single package versions.
If you declare a dependency on the minimum supported version, any referencing project can upgrade the dependency to a newer version.
As long as the authors of the dependent package don't introduce breaking changes, it should work find.
Even if you use reflection to look at the actual assembly versions used, you will find that many package authors don't change the assembly version between releases. This is to avoid the need for binding redirects in classic .NET Framework projects as all versions are the same and NuGet will select the right DLL based on the resolved package version of the consuming project. Again, this is good for as long as there are no breaking changes.
A pattern you could use to support different packages is to provide many "platform" packages that the consumer can choose from. The platform-specific package would then reference a common package with shareable logic.
The "platform" would then be e.g. "MyLogic.XUnit" or "MyLogic.NUnit" (assuming test helpers as example) referencing "MyLogic.Common"
Upvotes: 2 <issue_comment>username_2: This is not a complete answer but I noticed on your [GitHub issue page](https://github.com/NuGet/Home/issues/6693) that you are referencing both .NET Standard and .NET Framework libraries in your project. This is known to NOT work correctly.
Quoting .NET Standard team's [announcement](https://github.com/dotnet/standard/issues/481),
>
> .. Another symptom is warnings at build time regarding assembly versions ..
>
>
>
which may be what you are running into.
Upvotes: -1 <issue_comment>username_3: If you insist on extern aliases - you can add multiple version references directly, as dll file, not as nuget package.
Suppose I want to take a dependency on Newtonsoft.Json package version 10.0.3+.
However if user has version 11 installed - I want to use generic `JsonConverter` class available only in this version (11). Then my csproj might look like this:
```
netstandard2.0
1.0.4
Newtonsoft.Json.v11.dll
js11
true
```
Then I have proxy interface:
```
public interface ISerializer {
string Serialize(T obj);
}
```
And two implementations, v10 (uses global, non-aliased namespace):
```
using System;
using global::Newtonsoft.Json;
namespace NugetRefMain {
internal class Js10Serializer : ISerializer
{
public string Serialize(T obj)
{
Console.WriteLine(typeof(JsonConvert));
return JsonConvert.SerializeObject(obj);
}
}
}
```
And v11
```
extern alias js11;
using System;
using js11::Newtonsoft.Json;
namespace NugetRefMain {
internal class Js11Serializer : ISerializer {
public string Serialize(T obj) {
// using JsonConverter, only available in v11
Console.WriteLine(typeof(JsonConverter));
return JsonConvert.SerializeObject(obj);
}
}
}
```
And finally factory which creates serializer depending on current available json.net version:
```
public static class Serializers {
public static ISerializer Create() {
var version = typeof(JsonConvert).Assembly.GetName().Version;
if (version.Major == 10)
return new Js10Serializer();
return new Js11Serializer();
}
}
```
Now if I pack this as nuget - it will have single dependency on `Newtonsoft.Json` version `10.0.3` and that's all. However, if user installs `Newtonsoft.Json` of version 11 - it will use capabilities available in this version.
Drawbacks:
* Visual Studio \ Resharper intellisense doesn't like this approach sometimes and shows intellisense errors when in reality everything compiles just fine.
* You might have "version conflict" warnings on compilation.
Upvotes: 4
|
2018/03/15
| 968 | 4,024 |
<issue_start>username_0: I have searched all over and no solution works. Here is how I am inserting data:
```
string value = db.StringGet("test");
string cleaned = value.Replace("u'", "'").Replace("\"", "");
var jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(cleaned);
Dictionary dict = Newtonsoft.Json.JsonConvert.DeserializeObject>(jsonDoc);
values.Add(dict);
\_collection.InsertMany(values.Select(x => x.ToBsonDocument()));
```
Here is how the data looks in the database
```
{
"_id" : ObjectId("5aaabf7ac03af44892673031"),
"_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson",
"_v" : {
"profile" : "myprofile",
"source" : "thesource",
"hostname" : "myhost",
"pgm" : "mypgm"
}
}
```
I dont want the data formatted like this in mongo. The reason my is because I have several clients accessing the db. I would rather have the data formatted like this:
```
{
"_id" : ObjectId("5aaabf7ac03af44892673031"),
"profile" : "myprofile",
"source" : "thesource",
"hostname" : "myhost",
"pgm" : "mypgm"
}
```<issue_comment>username_1: In our team we solved it by serializing and deserializing the object, making it an ExpandoObject. Try something like this:
```
JsonSerializer DynamicDataJsonSerializer;
DynamicDataJsonSerializer = JsonSerializer.Create(JsonConverterSetup.GetTransparentSerializerSettings());
MyClass dataToSaveToMogo;
var dataToSaveToMogoAsDynamic = DynamicDataJsonSerializer.Deserialize(DynamicDataJsonSerializer.Serialize(dataToSaveToMogo));
```
then save dataToSaveToMogoAsDynamic.
Hope it helps
Upvotes: 1 <issue_comment>username_2: You will need to call the Remove property of the BsonDocument class and specify "\_t" as parameter to be able to remove the "\_t" key. Same goes with "\_v"
```
MyClass item = new MyClass();
var returnDocument = new BsonDocument(item.ToBsonDocument());
returnDocument.Remove("_t");
collection.InsertOne(returnDocument);
```
Upvotes: 0 <issue_comment>username_3: This solution works 100%.
```
var bsonDocument = new BsonDocument(userActivityDoc.ToBsonDocument());
if (bsonDocument.TryGetValue("AdditionalData", out BsonValue additionalData))
{
additionalData.ToBsonDocument().Remove("_t");
}
await _genericRepository.AddOneAsync(BsonSerializer.Deserialize(bsonDocument));
```
Upvotes: 0 <issue_comment>username_3: the finally solution for remove "\_t" from all nested values:
```
if (bsonDocument.TryGetValue("AdditionalData", out var additionalData) && !additionalData.IsBsonNull)
{
RemoveAllTObject(additionalData.ToBsonDocument());
//additionalData.ToBsonDocument().Remove("_t");
}
private void RemoveAllTObject(BsonDocument bsonDocument)
{
bsonDocument.Remove("_t");
foreach (var bsonElement in bsonDocument)
{
if (!bsonElement.Value.IsBsonNull)
{
if (bsonElement.Value.GetType() == typeof(BsonArray))
{
foreach (var bsonValue in bsonElement.Value.AsBsonArray)
{
if (bsonValue.GetType() == typeof(BsonDocument))
RemoveAllTObject(bsonValue.AsBsonDocument);
}
}
if (bsonElement.Value.GetType() == typeof(BsonDocument))
{
var bDocument = bsonElement.Value.AsBsonDocument;
if (bsonDocument.IsBsonNull)
continue;
if (bDocument.ElementCount > 0)
{
RemoveAllTObject(bDocument);
}
}
}
}
}
```
Upvotes: 0
|
2018/03/15
| 298 | 1,060 |
<issue_start>username_0: I want to call a function, if a key was released, because I program a little Jump'n'Run and for that I have to know that, because if I use a "normal" handler which is called if a key is pressed, it don't works, because the handler is not called often enough.
I don't want to use jquery or something else, only native JavaScript.
Thank you in advance.<issue_comment>username_1: Checkout the snipper below. I think this is all you're looking for.
```
document.addEventListener('keyup', (event) => {
const keyName = event.key;
alert('keyup event\n\n' + 'key: ' + keyName);
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
document.addEventListener('keyup', function (){
// do something
});
```
Upvotes: 0 <issue_comment>username_3: [MDN documentation for `keyup` event](https://developer.mozilla.org/en-US/docs/Web/Events/keyup)
```js
document.getElementById('myField').addEventListener('keyup', e => {
console.log(`keyup event fired for key: ${e.key}`);
});
```
```html
Type here:
```
Upvotes: 2
|
2018/03/15
| 2,117 | 6,890 |
<issue_start>username_0: i'm trying to add an Image to the first column of every row on a treeview, but no matter what I do, always end up with the name of the object "pyimage1" showed instead of the actual image.
[As this image shows](https://i.stack.imgur.com/VrFYu.png)
The code that i'm using is something like this.
```
from tkinter import PhotoImage.
self._img = PhotoImage(file="resources\information_picto.gif")
self.tree.insert('', 'end', values= self._image,self.name, self.status, self.cores, self.turn, self.added_time)
```
I've tried with png, with the same result, I know that my image object has been correctly created, because when debugging I can see the properties of the image, but I can't make it to show on the treeview row.
**Edit:**
```
def __init__(self, master, **kw):
self.SortDir = True
f = ttk.Frame(master)
f.pack(fill=BOTH, expand=True)
self.dataCols = ('Project Name', 'Status', 'Cores', 'Turn', 'Added date/time')
self.tree = ttk.Treeview(columns=self.dataCols,
show='headings')
self.tree.column("Project Name", anchor="center")
self.tree.grid(in_=f, row=0, column=0, sticky=NSEW)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
style = ttk.Style(master)
style.configure('Treeview', rowheight=38)
self._img = PhotoImage(file="resources\information_picto.gif")
self.tree.insert('', 'end', text="#0's text", image=self._img,
value=("A's value", "B's value"))
```
I'm trying with the above code, it's pretty similar to yours, but i can't find my error, however I've watch that "text" nor "image" field appear on the row, just the list of values that i passed as "value", any thoughts?<issue_comment>username_1: You can display your image using the `image` argument in the `w.insert` method. See below.
```
from tkinter import PhotoImage.
self._img = PhotoImage(file="resources\information_picto.gif")
self.tree.insert('', 'end', text='Information_picto.gif', open=True, image=self._img,
value=(self.name, self.status, self.cores, self.turn, self.added_time))
```
**Edit:**
Here is an example script showing the basic setup of a ttk.Treeview widget and how you can include an image to the #0 column and 1st row (below heading) of the widget.
```
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk
class App(ttk.Frame):
def __init__(self, parent=None, *args, **kwargs):
ttk.Frame.__init__(self, parent)
self.parent = parent
# Create Treeview
self.tree = ttk.Treeview(self, column=('A','B'), selectmode='none', height=7)
self.tree.grid(row=0, column=0, sticky='nsew')
# Setup column heading
self.tree.heading('#0', text=' Pic directory', anchor='center')
self.tree.heading('#1', text=' A', anchor='center')
self.tree.heading('#2', text=' B', anchor='center')
# #0, #01, #02 denotes the 0, 1st, 2nd columns
# Setup column
self.tree.column('A', anchor='center', width=100)
self.tree.column('B', anchor='center', width=100)
# Insert image to #0
self._img = tk.PhotoImage(file="imagename.gif") #change to your file path
self.tree.insert('', 'end', text="#0's text", image=self._img,
value=("A's value", "B's value"))
if __name__ == '__main__':
root = tk.Tk()
root.geometry('450x180+300+300')
app = App(root)
app.grid(row=0, column=0, sticky='nsew')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()
```
[](https://i.stack.imgur.com/pRdm2.png)
**Respond to your Edit:**
See comments in the script for explanation. Also suggest you experiment the earlier script I had provided you to help you better understand how to use Treeview widget. Have fun.
```
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# tkinter modules
import tkinter as tk
import tkinter.ttk as ttk
class App(ttk.Frame):
def __init__(self, master, **kw):
self.SortDir = True
#f = ttk.Frame(master) #1. this widget is self, no need to assign to f. 2. You missed out .__init__().
ttk.Frame.__init__(self, master)
#f.pack(fill=tk.BOTH, expand=True)# redundant. done by app.grid
#self.dataCols = ('Project Name', 'Status', 'Cores', 'Turn', 'Added date/time')
#I have removed 'Project Name' since it is #0. self.dataCols is for #01, #02, .. onwards
self.dataCols = ('Status', 'Cores', 'Turn', 'Added date/time')
#self.tree = ttk.Treeview(self, columns=self.dataCols, show='headings')
# Did not define widget's parent? I have added. Picture not shown because u used option show='headings'
self.tree = ttk.Treeview(self, columns=self.dataCols)
#self.tree.column("Project Name", anchor="center")
#self.tree.grid(in_=f, row=0, column=0, sticky=tk.NSEW)
# I have removed "in_=f" since parent has been defined.
self.tree.grid(row=0, column=0, sticky=tk.NSEW)
# Setup column heading
self.tree.heading('#0', text='Project Name', anchor='center')
self.tree.heading('#1', text='Status', anchor='center')
self.tree.heading('#2', text='Cores', anchor='center')
self.tree.heading('#3', text='Turn', anchor='center')
self.tree.heading('#4', text='Added date/time', anchor='center')
#f.rowconfigure(0, weight=1) # Use with .grid but not for .pack positioning method
#f.columnconfigure(0, weight=1) # same as above
style = ttk.Style(master)
style.configure('Treeview', rowheight=38)
self._img = tk.PhotoImage(file="test50.gif")
self.tree.insert('', 'end', text="#0's text", image=self._img,
value=("A's value", "B's value"))
if __name__ == '__main__':
root = tk.Tk()
root.geometry('450x180+300+300')
app = App(root)
app.grid(row=0, column=0, sticky='nsew')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is simpler without classes if anyone needs:
```
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry('500x500')
tree = ttk.Treeview(root, column=('A','B'), selectmode='browse', height=10)
tree.grid(row=0, column=0, sticky='nsew')
tree.heading('#0', text='Pic directory', anchor='center')
tree.heading('#1', text='A', anchor='center')
tree.heading('#2', text='B', anchor='center')
tree.column('A', anchor='center', width=100)
tree.column('B', anchor='center', width=100)
img = tk.PhotoImage(file="1.png")
tree.insert('', 'end', text="#0's text", image=img, value=("Something", "Another Thing"))
root.mainloop()
```
Upvotes: 1
|
2018/03/15
| 660 | 2,131 |
<issue_start>username_0: I tried to get the latest version of CMake, as OpenSUSE is stuck to 3.5.2.
```
version=3.10
build=2
mkdir ~/temp
cd ~/temp
wget https://cmake.org/files/v$version/cmake-$version.$build.tar.gz
tar -xzvf cmake-$version.$build.tar.gz
cd cmake-$version.$build/
./bootstrap
make -j3
sudo make install
```
But something went silently wrong:
```
VM-LINUX:~/temp/cmake-3.10.2 # cmake --version
CMake Error: Could not find CMAKE_ROOT !!!
CMake has most likely not been installed correctly.
Modules directory not found in
/usr/local/share/cmake
cmake version 3.5.2
CMake suite maintained and supported by Kitware (kitware.com/cmake).
```
So I tried another way: change the version in the update repositories! And then I discovered that che CMake package is stuck at version 3.5.2 in OpenSUSE 42.3.
How can I add a repository so that I always have the latest version?
I'm a total newbie of Linux.<issue_comment>username_1: I assume you were following ["How do I install the latest version of cmake from the command line?"](https://askubuntu.com/questions/355565/how-do-i-install-the-latest-version-of-cmake-from-the-command-line).
I had the same problem and your problem/solution is to be found in the comments:
>
> When I ran this, I got an error CMake Error: Could not find `CMAKE_ROOT` !!! and it failed to update cmake. – <NAME> Dec 25 '17 at 21:47
>
>
> This is not a solution to `UPDATE` but to `INSTALL` cmake. Try this command or google it to find a solution: `sudo apt-get remove cmake cmake-data` - Teocci Dec 26 '17 at 2:18
>
>
>
Upvotes: 0 <issue_comment>username_2: ```
Opensuse has provided Tumbleweed and Leap for us. Tumbleweed always includes the newest packages.
Leap has the most stable version packages.
```
Regards
Upvotes: 0 <issue_comment>username_3: I had the same error regarding CMAKE\_ROOT when installing CMake 3.12 from [Git](https://gitlab.kitware.com/cmake/cmake). The solution for me was to run:
`sudo ln -s /usr/local/share/cmake-3.12 /usr/local/share/cmake`
as it had installed in cmake-3.12 directory instead of cmake directory for some reason.
Upvotes: 1
|
2018/03/15
| 1,135 | 3,756 |
<issue_start>username_0: How to use two regular expression variable values with match count -1 in ForEach controller.
JMeter version: 3.1
Scenario:
Questions List page>Each question has unique ID> Need to click each question on the list page and the HTTP request takes two parameters - QuestionID and Title
For this scenario I could achieve for one parameter (title) by using ForEach controller with regular expression match count set to -1.
When I have another RegExp for QuestionID with match count set to -1, how to use in the same ForEach controller since it takes only one input variable and puts that in one output variable. Below is the current test plan structure.
JMeter TestPlan structure:
The HTTP request looks like:
`POST https://test.com:xx/test`
POST BODY:
`mode=pr&questionId=454&Title=abcde`
Here I have to put/get questionId and Title variable values, each title will have unique questionId.
ThreadGroup
--Req1
--Req2
---RegEx (title): with Match No. -1 (Debug Sampler shows match count: 4)
`---RegEx (QuestionID): with MAtch No. -1 (Debug sampler shows match count: 2)
Loop Controller
---ForEach Controller (for title input variable)
----HTTP req using ForEach controller's output variable
Run the test> it is able to successfully iterate through title variable values however how to use QuestionID variable also in ForEach controller so that the HTTP request can have both RegExp variables.
Please guide.
Jmeter Version: 4.0
[](https://i.stack.imgur.com/2zVZv.png)
[](https://i.stack.imgur.com/zg87L.png)
[](https://i.stack.imgur.com/4dwtb.png)
[](https://i.stack.imgur.com/IO5NJ.png)
[](https://i.stack.imgur.com/pBxih.png)
Counter-QuesitonID-req:
[](https://i.stack.imgur.com/nAE8Z.png)<issue_comment>username_1: 1. Add [Counter](http://jmeter.apache.org/usermanual/component_reference.html#Counter) test element as a child of the ForEach Controller and configure it as follows:
* Starting value: `1`
* Increment: `1`
* Maximum value: `${QuestionID_matchNr}`
* Reference name: `counter`
[](https://i.stack.imgur.com/VQ6MA.png)
2. Refer generated value using [`__evalVar() function`](https://jmeter.apache.org/usermanual/functions.html#__evalVar) like:
```
${__evalVar(QuestionID_${counter})}
```
where required
[](https://i.stack.imgur.com/uTfWw.png)
More information: [How to Use a Counter in a JMeter Test](https://www.blazemeter.com/blog/how-use-counter-jmeter-test)
Upvotes: 1 <issue_comment>username_2: You can use inside you ForEach loop, in case for example if it's called `foreachController` using an internal index introduced in [JMeter 4.0](https://jmeter.apache.org/changes.html)
>
> ForEach Controller now expose their current iteration as a variable
> named **jm**<"Name of your element">\_\_idx
>
>
>
The problem it's started with 0, and QuestionID index start with 1,
So you need to increase value first by
1. Adding a Test action
2. Under it add User Parameters with variable name N and value which increment by 1:
```
${__intSum(${__jm__foreachController__idx},1,)}
```
3. then use `N` index to get correlate `QuestionID` variable inside loop using:
```
${__V(QuestionID_${N})}
```

Upvotes: 3 [selected_answer]
|
2018/03/15
| 890 | 2,638 |
<issue_start>username_0: For the purpose of protecting research subjects from being identifiable in data sets, I'm interested in anonymizing vectors in R. However, I also want to be able to refer to the output when writing up the research (e.g. "subject [random id] showed ..."). I've found that I can use the anonymizer package to easily generate short hashs, but while referring to short hashes in writing is doable, it is not exactly ideal (e.g. "subject f4d35fab showed ..." is difficult to remember, a bit of a mouthful, and would make it difficult to distinguish between other hashed data, e.g. "subject f4d35fab from 8b3bd334 showed ...").
Is there a way to either convert hashes into random human-readable strings or to anonymize the data in a non-crypto-centric way even?<issue_comment>username_1: What about just assigning a random number to each subject:
```
> subjects <- c("Matthew", "Mark", "Luke", "John")
> subjects.anon <- sample(length(subjects))
> subjects.anon
[1] 1 4 2 3
```
Then you can talk about subject 4 with the data that refers to Mark.
And if you want the numbers unrelated to the number of subjects:
```
sample(1000, length(subjects)) # [1] 789 103 435 983
```
Upvotes: 2 <issue_comment>username_2: Take the first m characters of the hash, as long as it's unique in the first m. (That value of m will tend to be O(log(N)) where N is the number of subjects.) Here's sample code:
```
set.seed(1)
v <- do.call(paste0, replicate(n=8, sample(LETTERS, size=100, replace=T), simplify=F))
unique_in_first_m_chars <- function(v, m) {
length(unique(substring(v, 1, m))) == length(v)
}
unique_in_first_m_chars(v, 4)
[1] TRUE
unique_in_first_m_chars(v, 3)
[1] FALSE
unique_in_first_m_chars(v, 2)
[1] FALSE
```
Upvotes: 0 <issue_comment>username_3: Just use a reference list of human readable names and match it up to each unique value of the true ID. It really depends on how many values you need to create aliases for.
One such source is a list of baby names (here, the 1000 most common names from 2010). For example
```
library(babynames)
library(dplyr)
samples <- data.frame(id=1:50, age=rnorm(50, 30, 5))
translate <- babynames %>% filter(year==2010) %>%
top_n(1000, n) %>%
sample_n(length(unique(samples$id))) %>%
select(alias_id=name) %>%
bind_cols(id=unique(samples$id))
translate
# alias_id id
#
# 1 Savanna 1
# 2 Jasmin 2
# 3 Natalie 3
# 4 Omar 4
# 5 Tristan 5
# 6 Jeremiah 6
# 7 Arielle 7
# 8 Tanner 8
# 9 Francesca 9
# 10 Devin 10
# # ... with 40 more rows
```
now we have a translation table that we can use to swap out the real IDs for names.
Upvotes: 1
|
2018/03/15
| 809 | 2,293 |
<issue_start>username_0: I am trying to use the JawsDB Maria with spring boot application on Heroku.
I always got the error when trying to create the connection, not only the program but also the sql browser.
The error as below:
>
> User '-----' has exceeded the 'max\_user\_connections' resource (current value: 10)
>
>
>
Does anybody know why ?
Where can I check who create the connections and can I close the connections ?<issue_comment>username_1: What about just assigning a random number to each subject:
```
> subjects <- c("Matthew", "Mark", "Luke", "John")
> subjects.anon <- sample(length(subjects))
> subjects.anon
[1] 1 4 2 3
```
Then you can talk about subject 4 with the data that refers to Mark.
And if you want the numbers unrelated to the number of subjects:
```
sample(1000, length(subjects)) # [1] 789 103 435 983
```
Upvotes: 2 <issue_comment>username_2: Take the first m characters of the hash, as long as it's unique in the first m. (That value of m will tend to be O(log(N)) where N is the number of subjects.) Here's sample code:
```
set.seed(1)
v <- do.call(paste0, replicate(n=8, sample(LETTERS, size=100, replace=T), simplify=F))
unique_in_first_m_chars <- function(v, m) {
length(unique(substring(v, 1, m))) == length(v)
}
unique_in_first_m_chars(v, 4)
[1] TRUE
unique_in_first_m_chars(v, 3)
[1] FALSE
unique_in_first_m_chars(v, 2)
[1] FALSE
```
Upvotes: 0 <issue_comment>username_3: Just use a reference list of human readable names and match it up to each unique value of the true ID. It really depends on how many values you need to create aliases for.
One such source is a list of baby names (here, the 1000 most common names from 2010). For example
```
library(babynames)
library(dplyr)
samples <- data.frame(id=1:50, age=rnorm(50, 30, 5))
translate <- babynames %>% filter(year==2010) %>%
top_n(1000, n) %>%
sample_n(length(unique(samples$id))) %>%
select(alias_id=name) %>%
bind_cols(id=unique(samples$id))
translate
# alias_id id
#
# 1 Savanna 1
# 2 Jasmin 2
# 3 Natalie 3
# 4 Omar 4
# 5 Tristan 5
# 6 Jeremiah 6
# 7 Arielle 7
# 8 Tanner 8
# 9 Francesca 9
# 10 Devin 10
# # ... with 40 more rows
```
now we have a translation table that we can use to swap out the real IDs for names.
Upvotes: 1
|
2018/03/15
| 1,084 | 3,913 |
<issue_start>username_0: Have a look at the following that demonstrates my issue with Visual Studio 2017 compiler
```
public interface IFoo
{
string Key { get; set; }
}
public class Foo : IFoo
{
public string Key { get; set; }
}
class Program
{
static void Main(string[] args)
{
PrintFoo(new Foo() { Key = "Hello World" });
Console.ReadLine();
}
private static void PrintFoo(T foo) where T : IFoo
{
//set breakpoint here and try to look at foo.Key
Console.WriteLine(foo.Key);
}
}
```
When I make a breakpoint inside the `PrintFoo` method and want to look at the `Key` property of `foo` Visual Studio wont provide a tooltip for me.
By adding the `foo.Key` to the watch window I receive the following error:
>
> error CS1061: 'T' does not contain a definition for 'Key' and no
> extension method 'Key' accepting a first argument of type 'T' could be
> found (are you missing a using directive or an assembly reference?)
>
>
>
When I change the generic declaration to `Foo` instead of `IFoo` the compiler can acces the 'Key' property, so this:
```
private static void PrintFoo(T foo) where T : Foo
{
//set breakpoint here and try to look at foo.Key
Console.WriteLine(foo.Key);
}
```
Is there a way to make it work?
**Edit:**
Both, looking at the local window and mouse over `foo` to get the tooltip and than expanding the properties works.
Adding `foo.Key` to the watch window or writing `?foo.Key` into immediate window brings the mentioned error, and you wont get a tooltip when you mouse over `Key` of `foo.Key`
Tested with Visual Studio 2015, 2017.
[](https://i.stack.imgur.com/0eAWh.png)<issue_comment>username_1: There are two workarounds for this issue. Use Tools > Options > Debugging > General. You can tick "Use Managed Compatibility Mode" or "Use the legacy C# and VB.NET expression evaluators".
"Use Managed Compatibility Mode" is unnecessarily cryptic, what it actually does is replace the new debugging engine with the one that was last used in VS2010. The good one. It in effect also gives you the legacy expression evaluator. I recommend you use this one since it also avoids a bunch of other bugs in the new debugging engine. Which got especially buggy in VS2015.
Very few reasons I ever discovered to turn it back off. You miss out on recently added debugger features, I only know of method return value inspection, edit+continue for 64-bit code and the new portable PDB format that is used in .NETCore on non-Windows systems. It *must* be used to debug C++/CLI code. I don't know what is better about the new expression evaluator, never noticed anything. Pretty easy to live without them, at least for me.
I'm not privy enough to the internals of the debugger team to really tell what is going on. But it doesn't look that good, VS2017 added some new nasty failure modes with the new debugging engine collapsing into a pile of rubble at the worst possible time. Take these options at their face value, they surely exist because they know the latest versions are not up to snuff.
---
Update: as pointed out by Rand, this particular defect does appear to have been addressed. I'm seeing correct behavior in version 15.9.3.
Upvotes: 3 <issue_comment>username_2: Bug got fixed in Visual Studio 2019:
<https://developercommunity.visualstudio.com/content/problem/216341/compiler-doesnt-recognise-property-in-generic-if-d.html>
Comment by <NAME> [MSFT]:
>
> It seems that the issue is not reproducible in the current Visual
> Studio. I tried it with VS 2019 Preview 2. The scenario works fine.
> Thank you for your feedback!
>
>
>
Also tried to reproduce it on my Preview Version 1.1 and it is fixed there aswell.
Gave the latest Version of Visual Studio 2017 (15.9.5) a try aswell and can report it got fixed there aswell.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 515 | 1,806 |
<issue_start>username_0: Below is my requirement in the picture

The 1st table is at least granularity.The avg is calculated by `Date + Place`.So the avg is `565 = (2865/5)`.
Coming to the second table.The avg for place 702 is 114 which is right and for 704 it is 866 which is also right.But the final ans is the same as the avg for all 5 records.
But my output should be like avg at `Date + Place` level for single `Date + Place` but when two places are selected it should avg at place level but sum at the total output..the final value should be **980** (sum(114+866))
Can someone have a solution for this?<issue_comment>username_1: Try this:
```
AvgA = SUMX(SUMMARIZE(Table2, Table2[Place], "A", AVERAGE(Table2[A])), [A])
```
This will take the average `A` grouping by each `Place` and then sum them up for the subtotal.
Upvotes: 0 <issue_comment>username_2: As with any average in SSAS Multidimensional you will need to create two physical measures. The first is a Sum of A which is AggregateFunction=Sum. The second is a Count of Rows which is AggregateFunction=Count.
The quicker way to implement your calculation is with this calculated measure:
```
SUM(
EXISTING [Place].[Place].[Place].Members,
DIVIDE( [Measures].[Sum of A], [Measures].[Count of Rows] )
)
```
However if you want to get better performance and properly handle multi-select filters then create a physical measure called Avg A which is AggregateFunction=Sum off a new column in your SQL table which is always 0. Then overwrite the values in that measure with the following scope statement:
```
SCOPE([Place].[Place].[Place].Members);
[Measures].[Avg A] = DIVIDE( [Measures].[Sum of A], [Measures].[Count of Rows] );
END SCOPE;
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,001 | 3,008 |
<issue_start>username_0: **Question: How can I create a while loop that lists unique names and a count of how many times that name is listed in database?**
*I will never know what names will be listed in database at any given time so I cannot hard code this.*
Database:
---------
```
| id | name | age |
| 1 | Bob | 35 |
| 2 | Jake | 30 |
| 3 | Bob | 25 |
| 4 | Bob | 45 |
| 5 | Jake | 78 |
| 6 | Heather | 23 |
```
code to sort by name
--------------------
```
$query = $con->query("SELECT id,name,age FROM table order by name ASC")
if ($query->num_rows > 0) {
while ($result = $query->fetch_assoc()) {
// while loop
}
}
```
Ideal Results
-------------
```
Bob (3)
Heather (1)
Jake (2)
```
I don't know if this is php code in while loop or if this is a specific query I can run to achieve this. Any help would be greatly appreciated.<issue_comment>username_1: You can do this in your SQL query...
```
$query = $con->query("SELECT name, count(id) as total
FROM table
group by name
order by name ASC")
```
Using count(id) will count the number of id's within the group by name.
**Update:**
The other answer gives you a way of doing it inside a for loop. But another version is if you do something like...
```
$query = $con->query("SELECT id,name,age FROM table order by name ASC")
if ($query->num_rows > 0) {
$data = $query->fetch_all(MYSQLI_ASSOC);
$names = array_column($data, 'name');
$count = array_count_values($names);
print_r($count);
}
```
This just fetches all of the data from the SQL statement, then extract the name column and count the unique values from this array.
Upvotes: 4 [selected_answer]<issue_comment>username_2: While I would usually do it in SQL with `GROUP_BY` and `COUNT()` - If you ever need to do it in PHP you can use one of the follwing ways.
Assuming you have data in this form:
```
$data = [
['id' => 1, 'name' => 'Bob', 'age' => 35],
['id' => 2, 'name' => 'Jake', 'age' => 30],
['id' => 3, 'name' => 'Bob', 'age' => 25],
['id' => 4, 'name' => 'Bob', 'age' => 45],
['id' => 5, 'name' => 'Jake', 'age' => 78],
['id' => 6, 'name' => 'Heather', 'age' => 23],
];
```
One method would be:
```
$counts = [];
foreach ($data as $row) {
if (isset($counts[$row['name']])) {
$counts[$row['name']] += 1;
} else {
$counts[$row['name']] = 1;
}
}
```
And here is another one, which is (IMHO) more elegant, but slower:
```
$groups = [];
foreach ($data as $row) {
$groups[$row['name']][] = $row;
}
$counts = array_map('count', $groups);
```
Both methods would create an array like this:
```
[
'Bob' => 3,
'Jake' => 2,
'Heather' => 1,
];
```
Demo: <http://rextester.com/PTCC84943>
The foreach loop can also be replced with `while ($row = $query->fetch_assoc())`
Upvotes: 1
|
2018/03/15
| 952 | 3,027 |
<issue_start>username_0: I'm Vincent, a French student. For a school project, my group and I are looking to make a 360 app on iOS. The idea is that the user will use the app with a cardboard, and live a 360 experience. Noone in my group never did this, so here I am, to get so good advices on which techs should we use to make our project live.
<https://i.stack.imgur.com/GL38c.jpg> (Illustration of the user using the app)
We find out that ArKit and Unity using the Google SDK VR are the two main techs to make what we want to, but the thing is that we're a little scared about choosing the wrong one. ArKit seems fine, but this is in 3D. We're more looking to project 2D image around the image and he can move the head to navigate between them. Unity, on its side, seems too much, and I not sure that the scripting / animating render well.
So what do you guys think ? ArKit ? Unity ? Maybe another thing ? I surely forget something, so please ask for more details :). Thanks !<issue_comment>username_1: You can do this in your SQL query...
```
$query = $con->query("SELECT name, count(id) as total
FROM table
group by name
order by name ASC")
```
Using count(id) will count the number of id's within the group by name.
**Update:**
The other answer gives you a way of doing it inside a for loop. But another version is if you do something like...
```
$query = $con->query("SELECT id,name,age FROM table order by name ASC")
if ($query->num_rows > 0) {
$data = $query->fetch_all(MYSQLI_ASSOC);
$names = array_column($data, 'name');
$count = array_count_values($names);
print_r($count);
}
```
This just fetches all of the data from the SQL statement, then extract the name column and count the unique values from this array.
Upvotes: 4 [selected_answer]<issue_comment>username_2: While I would usually do it in SQL with `GROUP_BY` and `COUNT()` - If you ever need to do it in PHP you can use one of the follwing ways.
Assuming you have data in this form:
```
$data = [
['id' => 1, 'name' => 'Bob', 'age' => 35],
['id' => 2, 'name' => 'Jake', 'age' => 30],
['id' => 3, 'name' => 'Bob', 'age' => 25],
['id' => 4, 'name' => 'Bob', 'age' => 45],
['id' => 5, 'name' => 'Jake', 'age' => 78],
['id' => 6, 'name' => 'Heather', 'age' => 23],
];
```
One method would be:
```
$counts = [];
foreach ($data as $row) {
if (isset($counts[$row['name']])) {
$counts[$row['name']] += 1;
} else {
$counts[$row['name']] = 1;
}
}
```
And here is another one, which is (IMHO) more elegant, but slower:
```
$groups = [];
foreach ($data as $row) {
$groups[$row['name']][] = $row;
}
$counts = array_map('count', $groups);
```
Both methods would create an array like this:
```
[
'Bob' => 3,
'Jake' => 2,
'Heather' => 1,
];
```
Demo: <http://rextester.com/PTCC84943>
The foreach loop can also be replced with `while ($row = $query->fetch_assoc())`
Upvotes: 1
|
2018/03/15
| 291 | 913 |
<issue_start>username_0: all!
I am having a problem with selecting the s separately from each other. I want to style the first differently than the second .
It would be much easier (and wouldn't need to be asked here) to assign a class/id to those s but I cannot do that because I am using a WordPress theme.
```
```
Thank you!<issue_comment>username_1: What about this:
```css
.wrapper > div:first-child p.a {
color:red;
}
.wrapper > div:last-child p.a {
color:blue;
}
```
```html
aa
bb
aa
bb
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Just select it with nth-of-type and the direct descendant selector.
nth-child works too if this is the exact structure and not any different element besides in that
```css
.wrapper > div:first-of-type p.a {
color:blue;
}
.wrapper > div:nth-of-type(2) p.a {
color:pink;
}
```
```html
aa
bb
aa
bb
```
Upvotes: 0
|
2018/03/15
| 493 | 1,989 |
<issue_start>username_0: I want to use Array.find instead of $.each so it stops looping once it has found the result, but I cannot figure out the correct syntax to return the zipcode.
```
navigator.geolocation.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latLng
}, function (results, status) {
var searchAddressComponents = results[0].address_components;
var zipcode = "";
//searchAddressComponents.find(function() {
//});
/* function isZipcode() {
if(results[0].address_components.types[0]=="postal_code"){
zipcode = element.short_name;
}
}*/
//THIS WORKS BUT WANT TO USE ARRAY.FIND to return Zipcode
$.each(searchAddressComponents, function(){
if(this.types[0]=="postal_code"){
zipcode = this.short_name;
}
});
}); //END OF GEOCODER
});
```<issue_comment>username_1: There are many ways to skin this cat. But if you want to use [`Array#find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find), here's how:
```js
zipcode = searchAddressComponents.find(component => component.types[0] == "postal_code").short_name;
```
---
For pre-ES6, the function is as follows
```
zipcode = searchAddressComponents.find(function (component) {
return component.types[0] == "postal_code";
}).short_name;
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This should work (assuming you have access to ES6 syntax, such as arrow functions):
```
const zipcode = searchAddressComponents.find(
component => component.types[0] === 'postal_code'
).short_name;
```
Upvotes: 1
|
2018/03/15
| 805 | 3,014 |
<issue_start>username_0: It seems that there is a bug in the O-O support in **PowerShell**.
When instantiating an object of a class with a constructor that accepts a **List< T >** and **this is the only parameter**, PowerShell cannot find a proper constructor.
Code sample:
```
class MyClass
{
MyClass(
#[int]$i,
[System.Collections.Generic.List[string]] $theparams)
{
}
}
$parameters = New-Object System.Collections.Generic.List[string];
$foo = New-Object MyClass -ArgumentList @(
#1,
$parameters)
```
>
> Constructor not found. Cannot find an appropriate constructor for type MyClass.
>
>
>
Uncommenting the `[int]` parameter makes it work fine.
**Workaround**: since Powershell doesn't handle visibility of the members, if the parameter is used to assign a class member then you can directly assign it outside the constructor.<issue_comment>username_1: I suggest you use the constructor syntax since you're on PSv5 anyways. This worked in my testing and there may be something funky going on with `New-Object`:
```
class MyClass
{
MyClass([System.Collections.Generic.List[string]] $Params) { }
}
[MyClass]::new([System.Collections.Generic.List[string]]::new())
```
Upvotes: 2 <issue_comment>username_2: To avoid the pitfall discussed here, consider using the class' static `::new()` method (PSv5+), as demonstrated in [username_1's helpful answer](https://stackoverflow.com/a/49307753/45375).
Note: **The following applies not just to `New-Object`, but to *all* cmdlets that accept an array of arguments via a single parameter** (typically named `-ArgumentList` / alias `-Args`), **notably also `Invoke-Command` and `Start-Job`.**
To find all commands that have an `-ArgumentList` parameter, run `Get-Help * -Parameter ArgumentList`
---
**To pass a collection *as a whole* as *the only argument* to `New-Object`'s `-ArgumentList` parameter, you must *wrap it in an aux. array* using `,`, the array-construction operator**[1]:
```bash
New-Object MyClass -ArgumentList (, $parameters)
```
Without the wrapper, the elements of collection `$parameters` would be interpreted as *individual* constructor arguments.
However, **if there is *at least one other explicitly enumerated argument*, the wrapping is no longer needed**:
```bash
# With `[int] $i` as the 1st constructor argument defined:
New-Object MyClass -ArgumentList 1, $parameters
```
The reason is that `1, $parameters` constructs an array in a manner that *implicitly* passes `$parameters` as a *single* argument: `$parameters` *as a whole* becomes the array's 2nd argument.
---
---
[1] Note that `@($parameters)` would *not* work, because `@(...)`, the array-subexpression operator, is a *no-op* (loosely speaking) if the expression already *is* an array.
I say loosely speaking, because `@(...)` actually *rebuilds* the input collection as a (new) `[object[]]` array - which has performance implications and can result in a different collection type.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 377 | 1,655 |
<issue_start>username_0: I am planning on learning HP Exstream. What are the prerequisite for learning HP Exstream.
What language is it in. Please share any materials.<issue_comment>username_1: You will need to pay for the courses just like everyone else.
There is little to nothing online. If you contact the vendor, you can arrange for training. As for the programming language, it is similar to VB except when it's not. That's really the best advice I can give you.
The syntax works exactly like VB, but it has almost none of the intrinsic functions. Those are provided in one of the HP Exstream Training Manuals.
Upvotes: 1 <issue_comment>username_2: Exstream Version 9 and less have the capabilities to shell out into windows and call any program you desire via its compiled .PUB file. The PUB file contains everything on a documents page/s or template of pages which also can house any variable driven tables columns rows cells or text boxes or actual letters words or phrases if in effect if-then-else include or exclude ro call a subroutine or function. Pages can flow, tables can grow and flow as well as text that may populate a string or integer variable, That text being an XML element, flat ascii line by line file or ebcdic line mode also known as Columnar records whereas each record is a customer record that gets turned into an invoice, bill, statement or letter, i.e. CCM Customer Communication Management & Correspondences.
Version 16, Beginning with the OpenText Acquire of Exstream Suite products from HP and their so called first release of the product Hence buying it all from HP in 2016. Can do this as well v16+.
Upvotes: 0
|
2018/03/15
| 1,234 | 4,614 |
<issue_start>username_0: I've got a `public static List DoggieList;`
`DoggieList` is appended to and written to by multiple processes throughout my application.
We run into this exception pretty frequently:
>
> Collection was modified; enumeration operation may not execute
>
>
>
Assuming there are multiple classes writing to `DoggieList` how do we get around this exception?
Please note that this design is not great, but at this point we need to quickly fix it in production.
**How can we perform mutations to this list safely from multiple threads?**
I understand we can do something like:
```
lock(lockObject)
{
DoggieList.AddRange(...)
}
```
**But can we do this from multiple classes against the same `DoggieList`?**<issue_comment>username_1: Using `lock` a the disadvantage of preventing concurrent readings.
An efficient solution which does not require changing the collection type is to use a [ReaderWriterLockSlim](https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim(v=vs.110).aspx)
```
private static readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
```
With the following extension methods:
```
public static class ReaderWriterLockSlimExtensions
{
public static void ExecuteWrite(this ReaderWriterLockSlim aLock, Action action)
{
aLock.EnterWriteLock();
try
{
action();
}
finally
{
aLock.ExitWriteLock();
}
}
public static void ExecuteRead(this ReaderWriterLockSlim aLock, Action action)
{
aLock.EnterReadLock();
try
{
action();
}
finally
{
aLock.ExitReadLock();
}
}
}
```
which can be used the following way:
```
_lock.ExecuteWrite(() => DoggieList.Add(new Doggie()));
_lock.ExecuteRead(() =>
{
// safe iteration
foreach (MyDoggie item in DoggieList)
{
....
}
})
```
And finally if you want to build your own collection based on this:
```
public class SafeList
{
private readonly ReaderWriterLockSlim \_lock = new ReaderWriterLockSlim();
private readonly List \_list = new List();
public T this[int index]
{
get
{
T result = default(T);
\_lock.ExecuteRead(() => result = \_list[index]);
return result;
}
}
public List GetAll()
{
List result = null;
\_lock.ExecuteRead(() => result = \_list.ToList());
return result;
}
public void ForEach(Action action) =>
\_lock.ExecuteRead(() => \_list.ForEach(action));
public void Add(T item) => \_lock.ExecuteWrite(() => \_list.Add(item));
public void AddRange(IEnumerable items) =>
\_lock.ExecuteWrite(() => \_list.AddRange(items));
}
```
This list is totally safe, multiple threads can add or get items in parallel without any concurrency issue. Additionally, multiple threads can get items in parallel without locking each other, it's only when writing than 1 single thread can work on the collection.
Note that this collection does not implement `IEnumerable` because you could get an enumerator and forget to dispose it which would leave the list locked in read mode.
Upvotes: 1 <issue_comment>username_2: you can also create you own class and encapsulate locking thing in that only, you can try like as below ,
you can add method you want like addRange, Remove etc.
```
class MyList {
private object objLock = new object();
private List list = new List();
public void Add(int value) {
lock (objLock) {
list.Add(value);
}
}
public int Get(int index) {
int val = -1;
lock (objLock) {
val = list[0];
}
return val;
}
public void GetAll() {
List retList = new List();
lock (objLock) {
retList = new List(list);
}
return retList;
}
}
```
---
Good stuff : Concurrent Collections very much in detail :<http://www.albahari.com/threading/part5.aspx#_Concurrent_Collections>
making use of concurrent collection [ConcurrentBag](https://msdn.microsoft.com/en-us/library/dd381779(v=vs.110).aspx) Class can also resolve issue related to multiple thread update
Example
```
using System.Collections.Concurrent;
using System.Threading.Tasks;
public static class Program
{
public static void Main()
{
var items = new[] { "item1", "item2", "item3" };
var bag = new ConcurrentBag();
Parallel.ForEach(items, bag.Add);
}
}
```
Upvotes: 1 <issue_comment>username_3: make `DoggieList` of type `ConcurrentStack` and then use `pushRange` method. It is thread safe.
```
using System.Collections.Concurrent;
var doggieList = new ConcurrentStack();
doggieList.PushRange(YourCode)
```
Upvotes: 0
|
2018/03/15
| 700 | 2,782 |
<issue_start>username_0: As in title. I have a String `shoppingListId` which holds current clicked in `RecyclerView` documentID and I wonder how to delete this selected document ID.
I tried the following one but it doesn't works because of Incompatible types:
```
FirebaseFirestore docRef = FirebaseFirestore.getInstance();
DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);
selectedDoc.delete();
```
How to get Instance to DocumentReference, and then delete selected document? I guess this is probably so easy, but Im stuck at it.

Changed the code, there aren't any Errors right now, but still it doesn't works.<issue_comment>username_1: I think you are following this **[tutorial](https://www.youtube.com/playlist?list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee)**, which is actually made by me.
The problem in your code is in the following line:
```
DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);
```
You cannot delete a product using only that line of code. Your code is not complete. To solve this, change that line with:
```
DocumentReference productIdRef = rootRef.collection("products").document(shoppingListId)
.collection("shoppingListProducts").document(productId);
productIdRef.delete().addOnSuccessListener(aVoid -> Snackbar.make(shoppingListViewFragment, "Product deleted!", Snackbar.LENGTH_LONG).show());
```
If you want to delete a ShoppingList, first you need to delete everything that is beneath it. So in order to delete a particular shopping list, first you need to find all the documents beneath the `shoppingListProducts` collection, delete them and right after that you'll be able to delete the `shoppingListId` document.
Upvotes: 2 <issue_comment>username_2: ```
FirebaseFirestore docRef = FirebaseFirestore.getInstance();
docRef.collection("products").document(shoppingListId)
.delete()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
// You can write what you want after the deleting process.
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
```
Upvotes: 2 <issue_comment>username_3: ```
DocumentReference documentReference = firestore.collection("products").document(productid);
documentReference.delete().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Payment\_Successful.this, "ok", Toast.LENGTH\_SHORT).show();
} else {
Toast.makeText(Payment\_Successful.this, "Not", Toast.LENGTH\_SHORT).show();
}
}
```
Upvotes: 0
|
2018/03/15
| 695 | 2,467 |
<issue_start>username_0: For example: insert 1 5 88 99 7 in a set if 1,5,88,99,7 is given as an input and then pressed Enter.
My code:
```
#include
using namespace std;
set num;
set ::iterator i;
int main()
{
int a;
while(a=getchar())
{
if(a!='\n')
{
if(a!=',')
num.insert(a);
}
else
break;
}
for(i=num.begin(); i!=num.end(); i++)
cout<<\*i<
```
The output I'm getting:
1
5
7
8
9<issue_comment>username_1: I think you are following this **[tutorial](https://www.youtube.com/playlist?list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee)**, which is actually made by me.
The problem in your code is in the following line:
```
DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);
```
You cannot delete a product using only that line of code. Your code is not complete. To solve this, change that line with:
```
DocumentReference productIdRef = rootRef.collection("products").document(shoppingListId)
.collection("shoppingListProducts").document(productId);
productIdRef.delete().addOnSuccessListener(aVoid -> Snackbar.make(shoppingListViewFragment, "Product deleted!", Snackbar.LENGTH_LONG).show());
```
If you want to delete a ShoppingList, first you need to delete everything that is beneath it. So in order to delete a particular shopping list, first you need to find all the documents beneath the `shoppingListProducts` collection, delete them and right after that you'll be able to delete the `shoppingListId` document.
Upvotes: 2 <issue_comment>username_2: ```
FirebaseFirestore docRef = FirebaseFirestore.getInstance();
docRef.collection("products").document(shoppingListId)
.delete()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
// You can write what you want after the deleting process.
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
```
Upvotes: 2 <issue_comment>username_3: ```
DocumentReference documentReference = firestore.collection("products").document(productid);
documentReference.delete().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Payment\_Successful.this, "ok", Toast.LENGTH\_SHORT).show();
} else {
Toast.makeText(Payment\_Successful.this, "Not", Toast.LENGTH\_SHORT).show();
}
}
```
Upvotes: 0
|
2018/03/15
| 749 | 2,828 |
<issue_start>username_0: So I wrote a Fibonacci sequence function like this:
```
CREATE OR REPLACE FUNCTION fibonacci (lastN INTEGER)
RETURNS int AS $$
BEGIN
WITH RECURSIVE t(a, b) AS (
VALUES(0,1)
UNION ALL
SELECT GREATEST(a, b), a + b AS a from t
WHERE b < $1
)
SELECT a FROM t;
END;
$$ LANGUAGE plpgsql;
```
But when I called:
```
SELECT * FROM fibonacci(20);
```
the console shows:
```
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function fibonacci(integer) line 5 at SQL statement
```
I think the Return statement should return the query result but it isn't. I'm completely a new guy on writing SQL functions like this.<issue_comment>username_1: I think you are following this **[tutorial](https://www.youtube.com/playlist?list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee)**, which is actually made by me.
The problem in your code is in the following line:
```
DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);
```
You cannot delete a product using only that line of code. Your code is not complete. To solve this, change that line with:
```
DocumentReference productIdRef = rootRef.collection("products").document(shoppingListId)
.collection("shoppingListProducts").document(productId);
productIdRef.delete().addOnSuccessListener(aVoid -> Snackbar.make(shoppingListViewFragment, "Product deleted!", Snackbar.LENGTH_LONG).show());
```
If you want to delete a ShoppingList, first you need to delete everything that is beneath it. So in order to delete a particular shopping list, first you need to find all the documents beneath the `shoppingListProducts` collection, delete them and right after that you'll be able to delete the `shoppingListId` document.
Upvotes: 2 <issue_comment>username_2: ```
FirebaseFirestore docRef = FirebaseFirestore.getInstance();
docRef.collection("products").document(shoppingListId)
.delete()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
// You can write what you want after the deleting process.
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
```
Upvotes: 2 <issue_comment>username_3: ```
DocumentReference documentReference = firestore.collection("products").document(productid);
documentReference.delete().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Payment\_Successful.this, "ok", Toast.LENGTH\_SHORT).show();
} else {
Toast.makeText(Payment\_Successful.this, "Not", Toast.LENGTH\_SHORT).show();
}
}
```
Upvotes: 0
|
2018/03/15
| 6,449 | 23,710 |
<issue_start>username_0: I don't understand how `LayoutBuilder` is used to get the height of a widget.
I need to display the list of Widgets and get their height, so I can compute some special scroll effects. I am developing a package and other developers provide a widget (I don't control them). I read that LayoutBuilder can be used to get the height.
In a very simple case, I tried to wrap a widget in LayoutBuilder.builder and put it in the stack, but I always get `minHeight` `0.0`, and `maxHeight` `INFINITY`. Am I misusing the LayoutBuilder?
It seems that LayoutBuilder is a no go. I found the [CustomSingleChildLayout](https://docs.flutter.io/flutter/widgets/CustomSingleChildLayout-class.html) which is almost a solution.
I extended that delegate, and I was able to get the height of widget in `getPositionForChild(Size size, Size childSize)` method. *but*, the first method that is called is `Size getSize(BoxConstraints constraints)` and as constraints, I get 0 to INFINITY because I'm laying these CustomSingleChildLayouts in a ListView.
My problem is that SingleChildLayoutDelegate `getSize` operates like it needs to return the height of a view. I don't know the height of a child at that moment. I can only return *constraints.smallest* (which is 0, and the height is 0), or *constraints.biggest* which is infinity and crashes the app.
In the documentation it even says:
>
> ...but the size of the parent cannot depend on the size of the child.
>
>
>
And that's a weird limitation.<issue_comment>username_1: To get the size/position of a widget on screen, you can use `GlobalKey` to get its `BuildContext` to then find the `RenderBox` of that specific widget, which will contain its global position and rendered size.
There is just one thing to be careful of: That context may not exist if the widget is not rendered. Which can cause a problem with `ListView` as widgets are rendered only if they are potentially visible.
Another problem is that you can't get a widget's `RenderBox` during the `build` call as the widget hasn't been rendered yet.
---
*But what if I need to get the size during the build! What can I do?*
There's one cool widget that can help: `Overlay` and its `OverlayEntry`. They are used to display widgets on top of everything else (similar to the stack).
But the coolest thing is that they are on a different `build` flow; they are built *after* regular widgets.
That have one super cool implication: `OverlayEntry` can have a size that depends on widgets of the actual widget tree.
---
*Okay. But don't OverlayEntry requires to be rebuilt manually?*
Yes, they do. But there's another thing to be aware of: `ScrollController`, passed to a `Scrollable`, is a listenable similar to `AnimationController`.
Which means you could combine an `AnimatedBuilder` with a `ScrollController`. It would have the lovely effect to rebuild your widget automatically on a scroll. Perfect for this situation, right?
---
Combining everything into an example:
In the following example, you'll see an overlay that follows a widget inside a `ListView` and shares the same height.
```
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
final controller = ScrollController();
OverlayEntry sticky;
GlobalKey stickyKey = GlobalKey();
@override
void initState() {
if (sticky != null) {
sticky.remove();
}
sticky = OverlayEntry(
builder: (context) => stickyBuilder(context),
);
SchedulerBinding.instance.addPostFrameCallback((\_) {
Overlay.of(context).insert(sticky);
});
super.initState();
}
@override
void dispose() {
sticky.remove();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: controller,
itemBuilder: (context, index) {
if (index == 6) {
return Container(
key: stickyKey,
height: 100.0,
color: Colors.green,
child: const Text("I'm fat"),
);
}
return ListTile(
title: Text(
'Hello $index',
style: const TextStyle(color: Colors.white),
),
);
},
),
);
}
Widget stickyBuilder(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (\_,Widget child) {
final keyContext = stickyKey.currentContext;
if (keyContext != null) {
// widget is visible
final box = keyContext.findRenderObject() as RenderBox;
final pos = box.localToGlobal(Offset.zero);
return Positioned(
top: pos.dy + box.size.height,
left: 50.0,
right: 50.0,
height: box.size.height,
child: Material(
child: Container(
alignment: Alignment.center,
color: Colors.purple,
child: const Text("^ Nah I think you're okay"),
),
),
);
}
return Container();
},
);
}
}
```
**Note**:
When navigating to a different screen, call the following. Otherwise, sticky would stay visible.
```dart
sticky.remove();
```
Upvotes: 9 [selected_answer]<issue_comment>username_2: If I understand correctly, you want to measure the dimension of some arbitrary widgets, and you can wrap those widgets with another widget. In that case, the method in the [this answer](https://stackoverflow.com/a/50682918/2368223) should work for you.
Basically, the solution is to bind a callback in the widget lifecycle, which will be called after the first frame is rendered, and from there you can access `context.size`. The catch is that you have to wrap the widget you want to measure within a stateful widget. And, if you absolutely need the size within `build()` then you can only access it in the second render (it's only available after the first render).
Upvotes: 3 <issue_comment>username_3: This is (I think) the most straightforward way to do this.
Copy-paste the following into your project.
Using `RenderProxyBox` results in a slightly more correct implementation, because it's called on every rebuild of the child and its descendants, which is not always the case for the top-level build() method.
Note: This is not exactly an efficient way to do this, as pointed by Hixie [here](https://github.com/flutter/flutter/issues/14488#issuecomment-675837800). But it is the easiest.
```dart
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
typedef void OnWidgetSizeChange(Size size);
class MeasureSizeRenderObject extends RenderProxyBox {
Size? oldSize;
OnWidgetSizeChange onChange;
MeasureSizeRenderObject(this.onChange);
@override
void performLayout() {
super.performLayout();
Size newSize = child!.size;
if (oldSize == newSize) return;
oldSize = newSize;
WidgetsBinding.instance!.addPostFrameCallback((_) {
onChange(newSize);
});
}
}
class MeasureSize extends SingleChildRenderObjectWidget {
final OnWidgetSizeChange onChange;
const MeasureSize({
Key? key,
required this.onChange,
required Widget child,
}) : super(key: key, child: child);
@override
RenderObject createRenderObject(BuildContext context) {
return MeasureSizeRenderObject(onChange);
}
@override
void updateRenderObject(
BuildContext context, covariant MeasureSizeRenderObject renderObject) {
renderObject.onChange = onChange;
}
}
```
Then, simply wrap the widget whose size you would like to measure with `MeasureSize`.
```
var myChildSize = Size.zero;
Widget build(BuildContext context) {
return ...(
child: MeasureSize(
onChange: (size) {
setState(() {
myChildSize = size;
});
},
child: ...
),
);
}
```
So yes, the size of the parent **can** depend on the size of the child if you try hard enough.
---
Personal anecdote: This is handy for restricting the size of widgets like `Align`, which likes to take up an absurd amount of space.
Upvotes: 7 <issue_comment>username_4: `findRenderObject()` returns the `RenderBox` which is used to give the size of the drawn widget and it should be called after the widget tree is built, so it must be used with some callback mechanism or `addPostFrameCallback()` callbacks.
```
class SizeWidget extends StatefulWidget {
@override
_SizeWidgetState createState() => _SizeWidgetState();
}
class _SizeWidgetState extends State {
final GlobalKey \_textKey = GlobalKey();
Size textSize;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((\_) => getSizeAndPosition());
}
getSizeAndPosition() {
RenderBox \_cardBox = \_textKey.currentContext.findRenderObject();
textSize = \_cardBox.size;
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Size Position"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"Currern Size of Text",
key: \_textKey,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
SizedBox(
height: 20,
),
Text(
"Size - $textSize",
textAlign: TextAlign.center,
),
],
),
);
}
}
```
**Output:**
[](https://i.stack.imgur.com/i6tJp.png)
Upvotes: 3 <issue_comment>username_5: Use the [z\_tools](https://pub.dev/packages/z_tools) package.
The steps:
### 1. Change the *main* file
```dart
void main() async {
runZoned(
() => runApp(
CalculateWidgetAppContainer(
child: Center(
child: LocalizedApp(delegate, MyApp()),
),
),
),
onError: (Object obj, StackTrace stack) {
print('global exception: obj = $obj;\nstack = $stack');
},
);
}
```
### 2. Use in a function
```dart
_Cell(
title: 'cal: Column-min',
callback: () async {
Widget widget1 = Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 100,
height: 30,
color: Colors.blue,
),
Container(
height: 20.0,
width: 30,
),
Text('111'),
],
);
// size = Size(100.0, 66.0)
print('size = ${await getWidgetSize(widget1)}');
},
),
```
Upvotes: 0 <issue_comment>username_6: Here's a sample of how you can use [`LayoutBuilder`](https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html) to determine the widget's size.
Since the `LayoutBuilder` widget is able to determine its parent widget's constraints, one of its use cases is to be able to have its child widgets adapt to their parent's dimensions.
```dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
var dimension = 40.0;
increaseWidgetSize() {
setState(() {
dimension += 20;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(children: [
Text('Dimension: $dimension'),
Container(
color: Colors.teal,
alignment: Alignment.center,
height: dimension,
width: dimension,
// LayoutBuilder inherits its parent widget's dimension. In this case, the Container in teal
child: LayoutBuilder(builder: (context, constraints) {
debugPrint('Max height: ${constraints.maxHeight}, max width: ${constraints.maxWidth}');
return Container(); // Create a function here to adapt to the parent widget's constraints
}),
),
]),
),
floatingActionButton: FloatingActionButton(
onPressed: increaseWidgetSize,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
```
Demo
[](https://i.stack.imgur.com/mJE6g.gif)
Logs
```none
I/flutter (26712): Max height: 40.0, max width: 40.0
I/flutter (26712): Max height: 60.0, max width: 60.0
I/flutter (26712): Max height: 80.0, max width: 80.0
I/flutter (26712): Max height: 100.0, max width: 100.0
```
You can also use [MediaQuery](https://api.flutter.dev/flutter/widgets/MediaQuery-class.html) to achieve a similar function.
```dart
@override
Widget build(BuildContext context) {
var screenSize = MediaQuery.of(context).size;
if (screenSize.width > layoutSize) {
return Widget();
} else {
return Widget(); // Widget if doesn't match the size
}
}
```
Upvotes: 5 <issue_comment>username_7: The easiest way is to use [MeasuredSize](https://pub.dev/packages/measured_size). It's a widget that calculates the size of its child at runtime.
You can use it like so:
```
MeasuredSize(
onChange: (Size size) {
setState(() {
print(size);
});
},
child: Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
);
```
You can find it here: <https://pub.dev/packages/measured_size>
Upvotes: 1 <issue_comment>username_8: **Let me give you a widget for that**
```
class SizeProviderWidget extends StatefulWidget {
final Widget child;
final Function(Size) onChildSize;
const SizeProviderWidget(
{Key? key, required this.onChildSize, required this.child})
: super(key: key);
@override
_SizeProviderWidgetState createState() => _SizeProviderWidgetState();
}
class _SizeProviderWidgetState extends State {
@override
void initState() {
///add size listener for first build
\_onResize();
super.initState();
}
void \_onResize() {
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
if (context.size is Size) {
widget.onChildSize(context.size!);
}
});
}
@override
Widget build(BuildContext context) {
///add size listener for every build uncomment the fallowing
///\_onResize();
return widget.child;
}
}
```
Just wrap the `SizeProviderWidget` with `OrientationBuilder` to make it respect the orientation of the device.
Upvotes: 4 <issue_comment>username_9: It's easy and still can be done in StatelessWidget.
```
class ColumnHeightWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final scrollController = ScrollController();
final columnKey = GlobalKey();
_scrollToCurrentProgress(columnKey, scrollController);
return Scaffold(
body: SingleChildScrollView(
controller: scrollController,
child: Column(
children: [],
),
),
);
}
void _scrollToCurrentProgress(GlobalKey> columnKey,
ScrollController scrollController) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final RenderBox renderBoxRed =
columnKey.currentContext.findRenderObject();
final height = renderBoxRed.size.height;
scrollController.animateTo(percentOfHeightYouWantToScroll \* height,
duration: Duration(seconds: 1), curve: Curves.decelerate);
});
}
}
```
In the same manner, you can calculate any widget child height and scroll to that position.
Upvotes: 0 <issue_comment>username_10: **I made this widget as a simple stateless solution:**
```
class ChildSizeNotifier extends StatelessWidget {
final ValueNotifier notifier = ValueNotifier(const Size(0, 0));
final Widget Function(BuildContext context, Size size, Widget child) builder;
final Widget child;
ChildSizeNotifier({
Key key,
@required this.builder,
this.child,
}) : super(key: key) {}
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(\_) {
notifier.value = (context.findRenderObject() as RenderBox).size;
},
);
return ValueListenableBuilder(
valueListenable: notifier,
builder: builder,
child: child,
);
}
}
```
**Use it like this**
```
ChildSizeNotifier(
builder: (context, size, child) {
// size is the size of the text
return Text(size.height > 50 ? 'big' : 'small');
},
)
```
Upvotes: 3 <issue_comment>username_11: There isn't any direct way to calculate the size of the widget, so to find that we have to take the help of the context of the widget.
Calling *context.size* returns us the *Size* object, which contains the height and width of the widget. *context.size* calculates the render box of a widget and returns the size.
Check out *[Flutter: How can I get the height of the widget?](https://medium.com/flutterworld/flutter-how-to-get-the-height-of-the-widget-be4892abb1a2)*.
Upvotes: 2 <issue_comment>username_12: It might be this could help.
It was tested on Flutter: 2.2.3
Copy the below code to your project.
```
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class WidgetSize extends StatefulWidget {
final Widget child;
final Function onChange;
const WidgetSize({
Key? key,
required this.onChange,
required this.child,
}) : super(key: key);
@override
_WidgetSizeState createState() => _WidgetSizeState();
}
class _WidgetSizeState extends State {
@override
Widget build(BuildContext context) {
SchedulerBinding.instance!.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
var widgetKey = GlobalKey();
var oldSize;
void postFrameCallback(\_) {
var context = widgetKey.currentContext;
if (context == null)
return;
var newSize = context.size;
if (oldSize == newSize)
return;
oldSize = newSize;
widget.onChange(newSize);
}
}
```
Declare a variable to store **Size**.
```
Size mySize = Size.zero;
```
Add the following code to get the size:
```
child: WidgetSize(
onChange: (Size mapSize) {
setState(() {
mySize = mapSize;
print("mySize:" + mySize.toString());
});
},
child: ()
```
Upvotes: 2 <issue_comment>username_13: ```
**Credit to @Manuputty**
class OrigChildWH extends StatelessWidget {
final Widget Function(BuildContext context, Size size, Widget? child) builder;
final Widget? child;
const XRChildWH({
Key? key,
required this.builder,
this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return OrientationBuilder(builder: (context, orientation) {
return ChildSizeNotifier(builder: builder);
});
}
}
class ChildSizeNotifier extends StatelessWidget {
final ValueNotifier notifier = ValueNotifier(const Size(0, 0));
final Widget Function(BuildContext context, Size size, Widget? child) builder;
final Widget? child;
ChildSizeNotifier({
Key? key,
required this.builder,
this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
WidgetsBinding.instance!.addPostFrameCallback(
(\_) {
notifier.value = (context.findRenderObject() as RenderBox).size;
},
);
return ValueListenableBuilder(
valueListenable: notifier,
builder: builder,
child: child,
);
}
}
\*\*Simple to use:\*\*
OrigChildWH(
builder: (context, size, child) {
//Your child here: mine:: Container()
return Container()
})
```
Upvotes: -1 <issue_comment>username_14: This is [Remi's answer](https://stackoverflow.com/questions/49307677/how-can-i-get-the-height-of-a-widget/49650741#49650741) with null safety. Since the edit queue is full, I have to post it here.
```
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
MyHomePageState createState() => MyHomePageState();
}
class MyHomePageState extends State {
final controller = ScrollController();
OverlayEntry? sticky;
GlobalKey stickyKey = GlobalKey();
@override
void initState() {
sticky?.remove();
sticky = OverlayEntry(
builder: (context) => stickyBuilder(context),
);
SchedulerBinding.instance
.addPostFrameCallback((\_) => Overlay.of(context)?.insert(sticky!));
super.initState();
}
@override
void dispose() {
sticky?.remove();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
body: ListView.builder(
controller: controller,
itemBuilder: (context, index) {
if (index == 6) {
return Container(
key: stickyKey,
height: 100.0,
color: Colors.green,
child: const Text("I'm fat"),
);
}
return ListTile(
title: Text(
'Hello $index',
style: const TextStyle(color: Colors.white),
),
);
},
),
);
Widget stickyBuilder(BuildContext context) => AnimatedBuilder(
animation: controller,
builder: (\_, Widget? child) {
final keyContext = stickyKey.currentContext;
if (keyContext == null || !keyContext.mounted) {
return Container();
}
final box = keyContext.findRenderObject() as RenderBox;
final pos = box.localToGlobal(Offset.zero);
return Positioned(
top: pos.dy + box.size.height,
left: 50.0,
right: 50.0,
height: box.size.height,
child: Material(
child: Container(
alignment: Alignment.center,
color: Colors.purple,
child: const Text("Nah I think you're okay"),
),
),
);
},
);
}
```
Upvotes: 1 <issue_comment>username_15: In cases where you don't want to wait for a frame to get the size, but want to know it *before* including it in your tree:
The simplest way is to follow the example of the [BuildOwner](https://api.flutter.dev/flutter/widgets/BuildOwner-class.html) documentation.
With the following you can just do
```dart
final size = MeasureUtil.measureWidget(MyWidgetTree());
```
```dart
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Small utility to measure a widget before actually putting it on screen.
///
/// This can be helpful e.g. for positioning context menus based on the size they will take up.
///
/// NOTE: Use sparingly, since this takes a complete layout and sizing pass for the subtree you
/// want to measure.
///
/// Compare https://api.flutter.dev/flutter/widgets/BuildOwner-class.html
class MeasureUtil {
static Size measureWidget(Widget widget, [BoxConstraints constraints = const BoxConstraints()]) {
final PipelineOwner pipelineOwner = PipelineOwner();
final _MeasurementView rootView = pipelineOwner.rootNode = _MeasurementView(constraints);
final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
final RenderObjectToWidgetElement element = RenderObjectToWidgetAdapter(
container: rootView,
debugShortDescription: '[root]',
child: widget,
).attachToRenderTree(buildOwner);
try {
rootView.scheduleInitialLayout();
pipelineOwner.flushLayout();
return rootView.size;
} finally {
// Clean up.
element.update(RenderObjectToWidgetAdapter(container: rootView));
buildOwner.finalizeTree();
}
}
}
class \_MeasurementView extends RenderBox with RenderObjectWithChildMixin {
final BoxConstraints boxConstraints;
\_MeasurementView(this.boxConstraints);
@override
void performLayout() {
assert(child != null);
child!.layout(boxConstraints, parentUsesSize: true);
size = child!.size;
}
@override
void debugAssertDoesMeetConstraints() => true;
}
```
This creates an entirely new render tree separate from the main one, and won’t be shown on your screen.
So for example
```dart
print(
MeasureUtil.measureWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.abc),
SizedBox(
width: 100,
),
Text("<NAME>")
],
),
),
),
);
```
Would give you `Size(210.0, 24.0)`.
Upvotes: 3
|
2018/03/15
| 845 | 3,036 |
<issue_start>username_0: It's just a simple question but couldn't find any helpful solution or hints...I have the current TYPO3 version and watched some videos on YouTube about it and wondered why I have no autocomplete when writing some TypoScript.
I saw it in this video: <https://www.youtube.com/watch?v=ZCSIK3lFfwM&list=PL1D69sw7eWECaiqIOLhcSnjgTTjLJdd4I&index=5> at 03:45
Is it possible to do it in the newest version or do I have to use an IDE?<issue_comment>username_1: ---
The TYPO3 core offers the extension "**t3editor**", which is based on CodeMirror and provides syntax highlighting and codecompletion.
I suspect it just isn't activated in your TYPO3 instance. You can check this in the Extension Manager in your TYPO3 backend.
---
**1st edit:** As the extension seems to be working in general – please try writing `config.` on a new line in your editor. The Top Level Objects (e.g. *config*) aren't auto-completed in the backend, but it should open a box with suggested configurations after you wrote the dot.
t3editor has some restrictions: Nesting isn't supported (see example below). I read it can have problems inside conditions, too.
```
// This is auto-completed:
config.no_cache = 1
// This isn't:
config {
no_cache = 1
}
```
In short: t3editor can only help you to a certain degree. It is considered best practice to save all TypoScript (and everything else related to templating) in files into a dedicated templating extension (or *sitepackage*) and use an IDE. There are TypoScript auto-complete plugins for several editors and IDEs, for example PhpStorm.
---
If you want more information about using sitepackages, see [this video series on YouTube](https://www.youtube.com/watch?v=HtBmim7pc0o "Tutorial - Site Packages - Part 1") by the offical TYPO3 account, or take a look at [my personal templating extension](https://github.com/username_1/basetemplate8 "basetemplate8 on GitHub") which I use for new websites.
---
**2nd edit:** After you wrote you're using the Sprint Release 9.1.0, I was able to test the behaviour in this version and can confirm that code completion won't work in it.
Actually, that seems to be the intended future behaviour of *t3editor* for the TYPO3 core team. They want to remove this extension in TYPO3 v10 altogether (it's planned to be available on GitHub then). The reason is that they don't recommend to use/save TypoScript directly in the database, but in a separate template extension (see explanation above).
Sources:
* [TYPO3 Bug tracker, issue #81885](https://forge.typo3.org/issues/81885)
* Communication platform [TYPO3 Slack](https://forger.typo3.com/slack), Channel `#typo3-cms-coredev`, Nov 19th, 2017
So again, I recommend to use an API instead.
Upvotes: 1 <issue_comment>username_2: First install the extension ts3editor.
Then you can "activate" auto complete just by pressing CTRL+SPACE. For example, write:
->config.
then press
->"CTRL+SPACE"
then the autocomplete advice/suggestion will pop-up.
I use version 9 and it works fine.
Upvotes: 2
|
2018/03/15
| 784 | 3,150 |
<issue_start>username_0: I wrote some code to get data from Firebase, but it shows some errors. I will explain the errors below and attach a picture.

**First error when I put the mouse on it, message show:**
'onStart()' in 'com.abdullrahman.eng.myapp.FriendsFragment' clashes with 'onStart()' in 'android.app.Fragment'; attempting to assign weaker access privileges ('protected'); was 'public'
**Second error when I put the mouse on it, message show:**
Method does not override method from its superclass
Can anyone solve these problems and help me?
The code:
```
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter(
Friends.class,
R.layout.users\_single\_layout,
FriendsViewHolder.class,
mUsersDatabase
) {
@Override
protected void populateViewHolder(FriendsViewHolder friendsViewHolder, Friends friends, int position) {
friendsViewHolder.setDisplayName(friends.getName());
friendsViewHolder.setUserStatus(friends.getStatus());
friendsViewHolder.setUserImage(friends.getThumb\_image(), mMainView.getContext());
final String user\_id = getRef(position).getKey();
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent profileIntent = new Intent(getActivity(), UserProfile.class);
profileIntent.putExtra("user\_id", user\_id);
startActivity(profileIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
```<issue_comment>username_1: Errors do say a lot about the problem you have.
The first error is caused by `protected` access modifier on the onStart() method, while it should be `public`.
It should be
```
@Override
public void onStart() {
super.onStart();
// rest of the code
}
```
instead of
```
@Override
protected void onStart() {
super.onStart();
// rest of the code
}
```
You can find some more information about the error reason in [docs available on Oracle site](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8.3).
The second problem is related to the definition of FirebaseRecyclerAdapter. Looks like there is no method like
```
protected void populateViewHolder(FriendsViewHolder friendsViewHolder, Friends friends, int position).
```
I'd suggest checking docs/sources of this class to get info about how the override method should look for the version of Firebase you are using in your project.
Also, as I can see you are using IntelliJ IDEA or some similar IDE, so you can use [built-in feature to implement/override the correct method](https://www.jetbrains.com/help/idea/overriding-methods-of-a-superclass.html).
Upvotes: 2 [selected_answer]<issue_comment>username_2: Change your protected modifier to public and it'll go away.
In Java, the overriding method can have the same or weaker access compared to the parent method... Here the parent class declares the method as public so you have no other choice but to override it with a public access modifier as it's the weakest access possible.
Upvotes: 0
|
2018/03/15
| 988 | 3,591 |
<issue_start>username_0: I'm trying to manipulate views inside a dialog, but the only way I can retrieve the views is in the Java old fashioned way, like this:
```
class MyDialog: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val alert = AlertDialog.Builder(context!!)
val inflater = LayoutInflater.from(activity)
val view = inflater?.inflate(R.layout.pg_dialog, null)
with(alert) {
setView(view)
setNeutralButton(R.string.scambio_back, DialogInterface.OnClickListener({ _: DialogInterface, _: Int -> dialog.dismiss() }))
}
view?.findViewById(R.id.dialog\_name)?.text = person.name
view?.findViewById(R.id.dialog\_surname)?.text = person.surname
return alert.create()
}
}
```
Do you know any way to retrieve inner views in Kotlin, avoiding findViewById?
[Edit] Here's the build.gradle file:
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.project.persons"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.android.support:support-v4:27.0.2'
// Firebase
implementation 'com.google.firebase:firebase-auth:11.8.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
implementation 'com.firebaseui:firebase-ui-auth:3.2.2'
implementation 'com.facebook.android:facebook-android-sdk:4.30.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'
```<issue_comment>username_1: Since your question is a little bit unclear I'd say you refer to do something like this :
Do import `apply plugin: 'kotlin-android-extensions` in your `build.gradle`
Then you have to import this in your `Activity`
```
import kotlinx.android.synthetic.main.activity_pg_dialog.*
```
If you for example have a `TextView` with an id `test` you could do this:
```
test.setText("test text!!")
```
References :
[Documentation Kotlin Android Extensions](https://kotlinlang.org/docs/tutorials/android-plugin.html)
[Example Kotlin Android Extendions](https://antonioleiva.com/kotlin-android-extensions/)
Upvotes: -1 <issue_comment>username_2: In this case, when you're not in a `Fragment` or an `Activity`, but have a `View` reference that you want to search for children with a given ID, you can use Kotlin Android Extensions with this syntax:
```
view.dialog_name.text = person.name
view.dialog_surname.text = person.surname
```
As with always when using Extensions, make sure you have the correct imports.
Upvotes: 2
|
2018/03/15
| 815 | 2,703 |
<issue_start>username_0: I've this HTML / Javascript code ....
```
Title
var city= "Torino";
$.ajax({
url: "http://www.mysite1.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php?",
method: "GET",
crossDomain: true,
data: {municipality: city, distance:0}
})
.done(function(output) {
alert("OK!");
})
.fail(function() {
// handle error response
alert("KO!");
})
```
... published here ...
```
http://www.mysite2.com/OpenProntoSoccorso/WebMapping/test2.html
```
In the web server (Apache 2.4 on Ubuntu 14.04) <http://www.mysite1.org/>.... I've modified my apache2.conf file in this way ....
```
Order Allow,Deny
Allow from all
AllowOverride all
Header set Access-Control-Allow-Origin "\*"
```
following these instructions [How to allow Cross domain request in apache2](https://stackoverflow.com/questions/29150384/how-to-allow-cross-domain-request-in-apache2).
I've still the following error in my web browser console (Network tab ..)
```
Failed to load http://www.mysite1.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php?&municipality=Torino&distance=0: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mysite2.com' is therefore not allowed access.
```
Where am I doing wrong?
Thanks in advance<issue_comment>username_1: I've found that there was an error in my apache2.conf file ....
This is the right configuration (forgot "html" after "www" .. sorry ...) ...
```
Order Allow,Deny
Allow from all
AllowOverride all
Header set Access-Control-Allow-Origin "\*"
```
All works fine now ...
Upvotes: 1 <issue_comment>username_2: Ubuntu Apache2 solution that worked for me
.htaccess edit did not work for me I had to modify the conf file.
>
> nano /etc/apache2/sites-available/mydomain.xyz.conf
>
>
>
```
ServerName mydomain.xyz
ServerAlias www.mydomain.xyz
ServerAdmin <EMAIL>
DocumentRoot /var/www/mydomain.xyz/public
### following three lines are for CORS support
Header add Access-Control-Allow-Origin "\*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
ErrorLog ${APACHE\_LOG\_DIR}/error.log
CustomLog ${APACHE\_LOG\_DIR}/access.log combined
SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem
```
then type the following command
-------------------------------
>
> a2enmod headers
>
>
>
make sure cache is clear before trying
--------------------------------------
Upvotes: 0
|
2018/03/15
| 826 | 3,013 |
<issue_start>username_0: How can I know if a class is annotated with `javax.persistence.Entity`?
**Person (Entity)**
```
@Entity
@Table(name = "t_person")
public class Person {
...
}
```
**PersonManager**
```
@Stateless
public class PersonManager {
@PersistenceContext
protected EntityManager em;
public Person findById(int id) {
Person person = this.em.find(Person.class, id);
return person;
}
```
I try to do it with instance of as the following
```
@Inject
PersonManager manager;
Object o = manager.findById(1);
o instanceof Entity // false
```
however the result is `false`, shouldn't it be `true`?<issue_comment>username_1: If the statement
```
sessionFactory.getClassMetadata( HibernateProxyHelper.getClassWithoutInitializingProxy( Person.class ) ) != null;
```
is true, than it is an entity.
Upvotes: 1 <issue_comment>username_2: @NiVer's answer is valid. But, if you don't have a session or sessionFactory at that point you could use Reflection. Something like:
```
o.getClass().getAnnotation(Entity.class) != null;
```
Upvotes: 1 <issue_comment>username_3: While the existing answers provide a (somehow) working solution, some things should be noted:
1. Using an approach based on Reflection implies (a) Performance Overhead and (b) Security Restrictions (see [Drawbacks of Reflection](https://docs.oracle.com/javase/tutorial/reflect/)).
2. Using an ORM-specific (here: Hibernate) approach risks portability of the code towards other execution environments, i.e., application containers or other customer-related settings.
Luckily, there is a third *JPA*-only way of detecting whether a certain Java class (type) is a (managed) `@Entity`. This approach makes use of standardized access to the `javax.persistence.metamodel.MetaModel`. With it you get the method
>
> Set < EntityType > getEntities();
>
>
>
It only lists types annotated with `@Entity` AND which are detected by the current instance of EntityManager you use. With every object of `EntityType` it is possible to call
>
> Class< ? > getJavaType();
>
>
>
For demonstration purposes, I quickly wrote a method which requires an instance of `EntityManager` (here: `em`), either injected or created ad-hoc:
```
private boolean isEntity(Class clazz) {
boolean foundEntity = false;
Set> entities = em.getMetamodel().getEntities();
for(EntityType entityType :entities) {
Class entityClass = entityType.getJavaType();
if(entityClass.equals(clazz)) {
foundEntity = true;
}
}
return foundEntity;
}
```
You can provide such a method (either public or protected) in a central place (such as a Service class) for easy re-use by your application components. The above example shall just give a direction of what to look for aiming at a pure *JPA* approach.
For reference see sections 5.1.1 (page 218) and 5.1.2 (page 219f) of the [JPA 2.1 specification](http://download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf).
Hope it helps.
Upvotes: 2
|
2018/03/15
| 313 | 1,305 |
<issue_start>username_0: I am writing a function that when clicking on an image, it will add an event listener to another image. When creating the event listener, myFunction() is being called right away and not waiting for the click on #firstStep
```
function firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click", myFunction());
}
```<issue_comment>username_1: The parameter should be `myFunction` instead of `myFunction()`.
Upvotes: 2 <issue_comment>username_2: You're not adding the `myFunction` as callback, but the return of the call to `myFunction`.
You must pass the function, not invoke it:
```
enfunction firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click", myFunction);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: call that function like below
```
function firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click",
myFunction);
}
```
remove parenthesis from `myFunction`.
Upvotes: 1 <issue_comment>username_4: The parenthesis make the function fire straight away. Change the end of your snippet by taking out the parenthesis.
`("click", myFunction());` to `("click", myFunction);`
Upvotes: 0
|
2018/03/15
| 1,176 | 4,995 |
<issue_start>username_0: I have a generic repository architecture that looks like this:
**Repository**
```
public interface IRepository where T: class
{
IList Get(Func where);
}
public abstract class Repository : IRepository where T: class
{
private readonly DbSet \_entity;
protected Repository(ApplicationDbContext dbContext)
{
\_entity = dbContext.Set();
}
public IList Get(Func where)
{
return \_entity.Where(where).ToList();
}
}
```
Then concrete implementations are created like this:
**UserRepository**
```
public class UserRepository : Repository
{
public UserRepository(ApplicationDbContext dbContext) : base(dbContext) {}
// Can add any other methods I want that aren't included in IRepository
}
```
I'll likely have quite a few services, so rather than having each one passed into the controller individually, I thought I'd try passing in a single factory that can produce repositories for me.
**RepositoryFactory**
```
public interface IRepositoryFactory
{
T GetRepository() where T : class;
}
public class RepositoryFactory : IRepositoryFactory
{
private readonly IServiceProvider \_provider;
public RepositoryFactory(IServiceProvider serviceProvider)
{
\_provider = serviceProvider;
}
public T GetRepository() where T : class
{
return \_provider.GetRequiredService(); // ERROR: No service for type 'UserRepository' has been registered
}
}
```
Now, in setting up dependency injection, I registered the services like this:
**Startup.cs**
```
public void ConfigureServices(IServiceCollection services)
{
// [...]
services.AddScoped, UserRepository>();
services.AddScoped();
// [...]
}
```
This is all used in the controller like this:
**Controller**
```
public class HomeController : Controller
{
private readonly UserRepository _userRepository;
public HomeController(IRepositoryFactory repositoryFactory)
{
_userRepository = repositoryFactory.GetRepository(); // ERROR: No service for type 'UserRepository' has been registered
}
// [...]
}
```
When I call `_provider.GetRequiredService()` in the `repositoryFactory.GetRepository()` method, I get the error in the comment above.
The `RepositoryFactory` is coming through just fine, but the `UserRepository` isn't getting registered. What am I missing? I've tried calling the `GetRepository` method outside of the constructor, and I've tried change `AddScoped` to the other `Add` variants (Transient and Singleton), but to no avail.<issue_comment>username_1: You are taking dependency on `UserRepository`, which is implementation and not interface, that's not good (given that you actually have that interface registered in container). Instead you need to take dependency on interface: `IRepository`. So change your factory interface:
```
public interface IRepositoryFactory
{
IRepository GetRepository() where T : class;
}
```
Implementation:
```
public IRepository GetRepository() where T : class
{
return \_provider.GetRequiredService>(); // ERROR: No service for type 'UserRepository' has been registered
}
```
And controller:
```
public class HomeController : Controller
{
private readonly IRepository \_userRepository;
public HomeController(IRepositoryFactory repositoryFactory)
{
\_userRepository = repositoryFactory.GetRepository(); // ERROR: No service for type 'UserRepository' has been registered
}
// [...]
}
```
Now it doesn't work, because you registered `IRepository` in container (with implementation being `UserRepository`), but `UserRepository` which you are trying to resolve is not registered (and as said above - you should not resolve it anyway).
Upvotes: 4 [selected_answer]<issue_comment>username_2: Looks like my problem had to do with my understanding of `AddScoped`. Looking at the docs, the two type parameters in `AddScoped` are `TService` and `TImplementation`. So in my Startup class above, the **SERVICE** I'm registering is `IRepository`, not `ApplicationRepository`. The **IMPLEMENTATION** I'm registering is `ApplicationRepository`.
To fix this, I changed my `Startup` class to say that `UserRepository` is the service being registered.
```
public void ConfigureServices(IServiceCollection services)
{
// [...]
// OLD: services.AddScoped, UserRepository>();
services.AddScoped();
services.AddScoped();
// [...]
}
```
But this approach relies on an implementation rather than an abstraction (interface), so I took it a step further and introduced an interface for the `UserRepository` class and registered that in `Startup`.
**UserRepository**
```
public interface IUserRepository : IRepository
{
void DoTheThing();
}
public class UserRepository : Repository, IUserRepository
{
public UserRepository(ApplicationDbContext dbContext) : base(dbContext) {}
public void DoTheThing()
{
}
}
```
**Startup**
```
public void ConfigureServices(IServiceCollection services)
{
// [...]
services.AddScoped();
services.AddScoped();
// [...]
}
```
Upvotes: 3
|
2018/03/15
| 435 | 1,477 |
<issue_start>username_0: My code (simplified):
HTML:
```
Title
Title
=====
```
JS:
```
const container = document.querySelector('#container');
for (i = 0; i < 16; i++) {
for (let x = 0; x < 16; x++) {
const cellSize = 512 / 16;
const cell = document.createElement('div');
cell.style.width = cellSize + 'px';
cell.style.height = cellSize + 'px';
container.appendChild(cell);
}
};
```
Console:
```
Uncaught TypeError: Cannot read property 'appendChild' of null
```
What have I done wrong here? It might just be my browser (I'm using Chrome). Is it because the constants are being referenced inside the for loop?<issue_comment>username_1: Your document is not ready yet. You need to wait for the document to be rendered before applying JavaScript to it.
Therefore you should call your script after the HTML.
```
Title
Title
=====
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: You should use `getElementById()` instead to retrieve your `div`. Try this:
```
var container = document.getElementById('container');
for (i = 0; i < 16; i++) {
for (let x = 0; x < 16; x++) {
var cellSize = 512 / 16;
var cell = document.createElement('div');
cell.style.opacity = 0.0;
cell.style.width = cellSize + 'px';
cell.style.height = cellSize + 'px';
container.appendChild(cell);
}
};
```
Also make sure the script runs AFTER loading the html.
Upvotes: -1
|
2018/03/15
| 410 | 1,438 |
<issue_start>username_0: So I want to know if there is a possible way to add a box where it says my previous calculations. For example, if I put 4+4=8 then there would be a box where it says that... previous calculation was 4+4=8
Here is my code, but I don't know how to add the box to this code.
```
Kalkulaator
function calc()
{
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
var oper = document.getElementById('operaatorid').value;
if(oper === '+')
{
document.getElementById('tulemus').value = number1+number2;
}
}
+
=
```<issue_comment>username_1: Your document is not ready yet. You need to wait for the document to be rendered before applying JavaScript to it.
Therefore you should call your script after the HTML.
```
Title
Title
=====
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: You should use `getElementById()` instead to retrieve your `div`. Try this:
```
var container = document.getElementById('container');
for (i = 0; i < 16; i++) {
for (let x = 0; x < 16; x++) {
var cellSize = 512 / 16;
var cell = document.createElement('div');
cell.style.opacity = 0.0;
cell.style.width = cellSize + 'px';
cell.style.height = cellSize + 'px';
container.appendChild(cell);
}
};
```
Also make sure the script runs AFTER loading the html.
Upvotes: -1
|
2018/03/15
| 882 | 2,842 |
<issue_start>username_0: I have a bash `while read line` block reading from a text file specified by `$filename`:
```
IFS=''
while read -r line
do
...
done < $filename
```
Instead of reading the whole file each time, I would like to supply different inputs in the redirect depending on the arguments supplied to the script.
* Whole file: `done < "$filename"`
* start at line x: `done < <(tail -n +"$x" "$filename")`
* line x to line y: `done < <(tail -n +"$x" "$filename" | head -n "$y")`
* start to line y: `done < <(head -n "$y" "$filename")`
How can I assign these inputs to a variable ahead of time to be read by the while loop?
---
My input file is ~4GB with some 58M lines (all with different lengths), and may grow or shrink from time to time. Reading <https://unix.stackexchange.com/questions/47407/cat-line-x-to-line-y-on-a-huge-file> it appears that `tail | head` is the fastest method to read from the middle of a file, so given the file size, I'm deliberately avoiding `awk` and `sed` for the most part.<issue_comment>username_1: I might handle all of these as part of the loop condition, with an explicitly maintained line counter.
```
start=10
end=30
i=0
while ((i <= end )) && IFS= read -r line; do
(( i++ >= start )) || continue
...
done < "$filename"
```
However, if you might skip a significant number of lines at the beginning, it might be more efficient to use `sed`
```
while IFS= read -r line; do
...
done < <(sed -n "$start,$stop p" "$filename")
```
or `awk`:
```
while IFS= read -r line; do
...
done < <(awk -v start "$start" -v end "$end" 'NR >= start && NR <= end' "$filename")
```
This then raises the question of how much of the body of the `while` loop can be moved into `awk` itself.
Upvotes: 1 <issue_comment>username_2: Your data is too big to read in whole. The good news is that the contents of a process substitution is a shell script, so you can write:
```
while IFS= read -r line; do
...
done < <(
if [[ $x && $y ]]; then tail -n +"$x" "$filename" | head -n "$y"
elif [[ $x ]]; then tail -n +"$x" "$filename"
elif [[ $y ]]; then head -n "$y" "$filename"
else cat "$filename"
fi
)
```
One thing I don't like about process substitutions is that code **follows** the loop for which it is input. It would be nice if it appeared first. I think this will work, but is untested:
```
# set up file descriptor 3
exec 3< <(
if [[ $x && $y ]]; then tail -n +"$x" "$filename" | head -n "$y"
elif [[ $x ]]; then tail -n +"$x" "$filename"
elif [[ $y ]]; then head -n "$y" "$filename"
else cat "$filename"
fi
)
# iterate over lines read from fd 3
while IFS= read -u3 -r line; do
...
done
# close fd 3
exec 3<&-
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 344 | 1,270 |
<issue_start>username_0: Hi I'm trying to execute a function if the dropdown-menu of bootstrap is closed. Surely I can just add the function call if the menu dropdown-toggle is click. But my concern is what if the user didn't click the dropdown-toggle but instead clicked outside or on other element. The dropdown-menu closes if I click on other element.
Is there a way or is there any callback on bootstrap if the dropdown-menu is closed?
I tried this but its not working
```
$('.dropdown-menu').on('shown.bs.collapse', function(e) {
alert("Close");
});
```<issue_comment>username_1: Try with this parameter:
```
$('.dropdown-menu').on('hidden.bs.dropdown', function(e) {
alert("Close");
})
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can find dropdown events over here
<https://getbootstrap.com/docs/3.3/javascript/#dropdowns-events>
For quick help
```
$('.dropdown-menu').on('hide.bs.dropdown', function () {
// your code goes here when dropdown closed
})
```
Upvotes: 2 <issue_comment>username_3: Struggle with this today and resolve it selecting the button id and not the menu class. I was using Bootstrap 5
```
$('#myDropdownBtnId').on('hidden.bs.dropdown', function(e) {
alert("Dropdown closed!!!");
})
```
Upvotes: 0
|
2018/03/15
| 645 | 2,023 |
<issue_start>username_0: I have a php script that sends emails using PHPMailer see below:
```
$mail = new PHPMailer(true);
try {
$debug = NULL;
$mail->Debugoutput = function($str, $level) {
$GLOBALS['debug'] .= "$level: $str\n";
};
$mail->isSMTP();
$mail->Host = 'xxxxxxx';
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Username = 'xxxxxx';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('<EMAIL>', 'xxx');
$mail->addAddress('<EMAIL>');
$mail->isHTML(true);
$mail->Subject = 'xx';
$email_content = 'test
';
$mail->Body = $email_content;
$mail->send();
fncSaveLog($debug);
} catch (Exception $e) {
fncSaveLog($mail->ErrorInfo);
}
```
the fncSaveLog is a function that saves debug info to database but I see always NULL for debug in my DB, it seems the output is never caught. Any idea how to fix this please?
Thanks.<issue_comment>username_1: To throw an exception in Php you have to use
```
throw new Exception('Your exception message');
```
Then your catch statement will show you your error message,
use this to look for errors.
Upvotes: 0 <issue_comment>username_2: Your setting `NULL` to save into the db. Try the below instead:
```
$mail = new PHPMailer(true);
try {
$mail->Debugoutput = function($str, $level) {
$GLOBALS['debug'] .= "$level: $str\n";
};
$mail->isSMTP();
$mail->Host = 'xxxxxxx';
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Username = 'xxxxxx';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('<EMAIL>', 'xxx');
$mail->addAddress('<EMAIL>');
$mail->isHTML(true);
$mail->Subject = 'xx';
$email_content = 'test
';
$mail->Body = $email_content;
$mail->send();
$debug = $GLOBALS['debug'];
fncSaveLog($debug);
} catch (Exception $e) {
fncSaveLog($mail->ErrorInfo);
}
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 569 | 1,763 |
<issue_start>username_0: I am attempting to change the asl of a file (100KB.file) I have within IBM COS: bucket: 'devtest1.ctl-internal.nasv.cos' and am receiving the following message:
>
> An error occurred (AccessDenied) when calling the PutObjectAcl
> operation: Access Denied
>
>
>
It seems like my AWS credentials (or call) do not have the correct permissions to allow the ACL update.
Command:
>
> aws --endpoint-url=<https://s3.us-south.objectstorage.softlayer.net>
> s3api put-object-acl --bucket devtest1.ctl-internal.nasv.cos --key
> 100KB.file --acl public-read
>
>
>
Return:
>
> An error occurred (AccessDenied) when calling the PutObjectAcl
> operation: Access Denied
>
>
><issue_comment>username_1: To throw an exception in Php you have to use
```
throw new Exception('Your exception message');
```
Then your catch statement will show you your error message,
use this to look for errors.
Upvotes: 0 <issue_comment>username_2: Your setting `NULL` to save into the db. Try the below instead:
```
$mail = new PHPMailer(true);
try {
$mail->Debugoutput = function($str, $level) {
$GLOBALS['debug'] .= "$level: $str\n";
};
$mail->isSMTP();
$mail->Host = 'xxxxxxx';
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Username = 'xxxxxx';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('<EMAIL>', 'xxx');
$mail->addAddress('<EMAIL>');
$mail->isHTML(true);
$mail->Subject = 'xx';
$email_content = 'test
';
$mail->Body = $email_content;
$mail->send();
$debug = $GLOBALS['debug'];
fncSaveLog($debug);
} catch (Exception $e) {
fncSaveLog($mail->ErrorInfo);
}
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 5,520 | 17,261 |
<issue_start>username_0: I am beginner in Spring boot programming. But I am still creating a software application which is based on shopping cart web, being developed with Spring boot. But suddenly, I got an error again and again which returns null and null point exception inside in save function(Repository).
I don't know why. I have tried several times to execute but It won't work. I don't know about spring boot debugging with remote servers. Anyway, I used jsp pages as my view to return all the data and test. That is how I testing.
This is my Controller
```
@RequestMapping(value = "/addwishlist", method = RequestMethod.GET)
public ModelAndView AddToWishlist(@Valid @ModelAttribute Adds add, BindingResult bindingResult, HttpSession session) {
String usrnm = (String) session.getAttribute("username");
Adds adds = addsService.getAddById(add.getAdid());
//wishlist wish = new wishlist(,,,,,usrnm);
ModelAndView model = new ModelAndView();
wishlist wish = new wishlist();
wish.setAdID(add.getAdid());
wish.setAdtitle(add.getAdtitle());
wish.setAdprice(6);
wish.setAdquantity(545);
wish.setPictureurl1(add.getPictureurl1());
wish.setUsername(usrnm);
if (wishService.WishListSave(wish)) {
return new ModelAndView("redirect:/viewishlist");
} else {
model.addObject("user", new User());
model.setViewName("login");
return model;
}
}
```
This is my Repository
```
public interface WishRepository extends CrudRepository {
}
```
This is my service package which includes Services and Service implementation
```
public interface WishService {
public boolean WishListSave(wishlist wish);
public boolean WishListDelete(wishlist wish);
public boolean WishlistClean(String username);
public List CheckWithUsername(String username);
public wishlist ViewOneWishList(String username,int adid);
}
package rego.webapp.de.repositoryservices;
import java.util.List;
import org.springframework.stereotype.Service;
import rego.webapp.de.models.wishlist;
import rego.webapp.de.repositories.WishRepository;
@Service("wishService")
public class WishServiceImpl implements WishService {
public WishRepository wishRepository;
@Override
public boolean WishListSave(wishlist wish) {
if(wish!=null)
{
wishRepository.save(wish);
return true;
}
else
{
return false;
}
}
```
Did I do something wrong?. According to my idea I have already done implementing , but it returns false, as in null "wish" object. I don't know why. Please help me. Thanks in advnace.:)
**Exception**
```
java.lang.NullPointerException: null at thanu.webapp.sena.repositoryservices.WishServiceImpl.WishListSave(WishServiceImpl.java:20) ~[classes/:na] at thanu.webapp.sena.controllers.WishController.AddToWishlist(WishController.java:79) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151] at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_151] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_151] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23] at java.lang.Thread.run(Unknown Source) [na:1.8.0_151]
```<issue_comment>username_1: You're not initializing `wishRepository` in your service, so it is always `null`, and then you attempt to use it. Autowire it in from Spring in your constructor.
```
public class WishServiceImpl implements WishService {
private final WishRepository wishRepository;
@Autowired
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
// etc.
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try putting `@Autowired` on `public WishRepository wishRepository;`, or declare the variable as `private final`, create a constructor for it and mark the constructor as `@Autowired`
Upvotes: 0 <issue_comment>username_3: You didn't initialize `public WishRepository wishRepository` in your `WishServiceImpl`, so it is null. use `@Autowired` above the field, or even better, make a constructor and use `@Autowired` above it(for the reason to which constructor injection is better, google "field vs constructor injection"). The annotation tells spring to inject an instance to the field.
Upvotes: 0 <issue_comment>username_4: In your `WishServiceImpl` class mark the `WishRepository` with `@Autowired` annotation. Without this annotation container(Spring) will never know that is dependency should be injected.
From Spring version 4.3 if your class only one constructor it is not necessary to mark the constructor with `@Autowired` annotation.
```
public class WishServiceImpl implements WishService {
public WishRepository wishRepository;
// No need the annotation as this class only one constructor.
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
}
```
from Spring documentation
>
> So as of 4.3, you no longer need to specify an explicit injection annotation in such a single-constructor scenario. This is particularly elegant for classes which otherwise do not carry any container annotations at all.
>
>
>
Upvotes: 0
|
2018/03/15
| 543 | 2,340 |
<issue_start>username_0: I have an angular x(2 4 5) app, and i must make a post redirect to a bank page, so the user can pay something.
So, I want to create a form on the fly in my DOM and post it. Can't find the best way. It's easy to loop and create a form, but not easy to directly post it after drawing it.
thanks in advance<issue_comment>username_1: You're not initializing `wishRepository` in your service, so it is always `null`, and then you attempt to use it. Autowire it in from Spring in your constructor.
```
public class WishServiceImpl implements WishService {
private final WishRepository wishRepository;
@Autowired
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
// etc.
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try putting `@Autowired` on `public WishRepository wishRepository;`, or declare the variable as `private final`, create a constructor for it and mark the constructor as `@Autowired`
Upvotes: 0 <issue_comment>username_3: You didn't initialize `public WishRepository wishRepository` in your `WishServiceImpl`, so it is null. use `@Autowired` above the field, or even better, make a constructor and use `@Autowired` above it(for the reason to which constructor injection is better, google "field vs constructor injection"). The annotation tells spring to inject an instance to the field.
Upvotes: 0 <issue_comment>username_4: In your `WishServiceImpl` class mark the `WishRepository` with `@Autowired` annotation. Without this annotation container(Spring) will never know that is dependency should be injected.
From Spring version 4.3 if your class only one constructor it is not necessary to mark the constructor with `@Autowired` annotation.
```
public class WishServiceImpl implements WishService {
public WishRepository wishRepository;
// No need the annotation as this class only one constructor.
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
}
```
from Spring documentation
>
> So as of 4.3, you no longer need to specify an explicit injection annotation in such a single-constructor scenario. This is particularly elegant for classes which otherwise do not carry any container annotations at all.
>
>
>
Upvotes: 0
|
2018/03/15
| 812 | 3,265 |
<issue_start>username_0: I am currently learning Swift and can not continue. I create a dice game. If the "if query" is true, the program should pause briefly before a new query is possible.
```
@IBAction func guess(_ sender: Any) {
let diceRoll = arc4random_uniform(5)
let fingerErgebnis = diceRoll + 1
let fingerAntwort = String(fingerErgebnis)
if fingerTextfield.text == fingerAntwort{
ergebnis.text = "Richtig erraten!"
ergebnis.textColor = UIColor.green
ergebnis.font = ergebnis.font.withSize(20)
bild.image = UIImage(named: ("win.jpg"))
button.setTitle("Neues Spiel!", for: .normal)
fingerTextfield.text = " "
sleep (2)
}else if fingerErgebnis == 1 {
ergebnis.text = "Leider falsch! Die Zahl war \(fingerAntwort)."
ergebnis.textColor = UIColor.red
bild.image = UIImage(named: ("finger1.jpg"))
button.setTitle("Versuch es nochmal!", for: .normal)
} ...
```
As far as everything works, but I want that everything is running first and I have to wait 2 seconds until I can click the button again. My test is paused first, then the rest of the if commands are executed. I want that the other way around.
Sorry for my terrible english ;)<issue_comment>username_1: You're not initializing `wishRepository` in your service, so it is always `null`, and then you attempt to use it. Autowire it in from Spring in your constructor.
```
public class WishServiceImpl implements WishService {
private final WishRepository wishRepository;
@Autowired
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
// etc.
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try putting `@Autowired` on `public WishRepository wishRepository;`, or declare the variable as `private final`, create a constructor for it and mark the constructor as `@Autowired`
Upvotes: 0 <issue_comment>username_3: You didn't initialize `public WishRepository wishRepository` in your `WishServiceImpl`, so it is null. use `@Autowired` above the field, or even better, make a constructor and use `@Autowired` above it(for the reason to which constructor injection is better, google "field vs constructor injection"). The annotation tells spring to inject an instance to the field.
Upvotes: 0 <issue_comment>username_4: In your `WishServiceImpl` class mark the `WishRepository` with `@Autowired` annotation. Without this annotation container(Spring) will never know that is dependency should be injected.
From Spring version 4.3 if your class only one constructor it is not necessary to mark the constructor with `@Autowired` annotation.
```
public class WishServiceImpl implements WishService {
public WishRepository wishRepository;
// No need the annotation as this class only one constructor.
public WishServiceImpl(WishRepository wishRepository) {
this.wishRepository = wishRepository;
}
}
```
from Spring documentation
>
> So as of 4.3, you no longer need to specify an explicit injection annotation in such a single-constructor scenario. This is particularly elegant for classes which otherwise do not carry any container annotations at all.
>
>
>
Upvotes: 0
|
2018/03/15
| 1,839 | 5,561 |
<issue_start>username_0: So I want to print Jäger bomb and maçã in yellow where the rest of the line is standard white. The code I have is:
```
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
call :colorEcho 0e "Jäger bomb"
echo Jäger bomb
call :colorEcho 0e "maçã"
echo maçã
pause
exit
:colorEcho
echo off
"%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
```
The issue is that when it outputs it outputs as "`J,,ger`" and gives an error saying "`FINDSTR: Cannot open maøa`". But using the standard echo command both print fine. What's causing this and how do I fix it? Any help is much appreciated!<issue_comment>username_1: The error is a result of a limitation of the FINDSTR command, as described at <https://stackoverflow.com/a/8844873/1012053>. Here is the relevant portion of the extensive answer, with the most important bits in ***bold italics***
>
> ### Character limits for command line parameters - Extended ASCII transformation
>
>
> The null character (0x00) cannot appear in any string
> on the command line. Any other single byte character can appear in the
> string (0x01 - 0xFF). ***However, FINDSTR converts many extended ASCII
> characters it finds within command line parameters into other
> characters.*** This has a major impact in two ways:
>
>
> 1) Many extended ASCII characters will not match themselves if used as
> a search string on the command line. This limitation is the same for
> literal and regex searches. If a search string must contain extended
> ASCII, then the `/G:FILE` option should be used instead.
>
>
> ***2) FINDSTR may fail to find a file if the name contains extended ASCII characters and the file name is specified on the command line.
> If a file to be searched contains extended ASCII in the name, then the
> `/F:FILE` option should be used instead.***
>
>
>
So the problem can be solved by writing the name of the file to a file and using the `/F:file` option.
Note there is no need to write a new file with the backspace character for every call. You can use a constant file named @ if you treat your string as a folder, and then append `\..\@`. Your @ file content should contain 6 backspace characters to get back to the desired string.
The file paths cannot be quoted within the "files.txt" file. This could cause a problem if your string contains a poison character like `&`. So I store the string in a variable within quotes, and then write using delayed expansion without quotes to preserve the poison character.
```
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in (
'"prompt #$H#$E# & echo on & for %%b in (1) do rem"'
) do (
set "DEL=%%a"
)
"@"
call :colorEcho 0e "Jäger bomb"
echo(
call :colorEcho 0e "maçã"
echo(
call :colorEcho 0e "this & that"
echo(
pause
exit /b
:colorEcho
setlocal
set "str=%~2"
>files.txt echo !str!\..\@
findstr /v /a:%1 /f:files.txt /r "^$"
```
This code solves your immediate problem, but the code is still not very robust. Without too much thought, I know of 3 things that will cause it to fail
* `\` anywhere in the string
* `/` anywhere in the string
* `:` in the 2nd position
I'm sure there are many other potential problems.
You can find much more robust code at [How to have multiple colors in a Windows batch file?](https://stackoverflow.com/q/4339649/1012053).
Look at all the answers, as there are many variations on the theme.
You can choose your favorite :-)
Upvotes: 2 <issue_comment>username_2: You need add at the begin of the batch script the chcp command telling the codepage of the encoding of your script file.
If you save your script on utf-8 add: chcp 65001 > nul
If you save your script on ansi add: chcp 1252 > nul
All this is needed for cmd for interpret the extended characters of the batch file using the declared codepage instead the system codepage.
(save the next script with notepad++) :
It produces:
[](https://i.stack.imgur.com/9Z5dE.png)
```
@Echo Off
::This script file is encoded using utf-8
chcp 65001 >nul
::
::Call :Color A "######" \n E "" C " 23 " E "!" \n B "#&calc" \n
Call :Color 0e "Jäger bomb" \n
call :Color 0e "maçã" \n
Pause >Nul
Exit /B
:Color
:: v23c
:: Arguments: hexColor text [\n] ...
:: \n -> newline ... -> repeat
:: Supported in windows XP, 7, 8.
:: This version works using Cmd /U
:: In XP extended ascii characters are printed as dots.
:: For print quotes, use empty text.
SetLocal EnableExtensions EnableDelayedExpansion
Subst `: "!Temp!" >Nul &`: &Cd \
SetLocal DisableDelayedExpansion
Echo(|(Pause >Nul &Findstr "^" >`)
Cmd /A /D /C Set /P "=." >>` `.1
Copy /Y `.1 /B + `.1 /B + `.1 /B `.3 /B >Nul
Copy /Y `.1 /B + `.1 /B + `.3 /B `.5 /B >Nul
Copy /Y `.1 /B + `.1 /B + `.5 /B `.7 /B >Nul
)
:\_\_Color
Set "Text=%~2"
If Not Defined Text (Set Text=^")
SetLocal EnableDelayedExpansion
For %%\_ In ("&" "|" ">" "<"
) Do Set "Text=!Text:%%~\_=^%%~\_!"
Set /P "LF=" <` &Set "LF=!LF:~0,1!"
For %%# in ("!LF!") Do For %%\_ In (
\ / :) Do Set "Text=!Text:%%\_=%%~#%%\_%%~#!"
For /F delims^=^ eol^= %%# in ("!Text!") Do (
If #==#! EndLocal
If \==%%# (Findstr /A:%~1 . \` Nul
Type `.3) Else If /==%%# (Findstr /A:%~1 . /.\` Nul
Type `.5) Else (Cmd /A /D /C Echo %%#\..\`>`.dat
Findstr /F:`.dat /A:%~1 .
Type `.7))
If "\n"=="%~3" (Shift
Echo()
Shift
Shift
If ""=="%~1" Del ` `.1 `.3 `.5 `.7 `.dat &Goto :Eof
Goto :\_\_Color
```
Upvotes: 4 [selected_answer]
|
2018/03/15
| 3,898 | 15,191 |
<issue_start>username_0: I am trying out Flutter and I am trying to change the colour of the `BottomNavigationBar` on the app but all I could achieve was change the colour of the `BottomNavigationItem` (icon and text).
Here is where i declare my `BottomNavigationBar`:
```
class _BottomNavigationState extends State{
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: null,
body: pages(),
bottomNavigationBar:new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: const Icon(Icons.home),
title: new Text("Home")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.work),
title: new Text("Self Help")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.face),
title: new Text("Profile")
)
],
currentIndex: index,
onTap: (int i){setState((){index = i;});},
fixedColor: Colors.white,
),
);
}
```
Earlier I thought I had it figured out by editing `canvasColor` to green on my main app theme but it messed up the entire app colour scheme:
```
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
canvasColor: Colors.green
),
home: new FirstScreen(),
);
}
}
```<issue_comment>username_1: There is no option to specify the background color of `BottomNavigationBar` but to change the `canvasColor`. One way you can achieve it without messing up the whole app would be by wrapping `BottomNavigationBar` in a `Theme` with desired `canvasColor`.
Example:
```
bottomNavigationBar: new Theme(
data: Theme.of(context).copyWith(
// sets the background color of the `BottomNavigationBar`
canvasColor: Colors.green,
// sets the active color of the `BottomNavigationBar` if `Brightness` is light
primaryColor: Colors.red,
textTheme: Theme
.of(context)
.textTheme
.copyWith(caption: new TextStyle(color: Colors.yellow))), // sets the inactive color of the `BottomNavigationBar`
child: new BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: 0,
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.add),
title: new Text("Add"),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.delete),
title: new Text("Delete"),
)
],
),
),
```
Upvotes: 8 [selected_answer]<issue_comment>username_2: Try wrapping your `BottomNavigationBar` in a `Container` then set its `color`.
Example:
```
@override
Widget build(BuildContext context) {
return Scaffold(
body: pages(),
bottomNavigationBar:new Container(
color: Colors.green,
child: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.home),
title: Text("Home")
),
BottomNavigationBarItem(
icon: const Icon(Icons.work),
title: Text("Self Help")
),
BottomNavigationBarItem(
icon: const Icon(Icons.face),
title: Text("Profile")
)
],
currentIndex: index,
onTap: (int i){setState((){index = i;});},
fixedColor: Colors.white,
),
);
);
};
```
Upvotes: 2 <issue_comment>username_3: Simply add the `backgroundColor` property to `BottomNavigationBar`widget.
```
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: null,
body: pages(),
bottomNavigationBar:new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: const Icon(Icons.home),
title: new Text("Home")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.work),
title: new Text("Self Help")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.face),
title: new Text("Profile")
)
],
currentIndex: index,
onTap: (int i){setState((){index = i;});},
fixedColor: Colors.white,
backgroundColor: Colors.black45,
),
);
}
```
Upvotes: 1 <issue_comment>username_4: The accepted answer isn't entirely wrong. However, `BottomNavigationBar` does in-fact have a property of `backgroundColor`. As per the documentation
>
> If type is BottomNavigationBarType.shifting and the itemss, have BottomNavigationBarItem.backgroundColor set, the item's backgroundColor will splash and overwrite this color.
>
>
>
What this means is that the `BottomNavigation`'s backgroundColor will be overriden by the individual items backgroundColor because the default type is `BottomNavigationBarType.shifting`.
To fix this, simply add the following property to the declared `BottomNavigationbar` widget.
```
type: BottomNavigationBarType.fixed,
```
**Note**: If you do, however, want the shifting effect you will have to declare colors for each item, or wrap the widget that allows the overriding of the child widget(s) background color.
i.e Something like `Container` widget.
Upvotes: 6 <issue_comment>username_5: `BottomNavigationBar` could be either fixed or moving (shifting).
It is fixed if there are 3 items and changes to shifting for 4 or more items. We can override this behavior by setting `BottomNavigationBar.type` parameter.
* ### Fixed `BottomNavigationBar`
[](https://i.stack.imgur.com/PZV9m.png)
```dart
BottomNavigationBar(
type: BottomNavigationBarType.fixed, // Fixed
backgroundColor: Colors.black, // <-- This works for fixed
selectedItemColor: Colors.greenAccent,
unselectedItemColor: Colors.grey,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.call),
label: 'Call',
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
label: 'Message',
),
],
)
```
---
* ### Shifting `BottomNavigationBar`:
[](https://i.stack.imgur.com/JVZAG.gif)
```dart
BottomNavigationBar(
type: BottomNavigationBarType.shifting, // Shifting
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.call),
label: 'Call',
backgroundColor: Colors.blue, // <-- This works for shifting
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
label: 'Message',
backgroundColor: Colors.green, // <-- This works for shifting
),
],
)
```
Upvotes: 7 <issue_comment>username_6: can change by setting colors to backgroundColor property if type is fixed.
```
BottomNavigationBar(
backgroundColor: Colors.red,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon:Icon(Icons.home, color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Home'),),
BottomNavigationBarItem(
icon: Icon(Icons.work,color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Self Help'),),
BottomNavigationBarItem(
icon:Icon(Icons.face, color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Profile'),),
]
)
```
If the type is shifting it will use color inside bottomNavigationBarItem.
```
BottomNavigationBar(
backgroundColor: Colors.red,
type: BottomNavigationBarType.shifting,
items: [
BottomNavigationBarItem(
icon:Icon(Icons.home, color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Home'),
backgroundColor: Colors.red),
BottomNavigationBarItem(
icon: Icon(Icons.work,color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Self Help'),
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon:Icon(Icons.face, color: Color.fromARGB(255, 255, 255, 255)),
title: new Text('Profile'),
backgroundColor: Colors.amber),
]
)
```
You can see even though I have set backgroundColor property it does not apply that colors and the background color inside BottomNavigationBarItem widget will override that.
Found from [here](https://mightytechno.com/flutter-bottom-navigation/)
Upvotes: 4 <issue_comment>username_7: Set following properties to change the **background**, **selected** and **unselected** colors
```
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue,
selectedItemColor: Colors.black,
unselectedItemColor: Colors.white,
type: BottomNavigationBarType.fixed,
...
)
```
Upvotes: 4 <issue_comment>username_8: You can currently style them `BottomNavigationBar` directly from the `Theme`, like this:
```
ThemeData(
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: Colors.grey[900],
elevation: 10,
selectedLabelStyle: TextStyle(
color: Color(0xFFA67926), fontFamily: 'Montserrat', fontSize: 14.0
),
unselectedLabelStyle: TextStyle(
color: Colors.grey[600], fontFamily: 'Montserrat', fontSize: 12.0
),
selectedItemColor: Color(0xFFA67926),
unselectedItemColor: Colors.grey[600],
showUnselectedLabels: true,
),
)
```
Upvotes: 3 <issue_comment>username_9: The `title` is deprecated. We use `label` instead.
For `label`, we can use corresponding attributes: `selectedLabelStyle, unselectedLabelStyle`.
For example:
```
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: Theme.of(context).accentColor,
selectedFontSize: 0,
unselectedFontSize: 0,
iconSize: 22,
elevation: 0,
backgroundColor: Colors.transparent,
selectedIconTheme: IconThemeData(size: 28),
unselectedItemColor: Theme.of(context).focusColor.withOpacity(1),
selectedLabelStyle: Theme.of(context).textTheme.bodyText1.merge(TextStyle(fontSize: 12)),
unselectedLabelStyle: Theme.of(context).textTheme.button.merge(TextStyle(fontSize: 11)),
showUnselectedLabels: true,
currentIndex: widget.currentTabIdx,
onTap: (int i) {
this._selectTab(i);
},
showSelectedLabels: true,
// this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: SvgPicture.asset(IMAGE_ASSETS_ICONS_HOME) ,
activeIcon: SvgPicture.asset(IMAGE_ASSETS_ICONS_HOME, color: Theme.of(context).accentColor),
label: 'Home',
),
BottomNavigationBarItem(
label: 'Categories',
icon: SvgPicture.asset(IMAGE_ASSETS_ICONS_CATEGORY),
activeIcon: SvgPicture.asset(IMAGE_ASSETS_ICONS_CATEGORY, color: Theme.of(context).accentColor) ,
),
BottomNavigationBarItem(
icon: SvgPicture.asset(IMAGE_ASSETS_ICONS_ORDER_HISTORY, ) ,
activeIcon: SvgPicture.asset(IMAGE_ASSETS_ICONS_ORDER_HISTORY, color: Theme.of(context).accentColor ) ,
label: 'Order History',
),
BottomNavigationBarItem(
icon: SvgPicture.asset(IMAGE_ASSETS_ICONS_CART,) ,
activeIcon: SvgPicture.asset(IMAGE_ASSETS_ICONS_CART, color: Theme.of(context).accentColor) ,
label: 'Cart',
),
],
```
Upvotes: 3 <issue_comment>username_10: Just follow the given below code to customize according to your requirements. You just need to set the parent of NavigationBar with Theme and set **canvasColor** to change the background color
```
bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
canvasColor: kOrangeMaterialColor
),
child: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
currentIndex: _currentIndex,
onTap: _onTapItem,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home,
color: kWhiteColor,),
label: ''),
BottomNavigationBarItem(icon: Icon(Icons.notifications,
color: kWhiteColor,),
label: ''),
// BottomNavigationBarItem(icon: Icon(Icons.favorite_border,
// color: kWhiteColor,),
// label: ''),
BottomNavigationBarItem(icon: Icon(Icons.account_circle,
color: kWhiteColor,),
label: ''),
BottomNavigationBarItem(icon: Icon(Icons.settings,
color: kWhiteColor,),
label: ''),
],
),
),
```
Upvotes: 2 <issue_comment>username_11: use
```
BottomNavigationBar (
backgroundColor: Colors.red,
)
```
If not changing color with this wrap with material widget.
```
Material(
child:
BottomNavigationBar (
backgroundColor: Colors.red,
),
)
```
Upvotes: 0 <issue_comment>username_12: You can use this code :
```
BottomNavigationBar (
backgroundColor: Colors.red,
type: BottomNavigationBarType.fixed
)
```
Or warp `BottomNavigation` with `Theme` widget and change `canvasColor`.
```
Theme(
data: Theme.of(context).copyWith(canvasColor: Colors.green),
child: BottomNavigationBar(
// add your code ...
)
],
),
),
```
Upvotes: 2 <issue_comment>username_13: // it will work like this backgound color
```
import 'package:flutter/material.dart';
import 'package:pedometer/widgets/const.dart';
import 'package:pedometer/widgets/const.dart';
import 'package:pedometer/widgets/const.dart';
import 'package:pedometer/widgets/icon.dart';
import 'dashbord.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State createState() => \_MyStatefulWidgetState();
}
class \_MyStatefulWidgetState extends State {
int \_selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List \_widgetOptions = [
DashbordScreen(),
DashbordScreen(),
DashbordScreen(),
DashbordScreen(),
];
void \_onItemTapped(int index) {
setState(() {
\_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: \_widgetOptions.elementAt(\_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: const Color.fromARGB(255, 6, 17, 93),
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
// iconFun(path:Icons.home,context: context )
icon: Icon(Icons.home,color: Colors.white,size: 35,),
label: 'Home',
// backgroundColor: Colors.red,
),
BottomNavigationBarItem(
icon: Icon(Icons.auto\_graph\_outlined,color: Colors.white,size: 35),
label: 'Business',
backgroundColor: Colors.green,
),
BottomNavigationBarItem(
icon: Icon(Icons.health\_and\_safety,color: Colors.white,size: 35),
label: 'School',
// backgroundColor: Colors.purple,
),
BottomNavigationBarItem(
icon: Icon(Icons.settings,color: Colors.white,size: 35),
label: 'Settings',
// backgroundColor: Colors.pink,
),
],
currentIndex: \_selectedIndex,
selectedItemColor: Colors.white,
onTap: \_onItemTapped,
),
);
}
}
```
Upvotes: 1
|
2018/03/15
| 385 | 1,396 |
<issue_start>username_0: I want to make a site using django which include forms, but i am not able to find a way to include **form-control** classes in fields. Is there any way to do so?
When i try to install Django-widget-tweaks
```
Could not find a version that satisfies the requirement django-widjet-tweaks (from versions: )
No matching distribution found for django-widjet-tweaks
```<issue_comment>username_1: if use a form, you can put over forms.py in definition of form
using bootstrap for example
from django import forms
```
from django import forms
class CommentForm(forms.Form):
name = forms.CharField(max_length=20,
widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder': 'Name'}))
```
example in
<https://github.com/PrettyPrinted/intro_to_django>
Upvotes: 2 [selected_answer]<issue_comment>username_2: I suggest you to use `Django-Crispy-Forms` so you can easily use bootstrap without worry too much: <http://django-crispy-forms.readthedocs.io/en/latest/>
>
> django-crispy-forms provides you with a |crispy filter and {% crispy
> %} tag that will let you control the rendering behavior of your Django
> forms in a very elegant and DRY way. Have full control without writing
> custom form templates. All this without breaking the standard way of
> doing things in Django, so it plays nice with any other form
> application.
>
>
>
Upvotes: 0
|
2018/03/15
| 302 | 1,142 |
<issue_start>username_0: I am new to xamarin uitest, can any one please help me out how to verify the element is enabled or disabled with an example.
Thanks in advance.<issue_comment>username_1: I didn't really understand your question, but if what you're asking for is how to check if a toggle button is enabled, then you can go that way :
```
internal void SetToggle(string id, bool setToggled)
{
if (setToggled != IsToggled(id))
app.Tap(e => e.Property("id").Like(id));
}
internal bool IsToggle(string id)
{
return app.Query(e => e.Property("id").Like(id).Invoke("isChecked").Value())[0];
}
```
Upvotes: 0 <issue_comment>username_2: Assuming that you are using Xamarin's Repl then you can use the following
```
app.Query(c => c.Id("ElementID")).FirstOrDefault().Enabled
```
Repl will then return whether the element's enabled property is either true or false
From this, then you can then assign that line to a variable and assert against it
```
var elementEnabled = app.Query(c => c.Id("ElementID")).FirstOrDefault().Enabled;
assert.AreEqual(true, elementEnabled);
```
Upvotes: 2
|
2018/03/15
| 382 | 1,378 |
<issue_start>username_0: I realize that this is improper syntax, but why is JavaScript ignoring the first number and giving a response instead of breaking?
```
let myArray = [1,2,3,4]
myArray[0,1] // 2
myArray[1,3] // 4
myArray[3,0] // 1
```<issue_comment>username_1: It's not improper syntax.
That's just the comma operator in action.
-----------------------------------------
From [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator):
>
> The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
>
>
>
For instance, `[1,2][1,2]`, perhaps bizarrely enough, will return `undefined`.
Why?
The second `[` is interpreted by the compiler to be the array subscript operator, because JavaScript's semantics don't allow two arrays to be next to each other.
Thus, the second `1,2` must be an expression that evaluates to an index. `1,2` results in the first operand being evaluated, followed by the second, which is what's returned. So it uses index `2`, which of course doesn't exist in that array, and we get `undefined`.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is because it is [evaluating the comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) in each set of square brackets.
Upvotes: 1
|
2018/03/15
| 1,216 | 4,632 |
<issue_start>username_0: [This question](https://stackoverflow.com/questions/328525/how-can-i-set-default-values-in-activerecord) appears to be the most voted/relevant question on Stack Overflow about setting default values on models. Despite the numerous ways explored, none of them cover this issue.
Note that this is an API - so the default text for a reminder must be provided by the api, hence why I am storing in the database. Some users will wish to use that default, some will update it.
Here is my code that works, but it feels wrong, because I have had to set one of the default values (for `:body`) in the 'parent' (`User` model).
```
class User < ActiveRecord::Base
# Relationships
belongs_to :account
has_one :reminder
before_create :build_default_reminder
private
def build_default_reminder
build_reminder(body: get_default_body)
end
def get_default_body
<<~HEREDOC
This is a quick reminder about the outstanding items still on your checklist.
Thank you,
#{self.name}
HEREDOC
end
end
class Reminder < ApplicationRecord
# Relationships
belongs_to :user
# Default attributes
attribute :is_follow_up, :boolean, default: true
attribute :subject, :string, default: "your checklist reminder!"
attribute :greeting, :string, default: "Hi"
end
```
What I would much rather do is this, so that all defaults are in the same model (the child):
```
class User < ActiveRecord::Base
# Relationships
belongs_to :account
has_one :reminder
end
class Reminder < ApplicationRecord
# Relationships
belongs_to :user
# Default attributes
attribute :is_follow_up, :boolean, default: true
attribute :subject, :string, default: "your checklist reminder!"
attribute :greeting, :string, default: "Hi"
attribute :body, :string, default:
<<~HEREDOC
This is a quick reminder about the outstanding items still on your checklist.
Thank you,
#{self.user.name}
HEREDOC
end
```
but this of course throws the error:
```
undefined method `user' for #
```
The problem comes about because the default `:body` string must contain the name of the user. Is there a way to achieve this - ie. have all the defaults in `reminder` model, but somehow reference the user that created it?<issue_comment>username_1: I think the fact that this is tricky may be an indication that you might want to redesign this a little bit. In particular, it looks like you're mixing model logic with view logic.
You can fix this by moving the logic that actually creates the string closer to wherever it is going to be rendered (an ERB file, an email template, etc). Then, when you pass in the `Reminder` instance that you're generating the string for, the code that calls `@reminder.user.name` will work, as `@reminder`'s `.user` association is not blank.
Upvotes: 1 <issue_comment>username_2: >
> I think the fact that this is tricky may be an indication that you
> might want to redesign this a little bit. In particular, it looks like
> you're mixing model logic with view logic.
>
>
>
This was a pertinent observation by @username_1. So it's been redesigned - with help from the comment by @MrYoshiji so thanks guys!
I think the following is a better and more maintainable solution, especially once the app does need to be able to provide actual translations of these default english texts - so I will also create `custom_greeting` and `custom_subject` for those 2 attributes.
```
class User < ActiveRecord::Base
# Relationships
belongs_to :account
has_one :reminder
end
class Reminder < ApplicationRecord
# Relationships
belongs_to :user
# Default attributes
attribute :subject, :string, default: "your checklist reminder!"
attribute :greeting, :string, default: "Hi"
def body=(value)
self.custom_body = value
end
def body
custom_body.presence || I18n.t('reminder.default_body', name: self.user.name)
end
end
```
en.yml file:
```
reminder:
default_body: "\nThis is a quick reminder about the outstanding items still on your checklist.\
\nPlease click the button below to review the items we're still waiting on.\
\nThank you,\
\n%{name}"
```
([this question](https://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines) helped a lot for the multi-line text in yml)
([this question](https://stackoverflow.com/questions/35932408/overriding-getter-setter-in-rails-whilst-preserving-model-newattrib-blah) helped understand the getter/setter - see the answer about storing prices from @pascal betz)
Upvotes: 1 [selected_answer]
|
2018/03/15
| 1,006 | 4,033 |
<issue_start>username_0: Given following xml snippet
```
<!-- some more content --!>
```
removing namespace attributes with VTD-XML works well with following snippet:
```
private String removeNamespaces( String xml )
{
try
{
VTDGen generator = new VTDGen();
generator.setDoc( xml.getBytes() );
generator.parse( false );
VTDNav navigator = generator.getNav();
XMLModifier xm = new XMLModifier( navigator );
AutoPilot autoPilot = new AutoPilot( navigator );
autoPilot.selectXPath( "@*" );
int i = -1;
while ((i = autoPilot.evalXPath()) != -1)
{
if ( navigator.toString( i ).startsWith( "xmlns" ) )
{
xm.removeAttribute( i );
}
}
XMLByteOutputStream xbos = new XMLByteOutputStream( xm.getUpdatedDocumentSize() );
xm.output( xbos );
return new String( xbos.getXML() );
}
catch (Exception e)
{
throw new RuntimeException( e );
}
}
```
The result shows the element without the attributes but the blanks between have not be deleted:
```
<!-- some more content --!>
```
Usage of `navigator.expandWhiteSpaces( l )` et al. does not work because these methods are for elements but not for attributes.
To sum it up: Is it possible to remove attributes to get to a result like
```
<!-- some more content --!>
```<issue_comment>username_1: First of all, I think you can code "starts-with" more concisely in one of the two ways...
The first one uses the xpath function of starts-with(). It is technically a xpath 2.0 function, but they are supported in vtd-xml's xpath implementation.. along with contains() and ends-with()...
```
generator.parse( false );
VTDNav navigator = generator.getNav();
XMLModifier xm = new XMLModifier( navigator );
AutoPilot autoPilot = new AutoPilot( navigator );
autoPilot.selectXPath( "@*[starts-with(.,'xmlns')]" );
int i = -1;
while ((i = autoPilot.evalXPath()) != -1)
{
// if ( navigator.toString( i ).startsWith( "xmlns" ) )
//{
xm.removeAttribute( navigator.trimWhiteSpaces(i) );
//}
}
```
Or you can use VTDNav's startWith,contains or endWith functions directly, instead of explicity bringing a string object into existence (navigator.toString)
```
VTDNav navigator = generator.getNav();
XMLModifier xm = new XMLModifier( navigator );
AutoPilot autoPilot = new AutoPilot( navigator );
autoPilot.selectXPath( "@*" );
int i = -1;
while ((i = autoPilot.evalXPath()) != -1)
{
// if ( navigator.toString( i ).startsWith( "xmlns" ) )
//{
if (navigator.startsWith(i, "xmlns"))
xm.removeAttribute( i );
//}
}
```
Either way, i think that applying expandWhitespace on an attribute name-value pair segment may be a bit dangerous, since you could remove accidentally the delimiting white spaces and mess up a well-formed xml document...
Currently, cleaning up the throw-away white spaces is a work-in-progress. I hope it is not a show stopper. If it is, you will have to do it manually... it will be a bit tedious coding. But you will have to
1. find the start, and end offset of the attribute name value segment
2. Encoding the start offset and length into a 64-bit integer.
3. Call trimWhitespace with the right parameters to remove the extraneous white spaces at the end...
Upvotes: 1 [selected_answer]<issue_comment>username_2: Inspired by the tips of [username_1](https://stackoverflow.com/users/129732/username_1), my workaround snippet now is
```
while ((i = autoPilot.evalXPath()) != -1)
{
xm.removeAttribute( i );
xm.removeContent( navigator.getTokenOffset( i ) - 1, 1 );
}
```
This assumes that the leading blank of an attribute belongs to it and is therefore also removed. All other blanks are ignored and remain untouched.
Upvotes: 1
|
2018/03/15
| 2,161 | 6,491 |
<issue_start>username_0: ```
bool isPalindromeIterative(const char *s1){
int len=strlen(s1)-1;
if(len>0)
if(s1[0]==s1[len]){
len-=2;
isPalindromeIterative(s1+1);
}
else
return false;
return true;
}
```
I am writing about Palindrome.
And when I run it, it appears warning like this:
":79:13: warning: add explicit braces to avoid dangling else
[-Wdangling-else]"
Please help me ! Thanks!<issue_comment>username_1: There is formally nothing wrong with the code, unless you wanted the `else` to match the outer `if`. A common mistake.
If you add braces everywhere, it will be clear what you intended:
```
if(len>0)
{
if(s1[0]==s1[len])
{
len-=2;
isPalindromeIterative(s1+1);
}
else
{
return false;
}
}
```
Upvotes: 3 <issue_comment>username_2: It is a style warning against reading the if clauses wrong.
```
if(len>0) {
if(s1[0]==s1[len]){
len-=2;
isPalindromeIterative(s1+1);
}
} else {
return false;
}
```
is better to read and less error-prone.
We have similar coding guidelines in our company; for an `if`, which has bracket clauses, all `else` branches and all other `if`s within the `if` of the highest order have to have brackets.
Else your example could too easily be misread as e.g.
```
if(len>0)
if(s1[0]==s1[len]){
len-=2;
isPalindromeIterative(s1+1);
}
else
return false;
```
Upvotes: 2 <issue_comment>username_3: When you write,
```
if(len>0)
if(s1[0]==s1[len]){
// This has no effect on the recursive call.
len-=2;
// You missed the return in your post.
return isPalindromeIterative(s1+1);
}
else
return false;
```
it's most likely that you meant to associate the `else` with the second `if`.
```
if(len>0)
{
if(s1[0]==s1[len])
{
return isPalindromeIterative(s1+1);
}
else
return false;
}
```
However, the compiler does not use the indent to figure that out. It's possible that, from the compiler writer's point of view, you meant to associate the `else` with the first `if`:
```
if(len>0)
{
if(s1[0]==s1[len])
{
return isPalindromeIterative(s1+1);
}
}
else
{
return false;
}
```
Since this is common mistake made by developers, the compiler warns you and hopes that you will update the code so that it's less likely to turn into a runtime error.
---
I want to point out that the recursion logic you are using to detect whether a string is palindrome is wrong.
Let's say your string is "abxba".
In the first iteration, you compare `'a'` with `'a'`.
In the next iteration, you compare `'b'` with `'a'`, which is incorrect. You end up with the wrong answer.
You have to change your strategy a bit. Use:
```
bool isPalindromeIterative(const char *s1, int start, int end)
{
if ( start >= end )
{
return true;
}
if ( s1[start] == s1[end] )
{
return isPalindromeIterative(s1, start+1, end-1)
}
return false;
}
```
The start of the iterative call has to be made as:
```
isPalindromeIterative(s1, 0, strlen(s1)-1);
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Your original post headline mentioned iterative, and 'Iterative' is still part of your function name (even though it is recursive).
You marked this post as c++, but did not use classes.
The other answers addressed your specific questions about your error messages.
---
For your consideration, and because you have already selected a recursive answer, here is a possible C++ **iterative** solution **and tail-recursive** solution using **std::string&**.
```
#include
#include
class T589\_t
{
public:
int exec(int argc, char\* argv[])
{
if (argc < 2)
{
std::cerr << "\n please provide one or more string(s) to test"
<< std::endl;
return -1;
}
for (int i = 0; i < argc; ++i)
{
std::string s = argv[i];
{
std::string yesno = (isPalindromeIterative(s) ? " is" : " is not");
std::cout << "\n '" << s << "'" << yesno << " a palindrome (iterative)" << std::flush;
}
std::cout << std::endl;
{
std::string yesno = (isPalindromeRecursive(s) ? " is" : " is not");
std::cout << " '" << s << "'" << yesno << " a palindrome (recursive)" << std::endl;
}
} // for 0..argc
return 0;
}
private: // methods
bool isPalindromeIterative(const std::string& s1)
{ // ^^^^^^^^^
bool retVal = false; // guess s1 is not palindrome
int left = 0; // index of left most char
int right = static\_cast(s1.size()) - 1; // index of right most char
do { // iterative loop
if (s1[left] != s1[right]) break; // when not equal, is not palindrome
left += 1; right -= 1; // iterate!
if (left >= right) // all chars tested?
{
retVal = true; // confirm palindrome
break; // exit
}
} while (true);
return retVal;
}
// Notes './dumy589' // odd length 9
// ^-------^ [0] vs [8]
// ^-----^ [1] vs [7]
// ^---^ [2] vs [6]
// ^-^ [3] vs [5]
// ^ [4] == [4] // left >= right, break
// Notes 'abccba' // even length 6
// ^----^ [0] vs [5]
// ^--^ [1] vs [4]
// ^^ [2] vs [3]
// [3] vs [2] // left >= right, break
// Notes 'abcba' // odd length 5
// ^---^ [0] vs [4]
// ^-^ [1] vs [3]
// ^ [2] vs [2] // left >= right, break
// and bonus: tail recursion based on above iterative
// vvvvvvvvv
bool isPalindromeRecursive(const std::string& s1)
{
// index of left most char
int left = 0;
// index of right most char
int right = static\_cast(s1.size()) - 1;
return (isPalindromeRecursive(s1, left, right));
}
bool isPalindromeRecursive(const std::string& s1, int left, int right)
{
if (s1[left] != s1[right]) return false;
left += 1; right -= 1;
if ( left >= right ) return true;
return (isPalindromeRecursive(s1, left, right));
}
}; // class T589\_t
int main(int argc, char\* argv[])
{
T589\_t t589;
return t589.exec(argc, argv);
}
```
On Linux, argv[0] is the executable name.
environment:
Lubuntu 17.10,
g++ (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0
With invocation:
```
./dumy589 aba abccba tx s
```
This code reports:
```
'./dumy589' is not a palindrome (iterative)
'./dumy589' is not a palindrome (recursive)
'aba' is a palindrome (iterative)
'aba' is a palindrome (recursive)
'abccba' is a palindrome (iterative)
'abccba' is a palindrome (recursive)
'tx' is not a palindrome (iterative)
'tx' is not a palindrome (recursive)
's' is a palindrome (iterative)
's' is a palindrome (recursive)
```
Upvotes: 0
|
2018/03/15
| 739 | 2,795 |
<issue_start>username_0: My scenario is simple I have a simple Azure Function with B2C authentication on it and I'm writing unit tests but I found an issue, I'm not able to authenticate to the azure functions programmatically.
I'm able to access through the browser and even I can grab the token and put it into the unit test and it works fine, but when I try to generate a token using the ClientID, TenantID, etc. I get a token, but 401 Unauthorized response on the Azure functions.
**Is there a way to generate a valid B2C token programmatically (without login in the browser?**
The approach I'm using so far:
```
public static async Task GetAccessToken(string resourceUri, string clientId, string clientSecret)
{
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
string aadInstance = "https://login.microsoftonline.com/";
string tenant = ".onmicrosoft.com";
string authority = string.Concat(aadInstance, tenant);
AuthenticationContext authContext = new AuthenticationContext(authority);
return await authContext.AcquireTokenAsync(resourceUri, clientCredential);
}
```
I'm getting a token (EY.......) but is not valid, when I passed to the Azure Function request, it returns 401 Unauthorized.
Thanks in advance!
Ivan<issue_comment>username_1: Your unit test is acquiring a token from the Azure AD v1.0 endpoint rather than the Azure AD B2C v2.0 endpoint.
Your Azure function is expecting the token to be issued by the Azure AD B2C v2.0 endpoint.
In the short term, you can consider acquiring the token from the Azure AD B2C v2.0 endpoint by replaying the browser requests using the `HttpClient` class.
In the near term, [support for the resource owner password credential grant by Azure AD B2C](https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/13817784-add-support-for-resource-owner-password-credential) will enable your unit test to acquire a token from the Azure AD B2C v2.0 endpoint by POSTing a user credential to the endpoint.
Upvotes: 2 <issue_comment>username_2: A couple of months ago, Microsoft released a policy for resource owner password credentials flow, with that policy you can simulate a login passing the login details in a query as follows:
1. Create a ROPC policy in B2C
2. Register an application
3. Test the policy as follows:
```
https://te.cpim.windows.net/{B2C TENANT}/{ROPC B2C POLICY}/oauth2/v2.0/token?username={USERNAME}&password={<PASSWORD>}&grant_type=password&scope=openid+{CLIENT ID}+offline_access&client_id=[CLIENT ID]&response_type=token+id_token
```
You can find more detailed info [here](https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-ropc "https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-ropc")
Upvotes: 4 [selected_answer]
|
2018/03/15
| 1,184 | 4,995 |
<issue_start>username_0: I am looking at a code that I have to work on. And basically I have to add a validation to a listener of a button.
The code has already multiple validations. They are kind of set in a cascade.
The listener of the buttons calls an asyncCallBack method that if everything is ok, on the onsuccess part of the method calls for the next one, an that one on the next one, until it reaches the end and goes to the next page. I am not a fan of this approach because it is kind of messy. What would the best way to do that using best practices.
An example of the code:
```
Button btnOK = new Button("Aceptar");
btnOK.addListener(Events.Select, new Listener() {
public void handleEvent(ButtonEvent e) {
myService.getInfo1(1, txt, "N",
new AsyncCallback>() {
public void onFailure(Throwable caught) {
// goes back
return
}
public void onSuccess(
List result) {
// do some validation with the result
validation2();
}
}
}
}
public void validation2(){
myService.getDireccionCanalesElectronicos(id, new AsyncCallback() {
public void onSuccess(MyResult result) {
// do some validation with the result
validation3();
}
...
}
}
public void validation3(){
myService.getDireccionCanalesElectronicos(id, new AsyncCallback() {
public void onSuccess(MyResult result) {
// do some validation with the result
validation4();
}
...
}
}
```
Is there a better way of doing this, it seems messy and hard to follow. Adding another validation is complicated. It doesnt seem like a good practice.<issue_comment>username_1: Create 1 method in the servlet that calls all the validation methods and do just one call in the client ?
```
public void validation()
{
boolean ok = validation1();
if (ok) ok = validation2();
return validation;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Using mirco services is sometimes hard to deal with. As @username_1 mentioned, this is a way to go. But sometime you may want to handle the calls on the client side. Another one will be using this tiny framework: [sema4g](https://github.com/mvp4g/sema4g). It will help you to solve your problem.
A solution might look like that:
First create the sem4g commands:
```
private SeMa4gCommand createGetInfoCommand() {
return new AsyncCommand() {
// create callback
MethodCallbackProxy> proxy = new MethodCallbackProxy>(this) {
@Override
protected void onProxyFailure(Method method,
Throwable caught) {
// Enter here the code, that will
// be executed in case of failure
}
@Override
protected void onProxySuccess(Method method,
List response) {
// Enter here the code, that will
// be executed in case of success
}
};
@Override
public void execute() {
// That's the place for the server call ...
myService.getInfo1(1, txt, "N", proxy);
}
};
}
```
do that for all your calls;
```
private SeMa4gCommand createCommandGetDireccionCanalesElectronicos() {
return new AsyncCommand() {
// create callback
MethodCallbackProxy proxy = new MethodCallbackProxy(this) {
@Override
protected void onProxyFailure(Method method,
Throwable caught) {
// Enter here the code, that will
// be executed in case of failure
}
@Override
protected void onProxySuccess(Method method,
List response) {
// Enter here the code, that will
// be executed in case of success
}
};
@Override
public void execute() {
// That's the place for the server call ...
myService. getDireccionCanalesElectronicos(id, proxy);
}
};
}
```
Once you have done this for all your calls, create a sema4g context and run it:
```
try {
SeMa4g.builder()
.addInitCommand(new InitCommand() {
@Override
public void onStart() {
// Enter here your code, that
// should be executed when
// the context is started
})
.addFinalCommand(new FinalCommand() {
@Override
public void onSuccess() {
// Enter here the code, that will
// be executed in case the context
// ended without error
}
@Override
public void onFailure() {
// Enter here the code, that will
// be executed in case the context
// ended with an error
})
.add(createGetInfoCommand())
.add(createCommandGetDireccionCanalesElectronicos())
.build()
.run();
} catch (SeMa4gException e) {
// Ups, something wrong with the context ...
}
```
For more informations, read the documentation. If you have questions, feel free to ask: [SeMa4g Gitter room](https://gitter.im/SeMa4g/Lobby).
Hope that helps.
Upvotes: 1
|
2018/03/15
| 741 | 2,830 |
<issue_start>username_0: I have a website <http://demoqa.com/registration/>
I have been trying to verify that when a user clicks on and then clicks off a required field such as username or phone number that the error "required field" appears when no data has been entered.
Does anyone have any idea how to verify this? I was thinking
```
phone = self.driver.find_element_by_xpath("//div[contains(.,'Phone Number')]")
```
and then from that using something like getError = phone.find\_element\_by\_xpath() and using the (..) to try and move up to the parent class, but with no luck!
I thought it would have been easy but all the elements have the same class name. I suppose I could check for the text "this field is required" but I'd like to keep it neat and write a method so I can use it on each of the fields.
I've spent alot of today searching for it and trying different thing, so any help or ideas would be great.
Thanks!
Other Info:
I can tell you what happens before and after i click the field. My best guess at attacking this issue would be to verify the class name of the field "phone number" and then once clicked off, verify that the class name has changed. As you can see on top is before a click off and below is when the required field text appears
```
Phone Number
Phone Number
\* This field is required
```<issue_comment>username_1: Try to use below piece of code:
```
from selenium.common.exceptions import NoSuchElementException
error = "* This field is required"
phone = driver.find_element_by_xpath("//div[label='Phone Number']")
phone_input = phone.find_element_by_tag_name("input")
phone_label = phone.find_element_by_tag_name("label")
phone_input.click()
phone_label.click()
try:
phone.find_element_by_xpath(".//span[@class='legend error' and .='%s']" % error)
except NoSuchElementException:
print("No error displayed")
```
This should allow you to click inside input, outside input and check that error appears
If you need to make an assertion:
```
result = True
try:
phone.find_element_by_xpath(".//span[@class='legend error' and .='%s']" % error)
except NoSuchElementException:
result = False
assert result, "No error displayed"
```
Upvotes: 1 <issue_comment>username_2: I have my solution \*i think
seeing how the "div class name" changes when the required message appears I have a solution. I first find the element, get it's parents name by going up one level using the (..), i verify it's as it should be named "fieldset". I think trigger the error message, and repeat the process but make sure the "fieldset" has changed to "fieldset error"
```
getElementBase = self.driver.find_element_by_id('phone_9')
getElementClassRoot = getElementBase.find_element_by_xpath('..')
getElementClassRootName = getElementClassRoot.get_attribute('class')
```
Upvotes: 3
|
2018/03/15
| 538 | 1,979 |
<issue_start>username_0: I am using the Embed Widget on a Team Foundation Server 2017 dashboard to show an SSRS report. In particular, I would just like to either show the chart or the chart and the title. I do not want all of the navigation information to be visible. Is there a way for me to remove the navigation area in the rdl file or is there an option just to show the chart?
[](https://i.stack.imgur.com/nffUK.png)<issue_comment>username_1: Try to use below piece of code:
```
from selenium.common.exceptions import NoSuchElementException
error = "* This field is required"
phone = driver.find_element_by_xpath("//div[label='Phone Number']")
phone_input = phone.find_element_by_tag_name("input")
phone_label = phone.find_element_by_tag_name("label")
phone_input.click()
phone_label.click()
try:
phone.find_element_by_xpath(".//span[@class='legend error' and .='%s']" % error)
except NoSuchElementException:
print("No error displayed")
```
This should allow you to click inside input, outside input and check that error appears
If you need to make an assertion:
```
result = True
try:
phone.find_element_by_xpath(".//span[@class='legend error' and .='%s']" % error)
except NoSuchElementException:
result = False
assert result, "No error displayed"
```
Upvotes: 1 <issue_comment>username_2: I have my solution \*i think
seeing how the "div class name" changes when the required message appears I have a solution. I first find the element, get it's parents name by going up one level using the (..), i verify it's as it should be named "fieldset". I think trigger the error message, and repeat the process but make sure the "fieldset" has changed to "fieldset error"
```
getElementBase = self.driver.find_element_by_id('phone_9')
getElementClassRoot = getElementBase.find_element_by_xpath('..')
getElementClassRootName = getElementClassRoot.get_attribute('class')
```
Upvotes: 3
|
2018/03/15
| 244 | 738 |
<issue_start>username_0: I am using a Markov chain. When the chain arrives at a particular state, two files (a .png and an .mp3) need to open.
`s` is the current state of the chain, an integer from 1-59.
I can't seem to find how to open the file with the same number as 's'.
I'm sure it has something to do with `%str` formatting, but I can't seem to implement it.
```
img = Image.open('/.../.../s.png')
img.show()
```<issue_comment>username_1: You can format a string using a variable like this
```
>>> s = 10
>>> '/path/to/file/{}.png'.format(s)
'/path/to/file/10.png'
```
Upvotes: 0 <issue_comment>username_2: You should use the following line in your code:
```
img = Image.open('/.../.../{0}.png'.format(s))
```
Upvotes: 1
|
2018/03/15
| 2,189 | 6,934 |
<issue_start>username_0: I have a shapfile of school districts in Texas and am trying to use `ggplot2` to highlight 10 in particular. I've tinkered with it and gotten everything set up, but when I spot checked it I realized the 10 districts highlighted are not in fact the ones I want to be highlighted.
The shapefile can be downloaded from this link to the [Texas Education Agency Public Open Data Site](https://schoolsdata2-tea-texas.opendata.arcgis.com/datasets/e115fed14c0f4ca5b942dc3323626b1c_0).
```
#install.packages(c("ggplot2", "rgdal"))
library(ggplot2)
library(rgdal)
#rm(list=ls())
#setwd("path")
# read shapefile
tex <- readOGR(dsn = paste0(getwd(), "/Current_Districts/Current_Districts.shp")
# colors to use and districts to highlight
cols<- c("#CCCCCC", "#003082")
districts <- c("Aldine", "Laredo", "Spring Branch", "United", "Donna", "Brownsville", "Houston", "Bryan", "Galena Park", "San Felipe-Del Rio Cons")
# extract from shapefile data just the name and ID, then subset to only the districts of interest
dist_info <- data.frame(cbind(as.character(tex@data$NAME2), as.character(tex@data$FID)), stringsAsFactors=FALSE)
names(dist_info) <- c("name", "id")
dist_info <- dist_info[dist_info$name %in% districts, ]
# turn shapefile into df
tex_df <- fortify(tex)
# create dummy fill var for if the district is one to be highlighted
tex_df$yes <- as.factor(ifelse(tex_df$id %in% dist_info$id, 1, 0))
# plot the graph
ggplot(data=tex_df) +
geom_polygon(aes(x=long, y=lat, group=group, fill=yes), color="#CCCCCC") +
scale_fill_manual(values=cols) +
theme_void() +
theme(legend.position = "none")
```
As you'll see, when the plot gets created it looks like it's done exactly what I want. The problem is, those ten districts highlighted are not hte ones in the `districts` vector above. I've re-ran everything clean numerous times, double checked that I wasn't having a factor/character conversion issue, and double checked within the web data explorer that the IDs that I get from the shapefile are indeed the ones that should match with my list of names. I really have no idea where this issue could be coming from.
This is my first time working with shapefiles and `rgdal` so if I had to guess there's something simple about the structure that I don't understand and hopefully one of you can quickly point it out for me. Thanks!
Here's the output:
[](https://i.stack.imgur.com/fNA1f.jpg)<issue_comment>username_1: **Alternative 1**
With the `fortify` function add the argument `region` specifying "NAME2", the column id will include your district names then. Then create your dummy fill variable based on that column.
I am not familiar with Texas districts, but I assume the result is right.
```
tex <- tex <- readOGR(dsn = paste0(getwd(), "/Current_Districts/Current_Districts.shp"))
# colors to use and districts to highlight
cols<- c("#CCCCCC", "#003082")
districts <- c("Aldine", "Laredo", "Spring Branch", "United", "Donna", "Brownsville", "Houston", "Bryan", "Galena Park", "San Felipe-Del Rio Cons")
# turn shapefile into df
tex_df <- fortify(tex, region = "NAME2")
# create dummy fill var for if the district is one to be highlighted
tex_df$yes <- as.factor(ifelse(tex_df$id %in% districts, 1, 0))
# plot the graph
ggplot(data=tex_df) +
geom_polygon(aes(x=long, y=lat, group=group, fill=yes), color="#CCCCCC") +
scale_fill_manual(values=cols) +
theme_void() +
theme(legend.position = "none")
```
[](https://i.stack.imgur.com/moKCN.png)
**Alternative 2**
Without passing the argument region to `fortify` function. Addressing seeellayewhy's issue implementing previous alternative. We add two layers, no need to create dummy variable or merge any data frame.
```
tex <- tex <- readOGR(dsn = paste0(getwd(), "/Current_Districts/Current_Districts.shp"))
# colors to use and districts to highlight
cols<- c("#CCCCCC", "#003082")
districts <- c("Aldine", "Laredo", "Spring Branch", "United", "Donna", "Brownsville", "Houston", "Bryan", "Galena Park", "San Felipe-Del Rio Cons")
# Subset the shape file into two
tex1 <- subset(tex, NAME2 %in% districts)
tex2 <- subset(tex, !(NAME2 %in% districts))
# Create two data frames
tex_df1 <- fortify(tex1)
tex_df2 <- fortify(tex2)
# Plot two geom_polygon layers, one for each data frame
ggplot() +
geom_polygon(data = tex_df1,
aes(x = long, y = lat, group = group, fill = "#CCCCCC"),
color = "#CCCCCC")+
geom_polygon(data = tex_df2,
aes(x = long, y = lat, group = group, fill ="#003082")) +
scale_fill_manual(values=cols) +
theme_void() +
theme(legend.position = "none")
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: When trying to implement @username_1's solution of adding the "region" argument to the `fortify()` function, I got an error that I could solve through numerous other stack posts (`Error: isTRUE(gpclibPermitStatus()) is not TRUE`). I also tried using `broom::tidy()` which is the non-deprecated euqivalent to `fortify()` and had the same error.
Ultimately, I ended up implementing @luchanocho's solution from [here](https://stackoverflow.com/questions/40576457/keep-region-names-when-tidying-a-map-using-broom-package). I don't like the fact that it uses `seq()` to generate the ID because it's not necessarily preserving the proper order, but my case was simple enough that I could go through every district and confirm that the correct ones were highlighted.
My code is below. Output is the same as @username_1's answer. Since he obviously got the right result and used something that's not shaky the way the implemented solution is, I'm going to give him the answer assuming it works. The solution below can be considered a workaround if others experience the same error I got.
```
#install.packages(c("ggplot2", "rgdal"))
library(ggplot2)
library(rgdal)
#rm(list=ls())
#setwd("path")
# read shapefile
tex <- readOGR(dsn = paste0(getwd(), "/Current_Districts/Current_Districts.shp")
# colors to use and districts to highlight
cols<- c("#CCCCCC", "#003082")
districts <- c("Aldine", "Laredo", "Spring Branch", "United", "Donna", "Brownsville", "Houston", "Bryan", "Galena Park", "San Felipe-Del Rio Cons")
# convert shapefile to a df
tex_df <- fortify(tex)
# generate temp df with IDs to merge back in
names_df <- data.frame(tex@data$NAME2)
names(names_df) <- "NAME2"
names_df$id <- seq(0, nrow(names_df)-1) # this is the part I felt was sketchy
final <- merge(tex_df, names_df, by="id")
# dummy out districts of interest
final$yes <- as.factor(ifelse(final$NAME2 %in% districts, 1, 0))
ggplot(data=final) +
geom_polygon(aes(x=long, y=lat, group=group, fill=yes), color="#CCCCCC") +
scale_fill_manual(values=cols) +
theme_void() +
theme(legend.position = "none")
```
Upvotes: 0
|
2018/03/15
| 3,253 | 5,747 |
<issue_start>username_0: I need to add duration value for only continuous column's data. Suppose Execute data coming 3 times in this table and each time it is coming 3 times, 2 times and 1 times. So I want to add duration column's data 3 times as per continuous of state column.
What I need here that execute will show only 1 time instead of continuous as 3 times and again same rule for 2nd execute which is showing 2 times so it will also display 1 time with cumulative sum of duration column's value. So each iterate rows will come with sum of duration value and show as single row
```
CREATE TABLE Tools
([ID] int, [StartDatetime] varchar, [EndDatetime] varchar, [duration] int, [durationDatetime] varchar, [state] varchar(50), [stateCode] int)
;
INSERT INTO Tools
([ID], [StartDatetime], [EndDatetime], [duration], [durationDatetime], [state], [stateCode])
VALUES
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 100, '1900-01-01T00:16:39.7800000', 'Execute', 6),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 900, '1900-01-01T00:16:39.7800000', 'Execute', 6),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 400, '1900-01-01T00:16:39.7800000', 'Execute', 6),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 1000, '1900-01-01T00:16:39.7800000', 'other', 2),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 50, '1900-01-01T00:16:39.7800000', 'Execute', 6),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 52, '1900-01-01T00:16:39.7800000', 'Execute', 6),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 8, '1900-01-01T00:16:39.7800000', 'other', 2),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 4, '1900-01-01T00:16:39.7800000', 'other', 2),
(1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 740, '1900-01-01T00:16:39.7800000', 'Execute', 6)
```
[](https://i.stack.imgur.com/UoTNX.jpg)<issue_comment>username_1: I've added a KID column (identity), as <NAME> has pointed out you need an order.
>
>
> ```
> CREATE TABLE Tools
> (
> [KID] int identity,
> [ID] int,
> [StartDatetime] varchar(50),
> [EndDatetime] varchar(50),
> [duration] int,
> [durationDatetime] varchar(50),
> [state] varchar(50),
> [stateCode] int
> );
> GO
>
> ```
>
>
>
>
> ```
> INSERT INTO Tools ([ID], [StartDatetime], [EndDatetime], [duration], [durationDatetime], [state], [stateCode]) VALUES
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 100, '1900-01-01T00:16:39.7800000', 'Execute', 6),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 900, '1900-01-01T00:16:39.7800000', 'Execute', 6),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 400, '1900-01-01T00:16:39.7800000', 'Execute', 6),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 1000, '1900-01-01T00:16:39.7800000', 'other', 2),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 50, '1900-01-01T00:16:39.7800000', 'Execute', 6),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 52, '1900-01-01T00:16:39.7800000', 'Execute', 6),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 8, '1900-01-01T00:16:39.7800000', 'other', 2),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 4, '1900-01-01T00:16:39.7800000', 'other', 2),
> (1367, '2018-03-15 10:02:52', '2018-03-15T10:19:32.7000000', 740, '1900-01-01T00:16:39.7800000', 'Execute', 6);
> GO
>
> ```
>
>
>
>
> ```
> ;with r as
> (
> select *
> ,case when coalesce(lag(state) over (partition by ID order by KID), '') <> state then 1 end as reset
> from tools
> ), g as
> (
> select *, sum(reset) over (order by KID) as grp
> from r
> where state = 'Execute'
> )
> select ID, StartDatetime, EndDatetime, duration, durationDatetime, state, stateCode,
> sum(duration) over (partition by grp order by KID) CumulativeSum
> from g
> GO
>
> ```
>
>
> ```
>
> ID | StartDatetime | EndDatetime | duration | durationDatetime | state | stateCode | CumulativeSum
> ---: | :------------------ | :-------------------------- | -------: | :-------------------------- | :------ | --------: | ------------:
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 100 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 100
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 900 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 1000
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 400 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 1400
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 50 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 50
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 52 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 102
> 1367 | 2018-03-15 10:02:52 | 2018-03-15T10:19:32.7000000 | 740 | 1900-01-01T00:16:39.7800000 | Execute | 6 | 740
>
> Warning: Null value is eliminated by an aggregate or other SET operation.
>
> ```
>
>
*dbfiddle [here](http://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=5b521f9bcb41f8d14db50a1cb8bf4c0d)*
Upvotes: 0 <issue_comment>username_2: You can try this, I also got this scenario and found solution with this snippet.
```
select grp, value, min(id), max(id), count(*) as cnt
from (select t.*, (row_number() over (order by id) - row_number() over partition by value order by id)
) as grp
from table t
) t
group by grp, value;
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 418 | 1,477 |
<issue_start>username_0: I want to manipulate my text in python. I will use this text to embed as JavaScript data. I need the text in my text file to display exactly as follows. It should have the format I mention below, not only when it prints.
I have text:
`""text""`
and I want:
`\"text\"`
```
with open('phase2.2.1.csv', 'w', newline='') as csvFile:
writer = csv.writer(csvFile)
for b in batches:
writer.writerow([b.replace('\n', '').replace('""', '\\"')])
```
Unfortunately, the above yields
```
\""text\""
```
Any help will be much appreciated.<issue_comment>username_1: I would suggest:
```
.replace('""', '\\"')
```
And it really works, see:
```
In [8]: x = '""text""'
In [9]: print(x.replace('""', '\\"'))
\"text\"
```
Upvotes: 3 <issue_comment>username_2: If what you're trying to generate is JSON-encoded strings, the right way to do that is to use the `json` module:
```
text = json.dumps(text)
```
If you're trying to generate actual JavaScript source code, that's still *almost* the right answer. JSON is very close to being a subset of JavaScript—a lot closer than a quick&dirty fix for one error you happen to have noticed so far is going to be.
If you actually want to generate correct JS code for any possible string, you have to deal with the corner cases where JSON is not quite a subset of JS. But nobody ever does (it took years before anyone even noticed the difference in the specs).
Upvotes: 3 [selected_answer]
|
2018/03/15
| 473 | 1,974 |
<issue_start>username_0: Almost all of the buttons in my angular 4 app have asynchronous operations associated with them. I'm currently adding a loading spinner to each button manually whenever the button is clicked, and removing it when the operation concludes.
I've realized too late that I could have saved myself a lot of time refactoring etc, if I simply had a custom button component that took an asynchronous event handler and added/removed the spinner on its own.
I'm relatively new to angular 2+ and I'm wondering what a good approach to solving this would be. Should I do a custom component? Or just a custom directive? How do I require the clients of such a component/directive to provide me an asynchronous event handler? Do I use custom attributes or some kind of wrapping around the normal event handling?
I'm not asking for code, just the right features to use, I can take it from there.
Edit:
The loading spinner functionality is currently implemented for each button by showing/hiding an icon element via a boolean property in the corresponding component.<issue_comment>username_1: I would suggest:
```
.replace('""', '\\"')
```
And it really works, see:
```
In [8]: x = '""text""'
In [9]: print(x.replace('""', '\\"'))
\"text\"
```
Upvotes: 3 <issue_comment>username_2: If what you're trying to generate is JSON-encoded strings, the right way to do that is to use the `json` module:
```
text = json.dumps(text)
```
If you're trying to generate actual JavaScript source code, that's still *almost* the right answer. JSON is very close to being a subset of JavaScript—a lot closer than a quick&dirty fix for one error you happen to have noticed so far is going to be.
If you actually want to generate correct JS code for any possible string, you have to deal with the corner cases where JSON is not quite a subset of JS. But nobody ever does (it took years before anyone even noticed the difference in the specs).
Upvotes: 3 [selected_answer]
|
2018/03/15
| 415 | 1,360 |
<issue_start>username_0: I want to insert `Employee Id` but every time the `Window` appears.
>
> Enter Parameter Value Ad001
>
>
>
Ad001 is the value of `me.mstrEMpID`.
This is my procedure:
```vb
Dim db
Dim tmpempid As String
tmpempid = (Me.mstrEmpID)
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId]) VALUES ( TmpEmpId );"
DoCmd.OpenTable "Timesheet"
DoCmd.SetWarnings False
DoCmd.RunSQL sqlqry1
DoCmd.SetWarnings True
```
Do you know what is going wrong?<issue_comment>username_1: I would suggest:
```
.replace('""', '\\"')
```
And it really works, see:
```
In [8]: x = '""text""'
In [9]: print(x.replace('""', '\\"'))
\"text\"
```
Upvotes: 3 <issue_comment>username_2: If what you're trying to generate is JSON-encoded strings, the right way to do that is to use the `json` module:
```
text = json.dumps(text)
```
If you're trying to generate actual JavaScript source code, that's still *almost* the right answer. JSON is very close to being a subset of JavaScript—a lot closer than a quick&dirty fix for one error you happen to have noticed so far is going to be.
If you actually want to generate correct JS code for any possible string, you have to deal with the corner cases where JSON is not quite a subset of JS. But nobody ever does (it took years before anyone even noticed the difference in the specs).
Upvotes: 3 [selected_answer]
|
2018/03/15
| 865 | 2,271 |
<issue_start>username_0: I have a table that looks like the following:
```
col1 | col2 | col3 | col4
A | 1 | 2 | 4
A | 2 | 5 | 3
A | 5 | 1 | 6
B | 3 | 1 | 2
B | 4 | 4 | 4
```
I have another table where the records are unique and looks like the following:
```
col1 | col2
A | 2
B | 1
```
I want to query `Table 1` in such a way that I filter out only `n` number of records for each category in `Table 1` based on the value the categories have in `Table 2`.
Based on `Table 2` I need to extract 2 records for `A` and 1 record for `B`. I need the resulting queried table to look like the following:
```
col1 | col2 | col3 | col4
A | 2 | 5 | 3
A | 1 | 2 | 4
B | 3 | 1 | 2
```
The choice of the records are made based on `col4` sorted in ascending order. I am currently tring to do this on BigQuery.<issue_comment>username_1: You can use `row_number()` and `join`:
```
select t1.col1, t1.col2, t1.col3, t1.col4
from (select t1.*, row_number() over (partition by col1 order by col4) as seqnum
from table1 t1
) t1 join
table2 t2
on t2.col1 = t1.col1 and t1.seqnum <= t2.col2
order by t1.col1, t1.col4;
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Below is for BigQuery Standard SQL
```
#standardSQL
SELECT t.*
FROM (
SELECT ARRAY_AGG(t1 ORDER BY t1.col4) arr, MIN(t2.col2) cnt
FROM table1 t1 JOIN table2 t2 ON t1.col1 = t2.col1
GROUP BY t1.col1
), UNNEST(arr) t WITH OFFSET num
WHERE num < cnt
```
you can test / play with it using dummy data from your question as below
```
#standardSQL
WITH `table1` AS (
SELECT 'A' col1, 1 col2, 2 col3, 4 col4 UNION ALL
SELECT 'A', 2, 5, 3 UNION ALL
SELECT 'A', 5, 1, 6 UNION ALL
SELECT 'B', 3, 1, 2 UNION ALL
SELECT 'B', 4, 4, 4
), `table2` AS (
SELECT 'A' col1, 2 col2 UNION ALL
SELECT 'B', 1
)
SELECT t.*
FROM (
SELECT ARRAY_AGG(t1 ORDER BY t1.col4) arr, MIN(t2.col2) cnt
FROM table1 t1 JOIN table2 t2 ON t1.col1 = t2.col1
GROUP BY t1.col1
), UNNEST(arr) t WITH OFFSET num
WHERE num < cnt
```
with output as
```
Row col1 col2 col3 col4
1 A 2 5 3
2 A 1 2 4
3 B 3 1 2
```
Upvotes: 1
|
2018/03/15
| 1,543 | 5,685 |
<issue_start>username_0: I'm beginner in java programing and I encounter a problem. My aim is to relate slider, which give me number of figure's vertices, with simultaneously creating JFieldText fields of coordinates as it is on picture:[](https://i.stack.imgur.com/BqTY8.png)
My attempts led me to the problem where I'm creating those fields but there are to many cols despite of taking 2 in GridLayout and when I'm decreasing the value of vertices, fields doesn't. Here is my sample of code:
```
int vertices = 3;
slider.addChangeListener(new SpinerListener());
class SpinerListener implements ChangeListener {
public void stateChanged(ChangeEvent arg0) {
vertices = slider.getValue();
right.setLayout(new GridLayout(vertices, 2));//right is my panel
for (int i = 0; i < vertices*2; i++) {
fields[i] = new JTextField("Field " + i);
right.add(fields[i]);
}
right.removeAll();
}
}
```<issue_comment>username_1: If you must use JTextFields, then remove all the JTextFields *first* in the listener before re-adding the new JTextFields. You can use `GridLayout(0, 2)` for all since this means 2 columns and variable rows.
Possibly better: use a JTable and simply change the number of rows.
Upvotes: 0 <issue_comment>username_2: You could...
============
Use some kind of `List` - which provides a concept of dynamically sizeable container of objects, instead of using an array. With this, you could then determine if you need to add or remove items from the `List` depending on the new value of the `JSlider`.
```
private List fields = new ArrayList<>(3);
//....
class SpinerListener implements ChangeListener {
public void stateChanged(ChangeEvent arg0) {
vertices = slider.getValue();
if (vertices < fields.size()) {
List oldFields = fields.subList(vertices + 1, fields.size());
for (JTextField[] pairs : oldFields) {
for (JTextField field : pairs) {
right.remove(field);
}
}
fields.removeAll(oldFields);
right.revalidate();
right.repaint();
} else if (vertices > fields.size()) {
int count = (vertices - fields.size());
System.out.println("Add " + count + " new fields");
for (int index = 0; index < count; index++) {
JTextField[] pairs = new JTextField[2];
pairs[0] = new JTextField(4);
pairs[1] = new JTextField(4);
for (JTextField field : pairs) {
right.add(field);
}
fields.add(pairs);
}
right.revalidate();
right.repaint();
}
}
}
```
So, it's pretty basic, it simply compares the number of field pairs to the desired amount and grows or shrinks the `List` accordingly.
As to the `GridLayout`, you actually only need to set it once...
```
right = new JPanel(new GridLayout(0, 2));
```
From the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/awt/GridLayout.html#GridLayout-int-int-)
>
> **Parameters:**
> rows - the rows, with the value zero meaning
> any number of rows.
> cols - the columns, with the value zero
> meaning any number of columns.
>
>
>
But, personally, I'd be tempted to use a `GridBagLayout`, but that's me
And because I had to test the logic...
```
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JSlider slider;
private int vertices = 3;
private List fields = new ArrayList<>(3);
private JPanel right;
public TestPane() {
setLayout(new BorderLayout());
right = new JPanel(new GridLayout(0, 2));
add(new JScrollPane(right));
slider = new JSlider();
slider.addChangeListener(new SpinerListener());
slider.setValue(vertices);
add(slider, BorderLayout.NORTH);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
class SpinerListener implements ChangeListener {
public void stateChanged(ChangeEvent arg0) {
vertices = slider.getValue();
if (vertices < fields.size()) {
List oldFields = fields.subList(vertices + 1, fields.size());
for (JTextField[] pairs : oldFields) {
for (JTextField field : pairs) {
right.remove(field);
}
}
fields.removeAll(oldFields);
right.revalidate();
right.repaint();
} else if (vertices > fields.size()) {
int count = (vertices - fields.size());
System.out.println("Add " + count + " new fields");
for (int index = 0; index < count; index++) {
JTextField[] pairs = new JTextField[2];
pairs[0] = new JTextField(4);
pairs[1] = new JTextField(4);
for (JTextField field : pairs) {
right.add(field);
}
fields.add(pairs);
}
right.revalidate();
right.repaint();
}
}
}
}
}
```
Or you could...
===============
Use a `JTable`, which may be simpler and easier to manage - See [How to use tables](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html) for more details
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,932 | 6,156 |
<issue_start>username_0: <p>I have used the following <a href="https://regexr.com/" rel="nofollow noreferrer">tool</a> to build a valid <a href="https://en.wikipedia.org/wiki/Regular_expression" rel="nofollow noreferrer">regex</a> for mentions and hashtags. I have managed to match what I want in the inserted text, but I need the following matching problems to be resolved.</p>
<blockquote>
<ul>
<li><p>Only match those substrings which start and end with spaces. And in the case of a substring at the beginning or at the end of the string
that is valid (be it a hashtag or a mention), also take it.</p></li>
<li><p>The matches found by the regex only take the part that does not contain spaces, (that the spaces are only part of the rule, but not
part of the substring).</p></li>
</ul>
</blockquote>
<p>The regex that I have used is the following: <code>(([@]{1}|[#]{1})[A-Za-z0-9]+)</code></p>
<p>Some examples of validity and non-validity for string matches:</p>
<pre><code>"@hello friend" - @hello must be matched as a mention.
"@ hello friend" - here there should be no matches.
"hey@hello @hello" - here only the last @hello must be matched as a mention.
"@hello! hi @hello #hi ##hello" - here only the second @hello and #hi must be matched as a mention and hashtag respectively.
</code></pre>
<p>Another example in image, where only <code>"@word"</code> should be a valid mention:</p>
<p><a href="https://i.stack.imgur.com/aAcEA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aAcEA.png" alt="enter image description here"></a></p>
<p><strong>Update 16:35 (GMT-4) 3/15/18</strong></p>
<p>I found a way to solve the problem, using the <a href="https://regexr.com/" rel="nofollow noreferrer">tool</a> in PCRE mode (server) and using <code>negative lookbehind</code> and <code>negative lookahead</code>:</p>
<pre><code>(?<![^\s])(([@]{1}|[#]{1})[A-Za-z0-9]+)(?![^\s])
</code></pre>
<p>Here is the matches:</p>
<p><a href="https://i.stack.imgur.com/OfPJF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OfPJF.png" alt="enter image description here"></a></p>
<p>But now the doubt arises, it works with the regular expression in <code>C#</code>?, both the <code>negative lookahead</code> and the <code>negative lookbehind</code>, because for example in Javascript it would not work, as it was seen in the tool, it marks me with a red line.</p>
<issue_comment>username_1: <p>You can put the start/end of line with an or for spaces around your existing regex. </p>
<p>^ - start</p>
<p>$ - end</p>
<p>\s - space</p>
<pre><code>(^|\s+)(([@]{1}|[#]{1})[A-Za-z0-9]+)(\s+|$)
</code></pre>
Upvotes: 1 <issue_comment>username_2: <p>Try this pattern:</p>
<pre><code>(?:^|\s+)(?:(?<mention>@)|(?<hash>#))(?<item>\w+)(?=\s+)
</code></pre>
<p>Here it is broken down:</p>
<ul>
<li><code>(?:</code> creates a non-capturing group</li>
<li><code>^|\s+</code> matches the beginning of the String or Whitespace</li>
<li><code>(?:</code> creates a non-capturing group</li>
<li><code>(?<mention>@|(?<hash>#)</code> creates a group to match <code>@</code> or <code>#</code> and respectively named the groups mention and hash</li>
<li><code>(?<item>\w+)</code> matches any alphanumeric character one or more times and helps pull the item from the group for easy usage.</li>
<li><code>(?=\s+)</code> creates a positive look ahead to match any white-space</li>
</ul>
<p>Fiddle: <a href="https://regex101.com/r/VMO1sk/1" rel="nofollow noreferrer">Live Demo</a></p>
<p>You would then need to use the underlying language to trim the returning match to remove any leading/trailing whitespace.</p>
<p><strong>Update</strong>
Since you mentioned that you were using C#, I thought that I'd provide you with a .NET solution to solve your problem that does not require RegEx; while I did not test the results, I would guess that this would also be faster than using RegEx too.</p>
<p>Personally, my flavor of .NET is Visual Basic, so I'm providing you with a VB.NET solution, but you can just as easily run it through a converter since I never use anything that can't be used in C#:</p>
<pre><code>Private Function FindTags(ByVal lead As Char, ByVal source As String) As String()
Dim matches As List(Of String) = New List(Of String)
Dim current_index As Integer = 0
'Loop through all but the last character in the source
For index As Integer = 0 To source.Length - 2
'Reset the current index
current_index = index
'Check if the current character is a "@" or "#" and either we're starting at the beginning of the String or the last character was whitespace and then if the next character is a letter, digit, or end of the String
If source(index) = lead AndAlso (index = 0 OrElse Char.IsWhiteSpace(source, index - 1)) AndAlso (Char.IsLetterOrDigit(source, index + 1) OrElse index + 1 = source.Length - 1) Then
'Loop until the next character is no longer a letter or digit
Do
current_index += 1
Loop While current_index + 1 < source.Length AndAlso Char.IsLetterOrDigit(source, current_index + 1)
'Check if we're at the end of the line or the next character is whitespace
If current_index = source.Length - 1 OrElse Char.IsWhiteSpace(source, current_index + 1) Then
'Add the match to the collection
matches.Add(source.Substring(index, current_index + 1 - index))
End If
End If
Next
Return matches.ToArray()
End Function
</code></pre>
<p>Fiddle: <a href="https://dotnetfiddle.net/DaXbW4" rel="nofollow noreferrer">Live Demo</a></p>
Upvotes: 3 [selected_answer]<issue_comment>username_3: <p>This regex can do the job for you.</p>
<pre><code>[@#][A-Za-z0-9]+\s|\s[@#][A-Za-z0-9]+
</code></pre>
<p>The operator <strong>|</strong> is responsible for making a logical "or", so you have 2 different expressions to match.</p>
<pre><code>[@#][A-Za-z0-9]+\s
</code></pre>
<p>and</p>
<pre><code>\s[@#][A-Za-z0-9]+
</code></pre>
<p>where</p>
<pre><code>\s - space
</code></pre>
Upvotes: 0
|
2018/03/15
| 881 | 3,460 |
<issue_start>username_0: I have two users: teachers and students, each of them has different attributes. For example: student has one class, teacher has many classes, etc.
I would like to inherit OctoberCMS Users plugin, and add two controllers with these additional attributes (one for students and another for teachers). So, I've created two models extending user model. these 2 models use the same users table, and I added two tables for teachers and students, but I can't link them with the user table.
```
class Teacher extends User
{
public $hasOne=[
'mobile'=>'??',
]
}
```
So, I want to add a mobile field and other fields to every teacher in the teachers table, how can I do this?
Please note that I don't want to add fields to the users table. I want the shared columns in user table, teacher additional fields in teacher table, and student additional fields in students table.<issue_comment>username_1: Based on my opinion, you should choose different flow than yours. As per my experience, I think you have to make two separate models and controllers for Teachers and Students with separate tables.
After that, you have to assign relations between Teacher, Student and User.
For understanding relations, you can refer [Octobercms relations.](https://octobercms.com/docs/database/relations)
As per my point of view, relations should be given as per below:
In Teacher and Student model,
```
public $belongsTo = [
'user' => [ 'RainLab\User\Models\User' ],
];
```
And Rainlab User plugin have Group model so you can assign Users in different groups like 'teacher' and 'student'.
And further if you want to add extra field like model you can use User Plus plugin also [User Plus plugin.](http://octobercms.com/plugin/rainlab-userplus)
Upvotes: 1 <issue_comment>username_2: Well, This is the solution I get:
1- Add the additional fields of teachers and students to the users table.
2- Let the teacher and student models extend the user model
3- Add a function to each model to add user group (teacher or student) before saving.
4- Apply a filter on the controllers of teachers and students to list only them groups.
This is the full code:
```
class UserAddFields extends Migration
{
public function up()
{
if (Schema::hasColumn('users', 'mobile')) {
return;
}
Schema::table('users', function($table)
{
$table->string('mobile', 100)->nullable();
$table->integer('class_id', 100);
});
}
}
class Teacher extends User
{
public $belongsToMany = [
'groups' => [UserGroup::class, 'table' => 'users_groups', 'key' => 'user_id', 'otherKey' => 'user_group_id']
];
public function beforeCreate()
{
$this->groups=UserGroup::where('code','teachers')->first();
}
}
class Teachers extends Controller
{
public function listExtendQuery($query)
{
$query->whereHas('groups', function ($q){
$q->where('code', '=', "teachers");
});
}
}
```
and the same for students.
Upvotes: 2 <issue_comment>username_3: I used this video to add thee dependencies of each group
[Extending the User plugin](https://vimeo.com/108040919)
It works with only One Group, but when I try to add te custom fields with the same way, I get this error :
"Method ::\_\_toString() must not throw an exception, caught Illuminate\Database\Eloquent\JsonEncodingException: Error encoding model ..."
Upvotes: 0
|
2018/03/15
| 1,262 | 4,255 |
<issue_start>username_0: This seems to be a simple question, and I have looked at another thread and it seems I am doing the same thing, however without results.
This is my code to iteratively insert into a binary search tree, along with the structure and how to create a new node:
```
typedef struct node {
int data;
struct node *left;
struct node *right;
} node;
node *create_node(int data) {
node *n = calloc(1, sizeof(node));
n->data = data;
return n;
}
node *BST_insert_iterative(node *root, int data) {
node *temp = root;
if (root == NULL)
return create_node(data);
while (temp != NULL) {
if (data > temp->data)
temp = temp->right;
else
temp = temp->left;
}
temp = create_node(data);
return root;
}
```
When I print the tree I only receive the first node:
```
Inserting 8 into BST...
Inserting 50 into BST...
Inserting 74 into BST...
Inserting 59 into BST...
Inserting 31 into BST...
Inserting 73 into BST...
Inserting 45 into BST...
Inserting 79 into BST...
Inserting 24 into BST...
Inserting 10 into BST...
In order traversal
8
Height of tree: 0
```
However, using the recursive insert function:
```
node *BST_insert(node *root, int data) {
if (root == NULL)
return create_node(data);
if (root->data >= data)
root->left = BST_insert(root->left, data);
else (root->data < data)
root->right = BST_insert(root->right, data);
return root;
}
```
it works just fine and I get:
```
Inserting 8 into BST...
Inserting 50 into BST...
Inserting 74 into BST...
Inserting 59 into BST...
Inserting 31 into BST...
Inserting 73 into BST...
Inserting 45 into BST...
Inserting 79 into BST...
Inserting 24 into BST...
Inserting 10 into BST...
In order traversal
8
10
24
31
45
50
59
73
74
79
Height of tree: 4
```<issue_comment>username_1: In your insert function, you do not store the new node into the tree. You merely store in to a local variable `temp` and always return `root`.
You must keep a pointer to the link to be updated so the new node is inserted into the tree, or at the root of the tree. Here is a modified version:
```
typedef struct node {
int data;
struct node *left;
struct node *right;
} node;
node *create_node(int data) {
node *n = calloc(1, sizeof(node));
n->data = data;
n->left = n->right = NULL;
return n;
}
node *BST_insert_iterative(node *root, int data) {
node **pp = &root
while (*pp != NULL) {
if (data > (*pp)->data)
pp = &(*pp)->right;
else
pp = &(*pp)->left;
}
*pp = create_node(data);
return root;
}
```
Notes:
* There is no special case for an empty tree.
* Be aware that this approach will not be sufficient to keep the tree balanced.
Note also that your recursive function has a syntax error in what looks like a redundant test. You should simplify it this way:
```
node *BST_insert(node *root, int data) {
if (root == NULL)
return create_node(data);
if (root->data >= data) {
root->left = BST_insert(root->left, data);
} else {
root->right = BST_insert(root->right, data);
}
return root;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Chqrlie's answer worked, but I wanted to do it without using a double pointer.
I was able to do it after realizing my root was not connected to the newly created node.
Here is that solution:
```
node *BST_insert_iterative(node *root, int data)
{
node *temp = root;
int condition = 1;
if (root == NULL)
return create_node(data);
while (condition)
{
if (data > temp->data)
{
if (temp->right == NULL)
{
temp->right = create_node(data);
condition = 0;
}
else
temp = temp->right;
}
else
{
if (temp->left == NULL)
{
temp->left = create_node(data);
condition = 0;
}
else
temp = temp->left;
}
}
return root;
}
```
Upvotes: 0
|
2018/03/15
| 258 | 828 |
<issue_start>username_0: Does anyone know the current numbers for Calendar EventColors
<https://developers.google.com/apps-script/reference/calendar/event-color> Seems deprecated.
My calendar shows 12 colors to choose from.[](https://i.stack.imgur.com/hftsg.png)<issue_comment>username_1: My mistake the 12th represents the default Calendar color ("0"). Looks like they are all there. They are just slightly different in shade and Labelled differently.
Upvotes: 0 <issue_comment>username_2: ```
var color = 1;//Lavender
var color = 2;//Sage
var color = 3;//Grape
var color = 4;//Flamingo
var color = 5;//Banana
var color = 6;//Tangerine
var color = 7;//Peacock
var color = 8;//Graphite
var color = 9;//Blueberry
var color = 10;//Basil
var color = 11;//Tomato
```
Upvotes: 2
|
2018/03/15
| 886 | 3,592 |
<issue_start>username_0: I've done some research here and I understand that in Access nested joins cause issues.
I believe that is the issue in the first example.
```
SELECT
Recipe_Classes.RecipeClassDescription,
Recipes.RecipeTitle,
Recipes.Preparation,
Ingredients.IngredientName,
Recipe_Ingredients.RecipeSeqNo,
Recipe_Ingredients.Amount,
Measurements.MeasurementDescription
FROM (((
Recipe_Classes
LEFT JOIN Recipes
ON Recipe_Classes.RecipeClassID = Recipes.RecipeClassID)
INNER JOIN Recipe_Ingredients
ON Recipes.RecipeID = Recipe_Ingredients.RecipeID)
INNER JOIN Ingredients
ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID)
INNER JOIN Measurements
ON Measurements.MeasureAmountID = Recipe_Ingredients.MeasureAmountID
ORDER BY RecipeTitle, RecipeSeqNo;
```
I made an attempt to remove the nesting and created a right join in this example
```
SELECT
Recipe_Classes.RecipeClassDescription,
Recipes.RecipeTitle,
Recipes.Preparation,
Ingredients.IngredientName,
Recipe_Ingredients.RecipeSeqNo,
Recipe_Ingredients.Amount,
Measurements.MeasurementDescription
FROM (((
Ingredients
INNER JOIN Recipe_Ingredients
ON Ingredeints.IngredientID = Recipe_Ingredients.IngredientID)
INNER JOIN Measurements
ON Measurements.MeasureAmountID = Recipe_Ingredients.MeasureAmountID)
INNER JOIN Recipes
ON Recipes.RecipeID = Recipe_Ingredients.RecipeID)
RIGHT JOIN Recipe_Classes
ON Recipe_Classes.RecipeClassID = Recipes.RecipeClassID
ORDER BY RecipeTitle, RecipeSeqNo;
```
Can anyone point me in the right direction?<issue_comment>username_1: The issue may be the `left join` that is not needed. Try this `from` clause:
```
SELECT Recipe_Classes.RecipeClassDescription,
Recipes.RecipeTitle,
Recipes.Preparation,
Ingredients.IngredientName,
Recipe_Ingredients.RecipeSeqNo,
Recipe_Ingredients.Amount,
Measurements.MeasurementDescription
FROM (((Recipes LEFT JOIN
Recipe_Classes
ON Recipe_Classes.RecipeClassID = Recipes.RecipeClassID
) LEFT JOIN
Recipe_Ingredients
ON Recipes.RecipeID = Recipe_Ingredients.RecipeID
) LEFT JOIN
Ingredients
ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID
) LEFT JOIN Measurements
ON Measurements.MeasureAmountID = Recipe_Ingredients.MeasureAmountID
ORDER BY RecipeTitle, RecipeSeqNo;
```
Once you start with `LEFT JOIN`s, generally all the remaining joins should also be `LEFT JOIN`s.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Since your main focal point table is *Recipe\_Ingredients*, consider starting with this table in `FROM` and then `JOIN` the other parent tables and even nest the *Recipes* and *Recipe\_Classes* pair:
```
SELECT
c.RecipeClassDescription,
r.RecipeTitle,
r.Preparation,
i.IngredientName,
ri.RecipeSeqNo,
ri.Amount,
m.MeasurementDescription
FROM
((Recipe_Ingredients ri
INNER JOIN (Recipes r
RIGHT JOIN Recipe_Classes c
ON c.RecipeClassID = r.RecipeClassID)
ON r.RecipeID = ri.RecipeID)
INNER JOIN Ingredients i
ON i.IngredientID = ri.IngredientID)
INNER JOIN Measurements m
ON m.MeasureAmountID = ri.MeasureAmountID
ORDER BY r.RecipeTitle, ri.RecipeSeqNo;
```
Of course this is untested without data. Due to Access' `JOIN` requirements like parnetheses, it is often recommended for new users to build complex queries with MS Access' GUI Query Design then modify generated SQL as needed.
Upvotes: 0
|
2018/03/15
| 780 | 2,952 |
<issue_start>username_0: I am recieving an attribute error code -´which states that my tuple object has no attribute "size".
>
> AttributeError: 'tuple' object has no attribute 'size'
>
>
>
This is my code: <https://pastebin.com/uCE5Uy1M>
and this is the part of where I recieve the error:
```
for x in range(0, 640, tile.size):
for y in range(0, 480, tile.size):
for i in map_data:
tile = (i[0] * tile.size, i[1] * tile.size)
if (x, y) == tile:
window.blit(tile.textures_tags[i[2]], (x + globals.camera_x, y + globals.camera_y))
```
I am new to python and do not understand my error, since i did define "size" on my sec. python file, which I placed in the same folder. It worked perfectly fine before I added this part.
Here is the link to my sec file called textures.py : <https://pastebin.com/z1uMPBjd>
Could someone please explain this issue for me?<issue_comment>username_1: The issue may be the `left join` that is not needed. Try this `from` clause:
```
SELECT Recipe_Classes.RecipeClassDescription,
Recipes.RecipeTitle,
Recipes.Preparation,
Ingredients.IngredientName,
Recipe_Ingredients.RecipeSeqNo,
Recipe_Ingredients.Amount,
Measurements.MeasurementDescription
FROM (((Recipes LEFT JOIN
Recipe_Classes
ON Recipe_Classes.RecipeClassID = Recipes.RecipeClassID
) LEFT JOIN
Recipe_Ingredients
ON Recipes.RecipeID = Recipe_Ingredients.RecipeID
) LEFT JOIN
Ingredients
ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID
) LEFT JOIN Measurements
ON Measurements.MeasureAmountID = Recipe_Ingredients.MeasureAmountID
ORDER BY RecipeTitle, RecipeSeqNo;
```
Once you start with `LEFT JOIN`s, generally all the remaining joins should also be `LEFT JOIN`s.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Since your main focal point table is *Recipe\_Ingredients*, consider starting with this table in `FROM` and then `JOIN` the other parent tables and even nest the *Recipes* and *Recipe\_Classes* pair:
```
SELECT
c.RecipeClassDescription,
r.RecipeTitle,
r.Preparation,
i.IngredientName,
ri.RecipeSeqNo,
ri.Amount,
m.MeasurementDescription
FROM
((Recipe_Ingredients ri
INNER JOIN (Recipes r
RIGHT JOIN Recipe_Classes c
ON c.RecipeClassID = r.RecipeClassID)
ON r.RecipeID = ri.RecipeID)
INNER JOIN Ingredients i
ON i.IngredientID = ri.IngredientID)
INNER JOIN Measurements m
ON m.MeasureAmountID = ri.MeasureAmountID
ORDER BY r.RecipeTitle, ri.RecipeSeqNo;
```
Of course this is untested without data. Due to Access' `JOIN` requirements like parnetheses, it is often recommended for new users to build complex queries with MS Access' GUI Query Design then modify generated SQL as needed.
Upvotes: 0
|
2018/03/15
| 2,292 | 4,158 |
<issue_start>username_0: I have a large data set, a sample is given below:
```
df <- data.frame(stringsAsFactors=FALSE,
Date = c("2015-10-26", "2015-10-26", "2015-10-26", "2015-10-26",
"2015-10-27", "2015-10-27", "2015-10-27"),
Ticker = c("ANZ", "CBA", "NAB", "WBC", "ANZ", "CBA", "WBC"),
Open = c(29.11, 77.89, 32.69, 31.87, 29.05, 77.61, 31.84),
High = c(29.17, 77.93, 32.76, 31.92, 29.08, 78.1, 31.95),
Low = c(28.89, 77.37, 32.42, 31.71, 28.9, 77.54, 31.65),
Close = c(28.9, 77.5, 32.42, 31.84, 28.94, 77.74, 31.77),
Volume = c(6350170L, 2251288L, 3804239L, 5597684L, 5925519L, 2424679L,
5448863L)
)
```
* The problem I am trying to solve is the missing data for NAB on 27-10-2015
* I want the last value to repeat itself for the missing dates:
```
Date Ticker Open High Low Close Volume
```
>
>
> ```
> 2 2015-10-27 NAB 32.69 32.76 32.42 32.42 3804239
>
> ```
>
>
Any ideas on how to do this?
I have already unsuccessfully tried `gather` + `spread`<issue_comment>username_1: What if you tried something like this?
```
library(zoo)
res <- expand.grid(Date = unique(df$Date), Ticker = unique(df$Ticker))
res2 <- merge(res, df, all.x = TRUE)
res2 <- res2[order(res2$Ticker, res2$Date),]
res3 <- na.locf(res2)
res3[order(res3$Date, res3$Ticker),]
# Date Ticker Open High Low Close Volume
#1 2015-10-26 ANZ 29.11 29.17 28.89 28.90 6350170
#3 2015-10-26 CBA 77.89 77.93 77.37 77.50 2251288
#5 2015-10-26 NAB 32.69 32.76 32.42 32.42 3804239
#6 2015-10-26 WBC 31.87 31.92 31.71 31.84 5597684
#2 2015-10-27 ANZ 29.05 29.08 28.90 28.94 5925519
#4 2015-10-27 CBA 77.61 78.10 77.54 77.74 2424679
#8 2015-10-27 NAB 32.69 32.76 32.42 32.42 3804239
#7 2015-10-27 WBC 31.84 31.95 31.65 31.77 5448863
```
I'm assuming that if a Ticker/Day combo does not exist, you want to create one and `LOCF` it. This is what the `expand.grid` does.
Upvotes: 2 <issue_comment>username_2: Another potential solution (Note: I had to convert your date vector to Date format, but this could be reversed in the final output):
```
library(tidyr)
library(dplyr)
df <- data.frame(stringsAsFactors=FALSE,
Date = as.Date(c("2015-10-26", "2015-10-26", "2015-10-26", "2015-10-26",
"2015-10-27", "2015-10-27", "2015-10-27")),
Ticker = c("ANZ", "CBA", "NAB", "WBC", "ANZ", "CBA", "WBC"),
Open = c(29.11, 77.89, 32.69, 31.87, 29.05, 77.61, 31.84),
High = c(29.17, 77.93, 32.76, 31.92, 29.08, 78.1, 31.95),
Low = c(28.89, 77.37, 32.42, 31.71, 28.9, 77.54, 31.65),
Close = c(28.9, 77.5, 32.42, 31.84, 28.94, 77.74, 31.77),
Volume = c(6350170L, 2251288L, 3804239L, 5597684L, 5925519L, 2424679L,
5448863L))
tickers<- unique(df$Ticker)
dates<- as.Date(df$Date)
possibilities<- as.data.frame(unique(expand.grid(dates,tickers)))
colnames(possibilities)<- c('Date','Ticker')
missing<- anti_join(possibilities,df[,c('Date','Ticker')])
missing_filled<- if(nrow(missing)>0){
replacement<- cbind(missing,filter(df,Date==missing$Date-1,Ticker==missing$Ticker)[,3:7])
}
final<- arrange(rbind(df,replacement),Date)
```
Upvotes: 1 <issue_comment>username_3: `tidyr::complete` and `tidyr::fill` are built just for this situation:
```
library(tidyverse)
df %>%
complete(Date,Ticker) %>%
arrange(Ticker) %>%
fill(names(.)) %>%
arrange(Date)
#
# # A tibble: 8 x 7
# Date Ticker Open High Low Close Volume
#
# 1 2015-10-26 ANZ 29.11 29.17 28.89 28.90 6350170
# 2 2015-10-26 CBA 77.89 77.93 77.37 77.50 2251288
# 3 2015-10-26 NAB 32.69 32.76 32.42 32.42 3804239
# 4 2015-10-26 WBC 31.87 31.92 31.71 31.84 5597684
# 5 2015-10-27 ANZ 29.05 29.08 28.90 28.94 5925519
# 6 2015-10-27 CBA 77.61 78.10 77.54 77.74 2424679
# 7 2015-10-27 NAB 32.69 32.76 32.42 32.42 3804239
# 8 2015-10-27 WBC 31.84 31.95 31.65 31.77 5448863
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,347 | 4,764 |
<issue_start>username_0: Array of objects where the hierarchy objects is stored in hierarchy
property. nesting of objects are done based on this hierarchy
```
[
{
"hierarchy" : ["obj1"],
"prop1":"value"
},
{
"hierarchy" : ["obj1","obj2"],
"prop2":"value",
"prop3":"value"
},
{
"hierarchy" : ["obj1","obj3"],
"prop4":"value",
"prop5":"value"
},
{
"hierarchy" : ["obj1","obj3", "obj4"],
"prop6":"value",
"prop7":"value",
"arr" :["val1", "val2"]
}
]
```
Expected nested object, hierarchy key removed here
```
{
"obj1":{
"prop1":"value",
"obj2" : {
"prop2":"value",
"prop3":"value"
},
"obj3":{
"prop4":"value",
"prop5":"value",
"obj4" : {
"prop6":"value",
"prop7":"value",
"arr" :["val1", "val2"]
}
}
}
}
```
Code I tried but at line 8 unable to get the hierarchy
```
var input = "nested array as above";
var output = {};
var globalTemp = output;
for(var i = 0 ; i
```<issue_comment>username_1: You can use `forEach` and `reduce` methods and inside create shallow copy of current object and delete `hierarchy` property.
```js
const data = [{"hierarchy":["obj1"],"prop1":"value"},{"hierarchy":["obj1","obj2"],"prop2":"value","prop3":"value"},{"hierarchy":["obj1","obj3"],"prop4":"value","prop5":"value"},{"hierarchy":["obj1","obj3","obj4"],"prop6":"value","prop7":"value","arr":["val1","val2"]}]
const result = {}
data.forEach(function(o) {
o.hierarchy.reduce(function(r, e) {
const clone = Object.assign({}, o);
delete clone.hierarchy
return r[e] = (r[e] || clone)
}, result)
})
console.log(result)
```
Upvotes: 2 <issue_comment>username_2: With a newer version of javascript, you could use restparameters for the wanted value key/value pairs and build a nested structure by iterating the given hierarchy property by saving the last property for assigning the rest properties.
The reclaimed part `getFlat` uses an array as stack without recursive calls to prevent a depth first search which tries to get the most depth nodes first.
At start, the stack is an array with an array of the actual object and another object with an empty `hierarchy` property with an empty array, because actually no key of the object is known.
Then a `while` loop checks if the stack has some items and if so, it takes the first item of the stack and takes a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) for getting an object `o` for getting back all key/value pairs and another object `temp` with a single property `hierarchy` with an array of the path to the object `o`.
The `push` flag is set to `false`, because only found properties should be pushed later to the result set.
Now all properties of the object are checked and if
* the value is truthy (to prevent `null` values),
* the type is an object (`null` is an object) and
* the property is not an array
then a new object is found to inspect. This object is pushed to the stack with the actual path to it.
If not, then a value is found. This key/value pair is added to the `temp` object and the flag is set to `true`, for later pushing to the result set.
Proceed with the keys of the object.
Later check `push` and push `temp` object with `hierarchy` property and custom properties to the result set.
```js
function getFlat(object) {
var stack = [[object, { hierarchy: [] }]],
result = [],
temp, o, push;
while (stack.length) {
[o, temp] = stack.shift();
push = false;
Object.keys(o).forEach(k => {
if (o[k] && typeof o[k] === 'object' && !Array.isArray(o[k])) {
stack.push([o[k], { hierarchy: temp.hierarchy.concat(k) }]);
} else {
temp[k] = o[k];
push = true;
}
});
push && result.push(temp);
}
return result;
}
var data = [{ hierarchy: ["obj1"], prop1: "value" }, { hierarchy: ["obj1", "obj2"], prop2: "value", prop3: "value" }, { hierarchy: ["obj1", "obj3"], prop4: "value", prop5: "value" }, { hierarchy: ["obj1", "obj3", "obj4"], prop6: "value", prop7: "value", arr: ["val1", "val2"] }],
object = data.reduce((r, { hierarchy, ...rest }) => {
var last = hierarchy.pop();
hierarchy.reduce((o, k) => o[k] = o[k] || {}, r)[last] = rest;
return r;
}, {}),
reclaimedData = getFlat(object);
console.log(object);
console.log(reclaimedData);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,365 | 4,137 |
<issue_start>username_0: I've made a code that prints a 10x10 grid of O's. I wanted to make all the sides show "X" instead, so I used some if statements. The first 2 works fine but the third one makes everything in the grid "X" and I don't know why.
```
size = 10
def main():
setupBoard(size)
printBoard()
def setupBoard(size):
global board
board = [[0] * size for _ in range(size)]
for row in range(len(board)):
for col in range(len(board)):
if board[row][col] == board[0][col]: #top
board[row][col] = "X"
if board[row][col] == board[row][0]: #left
board[row][col] = "X"
if board[row][col] == board[size-1][size-1]: #right
board[row][col] = "X"
else:
board[row][col] = "O"
def printBoard():
for row in range(len(board)):
print("")
for col in range(len(board)):
print(board[row][col], end = " ")
main()
```
This outputs:
O O O O O O O O O
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
O X X X X X X X X X
When I want it to output:
X X X X X X X X X X X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X O O O O O O O O X
X X X X X X X X X X X
I have no idea of what's wrong and I've been fooling around for some time trying to figure out what's wrong. Help would be appreciated.<issue_comment>username_1: Your problem is these tests:
```
if board[row][col] == board[0][col]: #top
```
This isn't actually testing that your current `row, col` are on the top row. It's testing that whatever value is in your current `row, col` (which will be `0`) is the same as whatever value is in the top of that column (which will be `X` or `O`.
You just want to do this:
```
if (row, col) == (0, col):
```
Or, more simply:
```
if row == 0:
```
---
The next problem is that you've tried to put the bottom and right together into a single test. But that means you're only going to put an `X` in the bottom right corner, not in every bottom and every right slot. You either need two `if` statements, or an `if` statement with an `or` in it.
---
Finally, you have a bunch of separate `if` statements. This means the `else` attaches to the last one of them, not to all of them. In other words, everything that isn't on the right, you'll set to `O`, which will overwrite the `X` you set for the top and left edges. To fix that, you need to use `elif` to chain the `if`s together.
---
Putting it all together:
```
if row == 0: # top
board[row][col] = "X"
elif col == 0: # left
board[row][col] = "X"
elif row == size-1: # bottom
board[row][col] = "X"
elif col == size-1: # right
board[row][col] = "X"
else:
board[row][col] = "O"
```
Or you could `or` all those conditions together, because you do the same thing for every condition:
```
if row == 0 or col == 0 or row == size-1 or col == size-1:
board[row][col] = "X"
else:
board[row][col] = "O"
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This should not be the answer as it doesn't answer your question specifically -- but just do give you another perspective, you can make your life easier by doing it in such a way that you don't have to use an if statement at all, and gets rid of two levels of nesting. Usually in Python there is a better way than for/nexting through each item.
```
size = 10
def main():
board = setup_board(size)
print_board(board)
def setup_board(size):
board = [[0] * size for _ in range(size)]
board[0] = ['X'] * size
board[-1] = ['X'] * size
for i in range(1, size - 1):
row = ['O'] * size
row[0] = 'X'
row[-1] = 'X'
board[i] = row
return board
def print_board(board):
for row in range(len(board)):
print("")
for col in range(len(board)):
print(board[row][col], end=" ")
main()
```
Upvotes: 0
|
2018/03/15
| 1,025 | 3,515 |
<issue_start>username_0: So, I was optimizing a query I carried over from SQL, and I ran into a bit of a performance issue when compared to how it used to work in sql.
Basically, my php script is sending between 2 and 5 sets of two (numeric) values.
These have to be compare against id and doc from my collection's elements. Of course, the fewer elements in the predicate, the faster the query
My for with predicate looks like this right now:
```
for $p in collection("/db/col1")//set1/page[(id eq val1 and doc eq altval1) or (id eq val2 and doc eq altval2) or (id eq val3 and doc eq altval3) or (id eq val4 and doc eq altval4) or (id eq val5 and doc eq altval5)]
```
I need to somehow write a predicate that changes depending on the number of values. I tried writing a function that writes the conditions and calling it in the predicate, depending on how many values are passed, but that didn't seem to work.
I would really appreciate if someone knows a workaround for this.
Edit: Removed a typo in the code.<issue_comment>username_1: If `$val` and `$altval` are two sequences of values, then you can write the generic predicate
```
SOMETHING[some $i in 1 to count($val) satisfies (id=$val[$i] and doc=$altval[$i]]
```
But I've no idea how well it will perform.
Upvotes: 3 <issue_comment>username_2: If you wanted to use a function in the predicate, then something like the following could possibly work for you:
```
xquery version "3.1";
declare variable $local:criteria := array {
("val1", "altval1"),
("val2", "altval2"),
("val3", "altval3"),
("val4", "altval4"),
("val5", "altval5")
};
declare function local:match($id, $doc) as xs:boolean {
array:size(
array:filter($local:criteria, function($x) {
$id eq $x[1] and $doc eq $x[2]
})
) eq 1
};
collection("/db/col1")//set1//page[local:match(id, doc)]
```
Note - I have not tested the performance of the above.
Also maybe worth mentioning that ancestor lookup in eXist-db is very fast due to its [DLN node numbering](https://xml.niwa.co.nz/xml/xmlprague06.xml#N10151). So it may be worth testing if `//set1//page` is slower than say `//page[ancestor::set1]`.
Upvotes: 2 <issue_comment>username_3: I upvoted both answers since they both get the job done and I could clearly see an improvement. I don't want to select one over the other as I really think it's more a matter of taste at this point.
For my part, I found a third one which, specifically for this case is even faster. On the down side, it's horribly tedious, inelegant and very context specific. Also, while your answers can be adapted to several similar problems, this one only works in the case when you are 'triggering' the XQuery scripts externally. So here it goes:
I actually made FIVE different xql scripts, one that deals with 1 pair of values, one that deals with the first two pairs, on with the first three pairs etcetera.
So script one would contain:
```
for $p in collection("/db/col1")//set1/page[id eq val1 and doc1 eq altval1]
```
while in script five you would find something like the original:
```
for $p in collection("/db/col1")//set1/page[(id eq val1 and doc eq altval1) or (id eq val2 and doc eq altval2) or (id eq val3 and doc eq altval3) or (id eq val4 and doc eq altval4) or (id eq val5 and doc eq altval5)]
```
I then call them from my PHP script, depending on the number of parameters I need to send. I wouldn't attempt to scale this to more than five pairs, but for the moment it gets the job done.
Upvotes: 0
|
2018/03/15
| 260 | 942 |
<issue_start>username_0: Using Google Sheets, is there a way to create charts for only certain rows?
I have created some reports, but when the source list is sorted differently the report breaks because of using the data source as `'SourceTab'!A2:X2`. In the source tab I have about 60+ rows, but only want to report on certain rows.
I thought I could add a column to each row to create groupings, then in the chart call those groupings to create the reports.<issue_comment>username_1: you can **`QUERY()`** them out like this:
```
=QUERY({2:2; 4:5; 8:8}, "select *", 0)
```
[](https://i.stack.imgur.com/pKdlt.png)
Upvotes: 0 <issue_comment>username_2: `add a column to each row to create groupings` sounds a good idea. Just create your chart from all available data then filter your data to select only the rows flagged in that column.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,298 | 3,877 |
<issue_start>username_0: As a JS novice I am trying to store all values of an object inside separate divs. (per div the name of the chord and an image).
I get all values logged to the console, but when I store it inside a div I only get the final outcome of the loop, being the last value. In other words: I cant seem to find out how to store the values inside a div for each time the loop runs.
Thank you in forehand!
here the stuff:
```js
var output = document.getElementById('output');
// chords & tabs images
var chords = {
"C": {
"Chord" : "C",
"imgSrc" : "http://www.guitar-chords.org.uk/chord-images/c-major-1.gif"
},
"Cmaj9": {
"Chord" : "Cmaj9",
"imgSrc" : "http://www.totalguitarandbass.com/system/diagrams/495/original/CMaj9.png?1472445766"
}
};
// looping through
for(var key in chords) {
var value = chords[key];
// log
console.log(value);
// my silly attempt
output.innerHTML = "" + "" + value.Chord + "
===================
" + "";
}
```
```css
div {
box-sizing:border-box;
display:block;
}
.chord {
display:block;
float:left;
width:250px;
height:auto;
border:1px solid tomato;
}
.chord h1 {
font-size:2.4em;
text-align:center;
padding:5px;
}
.chord img {
display:block;
margin-top:25px;
width:200px;
height:auto;
padding:25px;
}
```<issue_comment>username_1: Using = overwrites any prior changes to the property.
You should use the += operator to append the next element to the innerHTML:
```js
var output = document.getElementById('output');
// chords & tabs images
var chords = {
"C": {
"Chord" : "C",
"imgSrc" : "http://www.guitar-chords.org.uk/chord-images/c-major-1.gif"
},
"Cmaj9": {
"Chord" : "Cmaj9",
"imgSrc" : "http://www.totalguitarandbass.com/system/diagrams/495/original/CMaj9.png?1472445766"
}
};
// looping through
for(var key in chords) {
var value = chords[key];
// log
console.log(value);
// vvvv Right here vvvvv
output.innerHTML += "" + "" + value.Chord + "
===================
" + "";
}
```
```css
div {
box-sizing:border-box;
display:block;
}
.chord {
display:block;
float:left;
width:250px;
height:auto;
border:1px solid tomato;
}
.chord h1 {
font-size:2.4em;
text-align:center;
padding:5px;
}
.chord img {
display:block;
margin-top:25px;
width:200px;
height:auto;
padding:25px;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a fiddle: <https://jsfiddle.net/treyeckels/jszzg1oa/>
The content of the div is always being replaced by your last line in your `for` loop, which is why the last item in your content array is what's always only displayed.
`innerHTML` is a property of the `output` node that you are retrieving using `getElementById`, so you are writing over the innerHTML of the node every loop.
Instead what you want to do is create new DOM nodes and append them to the last child in the `output` div or if you want to continue to use `innerHTML`, concatenate all of the contents together as a string and then set `output` innerHTML to the concatenated string.
Something like (in es6):
```
const chords = [
{
"Chord" : "C",
"imgSrc" : "http://www.guitar-chords.org.uk/chord-images/c-major-1.gif"
},
{
"Chord" : "Cmaj9",
"imgSrc" : "http://www.totalguitarandbass.com/system/diagrams/495/original/CMaj9.png?1472445766"
}
];
const getHTML = (chord, imgSrc) => {
return(
`
${chord}
========

`
)
};
const completeHTML = chords.reduce((prev, next) => {
return prev + getHTML(next.Chord, next.imgSrc);
}, '');
const output = document.getElementById('output');
output.innerHTML = completeHTML;
```
Upvotes: 0
|
2018/03/15
| 823 | 3,156 |
<issue_start>username_0: I am using Angular 5 and I seem to not be able to get data from ActivatedRoute using methods stated in other answers to my question.
app.routes.ts
```
export const AppRoutes = [
{
path : '',
component: HomeView,
pathMatch: 'full', data: {key: 'home', label: 'Home'}},
{
path : 'about',
loadChildren: './+about/about.module#AboutModule'
},
{
path : 'account/:id',
loadChildren: './+account/account.module#AccountModule',
canActivate: [AuthGuard],
data: {key: 'account', label: 'My Account'}
},
];
```
app.component.ts
```
@Component({
selector: 'ou-app',
templateUrl: 'app.component.html',
styleUrls: ['../styles/main.scss'],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private route: ActivatedRoute,
){}
ngOnInit(){
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
console.log('router events console... ', this.route);
});
}
}
```
I can't seem to get the data from the route under snapshot, root, children, firstChild, everything is null, or undefined<issue_comment>username_1: The issue is that you are not *at* the route that you are trying to look at. You need to go through the child routes. There is an example here: [Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute](https://stackoverflow.com/questions/38877123/retrieving-a-data-property-on-an-angular2-route-regardless-of-the-level-of-route)
I was able to modify your code as follows using the info from the above link.
```
router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
console.log(route.snapshot.data);
while (route .firstChild) route = route.firstChild;
return route;
})
.mergeMap(route => route.data)
.subscribe(x => {
console.log('router events console... ', x);
});
```
With this code I was able to get this:
[](https://i.stack.imgur.com/DHIpG.png)
**Update:** With RxJs v5.5 and above
```
ngOnInit() {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
mergeMap((route) => route.data))
.subscribe((event) => console.log('router events console... ', event));
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: I was able to solve my problem following this github issue: <https://github.com/angular/angular/issues/11812>
```
this.router.events.subscribe((data) => {
if (data instanceof RoutesRecognized) {
console.log(data.state.root.firstChild.data);
}
});
```
Upvotes: 0
|
2018/03/15
| 1,282 | 4,333 |
<issue_start>username_0: I have almost finished developing my login system and there is one more thing that I'm not sure about. So many debates I found on should the internet about counting invalid logins and locking users account. My system stores user names and passwords (that are salted and hashed) in database. If user enters invalid user name or password I keep track of their `Username`, `Password`, `LoginTime`, `SessionID`, `IP` and `Browser`. Here is example:
```
LoginID LoginTime LoginUN LoginPW LoginSessionID LoginIP LoginBrowser
1 2018-03-15 13:40:25.000 jpapis test E72E.cfusion 10.18.1.37 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
98 2018-03-15 13:48:45.000 mhart mypass55 E72E.cfusion 10.12.1.87 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
32 2018-03-15 14:29:14.000 skatre 1167mmB! 378E.cfusion 10.36.1.17 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
```
I'm wondering if I should lock account after X attempts? If so what would be the best practice to do that? Here is one approach that I found:
```
SELECT COUNT(LoginID) AS countID, DATEDIFF(mi,LoginTime,GETDATE ( )) AS TimeElapsed
FROM FailedLogins
WHERE (LoginUN = '#username#' OR LoginSessionID = '#SESSION.sessionid#' OR LoginIP = '#REMOTE_ADDR#')
AND DATEDIFF(mi,LoginTime,GETDATE ( )) <= 60
GROUP BY LoginID, LoginTime
HAVING COUNT(LoginID) >= 5;
```
Query above will look for `username`, `sessionID` or `IP` address. If either of these it's found in `FailedLogin` table within `60min` and it's greater than 5 I would lock the account. Only problem here is I'm not sure what this would prevent, brute force attack can send way too many attempts in 60min so I'm not sure what would be the benefit of checking failed logins this way. Is there better way to handle failed logins now days? Should I even lock the account? If anyone can provide some thoughts and examples please let me know. Thank you.<issue_comment>username_1: You must create a password lockout system only for **payed or premium accounts, or if the website you or someone else owns is extremely popular (More than 100,000 annual viewers)**, as they are most valued, and most likely to be attacked. If you expect such a volume of people, then it is best practice to implement this. You can see many large corporations doing this practice, Google locks people out of accounts because they can contain money like in Google Play Store Credits or Android Pay wallets. The same goes for Minecraft accounts, Netflix accounts, etc. The algorithm behind this is something like this :
```
if(md5($password)==$loginrow['login'])
{
//Do your login sequence here
}
else
{
if($loginrow['AttemptsInPastFifteenMinutes']>=15)
{
mysqli_query($dbconnect,'CREATE EVENT reset ON SCHEDULE EVERY 15 MINUTE DO UPDATE ' .$loginrow['user']. 'set AttemptsInPastFifteenMinutes = 0');
echo 'alert("You have typed in invalid passwords too many times. Please try again later.");';
}
else
{
mysqli_query($dbconnect,'UPDATE logins SET AttemptsInPastFifteenMinutes=' .($loginrow['AttemptsInPastFifteenMinutes'] + 1). ' WHERE user=' .$loginrow['user']');
echo 'alert("Invalid username or password");';
}
}
```
Upvotes: -1 <issue_comment>username_2: Agree with @Ageax on checking [Information Security](https://security.stackexchange.com/search?q=locking%20account%20failed%20login).
>
> I'm not sure that I need this kind of security check in my system.
>
>
>
Yes, you do. You always do. It's those that don't that often appear on the news.
Some best practices
* Lock account after X number of failed logins.
* Keep a record of Y past passwords (hashed, not plain text). When someone updates their password, check the new one against the old ones so they can't reuse recent passwords (compare hashes).
* Monitor failed attempts past X to determine if you need to block IP addresses if failed attempts become excessive.
* When a user's login fails, never tell them if it was specifically the user name or the password that was incorrect. You're just helping hackers progress faster.
Do some reading on the other site and see what else is recommended.
Upvotes: 2
|
2018/03/15
| 824 | 3,260 |
<issue_start>username_0: I am currently translating a C# Selenium framework to Java. In that framework I have a property that returns the current WebDriverWait;
`private WebDriverWait elementFindTimings;`
`.`
`.`
`.`
`public TimeSpan FindTimeout { get { return elementFindTimings.Timeout; } }`
I have translated this to a Java get method;
`private WebDriverWait elementFindTimings;`
`.`
`.`
`.`
`\\ The .getTimeout() method does not exist in the WebDriverWait class, I've`
`\\ put it in for example of what I'm trying to do.`
`public Duration getFindTimeout() { return elementFindTimings.getTimeout(); }`
However, the Java WebDriverWait - which extends FluentWait implementing Wait - does not appear to have a method that enables me to get the Duration value. Obviously I'm missing something here as the WebDriver code that uses WebDriverWait needs to get the Duration. Being new to Java I'm probably missing a key Java language thing here. So, how do I get the WebDriverWait duration?<issue_comment>username_1: You must create a password lockout system only for **payed or premium accounts, or if the website you or someone else owns is extremely popular (More than 100,000 annual viewers)**, as they are most valued, and most likely to be attacked. If you expect such a volume of people, then it is best practice to implement this. You can see many large corporations doing this practice, Google locks people out of accounts because they can contain money like in Google Play Store Credits or Android Pay wallets. The same goes for Minecraft accounts, Netflix accounts, etc. The algorithm behind this is something like this :
```
if(md5($password)==$loginrow['login'])
{
//Do your login sequence here
}
else
{
if($loginrow['AttemptsInPastFifteenMinutes']>=15)
{
mysqli_query($dbconnect,'CREATE EVENT reset ON SCHEDULE EVERY 15 MINUTE DO UPDATE ' .$loginrow['user']. 'set AttemptsInPastFifteenMinutes = 0');
echo 'alert("You have typed in invalid passwords too many times. Please try again later.");';
}
else
{
mysqli_query($dbconnect,'UPDATE logins SET AttemptsInPastFifteenMinutes=' .($loginrow['AttemptsInPastFifteenMinutes'] + 1). ' WHERE user=' .$loginrow['user']');
echo 'alert("Invalid username or password");';
}
}
```
Upvotes: -1 <issue_comment>username_2: Agree with @Ageax on checking [Information Security](https://security.stackexchange.com/search?q=locking%20account%20failed%20login).
>
> I'm not sure that I need this kind of security check in my system.
>
>
>
Yes, you do. You always do. It's those that don't that often appear on the news.
Some best practices
* Lock account after X number of failed logins.
* Keep a record of Y past passwords (hashed, not plain text). When someone updates their password, check the new one against the old ones so they can't reuse recent passwords (compare hashes).
* Monitor failed attempts past X to determine if you need to block IP addresses if failed attempts become excessive.
* When a user's login fails, never tell them if it was specifically the user name or the password that was incorrect. You're just helping hackers progress faster.
Do some reading on the other site and see what else is recommended.
Upvotes: 2
|
2018/03/15
| 409 | 1,261 |
<issue_start>username_0: Trying to translate linux cmd to python script
Linux cmds:
```
chmod 777 file1 file1/tmp file2 file2/tmp file3 file3/tmp
```
I know of `os.chmod(file, 0777)` but I'm not sure how to use it for the above line.<issue_comment>username_1: `os.chmod` takes a single filename as argument, so you need to loop over the filenames and apply `chmod`:
```
files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
os.chmod(file, 0o0777)
```
BTW i'm not sure why are you setting the permission bits to `777` -- this is asking for trouble. You should pick the permission bits as restrictive as possible.
Upvotes: 5 [selected_answer]<issue_comment>username_2: `chmod 777` will get the job done, but it's more permissions than you likely want to give that script.
It's better to limit the privileges to execution.
I suggest: `chmod +x myPthonFile.py`
Upvotes: -1 <issue_comment>username_3: If you want to use `pathlib`, you can use [`.chmod()` from that library](https://docs.python.org/3/library/pathlib.html#pathlib.Path.chmod)
```
from pathlib import Path
files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
Path(file).chmod(0o0777)
```
Upvotes: 0
|
2018/03/15
| 672 | 2,524 |
<issue_start>username_0: I'm trying to restore a database from a bak file. I found some code on how to do it grammatically but I'm not sure what I'm doing wrong. I'm getting an error:
Error:
Restore failed for Server 'www.freegamedata.com'.
I assume because i'm remotely connected? I'm not sure. The bak file is not on the server machine. I'm trying to build a desktop application that will install my database on the users server using my file. Here is my code:
```
private void Restore_Database()
{
try
{
Server server = new Server(Properties.Settings.Default.SQL_Server);
string filename = "Test.bak";
string filepath = System.IO.Directory.GetCurrentDirectory() + "\\file\\" + filename;
Restore res = new Restore();
res.Database = Properties.Settings.Default.SQL_Database;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(filepath, DeviceType.File);
res.PercentCompleteNotification = 10;
res.ReplaceDatabase = true;
res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);
res.SqlRestore(server);
}
catch(Exception ex)
{
}
}
```
I'm not sure if I'm going about this the correct way. I'd like to add my database with my data to the users server as a base database. Am I doing something wrong? My connection string is good so I know its not a connection issue.<issue_comment>username_1: `os.chmod` takes a single filename as argument, so you need to loop over the filenames and apply `chmod`:
```
files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
os.chmod(file, 0o0777)
```
BTW i'm not sure why are you setting the permission bits to `777` -- this is asking for trouble. You should pick the permission bits as restrictive as possible.
Upvotes: 5 [selected_answer]<issue_comment>username_2: `chmod 777` will get the job done, but it's more permissions than you likely want to give that script.
It's better to limit the privileges to execution.
I suggest: `chmod +x myPthonFile.py`
Upvotes: -1 <issue_comment>username_3: If you want to use `pathlib`, you can use [`.chmod()` from that library](https://docs.python.org/3/library/pathlib.html#pathlib.Path.chmod)
```
from pathlib import Path
files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
Path(file).chmod(0o0777)
```
Upvotes: 0
|
2018/03/15
| 952 | 2,812 |
<issue_start>username_0: I'm going through freeCodeCamp and am having trouble with their "Return Largest Numbers in Arrays" problem. The issue seems to be with my code for finding every fourth element in the second "for" loop. It looks like it's including the commas from the array "decArray". Any ideas on how to fix this or reorient my thinking process? I appreciate it!
The Instructions:
* Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
* Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].
* largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
* largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].
* largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
Here's My Code:
```js
function largestOfFour(arr) {
var decArray = []; // initialize variable to sort each subarray in descending order
var finalArray = []; // initialize variable for final array
// sort array values in descending numerical order instead of by alphabetical order
function sortNumber(a,b) {
return a - b;
}
// loop through initial array to sort each subarray in descending order
for (var i = 0; i < arr.length; i++) {
decArray += arr[i].sort(sortNumber).reverse() + ",";
}
// loop through decArray to find every fourth element
for (var j = 0; j < decArray.length; j += 4) {
finalArray.push(decArray[j]);
}
// return the final array
return finalArray;
}
// test array
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
```<issue_comment>username_1: decArray is an array so you are supposed to push items there instead of append string to it.
replace below line
```
decArray += arr[i].sort(sortNumber).reverse() + ",";
```
with this
```
decArray.push(...arr[i].sort(sortNumber).reverse());
```
Let me know if this works for you.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Actually the problem with your code is that when you are doing this `decArray += arr[i].sort(sortNumber).reverse() + ",";` you are converting array to string and at the end decArray will become string with info `5,4,3,1,....`, so when you doing decArrayj it will return 3 as it is the fifth element in string, so you getting wrong answer. To solve this either do this `finalArray.push(arr[i].sort(sortNumber).reverse()[0])` and remove thrid for loop. or try below code
```js
function largestOfFour(arr){
var finalArray = [];
for(i = 0, i2 = arr.length; i
```
Upvotes: 1
|
2018/03/15
| 1,374 | 4,829 |
<issue_start>username_0: AngularDart has a class called `AppView`, i.e. `abstract class AppView {}`.
One (at least) of these are generated for every class annotated with `@Component`:
```
// file.dart
@Component(...)
class DashboardComponent {}
// file.template.dart (Generated)
class ViewDashboardComponent extends AppView {}
```
I have code elsewhere in the framework that doesn't care what this `T` type is. I'm a little confused with Dart 2 what the "right" "anything" type to use. For example, I could use:
* `AppView`
* `AppView`
* `AppView`
* `AppView`
* `AppView`
I think more than one of these will "work". But which is the "right" one to use in this case?<issue_comment>username_1: I assume you know better than me, but my attempt
* `AppView` - works - same as `AppView`
* `AppView` - works - really means any type
* `AppView` - works - really means any type
* `AppView` - won't work, only `null` and `void` values match for `T`
* `AppView` - won't work, only `null` and `void` values match for `T`
`AppView` - works (see also comment below from lrn)
The difference between and would be that for values of type `T` with `T` == `dynamic` property or method access won't be checked statically, while for `T` == `Object` only methods and properties of the `Object` class can be accessed without a previous cast.
Upvotes: 1 <issue_comment>username_2: You should be fine to use `AppView` (or `AppView`) just about anywhere. I can think of two examples where this will get you into trouble though:
1. If you are *instantiating* an AppView, you definitely want that type parameter. See the following error when you don't:
```
$ cat a.dart
void main() {
List a = ["one", "two", "three"];
List b = a;
}
$ dart --preview-dart-2 a.dart
Unhandled exception:
type 'List' is not a subtype of type 'List' where
List is from dart:core
List is from dart:core
String is from dart:core
#0 main (file:///Users/sam/a.dart:3:20)
#1 \_startIsolate. (dart:isolate/isolate\_patch.dart:279:19)
#2 \_RawReceivePortImpl.\_handleMessage (dart:isolate/isolate\_patch.dart:165:12)
```
2. If you are ever *assigning a closure* to a site that expects a closure with one or more typed parameters that involve T, you will see a "uses dynamic as bottom" static error (from the analyzer), and probably a runtime error as well:
```
$ cat f.dart
void main() {
List a = ["one", "two", "three"];
a.map((String s) => s.toUpperCase());
List b = ["one", "two", "three"];
b.map((String s) => s.toUpperCase());
}
$ dart --preview-dart-2 f.dart
f.dart:3:9: Error: A value of type '(dart.core::String) → dart.core::String' can't be assigned to a variable of type '(dynamic) → dynamic'.
Try changing the type of the left hand side, or casting the right hand side to '(dynamic) → dynamic'.
a.map((String s) => s.toUpperCase());
^
f.dart:6:9: Error: A value of type '(dart.core::String) → dart.core::String' can't be assigned to a variable of type '(dynamic) → dynamic'.
Try changing the type of the left hand side, or casting the right hand side to '(dynamic) → dynamic'.
b.map((String s) => s.toUpperCase());
^
```
(I'm not certain *any* Dart tool yet has complete Dart 2 runtime and compile time semantics, so this might change slightly.)
In these cases, it is best to use [generic classes](https://www.dartlang.org/guides/language/language-tour#generics), [generic methods](https://www.dartlang.org/guides/language/language-tour#using-generic-methods), and [generic typedefs](https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md) to encapsulate, for a given scope, what the values of an object's type parameters might be.
I suspect there is a difference between `dynamic` and `Object` in Dart 2, and I think Günter covered this in his response, though if your code "doesn't care what this T type is", then you're probably not calling any methods on the component.
Edit: void
----------
`AppView` might be a good choice in this case, as an actual check that you *actually* never touch the underlying component (Object would probably serve the same purpose). See how we are allowed to access properties of a `List` but not properties of the elements:
```
$ cat g.dart
void main() {
var c = ["one", "two", "three"];
fn(c);
fn2(c);
}
int fn(List list) => list.length;
int fn2(List list) => list.first.length;
$ dart --preview-dart-2 g.dart
g.dart:9:40: Error: The getter 'length' isn't defined for the class 'void'.
Try correcting the name to the name of an existing getter, or defining a getter or field named 'length'.
int fn2(List list) => list.first.length;
^
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,008 | 3,364 |
<issue_start>username_0: I'm try to write a username field validator and one of the reqs is that the field must contain at least 2 numbers (more is ok, just no less). I thought I could do something like this, and the regex splits on the first number, but never on the second.
```
String[] arr = string.split("[0-9][0-9]");
return arr.length > 2;
```
Use cases:
Bob11
Bo1b1
11Bob
1Bob1<issue_comment>username_1: Use `string.match(‘.*\d.*\d.*’);`
It will look for one digit two times in a string.
Upvotes: -1 <issue_comment>username_2: Try this:
* .\* matches everything (from 0 to n times)
* [0-9] is number from 0-9
```js
Pattern pattern = Pattern.compile("[0-9].*[0-9]");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
return true;
}
```
And you can check regex in <https://www.freeformatter.com/regex-tester.html>
Upvotes: 2 [selected_answer]<issue_comment>username_3: You do not need RegEx for this. I'm not sure what language you're using, but it is safe to assume that a String in your language is essentially a Char array. If that is the case, then get the count of digit characters in the Char array and compare if it is greater than 1.
For example, here is a C# example:
```
String username = Console.ReadLine();
if (username.Count(c => Char.IsDigit(c)) > 1) {
Console.WriteLine("The String contains 2 or more digits.");
} else {
Console.WriteLine("The String did not contain 2 or more digits.");
}
```
This would likely yield faster results too.
Upvotes: -1 <issue_comment>username_4: `[^\d]*\d[^\d]*\d.*` should be one way to go (there are several..)
* [^\d]\* Matches any character which is not a digit (zero to infinite times)
* \d matches a single digit (once)
* .\* matches everything (zero to infinite times)
I use `[^\d]*` because `.*` is greedy and thus *might* match too much (depending on the language). Greedy behavior can be disabled by appending `?`: `.*?`
You can test it at <https://regex101.com/>.
Upvotes: 0 <issue_comment>username_5: Remove all non numeric characters using regex and count the length
Upvotes: 0 <issue_comment>username_6: Below is my version, that has an extremely fast execution, can be easily updated to different criteria, and has a better readability (at least to me):
*Regex*
`(\D*\d){2,}`
*Example*
```
Bob11 - Match
Bo1b1 - Match
11Bob - Match
1Bob1 - Match
11235 - Match
Bobb - Does NOT Match
Bob1 - Does NOT Match
Bo1b - Does NOT Match
1Bob - Does NOT Match
```
*Explanation*
`\D` - non digit.
`*` - (quantifier) zero or more times.
`\d` - one digit.
`(\D*\d)` - encapsulate the combination above as a group.
`{2,}` - (quantifier) ensures that the group occurs at least 2 times, being able to occur more times.
`(\D*\d){2,}` - So, `\D*` non digit zero or infinite times, followed by a `\d` digit, this combination repeated `{2,}` two or infinite times.
*Updating to different criteria*
The `^` (start string anchor) and `$` (end string anchor) can be included to ensure restriction, in case the criteria changes to be exact 2 or any other number.
This is an example that ensures no more, no less that 5 numbers anywhere in a string: `^(\D*\d){5}\D*$`. *The last \D* is necessary to allow the string to end with a non digit, validating the regex if the criteria of five digits be satisfied.\*
Upvotes: 3
|
2018/03/15
| 883 | 3,066 |
<issue_start>username_0: So i read out lines out of a file and then read out the lines via stringstream.
I found the Issue that because of the format of the line rarely 2 seperate parts are written together and get read together as one string. I tryed to fix that situation by putting the wrong read value back on the stream and read again but it looks like istringstream doesnt care i put the chars back. they simply dont get read out again.
Here the Problem broken down. S1 is a good string. S2 adresses the Issue with the wrong read in the comments:
In short. Is it possible to put a string back on istringstream and read it with the next operation??
```
#include
#include
#include
int main()
{
std::string device\_id; //126, I\_VS\_MainVoltageAvailabl
std::string ea\_type; //E
std::string address; //0.1
std::string data\_type; //BOOL
std::vector comment; //VS - Steuerspannung vorhanden / Main voltage available"
std::string s1 = "126,I\_Btn\_function\_stop E 1.2 BOOL Taster Stopp Funktion / Button Stop Function";
std::string s2 = "126,I\_VS\_MainVoltageAvailablE 0.1 BOOL VS - Steuerspannung vorhanden / Main voltage available";
std::istringstream ist{ s2 };
ist >> device\_id; // Read 126, I\_VS\_MainVoltageAvailablE the E should be read in ea\_type
ist >> ea\_type; // 0.1
//my idea
if (!ea\_type.empty() && isdigit(static\_cast(ea\_type[0]))) { //first is a digit so already next was read
for (const auto& x : ea\_type) //Try to put 0.1 in the stream
ist.putback(x);
ea\_type = device\_id[device\_id.size() - 1]; // = "E"
device\_id.pop\_back(); // = "126, I\_VS\_MainVoltageAvailabl"
}
ist >> address; // Expected "0.1" instead "BOOL" why 0.1 was putback on the stream???
ist >> data\_type;
for (std::string in; ist >> in;)
comment.push\_back(in);
}
```<issue_comment>username_1: As usual, people are ignoring return codes. `putback` has a return code for a reason, and when it is false, it means `putback` failed.
In particular, `std::istringstream` is *input* string stream, and as such, is input-only stream. Because of that, you can't use `putback` on it, it will always fail.
However, you can use `std::stringstream` instead, and with that `putback` will behave the way you want it to.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I would suggest that your logic is malformed. What you actually have is a fixed field format which is not amenable to the istream extraction operators.
You would do better to read a whole line of input, then extract the "fields" by their column offsets.
Or, read one byte at a time, appending to the string variable you want to extract, until you have read enough bytes to fill it. That is, read 29 bytes into device\_id, then however many (1? 8?) bytes into ea\_type, etc.
I want to question your comments, though. The istream string extractor `operator>>(std::istream&, std::string&)` will pull one *space delimited* token off the input stream. In other words, your first extraction pulls off `"126,"`. So the rest of the logic is completely wrong.
Upvotes: 1
|
2018/03/15
| 730 | 2,367 |
<issue_start>username_0: I have some components that look like this.
```
import { QLayout } from 'quasar'
import { Input } from 'vedana'
export default {
name: 'index',
components: {
QLayout,
Input
},
data () {
return {
something: ''
}
}
}
</code></pre>
<p>this v-input component looks like this:</p>
<pre><code><template>
<input
:type="type ? type : 'text'"
class="v-input"/>
</template>
<script>
export default {
props: ['type'],
name: 'v-input'
}
```
When I enter data into the input `something` does not bind to whatever is in the value of the input that is inside of v-input.
How do I achieve this?<issue_comment>username_1: <https://v2.vuejs.org/v2/guide/components.html#sync-Modifier>
```
export default {
props: ['type', 'value'],
name: 'v-input',
data:function(){
return {
inputVal: ''
};
},
watch:{
value: function(newValue){
this.$emit('update:value', newValue)
}
}
}
```
You need to pass your value to the input component using the `.sync` modifier so the changes will sync back to the parent.
Upvotes: 0 <issue_comment>username_2: To enable the use of [`v-model` the inner component must take a `value` property](https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model).
Bind the `value` to the inner using `:value`, not `v-model` (this would mutate the prop coming from the parent). And when the inner is edited, emit an `input` event for the parent, to update its value (`input` event will update the variable the parent has on `v-model`).
Also, if you have a default value for the `type` prop, declare it in `props`, not in the template.
Here's how your code should be
```
export default {
props: {
type: {default() { return 'text'; }},
value: {} // you can also add more restrictions here
},
name: 'v-input'
}
```
Info about what `props` can have: [Components / Passing data With Props](https://v2.vuejs.org/v2/guide/components.html#Passing-Data-with-Props).
Demo below.
```js
Vue.component('v-input', {
template: '#v-input-template',
props: {
type: {default() { return 'text'; }},
value: {} // you can also add more restrictions here
},
name: 'v-input'
});
new Vue({
el: '#app',
data: {
something: "I'm something"
}
});
```
```html
Parent something: {{ something }}
---
Child:
```
Upvotes: 4 [selected_answer]
|
2018/03/15
| 1,200 | 4,103 |
<issue_start>username_0: I'm trying to change the opacity of my `ion-backdrop` from `0.08` to `0.33`.
I've tried:
```
ion-backdrop {
opacity: 0.33 !important;
}
```
and setting `$popover-ios-background: rgba(0, 0, 0, 0.33);`.
Setting the value on `ion-backdrop` does work but since it's important, it doesn't animate the fade out.
How can I change the opacity of the backdrop?<issue_comment>username_1: There is currently an [open issue](https://github.com/ionic-team/ionic/issues/9105) about this in Ionic's GitHub. The only workaround listed there that doesn't break the animation is long and complex - too much to list here. A direct link to the solution: <https://github.com/ionic-team/ionic/issues/9105#issuecomment-375010398>
Upvotes: 0 <issue_comment>username_2: I’ve do it using the cssClass property in alertController (Ionic 4)
```
async alertError(message: string) {
const alert = await this.alertController.create({
cssClass: 'alertClass',
animated: true,
header: 'Error',
message,
buttons: ['OK']
});
await alert.present();
}
ion-alert {
&.alertClass{
background: rgb(0,0,0,.8);
}
}
```
Upvotes: 1 <issue_comment>username_3: I know I am a bit late to this party, but now with Ionic 5, you have a CSS selector that will do the job for you. That is mentioned in [their documentation](https://ionicframework.com/docs/api/modal#css-custom-properties) as well.
So basically all you could do is, initialize the modal and style it in your SCSS file.
This is my *component.ts* file:
```
import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
// ModalComponent is just a normal angular component, your path may vary
import { ModalComponent } from '../../modals/modal.component';
@Component({
selector: 'some-component',
templateUrl: './some-component.component.html',
styleUrls: ['./some-component.component.scss']
})
export class SomeComponentComponent {
constructor(
private modalController: ModalController,
) { }
async presentModal() {
const modal = await this.modalController.create({
component: ModalComponent,
cssClass: 'modal-class'
});
return await modal.present();
}
}
```
and my *component.scss* file:
```
.modal-class {
ion-backdrop {
--backdrop-opacity: 0.33;
}
}
```
Upvotes: 3 <issue_comment>username_4: I am guessing that this `ion-backdrop` question it's related with the **Ionic Alert Controller**. If that is the case than you need to apply CSS inside the `global.scss` (Ionic 3) file or `theme\variable.scss` (Ionic 4/5). This is required because `ion-backdrop` lives in the app as an **Ionic Global Component**.
Therefore find the mentioned file inside your Ionic project. It's usually in this directory *app > src > global.scss*.
Now let's suppose that we have this **Alert Controller** instanciated in some page class.
```
...
async serviceErrorAlert() {
const alert = await this.alertController.create({
cssClass: 'try-again-alert',
...
});
await alert.present();
}
...
```
As you can see this **Alert Controller** haves a CSS class of `try-again-alert`.
So to add all custom CSS that you want just go the style file and add your own style.
`global.scss` (Ionic 3):
```css
.try-again-alert {
--background: rgba(55, 67, 77, 0.9);
}
```
`theme\variable.scss` (Ionic 4/5):
I strongly recommend you to use CSS `background` attribute and `rgba()` property. With this approach you can now choose the color that you want (first three numbers) and the opacity of the color (fourth number).
Upvotes: 1 <issue_comment>username_5: I only managed to do it in Ionic 5 by using `background: rgba()` property with a desired alpha value.
*Page where modal is called*
```js
openModal(): Promise {
return this.modalCtrl.create({
component: ModalPage,
backdropDismiss: true,
cssClass: 'custom-class'
}).then(modal => {
modal.present();
});
}
```
*`app/theme/variable.css`*
```
.custom-class {
background: rgba(0,0,0,0.8); /*black with 0.8 opacity*/
}
```
Upvotes: 0
|
2018/03/15
| 2,593 | 7,681 |
<issue_start>username_0: I've got an Athena table where some fields have a fairly complex nested format. The backing records in S3 are JSON. Along these lines (but we have several more levels of nesting):
```
CREATE EXTERNAL TABLE IF NOT EXISTS test (
timestamp double,
stats array>,
dets array, header:struct>>,
pos struct
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES ('ignore.malformed.json'='true')
LOCATION 's3://test-bucket/test-folder/'
```
Now we need to be able to query the data and import the results into Python for analysis. Because of security restrictions I can't connect directly to Athena; I need to be able to give someone the query and then they will give me the CSV results.
If we just do a straight select \* we get back the struct/array columns in a format that isn't quite JSON.
Here's a sample input file entry:
```
{"timestamp":1520640777.666096,"stats":[{"time":15,"mean":45.23,"var":0.31},{"time":19,"mean":17.315,"var":2.612}],"dets":[{"coords":[2.4,1.7,0.3], "header":{"frame":1,"seq":1,"name":"hello"}}],"pos": {"x":5,"y":1.4,"theta":0.04}}
```
And example output:
```
select * from test
"timestamp","stats","dets","pos"
"1.520640777666096E9","[{time=15.0, mean=45.23, var=0.31}, {time=19.0, mean=17.315, var=2.612}]","[{coords=[2.4, 1.7, 0.3], header={frame=1, seq=1, name=hello}}]","{x=5.0, y=1.4, theta=0.04}"
```
I was hoping to get those nested fields exported in a more convenient format - getting them in JSON would be great.
Unfortunately it seems that cast to JSON only works for maps, not structs, because it just flattens everything into arrays:
```
SELECT timestamp, cast(stats as JSON) as stats, cast(dets as JSON) as dets, cast(pos as JSON) as pos FROM "sampledb"."test"
"timestamp","stats","dets","pos"
"1.520640777666096E9","[[15.0,45.23,0.31],[19.0,17.315,2.612]]","[[[2.4,1.7,0.3],[1,1,""hello""]]]","[5.0,1.4,0.04]"
```
Is there a good way to convert to JSON (or another easy-to-import format) or should I just go ahead and do a custom parsing function?<issue_comment>username_1: I have skimmed through all the documentation and unfortunately there seems to be no way to do this as of now. The only possible workaround is
[converting a struct to a json when querying athena](https://stackoverflow.com/questions/49081896/converting-a-struct-to-a-json-when-querying-athena)
```
SELECT
my_field,
my_field.a,
my_field.b,
my_field.c.d,
my_field.c.e
FROM
my_table
```
Or I would convert the data to json using post processing. Below script shows how
```
#!/usr/bin/env python
import io
import re
pattern1 = re.compile(r'(?<={)([a-z]+)=', re.I)
pattern2 = re.compile(r':([a-z][^,{}. [\]]+)', re.I)
pattern3 = re.compile(r'\\"', re.I)
with io.open("test.csv") as f:
headers = list(map(lambda f: f.strip(), f.readline().split(",")))
for line in f.readlines():
orig_line = line
data = []
for i, l in enumerate(line.split('","')):
data.append(headers[i] + ":" + re.sub('^"|"$', "", l))
line = "{" + ','.join(data) + "}"
line = pattern1.sub(r'"\1":', line)
line = pattern2.sub(r':"\1"', line)
print(line)
```
The output on your input data is
```
{"timestamp":1.520640777666096E9,"stats":[{"time":15.0, "mean":45.23, "var":0.31}, {"time":19.0, "mean":17.315, "var":2.612}],"dets":[{"coords":[2.4, 1.7, 0.3], "header":{"frame":1, "seq":1, "name":"hello"}}],"pos":{"x":5.0, "y":1.4, "theta":0.04}
}
```
Which is a valid JSON
[](https://i.stack.imgur.com/oMDQ9.png)
Upvotes: 4 [selected_answer]<issue_comment>username_2: The python code from @tarun almost got me there, but I had to modify it in several ways due to my data. In particular, I have:
* json structures saved in Athena as strings
* Strings that contain multiple words, and therefore need to be in between double quotes. Some of them contain "[]" and "{}" symbols.
Here is the code that worked for me, hopefully will be useful for others:
```
#!/usr/bin/env python
import io
import re, sys
pattern1 = re.compile(r'(?<={)([a-z]+)=', re.I)
pattern2 = re.compile(r':([a-z][^,{}. [\]]+)', re.I)
pattern3 = re.compile(r'\\"', re.I)
with io.open(sys.argv[1]) as f:
headers = list(map(lambda f: f.strip(), f.readline().split(",")))
print(headers)
for line in f.readlines():
orig_line = line
#save the double quote cases, which mean there is a string with quotes inside
line = re.sub('""', "#", orig_line)
data = []
for i, l in enumerate(line.split('","')):
item = re.sub('^"|"$', "", l.rstrip())
if (item[0] == "{" and item[-1] == "}") or (item[0] == "[" and item[-1] == "]"):
data.append(headers[i] + ":" + item)
else: #we have a string
data.append(headers[i] + ": \"" + item + "\"")
line = "{" + ','.join(data) + "}"
line = pattern1.sub(r'"\1":', line)
line = pattern2.sub(r':"\1"', line)
#restate the double quotes to single ones, once inside the json
line = re.sub("#", '"', line)
print(line)
```
Upvotes: 1 <issue_comment>username_3: This method is not by modifying the Query.
Its by Post Processing For Javascript/Nodejs we can use the npm package *athena-struct-parser*.
**Detailed Answer with Example**
<https://stackoverflow.com/a/67899845/6662952>
Reference - <https://www.npmjs.com/package/athena-struct-parser>
Upvotes: 0 <issue_comment>username_4: I used a simple approach to get around the struct -> json Athena limitation. I created a second table where the json columns were saved as raw strings. Using presto json and array functions I was able to query the data and return the valid json string to my program:
```
--Array transform functions too
select
json_extract_scalar(dd, '$.timestamp') as timestamp,
transform(cast(json_extract(json_parse(dd), '$.stats') as ARRAY), x -> json\_extract\_scalar(x, '$.time')) as arr\_stats\_time,
transform(cast(json\_extract(json\_parse(dd), '$.stats') as ARRAY), x -> json\_extract\_scalar(x, '$.mean')) as arr\_stats\_mean,
transform(cast(json\_extract(json\_parse(dd), '$.stats') as ARRAY), x -> json\_extract\_scalar(x, '$.var')) as arr\_stats\_var
from
(select '{"timestamp":1520640777.666096,"stats":[{"time":15,"mean":45.23,"var":0.31},{"time":19,"mean":17.315,"var":2.612}],"dets":[{"coords":[2.4,1.7,0.3], "header":{"frame":1,"seq":1,"name":"hello"}}],"pos": {"x":5,"y":1.4,"theta":0.04}}' as dd);
```
I know the query will take longer to execute but there are ways to optimize.
Upvotes: 0 <issue_comment>username_5: I worked around this by creating a second table using the same S3 location, but changed the field's data type to string. The resulting CSV then had the string that Athena pulled from the object in the JSON file and I was able to parse the result.
Upvotes: 0 <issue_comment>username_6: I also had to adjust the @tarun code, because I had more complex data and nested structures. Here is the solution I've got, I hope it helps:
```
import re
import json
import numpy as np
pattern1 = re.compile(r'(?<=[{,\[])\s*([^{}\[\],"=]+)=')
pattern2 = re.compile(r':([^{}\[\],"]+|()(?![{\[]))')
pattern3 = re.compile(r'"null"')
def convert_metadata_to_json(value):
if type(value) is str:
value = pattern1.sub('"\\1":', value)
value = pattern2.sub(': "\\1"', value)
value = pattern3.sub('null', value)
elif np.isnan(value):
return None
return json.loads(value)
df = pd.read_csv('test.csv')
df['metadata_json'] = df.metadata.apply(convert_metadata_to_json)
```
Upvotes: 0
|