date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19
| 737 | 2,312 |
<issue_start>username_0: I'm trying to read one column out of my Excel-file until it hits an empty cell, then it needs to stop reading.
My code so far:
```
import openpyxl
import os
def main():
filepath = os.getcwd() + "\test.xlsx"
wb = openpyxl.load_workbook(filename=filepath, read_only=True)
ws = wb['Tab2']
for i in range(2, 1000):
cellValue = ws.cell(row=i, column=1).Value
if cellValue != None:
print(str(i) + " - " + str(cellValue))
else:
break;
if __name__ == "__main__":
main()
```
By running this i get the following error when it hits an empty cell. Does anybody know how i can prevent this from happening.
```
Traceback (most recent call last):
File "testFile.py" in
main()
cellValue = sheet.cell(row=i, column=1).value
File "C:\Python34\lib\openpyxl\worksheet\worksheet.py", line 353, in cell
cell = self.\_get\_cell(row, column)
File "C:\Python34\lib\openpyxl\worksheet\read\_only.py", line 171, in \_get\_cell
cell = tuple(self.get\_squared\_range(column, row, column, row))[0]
IndexError: tuple index out of range
```<issue_comment>username_1: Try with max\_row to get the maximum number of rows.
```
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('exc_file.xlsx')
ws1 = wb['Sheet1']
for row in range(1,ws1.max_row):
if(ws1.cell(row,1).value is not None):
print(ws1.cell(row,1).value)
```
OR if you want to stop reading when it reaches an empty value you can simply:
```
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('exc_file.xlsx')
ws1 = wb['Sheet1']
for row in range(1,ws1.max_row):
if(ws1.cell(row,1).value is None):
break
print(ws1.cell(row,1).value)
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: This illustrates one of the reasons why I don't encourage the use of `ws.cell()` for reading worksheet. You're much better off with the higher level API `ws.iter_rows()` (`ws.iter_cols()` is not possible in read-only mode for performance reasons.
```py
for row in ws.iter_rows(min_col=1, max_col=1):
if row[0].value is None:
break
print("{0}-{1}".format(row[0].row, row[0].value))
```
iter\_rows should guarantee there is always a cell in reach row.
Upvotes: 2
|
2018/03/19
| 366 | 1,147 |
<issue_start>username_0: I need to drop the below lines containing text "-- MARK --" from the logs. I am using syslog-ng for shipping logs to centralized location. However, my config works fine but i need to apply a filter in order to drop below line to be shipped.
```
Mar 19 15:34:36 10.232.194.98 [Mar 19 15:34:37] [localhost] local_access_log : -- MARK --
```
Actually I am bit new to syslog-ng, Can anyone help me to create the filter to skip above line from syslog-ng client node?
Thanks,
Subi<issue_comment>username_1: here is how to use filters in general: <https://syslog-ng.com/documents/html/syslog-ng-ose-latest-guides/en/syslog-ng-ose-guide-admin/html/configuring-filters.html>
how to drop messages: <https://syslog-ng.com/documents/html/syslog-ng-ose-latest-guides/en/syslog-ng-ose-guide-admin/html/example-dropping-messages.html>
In this case, you'll probably need a message('-- MARK') filter.
Upvotes: 0 <issue_comment>username_2: Filters can do this, for example:
```
filter remove_a_line{ not match("MATCH-STRING-TO-DROP"); };
log { source(src); filter(remove_a_line); destination(/var/log/messages); };
```
Upvotes: 1
|
2018/03/19
| 527 | 1,833 |
<issue_start>username_0: I have fixed some syntactical errors in my code and now the program compiles fine. But when I execute the program the outputFile is empty. outputFile should have contents of inputFile in reverse order. I am trying to debug code in `CodeLite` IDE.
I need to debug the code with two arguments passed (inputFile and outputFile). I don't seem to find that option in `CodeLite` IDE. How do I do that ?
```
#include
#include
#include
#include
#define BUFFER\_SIZE 256
int main (int argc, char \*argv[]){
FILE \*inputFile, \*outputFile;
int fileSize;
int pointer;
char buffer[BUFFER\_SIZE];
/\* Check for correct user's inputs. \*/
if( argc !=3 ) {
fprintf(stderr, "USAGE: %s inputFile outputFile.\n", argv[0]);
exit(-1);
}
/\* Make sure input file exists. \*/
if( (inputFile = fopen(argv[1], O\_RDONLY))) {
fprintf(stderr, "Input file doesn't exist.\n");
exit(-1);
}
/\* Create output file, if it doesn't exist. Empty the file, if it exists. \*/
if((outputFile = fopen(argv[2], "a+"))) {
fclose(inputFile);
exit(-1);
}
/\* Find the size of the input file. \*/
fileSize = fseek(inputFile, 0, SEEK\_END);
/\* Read input file and write to output file in reversed order.\*/
for(pointer=fileSize-1; pointer>=0; pointer--) {
/\*Write content in the buffer to the output file \*/
while(!feof(inputFile))
{
fgets(buffer, BUFFER\_SIZE, inputFile); //reads 256 bytes at a time
fputs (buffer , outputFile );
}
}
fclose(inputFile);
fclose(outputFile);
return(0);
}
```<issue_comment>username_1: <http://codelite.org/LiteEditor/ProjectSettings>:
Project Settings >> General >> Command arguments
Upvotes: 3 [selected_answer]<issue_comment>username_2: 1. Right click on the project folder
2. Select project settings
3. General -> Execution -> Program Arguments
Upvotes: 0
|
2018/03/19
| 606 | 2,143 |
<issue_start>username_0: I am attempting to use the Azure Cloud Shell (browser based) to manage a classic VM. When I run this command:
```
Stop-AzureVM -ResourceGroupName -Name
```
I get this error:
```
Stop-AzureVM : The term 'Stop-AzureVM' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Stop-AzureVM -ResourceGroupName -Name
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Stop-AzureVM:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
```
Am I doing anything wrong, or is this just not supported in Cloud Shell?<issue_comment>username_1: By default, AzureRM Module is used. For PowerShell on Azure Cloudshell, you need to install classic ASM module. Just simply run
```
Install-Module Azure
```
Try to use `Get-Module -Name Azure*` to see if the ASM module is installed.
[](https://i.stack.imgur.com/tpjda.png)
Now you can play with your Azure classic resource.
If you have more than one subscription in ASM model, you need to set the subscription first, using
```
Select-AzureSubscription -Default -SubscriptionName "your_subscription_name"
```
Upvotes: 2 <issue_comment>username_2: >
> but that gives me Unable to load DLL 'IEFRAME.dll'
>
>
>
Azure cloud shell does **not** support use another account to login it.
>
> Cloud Shell also securely authenticates **automatically** for instant
> access to your resources through the Azure CLI 2.0 or Azure PowerShell
> cmdlets.
>
>
>
As a workaround, maybe you can use cloud shell bash to stop that VM(classic).
Azure CLI 1.0 support ASM and ARM, just change mode to ASM, you can use cloud shell to manage your classic VM, like this:
```
azure config mode asm
azure vm list
azure vm --help //get more information about CLI 1.0
```
[](https://i.stack.imgur.com/5CBZF.png)
Hope this helps.
Upvotes: 2 [selected_answer]
|
2018/03/19
| 2,091 | 7,264 |
<issue_start>username_0: I am new to swift and I am trying my hands with multithreading, a concept which doesn't seem to be famous in swift. Based on [this](https://stackoverflow.com/a/23679563/1941002) example of java's `synchronized`implementation I tried to do the same for swift based on examples given for swift on [another](https://stackoverflow.com/a/24103086/1941002) SO post. Here is my implementation:
```
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
public class TestThread {
var name : String;
var theDemo : TheDemo;
init(_ name : String, _ theDemo : TheDemo) {
self.theDemo = theDemo;
self.name = name;
run()
}
public func run() {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
self.theDemo.testSynced(self.name)
}
}
}
}
public class TheDemo {
private func synced(_ lock : Any, _ name : String, _ closure : (_ name : String) -> ()){
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
closure(name)
}
public func testSynced(_ name : String){
synced(self, name, test)
}
public func test(_ name : String) {
for i in 0..<4 {
let str = "\(name) :: \(i)"
let theDeadline = DispatchTime.now() + .seconds(i/2)
DispatchQueue.main.asyncAfter(deadline: theDeadline, execute: {
print(str)
})
}
}
}
var theDemo = TheDemo()
TestThread("THREAD 1", theDemo)
TestThread("THREAD 2", theDemo)
TestThread("THREAD 3", theDemo)
TestThread("THREAD 4", theDemo)
```
When I run the above code in the playground the result I get looks like the following
```
THREAD 1 :: 0
THREAD 1 :: 1
THREAD 2 :: 0
THREAD 2 :: 1
THREAD 3 :: 0
THREAD 3 :: 1
THREAD 4 :: 0
THREAD 4 :: 1
THREAD 1 :: 2
THREAD 1 :: 3
THREAD 2 :: 2
THREAD 2 :: 3
THREAD 3 :: 2
THREAD 3 :: 3
THREAD 4 :: 2
THREAD 4 :: 3
```
But I was expecting a result that looks like the following.
```
THREAD 1 :: 0
THREAD 1 :: 1
THREAD 1 :: 2
THREAD 1 :: 3
THREAD 2 :: 0
THREAD 2 :: 1
THREAD 2 :: 2
THREAD 2 :: 3
THREAD 3 :: 0
THREAD 3 :: 1
THREAD 3 :: 2
THREAD 3 :: 3
THREAD 4 :: 0
THREAD 4 :: 1
THREAD 4 :: 2
THREAD 4 :: 3
```
I wish to understand what I am doing wrong. Have I set my expectation also on the right path considering the concept of synchronisation and swift threads. I appreciate the help. thanks.
**EDIT**
Since I believe that I am misunderstood, I want to explain a bit more of what I want to do. What I basically want to achieve is a bit different than what I have written here in the code. This is a simplified version. I want to test it if `synchronized` works in a simple example and then I want to use it in another project. I am translating a project written for android to ios. In java multithreading I am using `synchronized` so that only one thread at a time can use that function. let's say there is a variable or a function that multiple threads can work on. When I put synchronized before the function name or the variable name, threads will have a lock. Now in my project I have several threads, that come and go, based on some sensor input - and before they die they make use of a common shared function. They could come at any point. For several reasons, we set that common function `synchronized` so that no two threads enter the function at the same time. Thus, when I am translating the code I looked for what would be similar in swift and I found one of the links that is linked to this question. And I tried to use that - and it didn't work for me. To err is human - and I probably have made a mistake somewhere. But I have spent time to read based on the schedule I have. (I partly said that multithreading isn't very famous in swift because of some places I have read for example [this](https://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html))<issue_comment>username_1: **Problem**
-----------
In `TheDemo`
```
let theDeadline = DispatchTime.now() + .seconds(i/2)
DispatchQueue.main.asyncAfter(deadline: theDeadline, execute: {
self.theDemo.testSynced(self.name)
```
**Solution**
------------
In `TestThread`:
```
DispatchQueue.global(qos: .background).async {
let theDeadline = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: theDeadline, execute: {
```
In `TheDemo`
```
for i in 0..<4 {
let str = "\(name) :: \(i)"
print(str)
}
```
**Explanation**
---------------
So. Each asynchronous task is completing so fast that they are getting deferred to the same time from now. You are getting an insight into how DispatchQueue's main thread handles the situation when you've asynced everything to the same time.
```
//Starts at some exact time
TestThread("THREAD 1", theDemo)
TestThread("THREAD 2", theDemo)
TestThread("THREAD 3", theDemo)
TestThread("THREAD 4", theDemo)
//Finishes at the same exact time. Too fast!
//
```
In my solution, the printing is in a single time context (the playground's main queue where you create all your custom threads). So it prints as you expect. You'll have to use a much finer unit (there isn't [nanoseconds]) or design it slightly differently like I showed you.
Upvotes: 1 <issue_comment>username_2: First of all, never test these things in a playground, as its output will not correctly simulate reality. Test in an actual app project.
Second, get rid of all this:
```
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
closure(name)
```
Do whatever it is you want done purely using GCD.
I'm not clear on what you do want done; the kerfuffle with `objc_sync_enter` and `asyncAfter` is just too mystifying for me. This stuff, however, is not at all mystifying, and is very well documented and explained (contrary to your claim).
From your desired output, it looks like you want to queue the "thread 1" operation and have it run from start to finish before the "thread 2" operation starts.
* One way to guarantee that is to queue these operations onto a *serial queue*, because that means that a queued operation cannot start until the queue ahead of it is empty. That's not happening in your code because you queue is a *concurrent* queue, meaning that the operations run *at the same time* (i.e. their steps can be interleaved with one another).
* Another way would be to call the "thread 1" operation with `sync` rather than `async`, because that means your code waits (blocks) until the operation completes and returns.
Here's an example of the first way, which I think is the better way:
```
let queue = DispatchQueue(label:"myqueue") // serial queue
func go() {
for i in 0..<4 {
let name = "Thread \(i)"
queue.async {
for i in 0..<4 {
let str = "\(name) :: \(i)"
print(str)
}
}
}
}
```
Output when we call `go()`:
```
Thread 0 :: 0
Thread 0 :: 1
Thread 0 :: 2
Thread 0 :: 3
Thread 1 :: 0
Thread 1 :: 1
Thread 1 :: 2
Thread 1 :: 3
Thread 2 :: 0
Thread 2 :: 1
Thread 2 :: 2
Thread 2 :: 3
Thread 3 :: 0
Thread 3 :: 1
Thread 3 :: 2
Thread 3 :: 3
```
That looks a lot like what you said you wanted.
Upvotes: 3 [selected_answer]
|
2018/03/19
| 766 | 3,011 |
<issue_start>username_0: Is there a way to catch any type of error the Ruby/Rails encounters?
I am making a network request. What I have seen so far is, it can return 404, timeout or even any empty response object?
I have handled them individually, it is not DRY, but is there a way to handle all these and those which I have not seen yet gracefully?
Many times even when the response object is analysed, sometimes it may not contain what I am looking for. Sure I can handle them individually.
I am curious to know if it is possible to define a use case to work with, everything apart from it, which I have not imagined, is just thrown an exception and does not break my application.
Is generic error handling possible in Ruby?<issue_comment>username_1: Are you looking for something like this? [Source.](http://mikeferrier.com/2012/05/19/rescuing-multiple-exception-types-in-ruby-and-binding-to-local-variable/)
```
begin
rand(2) == 0 ? ([] + '') : (foo)
rescue TypeError, NameError => e
puts "oops: #{e.message}"
end
```
If you are looking to implement these things in controllers, and want to DRY it up, try out rescuable. [Ruby API link.](http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html)
```
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :deny_access # self defined exception
rescue_from ActiveRecord::RecordInvalid, with: :show_errors
rescue_from 'MyAppError::Base' do |exception|
render xml: exception, status: 500
end
private
def deny_access
...
end
def show_errors(exception)
exception.record.new_record? ? ...
end
end
```
Upvotes: 2 <issue_comment>username_2: Yes its absolutely possible, there are a couple of different levels of rescuing exceptions in Ruby, as noted by Daryll you can specify different exceptions that go to the same handler like
```
begin
# potentially exception raising code
rescue Exception1, Exception2 => e
# run code if Exception1 or Exception2 get raised
end
```
You can also catch StandardError, which most Exceptions that you would want to catch inherit from. This is a good option if your looking for a catch all, like try this and keep going no matter what.
```
begin
# potentially exception raising code
rescue StandardError => e
# run code if StandardError or anything that inherits from StandardError is raised (most errors)
end
```
You can also catch Exception (**Dangerous**), which every Exception inherits from (including StandardError). You pretty much never want to do this since things like SyntaxErrors, SignalExceptions (you can catch Control-C and prevent terminating your script with it) and other internal errors also inherit from Exception. See <http://blog.honeybadger.io/ruby-exception-vs-standarderror-whats-the-difference/> for some more details
```
begin
syntax exception
rescue => e
puts "I even catch syntax errors!!!"
end
puts "I'll keep on executing though"
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 1,007 | 3,901 |
<issue_start>username_0: I have a simple subclass of `NSManagedObject` in a simple app supposed to collect data from an iPhone and send the data to a server.
This is what this class looks like:
```
import Foundation
import CoreData
extension TestSession {
@NSManaged var bootTime: NSNumber?
@NSManaged var accelerometerData: Data?
@NSManaged var gyroscopeData: Data?
@NSManaged var motionData: Data?
@NSManaged var magnetometerData: Data?
}
```
Now, suppose I have an instance `TodaysSession` of `TestSession`, that I'd like to send in a POST request.
What I was doing, until now, was covering this data to a string (say, unarchive `accelerometerData` to get an array of `CMAcceleration` objects, then convert the timestamp, x, y, and z components to CSV format).
This is very inefficient (in terms of string size and time).
I've done some research and found some options : Using `Codable`, though that didn't work for me, `NSKeyedArchiver`
But I'm not sure what advantage each offers, or if there are other, better options out there, that I don't know about (and didn't find in my research, not knowing what to look for)<issue_comment>username_1: Convert your managedObject to a dictionary and then convert that dictionary into json.
```
extension TestSession {
@NSManaged var bootTime: NSNumber?
@NSManaged var accelerometerData: Data?// Decode Data into Dictionary
@NSManaged var gyroscopeData: Data?// Decode Data into Dictionary
@NSManaged var motionData: Data?// Decode Data into Dictionary
@NSManaged var magnetometerData: Data?// Decode Data into Dictionary
var toJson: [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
let properties = self.entity.propertiesByName
for (key, description) in properties {
if let value = self.value(forKey: key) {
dictionary[key] = value as AnyObject
}
}
return dictionary
}
}
```
In your api call method just pass your `managedObject` and then use it like this..
```
func makeAPICall(session: TestSession) {
var requesst = URLRequest(url: URL(string: "https://yourURL.com/api")!)
requesst.httpMethod = "POST"
do{
let jsonData = JSONSerialization.data(withJSONObject: session.toJson, options: .prettyPrinted)
requesst.httpBody = jsonData
URLSession.shared.dataTask(with: requesst, completionHandler: { (data, response, error) in
}).resume()
}
catch let error {
print(error.localizedDescription)
}
}
```
Upvotes: 0 <issue_comment>username_2: You can make a `NSManagedObject` subclass adopt `Encodable` but consider that `Data` types must be `base64Encoded` before being sent in a HTTP request
```
extension TestSession : Encodable {
@NSManaged var bootTime: NSNumber?
@NSManaged var accelerometerData: Data?
@NSManaged var gyroscopeData: Data?
@NSManaged var motionData: Data?
@NSManaged var magnetometerData: Data?
private enum CodingKeys: String, CodingKey { case bootTime, accelerometerData, gyroscopeData, motionData, magnetometerData}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(bootTime, forKey: .bootTime)
try container.encode(accelerometerData?.base64EncodedString() , forKey: .accelerometerData)
try container.encode(gyroscopeData?.base64EncodedString() , forKey: .gyroscopeData)
try container.encode(motionData?.base64EncodedString() , forKey: .motionData)
try container.encode(magnetometerData?.base64EncodedString() , forKey: .magnetometerData)
}
}
```
Now you can easily encode an instance
```
do {
let sessionData = try JSONEncoder().encode(session)
// do something with sessionData
} catch { print(error) }
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 1,029 | 4,102 |
<issue_start>username_0: I am trying to update the document in elasticsearch which matches the id field. If the `formData.id` matches any of the documents in elasticsearch, I want it's `mobile_number` and `primary_email_id` to be updated. I also want to insert a new field `website` to the matching result. For this, I tried the following query:
```
function updateForm(formData) {
var deferred = Q.defer();
client.update({
index: 'collections',
type: 'automobiles',
id: '8s5WEbYZ6NUAliwOBf',
body: {
query: {
must: {
match : {
id: formData.id
}
},
},
doc: {
'mobile_number' : formData.phone,
'primary_email_id': formData.email,
'website' : formData.website
}
}
},function (error, response) {
if(error){
console.log(error);
return error;
}else {
deferred.resolve(response);
}
});
return deferred.promise;
}
```
This gives me the following error:
`Error: [action_request_validation_exception] Validation Failed: 1: script or doc is missing;`
I already have a doc field in my query. What modifications should I make to perform such an update? Is there any other better way for such an operation?<issue_comment>username_1: Convert your managedObject to a dictionary and then convert that dictionary into json.
```
extension TestSession {
@NSManaged var bootTime: NSNumber?
@NSManaged var accelerometerData: Data?// Decode Data into Dictionary
@NSManaged var gyroscopeData: Data?// Decode Data into Dictionary
@NSManaged var motionData: Data?// Decode Data into Dictionary
@NSManaged var magnetometerData: Data?// Decode Data into Dictionary
var toJson: [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
let properties = self.entity.propertiesByName
for (key, description) in properties {
if let value = self.value(forKey: key) {
dictionary[key] = value as AnyObject
}
}
return dictionary
}
}
```
In your api call method just pass your `managedObject` and then use it like this..
```
func makeAPICall(session: TestSession) {
var requesst = URLRequest(url: URL(string: "https://yourURL.com/api")!)
requesst.httpMethod = "POST"
do{
let jsonData = JSONSerialization.data(withJSONObject: session.toJson, options: .prettyPrinted)
requesst.httpBody = jsonData
URLSession.shared.dataTask(with: requesst, completionHandler: { (data, response, error) in
}).resume()
}
catch let error {
print(error.localizedDescription)
}
}
```
Upvotes: 0 <issue_comment>username_2: You can make a `NSManagedObject` subclass adopt `Encodable` but consider that `Data` types must be `base64Encoded` before being sent in a HTTP request
```
extension TestSession : Encodable {
@NSManaged var bootTime: NSNumber?
@NSManaged var accelerometerData: Data?
@NSManaged var gyroscopeData: Data?
@NSManaged var motionData: Data?
@NSManaged var magnetometerData: Data?
private enum CodingKeys: String, CodingKey { case bootTime, accelerometerData, gyroscopeData, motionData, magnetometerData}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(bootTime, forKey: .bootTime)
try container.encode(accelerometerData?.base64EncodedString() , forKey: .accelerometerData)
try container.encode(gyroscopeData?.base64EncodedString() , forKey: .gyroscopeData)
try container.encode(motionData?.base64EncodedString() , forKey: .motionData)
try container.encode(magnetometerData?.base64EncodedString() , forKey: .magnetometerData)
}
}
```
Now you can easily encode an instance
```
do {
let sessionData = try JSONEncoder().encode(session)
// do something with sessionData
} catch { print(error) }
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 970 | 3,288 |
<issue_start>username_0: I am writing a query where it pulls the previous months total # of renewals from table 1 and then divides it by the national average of working business days for that specific month from table 2 (both tables are in the same sever & database).
I have the queries for the above statement, I just do not know how to connect them.
The query is essentially: Total # of Renewal Volume for month A / # of business days in month A
From my understanding I need to make sure that the data in columns 'YR' and 'MTH' in table 1 match columns 'cal\_month' and 'cal\_year' in table 2. If so it would then take the total # of renewals in the 'volumes' column in table 1 and divide it by the # of business days in the 'national\_avg' column in table 2.
```
select volume, YR, MTH
from example.dbo.table1
where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
group by MTH, YR
select cal_month, cal_year, National_Avg
from example.dbo.table2
where cal_month = DATENAME(mm, DATEADD(month,-1,current_timestamp))
AND cal_year = DATENAME(yyyy, DATEADD(month,-1,current_timestamp))
```
Example
Table 1
```
Volume / MTH / YR
200 / 2 / 2018
```
Table 2
```
cal_month / cal_year / national_avg
February / 2018 / 22
```
Expected result:
9.09
I am fairly new with sql, I think I got the logic correct I'm just having trouble writing the correct syntax. I was thinking of using a temptable, I just dont have experience with one. Thank you<issue_comment>username_1: The answer to your question is `cross join`:
```
select . . .
from (select t1.volume, t1.YR, t1.MTH
from example.dbo.table1 t1
where datecompleted >= dateadd(month, -1, dateadd(day, 1 - day(current_timestamp), current_timestamp)) and
datecompleted < dateadd(day, 1 - day(current_timestamp), current_timestamp)
) v cross join
(select cal_month, t2.cal_year, t2.National_Avg
from example.dbo.table2 t2
where t2.cal_month = DATENAME(month, DATEADD(month,-1, current_timestamp)) and
t2.cal_year = DATENAME(year, DATEADD(month, -1, current_timestamp))
) n;
```
Note that I changed the date logic for the first subquery. It is better to not use function calls or type casts on the columns, because that can prevent the use of indexes.
I would recommend that you use the same time identifier in each table -- such as a date column for the beginning of the period.
Upvotes: 0 <issue_comment>username_2: Just wrap up both queries as subqueries and join on the necessary fields like below. Then you can easily create your new column by dividing volume by nationalavg
```
select *, volume/ case when National_Avg=0 then 1 else National_Avg end NewColumn from (select volume, YR, MTH
from example.dbo.table1
where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
group by MTH, YR)a
join
(select cal_month, cal_year, National_Avg
from example.dbo.table2
where cal_month = DATENAME(mm, DATEADD(month,-1,current_timestamp))
AND cal_year = DATENAME(yyyy, DATEADD(month,-1,current_timestamp)))b
on a.yr=b.cal_year and a.mth=b.cal_month
```
Upvotes: 2
|
2018/03/19
| 513 | 1,957 |
<issue_start>username_0: I was wondering whether you can use docker when creating a function for serverless computing ?
---
If so, how would it look like?
---
How a function handler would be specified?
---
Any articles or tutorials on this topic?
---
How could you apply these questions in AWS-Lambda context? Any specifics?
---
Thank you.<issue_comment>username_1: As far as we know already, when you run a lambda function it is already running in a container - that is how it is engineered at AWS (not sure if they have officially documented that), so my guess would be no, you can't pull a docker container into a lambda function.
However, if what you want to do is run docker containers in a more/less serverless way, check out aws fargate:
>
> AWS Fargate is a technology for Amazon ECS and EKS\* that allows you to
> run containers without having to manage servers or clusters. With AWS
> Fargate, you no longer have to provision, configure, and scale
> clusters of virtual machines to run containers. This removes the need
> to choose server types, decide when to scale your clusters, or
> optimize cluster packing. AWS Fargate removes the need for you to
> interact with or think about servers or clusters. Fargate lets you
> focus on designing and building your applications instead of managing
> the infrastructure that runs them.
>
>
>
<https://aws.amazon.com/fargate/>
Upvotes: 3 <issue_comment>username_2: AWS Lambda runs on AmazonLinux and doesn't give root permissions to run docker. There are also other limitations like max memory, timeout and diskspace which limit use of many docker images.
But some smart minds have figured a way around. Using `udocker` to run simple docker containers on Lambda and can be very useful for a few use cases.
Check out: <https://github.com/grycap/scar>
Original reference: <https://hackernoon.com/how-did-i-hack-aws-lambda-to-run-docker-containers-7184dc47c09b>
Upvotes: 2
|
2018/03/19
| 794 | 2,617 |
<issue_start>username_0: The assignment I have is this:
>
> Write a function that counts the number of times the values contained in a first vector are divisible by the values contained in a second vector.
>
>
> The function accepts as input:
>
>
> a (first) vector of numbers, say `vector_dividend`;
>
>
> a (second) vector of numbers, say `vector_divider`;
>
>
> The function returns:
>
>
> a single number, representing how many times the values in vector\_dividend are divisible by the values in vector\_divisor.
>
>
>
For instance, if `vector_dividend=[11,13,21,15,20]` and `vector_divider=[3,5]`, then the result is 4, because: 21 and 15 are divisible by 3; and 15 and 20 are divisible by 5.
This is what I came up with but wasn't able to execute
Any kind of help would be appreciated, thank you
```
vec1 <- c(10,2,3,6,20)
vec2 <- c(6,2)
div <- function(x,y){
i<-1
for(i in 1:length(x)){
if(x[i] / y[i] || y[i+1] != 1)
add <- i
i=i+1
}
return(i)
}
div(vec1,vec2)
```<issue_comment>username_1: As far as we know already, when you run a lambda function it is already running in a container - that is how it is engineered at AWS (not sure if they have officially documented that), so my guess would be no, you can't pull a docker container into a lambda function.
However, if what you want to do is run docker containers in a more/less serverless way, check out aws fargate:
>
> AWS Fargate is a technology for Amazon ECS and EKS\* that allows you to
> run containers without having to manage servers or clusters. With AWS
> Fargate, you no longer have to provision, configure, and scale
> clusters of virtual machines to run containers. This removes the need
> to choose server types, decide when to scale your clusters, or
> optimize cluster packing. AWS Fargate removes the need for you to
> interact with or think about servers or clusters. Fargate lets you
> focus on designing and building your applications instead of managing
> the infrastructure that runs them.
>
>
>
<https://aws.amazon.com/fargate/>
Upvotes: 3 <issue_comment>username_2: AWS Lambda runs on AmazonLinux and doesn't give root permissions to run docker. There are also other limitations like max memory, timeout and diskspace which limit use of many docker images.
But some smart minds have figured a way around. Using `udocker` to run simple docker containers on Lambda and can be very useful for a few use cases.
Check out: <https://github.com/grycap/scar>
Original reference: <https://hackernoon.com/how-did-i-hack-aws-lambda-to-run-docker-containers-7184dc47c09b>
Upvotes: 2
|
2018/03/19
| 617 | 2,320 |
<issue_start>username_0: I'm building a windows application, and I have this combobox refusing to get clean. I want the combo box items to be deleted between one button click to another. I tried :
```
SendDlgItemMessage(hWnd, IDC_LIST_COMMANDS, CB_RESETCONTENT, 0, 0);
```
and also:
```
SendMessage(CommandsListBox, CB_RESETCONTENT, 0, 0);
```
but none of them work. I dont get 0 when I call LB\_GETCOUNT after one of the above calls.
```
case SOME_EVENT:
ProfileHandler.IdentityIndex = (int)SendMessage(ProfilesCombo,
CB_GETCURSEL, 0, 0);
SendMessage(ProfilesCombo, CB_GETLBTEXT,
(WPARAM)ProfileHandler.stringIndex, (LPARAM)ProfileHandler.string);
if (ProfileHandler.IdentityIndex == -1) {
MessageBox(hWnd, "Invalid !", "Error !", MB_OK);
break;
}
StringsSet.clear();
if (fuc.GetStrings(string(ProfileHandler.string), &StringsSet)
== SERVER_ERROR) {
MessageBox(hWnd, "Error Loading strings", "Error !", MB_OK);
break;
}
SendMessage(CommandsListBox, CB_RESETCONTENT, 0, 0); // reset
content before writing strings
it = StringsSet.begin();
for (; it != StringsSet.end(); ++it)
{
(int)SendMessage(CommandsListBox, LB_ADDSTRING, 0,
(LPARAM)(*it).c_str());
}
break;
```
so, I between every SOME\_EVENT received by click, I want to clear the combobox, and load the string again.
right now what's happenning is that every time I click the button, and the SOME\_EVENT event received, I just load the commands all over again, causing a duplication .
any idea how to solve this??<issue_comment>username_1: Try `SendMessage(hChildWindows[1], CB_DELETESTRING, (WPARAM)0, (LPARAM)0);`
This message will clear only one line in ComboBox (Item or String)
Upvotes: 1 <issue_comment>username_2: I just wrote code that resets all items into a ComboBox. The correct way is to use:
SendMessage(hcombobox, CB\_RESETCONTENT, 0, 0);
I write this because the problem was that the user that started this thread was using a ListView and not a ComboBox.
<NAME> solved this issue.
I've written this to give visibility to the correct answer.
Forgive my mistakes.
Upvotes: 2
|
2018/03/19
| 1,052 | 2,820 |
<issue_start>username_0: [This](https://stackoverflow.com/questions/13959510/python-list-initialization-using-multiple-range-statements) tells us the way to prepare a list of numbers, including a range of continues numbers or discontinues numbers.
For example, `list(range(1,10)) + [20,30,40] + list(range(400,410))` will return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 40, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409]`.
But can I make it simpler by only inputting a string like `"1-10, 20, 30, 40, 400-410"`?
I can write a function using a for-loop to go through the numbers. Is there a more efficient way to write the function without using a for-loop?<issue_comment>username_1: I suggest that you instead write a function that allows to create more complex, piecewise ranges.
```
def piecewise_range(*args):
for arg in args:
yield from range(*arg)
piecewise_range((1, 10), (20, 50, 10), (400, 410))
```
The function `piecewise_range` then outputs a generator, so it allows you to have more complex range patterns and to preserve `range` laziness.
Upvotes: 0 <issue_comment>username_2: You can use a nested list comprehension, checking whether the current part contains a `-` and using either a `range` or creating a one-elemented list accordingly:
```
>>> s = "1-10, 20, 30, 40, 400-410"
>>> [n for part in s.split(", ") for n in (range(*map(int, part.split("-"))) if "-" in part else [int(part)])]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 40, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409]
```
Maybe split this up, for readability:
```
>>> to_list = lambda part: range(*map(int, part.split("-"))) if "-" in part else [int(part)]
>>> [n for part in s.split(", ") for n in to_list(part)]
```
Note: As in your first example, this will translate `"1-10"` to `[1, 2, ..., 9]`, without `10`.
---
As noted in comments, this will not work for negative numbers, though, trying to split `-3` or `-4--2` into pairs of numbers. For this, you could use regular expressions...
```
>>> def to_list(part):
... m =re.findall(r"(-?\d+)-(-?\d+)", part)
... return range(*map(int, m[0])) if m else [int(part)]
...
>>> s = "-10--5, -4, -2-3"
>>> [n for part in s.split(", ") for n in to_list(part)]
[-10, -9, -8, -7, -6, -4, -2, -1, 0, 1, 2]
```
... or just use a different delimiter for ranges, e.g. `-10:-5`.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Depending on where your input strings come from, you might do with something like this, named whatever you would want to name it:
```
import re
def gen_nums(input_string):
out = []
for item in re.split(r',\s*', input_string):
if '-' in item:
start, end = item.split('-')
out.extend(range(int(start), int(end)))
else:
out.append(int(item))
return out
```
Upvotes: 0
|
2018/03/19
| 809 | 2,604 |
<issue_start>username_0: thanks that i can ask questions here. I'm using rails 5.1.4 with ruby 2.5.0.
I have two models the model A and Model B.
```
Model A has_many bs
Model B belongs_to a
```
The admin-user can generate new a-entries and he can generate new b-entries. The no-admin-user can show, index or reserve.
**routes.rb**
```
resources :as, only: [:index, :show] do
resources :bs, only: [:index, :show, :reserve]
end
namespace :admin do
resources :as, only: [:create, :edit, :update, :destroy,
:show] do
member do
post :activate
get :activate
post :deactivate
get :deactivate
end
resources :bs, only: [:create, :edit, :update, :destroy, :show]
end
end
```
In the `app/views/admin/as/show.html.erb` you can see the values of the DB Entry of an a. So now my idea is to realise that you can add new B Entries of b with a form. I tried this show.html.erb
**show.html.erb**
```
<%=t("show")%>
--------------
**<%=t("title")%>**
<%= @a.title %>
**<%=t("description")%>**
<%= @a.description %>
**<%=t("email")%>:**
<%= @a.email %>
<%=t("entries")%>
-----------------
<%= render @a.bs %>
<%=t("addentry")%>
------------------
<%= form_with(model: [ @a, @admin.bs.build ], local: true) do |f| %>
<%= f.label :title %>
<%= f.text\_field :title %>
<%= f.label :description %>
<%= f.text\_area :description %>
<%= f.submit %>
```
The form will be generated, but the html-sourcecode don't show the "admin-route-path". But how do i this?
```
```
How have i to change the form\_with part, that i can add entries into the associated model from b?<issue_comment>username_1: Seems you want your form to hit the url `/admin/as/bs`.
To build links to a namespaced controller you can use this forms:
```
link_to [:admin, @a, @b], 'A admin show'
link_to admin_as_bs_path(@a, @b), 'A admin show'
```
The same is applicable to forms
```
form_for [:admin, @a, @b] do ...
form_for @a, url: admin_as_bs_path(@a, @b)
```
The name of the route helper might be wrong. Check `rake routes`'s output.
Upvotes: 1 <issue_comment>username_2: To get route that you are looking for you need to have nested resources. You can find a great explanation [here](https://stackoverflow.com/questions/2034700/form-for-with-nested-resources#4611932).
Upvotes: 0 <issue_comment>username_3: I found the solution for the associated model and it works fine. Can anyone confirm this. Thanks
`<%= form_with(model: [:admin, @a,B.new ], local: true) do |f| %>
<% end %>`
Upvotes: 0
|
2018/03/19
| 789 | 2,728 |
<issue_start>username_0: I'm programming some exercises about exceptions in C++ with NetBeans 8.1 Patch 1 on Windows 10 using MinGW 64 bits, but the expected result is not the same when I execute the code in IDE.
Here's the code:
```
#include
#include
using namespace std;
void f() {
throw 'A';
}
int main() {
try {
try {
f();
} catch (int) {
cout << "In catch (int) 1" << endl;
throw;
} catch (...) {
cout << "In catch (...) 1" << endl;
throw 65;
}
} catch (int&) {
cout << "In catch (int&)" << endl;
} catch (int) {
cout << "In catch (int) 2" << endl;
} catch (const int) {
cout << "In catch (const int)" << endl;
} catch (...) {
cout << "In catch (...) 2" << endl;
}
cout << "End of program" << endl;
return EXIT\_SUCCESS;
}
```
The terminal displays this :
```
In catch (int) 1
In catch (int&)
End of program
```
Normally, the terminal should display in the first line "In catch(...) 1", but I don't understand why the IDE doesn't display the good result.
I tried this code with g++ on PowerShell, same result, but with g++ on Linux Ubuntu, he displays the right result.
I don't have any suggestions.
Thank you for your help.
Kind regards.<issue_comment>username_1: [Integral promotions](http://eel.is/c++draft/conv.prom#1) are considered when a suitable catch is searched for. `'A'` is a character literal and is promoted to an `int`.
Thus:
1. `throw 'A';` is performed;
2. `catch (int)` after integral promotion;
3. `throw;` rethrows the same object ([no copy is made](http://en.cppreference.com/w/cpp/language/throw));
4. `catch (int&)` catches it (note: `catch (int)` could catch it but it is not the *nearest catch*);
5. program ends.
For your information, `[except.throw]/2` explains what *nearest* means:
>
> When an exception is thrown, control is transferred to the nearest handler with a matching type (`[except.handle]`);
> “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword
> was most recently entered by the thread of control and not yet exited.
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: This seems to be an implementation issue, because the behavior cannot be reliably reproduced even with MinWGW on Windows, depending on the version. In theory, there is [no conversion or promotion of the base types in the catch(..) block](http://en.cppreference.com/w/cpp/language/try_catch), only a user-defined class can be converted to a base class.
The question mentions the "right result" because in theory (and on most architectures tried), throw(char) cannot be caught by catch(int) but only by catch(...). Still, there is no clear explanation why this is not so in some cases.
Upvotes: 0
|
2018/03/19
| 686 | 1,619 |
<issue_start>username_0: The issue seems simple but I'm stack in it since hours, here is what looks like my data:
```
\N
PARIS PREMIERE,1375,7
RTL9,1376,7
TV BREIZH,1162,7
C+ CINEMA,1594,7
\N
C+ SPORT,1595,7
OCS MAX,799,7
```
The output I want to have is:
```
1375
1376
1162
1594
1595
799
```
For this I run this code:
```
list_data = data.split('\n')
for line in list_data:
for s in line.split(','):
params = s.split('\n')
```
But it seems not working. If you have any Idea how I can solve my issue please Help.
Thank you!<issue_comment>username_1: One way it use `pandas` to return the required list:
```
import pandas as pd
from io import StringIO
mystr = StringIO(r"""\N
PARIS PREMIERE,1375,7
RTL9,1376,7
TV BREIZH,1162,7
C+ CINEMA,1594,7
\N
C+ SPORT,1595,7
OCS MAX,799,7""")
df = pd.read_csv(mystr, header=None, delimiter='~')
res = df.loc[df[0] != r'\N', 0].str.split(',').str[-2].astype(int).tolist()
```
Result:
```
[1375, 1376, 1162, 1594, 1595, 799]
```
You can then do what you like with this list, e.g. write to a file, use elsewhere in your program, etc.
Upvotes: 0 <issue_comment>username_2: ```
params = []
list_data = data.split('\n')
for line in list_data:
if len(line.split(',')) == 3
params.append(line.split(',')[1])
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You can filter all undesirable delimeters:
```
import csv
with open('filename.csv') as f:
data = [int(i[-2]) for i in csv.reader(f) if len(i) > 1 or i[0] != '\\N']
print(data)
```
Output:
```
[1375, 1376, 1162, 1594, 1595, 799]
```
Upvotes: 1
|
2018/03/19
| 452 | 1,562 |
<issue_start>username_0: I want to test out hikaricp in TomEE. I have added the jar-file into my lib folder, and have tried defining the resources like this:
```
....
```
When I do this I get the following error upon startup:
```
org.apache.xbean.recipe.MissingFactoryMethodException: Instance factory method has signature public com.zaxxer.hikari.HikariJNDIFactory.getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) but expected signature public com.zaxxer.hikari.HikariJNDIFactory.getObjectInstance()
```
How can I define the HikariCP datasource in my tomee.xml?<issue_comment>username_1: I haven't done through tomee.xml, But tried with JPA using HsqlDB. below are JPA persistence.xml properties.Good Luck.
```
```
Upvotes: 2 <issue_comment>username_2: You can wrap the `HikariDataSource` within a `JTADataSourceWrapperFactory` in order to get JTA support ([see mail archives](http://tomee-openejb.979440.n4.nabble.com/HikariCP-configuration-in-TomEE-td4678838.html)).
Then, you can define it via `tomee.xml` or `resource.xml` as follows:
```
driverClassName org.hsqldb.jdbcDriver
jdbcUrl jdbc:hsqldb:mem:demo
username sa
<PASSWORD>
Delegate = hikariCP
```
In your `persistence.xml` add the data source via
```
java:openejb/Resource/demo
```
Just ensure, that the HikariCP library is available within your classpath.
Side note: Setting `hibernate.connection.provider_class` will create a connection pool within Hibernate, which is not managed by the container.
Upvotes: 3 [selected_answer]
|
2018/03/19
| 556 | 1,889 |
<issue_start>username_0: I'd like to select a record in sql and then update it, all in one statement or stored procedre.
So, I have this statement:
```
select top 1 ID, TimeStamp, Locked, Deleted
from TableName
where Locked='False' and Deleted='False'
order by TimeStamp asc
```
How can I select that statement and then set Locked='True' to the returning record.<issue_comment>username_1: if you use the output clause, you can see the updated record before it was updated by selecting from `deleted`
```
with cte as (
select top 1
ID,
TimeStamp,
Locked,
Deleted
from TableName
where Locked='False' and Deleted='False'
order by TimeStamp asc
)
update cte
set Locked = 'True'
output deleted.*
```
Upvotes: 2 <issue_comment>username_2: If you need it locked then I think this will do it.
Problem is you cannot use `top` with `update`.
```
create table #T (pk int identity primary key, ts timestamp not null, lock bit not null)
insert into #T (lock) values (1), (0), (1), (0), (0);
select *
from #T t
order by t.ts asc;
update tt
set tt.lock = 1
output deleted.*
from ( select top(1) t.*
from #T t with (UPDLOCK ROWLOCK)
where t.lock = 0
--and t.Deleted = 0
order by t.lock
) tt;
select *
from #T t
order by t.ts asc;
drop table #T
```
By taking the UPDLOCK the value(s) cannot be changed between the read and the write.
Upvotes: 0 <issue_comment>username_3: Do you need to return the data out or just update it?
If it's just update:
```
Update Tablename
Set Locked = 'True'
Where Locked = 'False'
and Deleted = 'False'
```
To give the result out:(add this after the udpate)
```
select top 1 ID, TimeStamp, Locked, Deleted
from TableName
where Locked = 'True'
and Deleted = 'False'
order by TimeStamp asc
```
Upvotes: -1
|
2018/03/19
| 466 | 1,637 |
<issue_start>username_0: How can i find a single object which is nested deeply in an array?
This is the code which works. But [0] isnt really save when it returns null or an empty array.
```
this.subscription = state.subscriptionsState.subscriptions
.map(subs => subs.subscriptions.find(sub => sub.id === subscriptionId))[0];
```
Is there a better / nicer way?
edit:
input data:
```
state.subscriptionsState.subscriptions = [
{
"name": "name",
"type": "type",
"subscriptions": [{
"id": 123456,
}]
}
]
```<issue_comment>username_1: You can `reduce` you base Array into a 1D Array containing only the subscriptions.
From then on it's a simple `.find()` which returns `undefined` if nothing was found, or the `subscription` if something was found.
```js
'use strict'
const items =[
{
"name": "name",
"type": "type",
"subscriptions": [{
"id": 123456,
}]
}
]
const result = items
.reduce((arr, item) => arr.concat(item.subscriptions), [])
.find(sub => sub.id === 123456)
console.log(result)
```
This should throw no errors if the base Array is empty, or if any 1st level item `subscriptions` `Array` property is empty, it would just return `undefined`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to simplify this if you have ES6:
```
const { subscriptionsState: { subscriptions } } = state
this.subscription = subscriptions.find(s => s.id === subscriptionId)
```
Upvotes: 0
|
2018/03/19
| 429 | 1,497 |
<issue_start>username_0: For some reason I'm having trouble selecting an existing blank value in a dropdown with jQuery. The blank option exists, but setting it via `$('#studyList option[value=""]').prop('selected', 'selected');` does not work (nor does `.prop('selected', true)`). Am I doing something wrong?
```js
$('#studyList').append(
$('Study 1'));
$('#studyList').append(
$('Study 2'));
$('#studyList').prepend("");
function clear() {
$('#studyList option[value=""]').prop('selected', 'selected');
}
```
```html
Clear
```<issue_comment>username_1: ```js
$('#studyList').append(
'Study 1'
);
$('#studyList').append(
'Study 2'
);
$('#studyList').prepend("");
$('#clear').on('click', function () {
$('#studyList').val('');
});
```
```html
Clear
```
Upvotes: 1 <issue_comment>username_2: Try this
```
$("#studyList").val("");
```
Upvotes: 0 <issue_comment>username_3: Name your function something other than `clear` as it conflicts with a [built-in function](https://stackoverflow.com/questions/7165570/is-clear-a-reserved-word-in-javascript)
```js
$('#studyList').append(
$('Study 1'));
$('#studyList').append(
$('Study 2'));
$('#studyList').prepend("");
function xclear() {
$('#studyList option[value=""]').prop('selected', 'selected');
}
```
```html
Clear
```
Also, as others have mentioned, you could also just set the value of the select with `$('#studylist').val('')`
Upvotes: 2 [selected_answer]
|
2018/03/19
| 1,368 | 4,747 |
<issue_start>username_0: I am working on a Google Sheets document(Link is at the end of this paragraph) which is meant to track accessories that people borrow. I have written a formula which updates the status of the entry as the following options: Good, Overdue, Returned, Returned Late, and Missing Info. My goal is to have the rows rearrange everyday to put the overdue items first, good status entries second, missing info third, and returned items last. I was able to something similar by using the built-in data filter. To do this I went to Data->Create Filter->Click on symbol on bottom right corner of status column->Sort Z-A. However this solution is manual as it isn't possible(to my knowledge) to run the filter function using the app script. Additionally, the order it sorts the rows isn't exactly what I need. I have written the following app script function to try to counter that however it doesn't seem to be working as imagined.
```
function swap(i, target, correctOrd){
var link = decVar();
var temp = 0;
temp = link.mainSheet.getRange(i, 1, 1, link.col).getValues();
var oneRowCopy = link.mainSheet.getRange(i,1,1, link.col);
var targetRow = link.mainSheet.getRange(target,1,1, link.col);
oneRowCopy.copyTo(targetRow);
temp.copyTo(targetRow);
}
function reArrange(){
var correctOrd = [].concat.apply([], getStatus());
var link = decVar(); var temp = 0;
for(var i = 2, j = 0; i
```
The rest of the code can be found in the script part of the document shared.
<https://docs.google.com/spreadsheets/d/15qaNHuMoVyEJmwR5pL9ruPFDeiNR60cKWLKxnfjaWko/edit?usp=sharing>
Please let me know if you have any ideas on how something like this could be done or what I'm doing wrong with my code.
Thank you!<issue_comment>username_1: You need to define a custom comparator for the `Array.prototype.sort()` method. Your comparator needs to return negative for when the first object comes before the second object, 0 when the two are interchangeable, and positive when the first comes after the second object.
To avoid a lot of nasty case considerations, this can be easily done by defining a "lookup table" which returns a numeric value for a given possible input value:
```
// Comparison object. Objects to come first should be ranked lower.
var ordering = {
"Good": 5, // Will come last.
"Missing Info": 2,
"Overdue": 1, // Will come first.
"Returned": 3,
"Returned Late": 4,
};
var compareIndex = 1; // Column B data, for example
var sheetData = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
sheetData.sort(function (row1, row2) {
// If the compare value is not found in the comparison object, or is convertible to "false" (e.g. 0)
// then the "|| 400" portion makes it default to a value of 400.
var v1 = ordering[row1[compareIndex]] || 400;
var v2 = ordering[row2[compareIndex]] || 400;
return (v1 - v2);
});
sheet.getRange(2, 1, sheetData.length, sheetData[0].length).setValues(sheetData);
```
By changing the values in the comparison object, you can change the order in which the rows are sorted. If you wanted "Good" ratings to come first, you would want the value of "Good" to be the lowest.
See also related questions like [this one](https://stackoverflow.com/questions/34977280/sorting-a-multi-dimensional-array-in-javascript-using-a-custom-sort-function).
Upvotes: 1 <issue_comment>username_2: Although inbuilt spreadsheet functions can be slow compared to Java script array functions, This custom built function can be used for your test case:
```
function OverdueGoodMissingReturned() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Main");
var lr = sh.getLastRow();
var lc = sh.getLastColumn();
var irng = sh.getRange(1,9,lr,1).getValues(); //get col I (StatusColumn)
var irngF = irng.map(flatten); //Flatten the 2D array
function flatten(e) {return e[0];}
var lr = irngF.indexOf(''); //Find actualLast Row (This is needed,because you filled all the rows with Data Validations)
var rng = sh.getRange(2,1,lr-1,lc); //getWholeRange
rng.sort(9); //Sort by the status Column 9,Default Sort is Good,Missing,Overdue,Returned
var rv = rng.getValues();
var irng = sh.getRange(1,9,lr,1).getValues();
var irngF = irng.map(flatten);
var O1 = irngF.indexOf('Overdue')+1; // Find first overdue
var O2 = irngF.lastIndexOf('Overdue')+1; //Find Last overdue
var mv = sh.getRange(O1+':'+O2); //getRange to move
sh.moveRows(mv,2); //Move Overdue to Top
}
```
Note: A lot of getRange calls could be cutoff ,If you don't fill the empty rows with data validations. `rng.sort` could also be cut short to `sheet.sort()`
Upvotes: 1 [selected_answer]
|
2018/03/19
| 1,147 | 3,345 |
<issue_start>username_0: I don't know if this is possible, but it's an interesting situation I came across in my project today.
A table of checkboxes. One type of checkboxes are hierarchical, which means that if one is checked, all checkboxes of the same type to the left of it are magically checked as well.
We need to send information only about the rightmost checked checkbox.
Here's an example for using jQuery code to accomplish it:
<https://codepen.io/oriadam/pen/Yapodm>
```js
$("input").click(function() {
$(".here").removeClass("here");
$("tr").each(function(i, tr) {
$(tr)
.find(".a:has(input:checked):last input:checked")
.each(function(i, elem) {
$(elem).parent().addClass("here");
});
});
});
```
```css
.here {
background: red;
}
.a input {
width: 2em;
height: 2em;
}
```
```html
| | | | | |
| --- | --- | --- | --- | --- |
| | | | | |
| | | | | |
| | | | | |
The challange:
Use a single jQuery(Sizzle) selector to get the rightmost checked checkbox of every tr, while considering only td that has class a.
```
Is there a way to use a single jQuery(Sizzle) selector to get the rightmost checked checkbox of every `tr`, while considering only `td` of class `a`.<issue_comment>username_1: You can certainly simplify that code:
```
$("tr").each(function(i, tr) {
$(tr).find(".a:has(input:checked):last").addClass("here");
});
```
```js
$("input").click(function() {
$(".here").removeClass("here");
$("tr").each(function(i, tr) {
$(tr).find(".a:has(input:checked):last").addClass("here");
});
});
```
```css
.here {
background: red;
}
.a input {
width: 2em;
height: 2em;
}
```
```html
| | | | | |
| --- | --- | --- | --- | --- |
| | | | | |
| | | | | |
| | | | | |
The challange:
Use a single jQuery(Sizzle) selector to get the rightmost checked checkbox of every tr, while considering only td that has class a.
```
...but I'm not seeing a way you'd get rid of that last `each` loop (or something else in its place, like `filter`), since you want to work within the row.
Upvotes: 1 <issue_comment>username_2: Try this, without-`.each`-loop variant:
```js
$("input").click(function() {
$(this).closest('tr').find('td.a').removeClass('here')
.parent().children('.a:has(input:checked):last').addClass('here');
});
```
```css
.here {
background: red;
}
.a input {
width: 2em;
height: 2em;
}
```
```html
| | | | | |
| --- | --- | --- | --- | --- |
| | | | | |
| | | | | |
| | | | | |
```
Upvotes: 0 <issue_comment>username_3: You could use a filter:
```js
$("input").click(function() {
$(".here").removeClass("here");
$('.a:has(input:checked)').filter(function() { // get all .a that have inputs checked in them
return !$(this).nextAll('.a:has(input:checked)').length; // only return .a that has no following siblings with an input checked in them
}).addClass("here");
});
```
```css
.here {
background: red;
}
.a input {
width: 2em;
height: 2em;
}
```
```html
| | | | | |
| --- | --- | --- | --- | --- |
| | | | | |
| | | | | |
| | | | | |
The challange:
Use a single jQuery(Sizzle) selector to get the rightmost checked checkbox of every tr, while considering only td that has class a.
```
Upvotes: 2
|
2018/03/19
| 520 | 1,839 |
<issue_start>username_0: I would like to use closure way to make following json:
```
{
"root": [
{
"key": "testkey",
"value": "testvalue"
}
]
}
```
I'm using following syntax:
```
new JsonBuilder().root {
'key'(testKey)
'value'(testValue)
}
```
But it produces:
```
{
"root": {
"key": "testkey",
"value": "testvalue"
}
}
```<issue_comment>username_1: Your example works correctly, because you pass a simple map for `root` key. You have to pass a list instead do produce expected output. Consider following example:
```
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder {
root((1..3).collect { [key: "Key for ${it}", value: "Value for ${it}"] })
}
println builder.toPrettyString()
```
In this example we pass a list of elements created with `(1..3).collect {}` to a `root` node. We have to split initialization from building a JSON body, because things like `new JsonBuilder().root([])` or even `builder.root([])` throw an exception, because there is no method that expects a parameter of type `List`. Defining list for node `root` inside the closure solves this problem.
### Output
```
{
"root": [
{
"key": "Key for 1",
"value": "Value for 1"
},
{
"key": "Key for 2",
"value": "Value for 2"
},
{
"key": "Key for 3",
"value": "Value for 3"
}
]
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can write something like below:
```
def json = new groovy.json.JsonBuilder()
json {
root (
[
{
key ('color')
value ('orange')
}
]
)
}
println json.toPrettyString()
```
Notice how array is passed to `root` in the above.
Upvotes: 3
|
2018/03/19
| 622 | 2,247 |
<issue_start>username_0: For example I have an entity field which starts null and will show the radio buttons, within the Admin pages once a radio button has been selected and saved into the entity then those radio buttons need to be 'disabled', still visible but not intractable.
```
protected function configureFormFields(FormMapper $form)
{
$form->add('radio_buttons', ChoiceType::class,
array('choices' => array(
"choice 1" => 'input1',
"choice 2" => 'input2'),
'choices_as_values' => true, 'multiple'=>false, 'expanded'=>true, 'disabled' => false));
}
```<issue_comment>username_1: Do it in your view.
Check if one of the choice exists, and implement a different code if it does.
I would also recommand to remove the radio buttons if it exists, and replace with a text. That will prevent some smartass to edit the DOM and change the choice.
Upvotes: 0 <issue_comment>username_2: Your can put a condition in your form to check wether a field is already filled or not.
(Assuming the method is named getRadioButton())
```
if ($this->getSubject()->getRadioButton() != null) {
$form->add(here tell than you need disabled buttons)
} else {
$form->add(here tell than you need buttons)
}
```
also, in form field, you can add "html" attribute doing this:
```
->add('radio_buttons', ChoiceType::class,array(
'what you want'=>'ok',
'attr'=>array("disabled" => true))
```
so finally it'd give something like
```
if ($this->getSubject()->getRadioButton() != null) {
$form->add('radio_buttons', ChoiceType::class,
array('choices' => array(
"choice 1" => 'input1',
"choice 2" => 'input2'),
'choices_as_values' => true,
'multiple'=>false,
'expanded'=>true,
'attr' => array('disabled'=>true),
));
} else {
$form->add('radio_buttons', ChoiceType::class,
array('choices' => array(
"choice 1" => 'input1',
"choice 2" => 'input2'),
'choices_as_values' => true,
'multiple'=>false,
'expanded'=>true,
));
}
```
For more information:
>
> <https://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/form_field_definition.html>
>
>
>
Upvotes: 2 [selected_answer]
|
2018/03/19
| 663 | 2,335 |
<issue_start>username_0: here is my **AdsController.php**
```
public function save(Request $request)
{
$this ->validate($request,[
'object'=>'required',
'description'=>'string',
]);
$ads = new Ad;
$current_user=Auth::user();
$ads->object = $request->input('object');
$ads->description = $request->input('description');
$ads->save();
$users = User::where(("id","!=",$current_user->id ) || ("admin","=",1 ))->get();
foreach ($users as $user) {
$user->notify(new NewAd($current_user, $ads));
}
return redirect('listads') ;
}
```
I want to post an ad to the admin only but i have an error
Please help me<issue_comment>username_1: Do it in your view.
Check if one of the choice exists, and implement a different code if it does.
I would also recommand to remove the radio buttons if it exists, and replace with a text. That will prevent some smartass to edit the DOM and change the choice.
Upvotes: 0 <issue_comment>username_2: Your can put a condition in your form to check wether a field is already filled or not.
(Assuming the method is named getRadioButton())
```
if ($this->getSubject()->getRadioButton() != null) {
$form->add(here tell than you need disabled buttons)
} else {
$form->add(here tell than you need buttons)
}
```
also, in form field, you can add "html" attribute doing this:
```
->add('radio_buttons', ChoiceType::class,array(
'what you want'=>'ok',
'attr'=>array("disabled" => true))
```
so finally it'd give something like
```
if ($this->getSubject()->getRadioButton() != null) {
$form->add('radio_buttons', ChoiceType::class,
array('choices' => array(
"choice 1" => 'input1',
"choice 2" => 'input2'),
'choices_as_values' => true,
'multiple'=>false,
'expanded'=>true,
'attr' => array('disabled'=>true),
));
} else {
$form->add('radio_buttons', ChoiceType::class,
array('choices' => array(
"choice 1" => 'input1',
"choice 2" => 'input2'),
'choices_as_values' => true,
'multiple'=>false,
'expanded'=>true,
));
}
```
For more information:
>
> <https://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/form_field_definition.html>
>
>
>
Upvotes: 2 [selected_answer]
|
2018/03/19
| 411 | 1,507 |
<issue_start>username_0: I have a JEE Service (JaxRx) secured with Keycloak, the authentication works, but when I want to apply security with `@RolesAllowed` I got `EJBAccessException`.
The service is deployed in Wildfly 11 and regarding the documentation, I propagated the security context to the EJB tier with `@SecurityDomain("keycloak")` and the next config file(`jboss-ejb3.xml`).
```
xml version="1.0" encoding="UTF-8"?
\*
keycloak
```
I installed the keycloak `security-domain` in Wildfly.
I was checking and I saw the SessionContext does not have the user, but the Web Context has it.
[](https://i.stack.imgur.com/2c7GV.png)
As you can see in the picture, the requesting user is identified in the RequestContext but in the SessionContext (context) is not present, it shows `anonymous` instead of the user.
Some ideas what could be missing in my service?<issue_comment>username_1: In this case was missing the `jboss-web.xml` file in my `WEB-INF` folder.
I added a file named `jboss-web.xml` with the below content and work like a charm.
```
xml version="1.0" encoding="UTF-8"?
keycloak
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I also had a similar issue because my EJB were not secure. It's mandatory to use either @PermitAll or @RolesAllowed annotation to secure the EJB. Without one of those annotations the user principal that you can retrieve from the EjbContext will be anonymous.
Upvotes: 1
|
2018/03/19
| 970 | 2,927 |
<issue_start>username_0: I have a Enum with Flags like this:
```
[Flags]
public enum ItemType
{
Shop,
Farm,
Weapon,
Process,
Sale
}
```
Then I have several objects in a list with some flags set and some flags not set. It looks like this:
```
public static List AllItems = new List
{
new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5, ItemUseAnimation = new Animation("Trinken", "amb@world\_human\_drinking@coffee@female@idle\_a", "idle\_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp\_player\_inteat@pnq", "intro", 0) },
new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb@prop\_human\_movie\_bulb@base","base", AnimationFlags.Loop)},
new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}
```
Then I go trough the list with a loop and ask if the flag `ItemType.Shop` is set or not, like this:
```
List allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
if (i.ItemType.HasFlag(ItemType.Shop))
{
API.consoleOutput(i.Name);
}
}
```
This is the output of my loop - it shows all items in the list, and the `.HasFlag` method always returns true in this case.
```
Wasserflasche
Sandwich
Apfel
Brötchen
```<issue_comment>username_1: Try to assign values to your enum
```
[Flags]
public enum ItemType
{
Shop = 1,
Farm = 2,
Weapon = 4,
Process = 8,
Sale = 16
}
```
Here are **some** [Guidelines for FlagsAttribute and Enum](https://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.110).aspx) (excerpt from Microsoft Docs)
* Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
* Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
Upvotes: 4 [selected_answer]<issue_comment>username_2: You should assign values to your enums. All the flags attribute does is change how the ToString method works. I would use a bitwise operator to make it less likely to make a mistake:
```
[Flags]
public enum ItemType
{
Shop = 1 << 0, // == 1
Farm = 1 << 1, // == 2
Weapon = 1 << 2, // == 4
Process = 1 << 3, // == 8
Sale = 1 << 4 // == 16
}
```
Upvotes: 2
|
2018/03/19
| 577 | 2,344 |
<issue_start>username_0: In CKEditor 5 I don't see field for target attribute in link dialog.
[](https://i.stack.imgur.com/cLnsP.png)
How to add such field? Or set target=\_blank as default.
Thanks<issue_comment>username_1: Since version `11.1.0` of a [Link Plugin](https://github.com/ckeditor/ckeditor5-link), there is added [link decorator](https://ckeditor.com/docs/ckeditor5/latest/features/link.html#custom-link-attributes-decorators) feature. This feature provides an easy way to define rules when and how to add some extra attributes to links.
There might be manual or automatic [decorators](https://ckeditor.com/docs/ckeditor5/latest/api/module_link_link-LinkConfig.html#member-decorators).
First provides a UI switch which might be toggled by the user. When the user edits a link and toggles it, then preconfigured attributes will be added to the link e.g. `target="_blank"`.
Second one, are applied automatically when content is obtained from the Editor. Here you need to provide a callback function which based on link's URL decides if a given set of attributes should be applied.
There is also a preconfigured decorator, which might be turn on with simple [`config.link.addTargetToExternalLinks=true`](https://ckeditor.com/docs/ckeditor5/latest/api/module_link_link-LinkConfig.html#member-addTargetToExternalLinks). It will add `target="blank"` and `rel="noopener noreferrer"` to all links started with: `http://`, `https://` or `//`.
Upvotes: 2 <issue_comment>username_2: You can achieve it by adding this code in CKEditor Initialization Script:
```
ClassicEditor
.create( document.querySelector( '#editor' ), {
// ...
link: {
decorators: {
openInNewTab: {
mode: 'manual',
label: 'Open in a new tab',
defaultValue: true, // This option will be selected by default.
attributes: {
target: '_blank',
rel: 'noopener noreferrer'
}
}
}
}
} )
.then( ... )
.catch( ... );
```
Here is the [Documentation Link](https://ckeditor.com/docs/ckeditor5/latest/features/link.html) . It will be working fine.
Upvotes: 2
|
2018/03/19
| 545 | 2,047 |
<issue_start>username_0: Create a default ASP.NET Core 2 MVC project normally, then modify the action a little:
```
public IActionResult About()
{
ViewData["Message"] = "This is Chinese[中文]";
return View();
}
```
And this is the view (About.cshtml):
```
### @ViewData["Message"]
### 这也是中文
```
This is the output result in browser:
```
### This is Chinese[中文]
### 这也是中文
```
I found that the Chinese text rendered by the '@' sign is html unicode escaped. The question is how to stop the '@' sign to escape my text?<issue_comment>username_1: According to [this article](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#customizing-the-encoders):
>
> By default encoders use a safe list limited to the Basic Latin Unicode
> range and encode all characters outside of that range as their
> character code equivalents. This behavior also affects Razor TagHelper
> and HtmlHelper rendering as it will use the encoders to output your
> strings.
>
>
>
The article also provides a proper way to customize default html encoder. Add following registration to `Startup.ConfigureServices` method:
```
services.AddSingleton(
HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
UnicodeRanges.CjkUnifiedIdeographs }));
```
Here is result html code after this adjustment:
```
### This is Chinese[中文]
### 这也是中文
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Issue**:
DotNet Core Controller is returning HTML that is not being rendered correctly because the HTML is being ESCAPED.
**Caveat**: It should be noted the 'auto escaping' performed by the framework is for safety issues to avoid unwanted or dangerious html being injected.
**Answer**:
```
@Html.Raw(ViewData["Message"])
```
**Rational**
When Razor calls custom functions that create HTML, the HTML that is returned is typically automatically escaped. This is by design and is not uncommon to many frameworks (like Rails). Anyway, the OUTPUT that custom function returns must be rendered as RAW.
Upvotes: 2
|
2018/03/19
| 913 | 3,315 |
<issue_start>username_0: We have a need to walk over all of the documents in our AWS ElasticSearch cluster, version 6.0, and gather a count of all the duplicate user ids.
I have tried using a Data Visualization to aggregate counts on the user ids and export them, but the numbers don't match another source of our data that is searchable via traditional SQL.
What we would like to see is like this:
USER ID COUNT
userid1 4
userid22 3
...
I am not an advanced Lucene query person and have yet to find an answer to this question. If anyone can provide some insight into how to do this, I would be appreciative.<issue_comment>username_1: The following query will count each id, and filter the ids which have <2 counts, so you'll get something in the likes of:
>
> id:2, count:2
>
>
> id:4, count:15
>
>
>
```
GET /index
{
"query":{
"match_all":{}
},
"aggs":{
"user_id":{
"terms":{
"field":"user_id",
"size":100000,
"min_doc_count":2
}
}
}
}
```
More here:<https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html>
Upvotes: 3 <issue_comment>username_2: If you want to get all duplicate userids with count
First you get to know maximum size of aggs.
find all maximum matches record via aggs cardinality.
```
GET index/type/_search
{
"size": 0,
"aggs": {
"maximum_match_counts": {
"cardinality": {
"field": "userid",
"precision_threshold": 100
}
}
}
}
```
get value of maximum\_match\_counts aggregations
Now you can get all duplicate userids
```
GET index/type/_search
{
"size": 0,
"aggs": {
"userIds": {
"terms": {
"field": "userid",
"size": maximum_match_counts,
"min_doc_count": 2
}
}
}
}
```
Upvotes: 3 <issue_comment>username_3: When you go with terms aggregation ([username_2](https://stackoverflow.com/a/49370085/889556) suggestion) and set aggregation size more than 10K you will get a warning about this approach will throw an error for the feature releases.
Instead of using terms aggregation you should go with [composite aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-aggregations-bucket-composite-aggregation.html) to scan all of your documents by pagination/afterkey method.
>
> the composite aggregation can be used to paginate all buckets from a multi-level aggregation efficiently. This aggregation provides a way to stream all buckets of a specific aggregation similarly to what scroll does for documents.
>
>
>
Upvotes: 0 <issue_comment>username_4: ```
GET /index
{
"query":{
"match_all":{}
},
"aggs":{
"user_id":{
"terms":{
"field":"user_id",
"size":65536,
"min_doc_count":2
}
}
}
}
this one is working perfectly, i have found issues in lot of end point ES url's using this query, this will help you in post man, postman will display an error if you run the query with size 100000,so better you can use size=65536, and you have to replace the "field":"user_id" name as well,it should be your field name
```
Upvotes: 0
|
2018/03/19
| 940 | 3,341 |
<issue_start>username_0: I am trying to display a key value from my JSON response in react. so something like this fieldData {**DMR\_5\_why\_who\_test**: "test", **why**: test}. I want to just be able to show the bolded values or key values. currently my code looks as follows. but it spits back [Object, Object] instead of my key value
```
dotesting = () => {
const j = Object.values(this.state.data);
var journalEntries = [];
for (var i = 0; i < j.length; i++){
journalEntries.push(
### {j[i].fieldData.toString()}
);
}
console.log({journalEntries})
return({journalEntries});
}
```<issue_comment>username_1: The following query will count each id, and filter the ids which have <2 counts, so you'll get something in the likes of:
>
> id:2, count:2
>
>
> id:4, count:15
>
>
>
```
GET /index
{
"query":{
"match_all":{}
},
"aggs":{
"user_id":{
"terms":{
"field":"user_id",
"size":100000,
"min_doc_count":2
}
}
}
}
```
More here:<https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html>
Upvotes: 3 <issue_comment>username_2: If you want to get all duplicate userids with count
First you get to know maximum size of aggs.
find all maximum matches record via aggs cardinality.
```
GET index/type/_search
{
"size": 0,
"aggs": {
"maximum_match_counts": {
"cardinality": {
"field": "userid",
"precision_threshold": 100
}
}
}
}
```
get value of maximum\_match\_counts aggregations
Now you can get all duplicate userids
```
GET index/type/_search
{
"size": 0,
"aggs": {
"userIds": {
"terms": {
"field": "userid",
"size": maximum_match_counts,
"min_doc_count": 2
}
}
}
}
```
Upvotes: 3 <issue_comment>username_3: When you go with terms aggregation ([username_2](https://stackoverflow.com/a/49370085/889556) suggestion) and set aggregation size more than 10K you will get a warning about this approach will throw an error for the feature releases.
Instead of using terms aggregation you should go with [composite aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-aggregations-bucket-composite-aggregation.html) to scan all of your documents by pagination/afterkey method.
>
> the composite aggregation can be used to paginate all buckets from a multi-level aggregation efficiently. This aggregation provides a way to stream all buckets of a specific aggregation similarly to what scroll does for documents.
>
>
>
Upvotes: 0 <issue_comment>username_4: ```
GET /index
{
"query":{
"match_all":{}
},
"aggs":{
"user_id":{
"terms":{
"field":"user_id",
"size":65536,
"min_doc_count":2
}
}
}
}
this one is working perfectly, i have found issues in lot of end point ES url's using this query, this will help you in post man, postman will display an error if you run the query with size 100000,so better you can use size=65536, and you have to replace the "field":"user_id" name as well,it should be your field name
```
Upvotes: 0
|
2018/03/19
| 1,030 | 3,432 |
<issue_start>username_0: I am trying to print StudentList from the class Student using the University class
Code for UniversityClass:
```
public class University {
Unit[] units = new Unit[3];
Student student1;
Student student2;
Student student3;
public void printStatus() {
System.out.println("Welcome to Java University");
System.out.println();
createUnits();
displayUnits();
System.out.println("Thank you for using Java University");
}
public void createUnits() {
units[0] = new Unit("FIT1234", "Advance Bogosorts");
student1 = new Student(1234, "Mark", "Stevens");
student2 = new Student(5678, "Steven", "Perry");
units[1] = new Unit("FIT2345", "Java Programming");
student3 = new Student(9012, "Cooper", "Smith");
units[2] = new Unit("FIT3456"," Java Fundamentals");
}
public void displayUnits() {
for (int i =0; i
```
Code for StudentList:
```
import java.util.ArrayList;
import java.util.List;
public class Unit {
private String unitcode;
private String unitname;
public Unit(String x,String y) {
unitcode = x;
unitname = y;
}
private final List studentList = new ArrayList<>();
public boolean addStudents(Student newStudents){
studentList.add(newStudents);
return true;
}
public String description() {
return unitcode + " " + unitname;
}
}
```
The output I get
```
Welcome to Java University
FIT1234 Advance Bogosorts
1234 <NAME>
5678 <NAME>
9012 <NAME>
FIT2345 Java Programming
1234 <NAME>
5678 <NAME>
9012 <NAME>
FIT3456 Java Fundamentals
1234 <NAME>
5678 <NAME>
9012 <NAME>
Thank you for using Java University
```
The output I want
```
Welcome to Java University
FIT1234 Advance Bogosorts
1234 <NAME>
5678 <NAME>
FIT2345 Java Programming
9012 <NAME>
FIT3456 Java Fundamentals
Thank you for using Java University
```
I don't get what I'm doing wrong. I made a studentlist and added each student into the list but I don't get the right output. Am I suppose to add the students into the Unit List instead so that each student is enrolled into a unit or am I printing in the wrong order? Can anyone please offer me a solution?<issue_comment>username_1: You can modify the method `displayUnits` to print only the students registered on a given course:
```
public void displayUnits() {
for (int i =0; i
```
To achieve this, you will need to
**1)** Add a getter method in the class `Unit`:
```
public class Unit {
...
private final List studentList = new ArrayList<>();
public List getStudents() {
return studentList;
}
...
}
```
**2)** Populate the list of students in your `Unit` objects - and likely get rid of the instance variables `student1`, `student2` and `student3`:
```
public void createUnits() {
units[0] = new Unit("FIT1234", "Advance Bogosorts");
units[0].studentList.add(new Student(1234, "Mark", "Stevens"));
units[0].studentList.add(new Student(5678, "Steven", "Perry"));
units[1] = new Unit("FIT2345", "Java Programming");
units[1].studentList.add(new Student(9012, "Cooper", "Smith"));
units[2] = new Unit("FIT3456"," Java Fundamentals");
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: There is no connection between units and students, so I think you need to add students to the units as well.....
Upvotes: 0
|
2018/03/19
| 734 | 2,327 |
<issue_start>username_0: My program is not returning the expected output, I tried very hard but I don't know how to do for this code. What can I do ?
**Expected output**
```
1 2 3 4 5 6 7 8 ......2000
```
**Actual output**
```
1 2 3 4 5 6 1 2 3 4 5 6 ..1000
```
**Main**
```
public class Race_ConditonTest {
public static void main(String[] args) {
Race_Condition2 R1 = new Race_Condition2();
Race_Condition2 R2 = new Race_Condition2();
R1.start();
R2.start();
}
}
```
**RaceCondition2 (sub class)**
```
public class Race_Condition2 extends Thread{
Race_Condition R= new Race_Condition();
public void run() {
R.sum();
}
}
```
**RaceCondition class (super class)**
```
public class Race_Condition {
int x=0;
public int Load(int x){
return x;
}
public void Store(int data) {
int x= data;
System.out.println(x);
}
public int Add(int i,int j) {
return i+j ;
}
public void sum() {
for (int i=0 ; i<1000 ; i++) {
this.x=Load(x);
this.x=Add(x,1);
Store(x);
}
}
}
```<issue_comment>username_1: You can modify the method `displayUnits` to print only the students registered on a given course:
```
public void displayUnits() {
for (int i =0; i
```
To achieve this, you will need to
**1)** Add a getter method in the class `Unit`:
```
public class Unit {
...
private final List studentList = new ArrayList<>();
public List getStudents() {
return studentList;
}
...
}
```
**2)** Populate the list of students in your `Unit` objects - and likely get rid of the instance variables `student1`, `student2` and `student3`:
```
public void createUnits() {
units[0] = new Unit("FIT1234", "Advance Bogosorts");
units[0].studentList.add(new Student(1234, "Mark", "Stevens"));
units[0].studentList.add(new Student(5678, "Steven", "Perry"));
units[1] = new Unit("FIT2345", "Java Programming");
units[1].studentList.add(new Student(9012, "Cooper", "Smith"));
units[2] = new Unit("FIT3456"," Java Fundamentals");
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: There is no connection between units and students, so I think you need to add students to the units as well.....
Upvotes: 0
|
2018/03/19
| 655 | 2,196 |
<issue_start>username_0: I am learning javascript. In one of the document, I read we can modify the length of array. I tried as below and it worked.
```
var array = new Array(1, 2, 3, 4 ,5);
array.length = 4;
```
Now array becomes [1, 2, 3, 4].
But the same is not working on Strings.
```
var str = new String("abcdef");
str.length = 5;
```
str is not getting modified. Is there any specific reason to not allow this behavior on strings?<issue_comment>username_1: Strings are immutable by design. You can't change them, but you can reassign the reference to a new string value. If you want to shorten a string, you can use the String slice() method.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice>
Upvotes: 3 [selected_answer]<issue_comment>username_2: When you log your String **object** in the console, you can see why this is not working:
```js
var str = new String("abcdef");
str.length = 5;
console.log(str)
```
Thus, you cannot set the `length` property here. We are talking about the "immutability" of strings in `JavaScript`.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
Upvotes: 1 <issue_comment>username_3: String are immutable. For a new length of the string, you need an assignment wich copies the string with a new length.
```js
var string = 'abcdef';
string = string.slice(0, 4);
console.log(string);
```
Upvotes: 2 <issue_comment>username_4: .length property is used differently for string, because they are immutable:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
If you want to alter the length of a string you can create a new string using slice.
Upvotes: 2 <issue_comment>username_5: >
> Attempting to assign a value to a string's .length property has no observable effect.
>
>
> [MDN Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)
>
>
>
```js
var myString = "bluebells";
// Attempting to assign a value to a string's .length property has no observable effect.
myString.length = 4;
console.log(myString);
/* "bluebells" */
```
Upvotes: 0
|
2018/03/19
| 726 | 2,433 |
<issue_start>username_0: I'm very much a beginner. This generates the "right" data off the URL, but when I try to generate a CSV file, the resultant Excel file is empty.
This is the code ...
```
import csv
import urllib.request
from bs4 import BeautifulSoup
f = open('dataoutput.csv', 'w', newline = "")
writer = csv.writer(f)
soup = BeautifulSoup(urllib.request.urlopen("https://www.rjobrien.co.uk/tools/quoteresult/symbol/FGBLM8").read(), 'lxml')
tbody = soup('table', {"class": "table table-bordered table-condensed"})[0].find_all('tr')
for row in tbody:
cols = row.findChildren(recursive=False)
cols = [ele.text.strip() for ele in cols]
writer.writerow(cols)
```<issue_comment>username_1: Strings are immutable by design. You can't change them, but you can reassign the reference to a new string value. If you want to shorten a string, you can use the String slice() method.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice>
Upvotes: 3 [selected_answer]<issue_comment>username_2: When you log your String **object** in the console, you can see why this is not working:
```js
var str = new String("abcdef");
str.length = 5;
console.log(str)
```
Thus, you cannot set the `length` property here. We are talking about the "immutability" of strings in `JavaScript`.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
Upvotes: 1 <issue_comment>username_3: String are immutable. For a new length of the string, you need an assignment wich copies the string with a new length.
```js
var string = 'abcdef';
string = string.slice(0, 4);
console.log(string);
```
Upvotes: 2 <issue_comment>username_4: .length property is used differently for string, because they are immutable:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
If you want to alter the length of a string you can create a new string using slice.
Upvotes: 2 <issue_comment>username_5: >
> Attempting to assign a value to a string's .length property has no observable effect.
>
>
> [MDN Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)
>
>
>
```js
var myString = "bluebells";
// Attempting to assign a value to a string's .length property has no observable effect.
myString.length = 4;
console.log(myString);
/* "bluebells" */
```
Upvotes: 0
|
2018/03/19
| 630 | 2,252 |
<issue_start>username_0: I have one table (Table A) with a description field (varchar(max)).
I have another table (Table B) with a field With keywords.
For all rows in table B I want to return all the rows from Table A that contain at least one occurence of the keyword specified in table A.
I have googled and searched on this site but haven't found any example how to do this. All the examples I have found are require you to input the search string instead of just running the query dynamically.<issue_comment>username_1: Strings are immutable by design. You can't change them, but you can reassign the reference to a new string value. If you want to shorten a string, you can use the String slice() method.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice>
Upvotes: 3 [selected_answer]<issue_comment>username_2: When you log your String **object** in the console, you can see why this is not working:
```js
var str = new String("abcdef");
str.length = 5;
console.log(str)
```
Thus, you cannot set the `length` property here. We are talking about the "immutability" of strings in `JavaScript`.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
Upvotes: 1 <issue_comment>username_3: String are immutable. For a new length of the string, you need an assignment wich copies the string with a new length.
```js
var string = 'abcdef';
string = string.slice(0, 4);
console.log(string);
```
Upvotes: 2 <issue_comment>username_4: .length property is used differently for string, because they are immutable:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length>
If you want to alter the length of a string you can create a new string using slice.
Upvotes: 2 <issue_comment>username_5: >
> Attempting to assign a value to a string's .length property has no observable effect.
>
>
> [MDN Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)
>
>
>
```js
var myString = "bluebells";
// Attempting to assign a value to a string's .length property has no observable effect.
myString.length = 4;
console.log(myString);
/* "bluebells" */
```
Upvotes: 0
|
2018/03/19
| 1,077 | 3,158 |
<issue_start>username_0: For example, the following (**invalid**) AU mobile phone number is considered valid by libphonenumber `++++++614- -12a345678(())&`:
[Tested in their demo site](https://libphonenumber.appspot.com/):
[](https://i.stack.imgur.com/Zn3eI.png)
[](https://i.stack.imgur.com/Nq6TI.png)
Code wise:
```
final String mobilePhoneNumber = "++++++614- -12a345678(())&";
final String region = "AU";
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
// true
// I don't get it, how come ++++++614- -12a345678(())& is even considered a possible number??
System.out.println(phoneNumberUtil.isPossibleNumber(mobilePhoneNumber, region));
final Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(mobilePhoneNumber, region);
// true
final boolean validNumberForRegion = phoneNumberUtil.isValidNumberForRegion(phoneNumber, region);
// true
final boolean validMobileNumber = phoneNumberUtil.getNumberType(phoneNumber).equals(PhoneNumberType.MOBILE);
```
Tested on the libphonenumber v8.9.2:
```
compile group: 'com.googlecode.libphonenumber', name: 'libphonenumber', version: '8.9.2'
```<issue_comment>username_1: For one, write a method to verify the input using regex. Something like:
```
boolean validPhone(String str){
str.matches("^[+]?\\d{2,4}(-?\\d{1,5}){0,2}$");
}
```
see also:
[This post,](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) [phoneregex.com](http://phoneregex.com/), and [rexlib's section,](http://regexlib.com/(X(1)A(68Lkt4Xhv7rOWXE3Gl3LgrU3It4-9Fk8E3JhrjgZJYRACC9VauD8sJ76bmDCGBBzNS9JTrMqBkG4DhQsnXroQr7TRTUNgyzw-gmpsGy_mMcG-ZipWY0QSkUkTzmNkgc0xJYk7GdttndTk5jQRJ53enyK-6DVy8gF063NH7XGsBVpvXFRxaXKvJ4ydZC6WRKd0))/ErrorPage.aspx?aspxerrorpath=/DisplayPatterns.aspxcattabindex=6&categoryId=7&AspxAutoDetectCookieSupport=1)
Upvotes: 0 <issue_comment>username_2: I know it's already been two years, but if someone is looking for an answer, then please consider looking [here](https://libphonenumber.appspot.com/phonenumberparser?number=%2B%2B%2B%2B%2B%2B614-++-12a345678%28%28%29%29%26&country=DE), as said upper. Between texts and tables, you'll find eventually this one:
[](https://i.stack.imgur.com/xn6bm.png)
Better said, the phone number is correct, but not the format. And thus, the one we need is the generally either the international or the national format plus region or country code.
For example:
```java
final String mobilePhoneNumber = "++++++614- -12a345678(())&";
final String region = "AU";
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(mobilePhoneNumber, region);
String formatted = phoneNumberUtil.format(number, PhoneNumberFormat.INTERNATIONAL);
String national = phoneNumberUtil.format(number, PhoneNumberFormat.NATIONAL);
System.out.println(formatted); // +61 412 345 678
System.out.println(national); // 0412 345 678
```
Upvotes: 2
|
2018/03/19
| 750 | 2,187 |
<issue_start>username_0: I'm considering using Dialogflow in my company but I am not fully convinced about security issues. Does anyone of you know if Google stores any input data that comes from users? In particular, any sensitive personal data?
Thank you in advance!
Best,
Marcin<issue_comment>username_1: For one, write a method to verify the input using regex. Something like:
```
boolean validPhone(String str){
str.matches("^[+]?\\d{2,4}(-?\\d{1,5}){0,2}$");
}
```
see also:
[This post,](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) [phoneregex.com](http://phoneregex.com/), and [rexlib's section,](http://regexlib.com/(X(1)A(68Lkt4Xhv7rOWXE3Gl3LgrU3It4-9Fk8E3JhrjgZJYRACC9VauD8sJ76bmDCGBBzNS9JTrMqBkG4DhQsnXroQr7TRTUNgyzw-gmpsGy_mMcG-ZipWY0QSkUkTzmNkgc0xJYk7GdttndTk5jQRJ53enyK-6DVy8gF063NH7XGsBVpvXFRxaXKvJ4ydZC6WRKd0))/ErrorPage.aspx?aspxerrorpath=/DisplayPatterns.aspxcattabindex=6&categoryId=7&AspxAutoDetectCookieSupport=1)
Upvotes: 0 <issue_comment>username_2: I know it's already been two years, but if someone is looking for an answer, then please consider looking [here](https://libphonenumber.appspot.com/phonenumberparser?number=%2B%2B%2B%2B%2B%2B614-++-12a345678%28%28%29%29%26&country=DE), as said upper. Between texts and tables, you'll find eventually this one:
[](https://i.stack.imgur.com/xn6bm.png)
Better said, the phone number is correct, but not the format. And thus, the one we need is the generally either the international or the national format plus region or country code.
For example:
```java
final String mobilePhoneNumber = "++++++614- -12a345678(())&";
final String region = "AU";
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(mobilePhoneNumber, region);
String formatted = phoneNumberUtil.format(number, PhoneNumberFormat.INTERNATIONAL);
String national = phoneNumberUtil.format(number, PhoneNumberFormat.NATIONAL);
System.out.println(formatted); // +61 412 345 678
System.out.println(national); // 0412 345 678
```
Upvotes: 2
|
2018/03/19
| 1,886 | 3,398 |
<issue_start>username_0: I've been struggling with the following problem:
I have a file with the following content
```
1521471079313,219,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,177,0,35
1521471080337,263,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,169,0,0
1521471081404,245,HTTP Request 12,200,OK,PROD 50 rpm 1-10,text,true,,5134,201,1,1,210,0,37
1521471082453,125,HTTP Request 13,200,OK,PROD 50 rpm 1-10,text,true,,8910,201,1,1,106,0,0
1521471083381,217,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,188,0,0
1521471084402,303,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,226,0,41
```
the first item in the list is an epoc timestamp and I want to convert it to a human readable one.
I tried the following command
```
cat file.csv|sed -E "s/^([0-9]*)(,.*)/$(date -r \1 '+%m-%d-%Y:%H:%M:%S')\2/p"
```
And it seemed to work but then I saw that it would convert it to:
```
01-01-1970:01:00:01,245,HTTP Request 13,200,OK,PROD 50 rpm 1-10,text,true,,8910,201,1,1,219,0,43
01-01-1970:01:00:01,276,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,217,0,0
01-01-1970:01:00:01,276,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,217,0,0
01-01-1970:01:00:01,242,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,216,0,34
01-01-1970:01:00:01,242,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,216,0,34
01-01-1970:01:00:01,147,HTTP Request 12,200,OK,PROD 50 rpm 1-10,text,true,,5134,201,1,1,119,0,0
01-01-1970:01:00:01,147,HTTP Request 12,200,OK,PROD 50 rpm 1-10,text,true,,5134,201,1,1,119,0,0
```
all timestamps look like "the beginning of time :-)" and not what I wanted.
I know that I have a command substitution in the sed and also two group references based on the former regex in the sed command but why it does not work stumps me.<issue_comment>username_1: You can parse a csv file easily with GNU `awk`. Your `$1` value is an EPOCH value in milli-seconds. You can use `strftime()` call to print the human readable format, after dividing the value by 1000 (i.e. to convert to seconds)
```
awk 'BEGIN{FS=OFS=","}{$1=strftime("%c",($1/1000))}1' file
```
and for in-place edit, use `gawk` or move the output to a temporary file and revert it back to the original
```
tmpfile=$(mktemp /tmp/abc.XXXXXX)
awk 'BEGIN{FS=OFS=","}{$1=strftime("%c",($1/1000))}1' file > "$tmpfile"
mv "$tmpfile" file
```
Upvotes: 3 <issue_comment>username_2: This works for me:
```
sed -r "s/^([0-9]+)(,.*)/echo \$(date -d @\1)\2/" sampl3.log > log.sh && bash log.sh
```
But you have to be secure, that no evil commands are contained in the log, and adapt your date format.
```
Mi 2. Jul 01:21:53 CEST 50183,219,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,177,0,35
Mi 2. Jul 01:38:57 CEST 50183,263,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,169,0,0
Mi 2. Jul 01:56:44 CEST 50183,245,HTTP Request 12,200,OK,PROD 50 rpm 1-10,text,true,,5134,201,1,1,210,0,37
Mi 2. Jul 02:14:13 CEST 50183,125,HTTP Request 13,200,OK,PROD 50 rpm 1-10,text,true,,8910,201,1,1,106,0,0
Mi 2. Jul 02:29:41 CEST 50183,217,HTTP Request 14,200,OK,PROD 50 rpm 1-10,text,true,,17665,204,1,1,188,0,0
Mi 2. Jul 02:46:42 CEST 50183,303,HTTP Request 11,200,OK,PROD 50 rpm 1-10,text,true,,30268,202,1,1,226,0,41
```
Upvotes: 2 [selected_answer]
|
2018/03/19
| 2,230 | 7,476 |
<issue_start>username_0: For `git cherry-pick` resulting in a conflict, why does Git suggest more changes than just from the given commit?
Example:
```
-bash-4.2$ git init
Initialized empty Git repository in /home/pfusik/cp-so/.git/
-bash-4.2$ echo one >f
-bash-4.2$ git add f
-bash-4.2$ git commit -m "one"
[master (root-commit) d65bcac] one
1 file changed, 1 insertion(+)
create mode 100644 f
-bash-4.2$ git checkout -b foo
Switched to a new branch 'foo'
-bash-4.2$ echo two >>f
-bash-4.2$ git commit -a -m "two"
[foo 346ce5e] two
1 file changed, 1 insertion(+)
-bash-4.2$ echo three >>f
-bash-4.2$ git commit -a -m "three"
[foo 4d4f9b0] three
1 file changed, 1 insertion(+)
-bash-4.2$ echo four >>f
-bash-4.2$ git commit -a -m "four"
[foo ba0da6f] four
1 file changed, 1 insertion(+)
-bash-4.2$ echo five >>f
-bash-4.2$ git commit -a -m "five"
[foo 0326e2e] five
1 file changed, 1 insertion(+)
-bash-4.2$ git checkout master
Switched to branch 'master'
-bash-4.2$ git cherry-pick 0326e2e
error: could not apply 0326e2e... five
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add ' or 'git rm '
hint: and commit the result with 'git commit'
-bash-4.2$ cat f
one
<<<<<<< HEAD
=======
two
three
four
five
>>>>>>> 0326e2e... five
```
I was expecting just the "five" line between the conflict markers.
Can I switch Git to my expected behavior?<issue_comment>username_1: Well... it seems to me this is an edge case, living at the intersection of "cherry-picking an insertion that was made in the source branch at a line that doesn't exist in the target branch", and "progression of changes that all are deemed one 'hunk' because each is adjacent to the one before".
These issues make git unsure what you intend, so it asks "what should I do" in the broadest way, giving you all the code you might need to make a correct decision.
If you init the file as
```
a
b
c
d
e
f
g
h
i
```
and then create changes like
```
x -- A <--(master)
\
C -- E -- G <--(branch)
```
(where commit labeled `A` uppercases the corresponding letter in the file, etc.), this is a case that will behave much more like you expect - because everything looks very clear to git and it just does the obvious thing when you say to cherry-pick `E` to `master`. (Not only does it not stick unrelated changes into conflict markers, but there are no conflict markers; it just works.)
Now to be clear - I'm not saying cherry-pick will only do the right thing in such clear-cut cases as mine. But just as your test case is kind of a "worst case" scenario for a cherry-pick, mine is an ideal case. There are many cases in between, and in practice people usually seem to get the results they want out of cherry-pick. (In case that sounds like an endorsement of the cherry-pick command, let me clarify: I think it's the most over-recommended command in the suite, and I never really use it. But it does work, within its defined boundaries.)
Basically remember two things:
1) If you insert a new line on the source branch, and a corresponding insertion point can't be unambiguously determined in the target branch, you're going to get a conflict and it will probably include "context" from the source branch
2) If two changes are adjacent - even though they don't overlap - they can still be considered in conflict.
Upvotes: 1 <issue_comment>username_2: Before we get any further, let's draw the commit graph:
```
A <-- master (HEAD)
\
B--C--D--E <-- foo
```
or, so that you can compare, here's the way Git draws it:
```
$ git log --all --decorate --oneline --graph
* 7c29363 (foo) five
* a35e919 four
* ee70402 three
* 9a179e6 two
* d443a2a (HEAD -> master) one
```
(Note that I turned your question into a command sequence, which I've appended; my commit hashes are of course different from yours.)
Cherry-pick is a peculiar form of merge
=======================================
The reason you see the somewhat pathological behavior here is that `git cherry-pick` is actually performing a merge operation. The oddest part about this is the chosen merge base.
### A normal merge
For a normal merge, you check out some commit (by checking out some branch which checks out the tip commit of that branch) and run `git merge *other*`. Git locates the commit specified by *`other`*, then uses the commit graph to locate the merge base, which is often pretty obvious from the graph. For instance when the graph looks like this:
```
o--o--L <-- ours (HEAD)
/
...--o--B
\
o--o--R <-- theirs
```
the merge base is simply commit `B` (for base).
To do the merge, Git then makes two `git diff`s, one from the merge base to our local commit `L` on the left, and their commit `R` on the right (sometimes called the *remote* commit). That is:
```
git diff --find-renames B L # find what we did on our branch
git diff --find-renames B R # find what they did on theirs
```
Git can then combine these changes, applying the combined changes to `B`, to make a new merge commit whose first parent is `L` and second parent is `R`. That final merge commit is a *merge commit*, which uses the word "merge" as an adjective. We often just call it *a merge*, which uses the word "merge" as a noun.
To get this merge-as-a-noun, though, Git had to run the merge machinery, to combine two sets of diffs. This is the process of *merging*, using the word "merge" as a verb.
### A cherry-pick merge
To do a cherry-pick, Git runs the merge machinery—the *merge as a verb*, as I like to put it—but picks out a peculiar merge base. The merge base of the cherry-pick is simply the *parent* of the commit being cherry-picked.
In your case, you're cherry-picking commit `E`. So Git is merging (verb) with commit `D` as the merge base, commit `A` as the left/local *L* commit, and commit `E` as the right-side *R* commit. Git generates the internal equivalent of two diff listings:
```
git diff --find-renames D A # what we did
git diff --find-renames D E # what they did
```
What *we* did was to *delete* four lines: the ones reading `two`, `three`, and `four`. What they did was to *add* one line: the one reading `five`.
### Using `merge.conflictStyle`
This all becomes somewhat clearer—well, *maybe* somewhat clearer —if we set `merge.conflictStyle` to `diff3`. Now instead of just showing us the ours and theirs sections surrounded by `<<<<<<<` etc., Git adds the *merge base* version as well, marked with `|||||||`:
```
one
<<<<<<< HEAD
||||||| parent of 7c29363... five
two
three
four
=======
two
three
four
five
>>>>>>> 7c29363... five
```
We now see that Git claims that we deleted three lines from the base, while they kept those three lines and added a fourth.
Of course, we need to understand that the merge base here was the parent of commit `E`, which is if anything "ahead of" our current commit `A`. It's not really true that we *deleted* three lines. In fact, we *never had the three lines in the first place.* We just have to deal with Git showing things *as if* we had deleted some lines.
Appendix: script to generate the clash
======================================
```
#! /bin/sh
set -e
mkdir t
cd t
git init
echo one >f
git add f
git commit -m "one"
git checkout -b foo
echo two >>f
git commit -a -m "two"
echo three >>f
git commit -a -m "three"
echo four >>f
git commit -a -m "four"
echo five >>f
git commit -a -m "five"
git checkout master
git cherry-pick foo
```
Upvotes: 5 [selected_answer]
|
2018/03/19
| 256 | 958 |
<issue_start>username_0: i followed this [article](https://collectiveidea.com/blog/archives/2016/05/31/beyond-yml-files-dynamic-translations) to implement translations through a admin page
This works great in my localhost, but when i push to heroku this message appears:
"/app/app/models/translation.rb:1:in `': superclass mismatch for class Translation (TypeError)"
My MODEL TRanslation:
```
class Translation < ApplicationRecord
end
```
Can anyone help me, i don't have any idea to solve this<issue_comment>username_1: Maybe **Translation** is already `key` class on heroku. If so, you have to rename that model.
Upvotes: 2 <issue_comment>username_2: I renamed the model, routes, controller, helpers and views to "Language", but keeping the table name as "translations". Then i put table\_name = 'translations' in Language Model:
app/model/language.rb
```
class Language < ApplicationRecord
self.table_name = "translations"
end
```
Upvotes: 1
|
2018/03/19
| 361 | 1,337 |
<issue_start>username_0: I have a through table, `doctor_specialties` that has a column ordinal that I would like to use in order to create a column named `primary_specialty` and also `secondary_specialty`. The logic for `primary_specialty` is `WHERE ordinal == 1`.
How can I add the `primary_specialty` and `secondary_specialty` columns? One approach would be to use a `WHERE` statement with the `INNER JOIN` but I think that would be less efficient?
```
SELECT pd.name AS "doctor_name",
s.name AS "primary_specialty" WHERE ds.ordinal == 1
FROM doctor_profiles AS dp
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id
```
Desired output is
```
name primary_specialty secondary_specialty
Josh Dermatology, Cosmetic Dermatology
Linda Primary Care null
```<issue_comment>username_1: Maybe **Translation** is already `key` class on heroku. If so, you have to rename that model.
Upvotes: 2 <issue_comment>username_2: I renamed the model, routes, controller, helpers and views to "Language", but keeping the table name as "translations". Then i put table\_name = 'translations' in Language Model:
app/model/language.rb
```
class Language < ApplicationRecord
self.table_name = "translations"
end
```
Upvotes: 1
|
2018/03/19
| 441 | 1,622 |
<issue_start>username_0: I am trying to get the last modified directory of a folder in the project directory. With the code below, I can get the last modified directory only for the scripts saved in the directory, but I want to get the last modified `subdir` of a folder, which is in project directory.
And I only want to fetch the folder name, not the whole path, because I will increment the folder name `+1` and create new one when the file limit is reached for the mentioned folder.
And my code is:
```
import os
import glob
all_subdirs = [d for d in os.listdir('/root/visual-
studio/testfolder/testsubdir/') if os.path.isdir(d)]
latest_subdir = max(all_subdirs, key=os.path.getmtime)
print(latest_subdir)
```
The script is saved to `testfolder` and when I run the script it only gives `testfolders` last modified directory. But I want to get the `testsubdirs` latest directory.
When I run the script below for `testsubdirs` I get this error:
```
Traceback (most recent call last):
File "/root/visual-studio/testfolder/test.py", line 40, in
latest\_subdir = max(all\_subdirs, key=os.path.getmtime)
ValueError: max() arg is an empty sequence
```<issue_comment>username_1: Maybe **Translation** is already `key` class on heroku. If so, you have to rename that model.
Upvotes: 2 <issue_comment>username_2: I renamed the model, routes, controller, helpers and views to "Language", but keeping the table name as "translations". Then i put table\_name = 'translations' in Language Model:
app/model/language.rb
```
class Language < ApplicationRecord
self.table_name = "translations"
end
```
Upvotes: 1
|
2018/03/19
| 1,026 | 3,789 |
<issue_start>username_0: I have an Angular component that uses [PrismJS](http://prismjs.com/) for syntax highlighting code blocks. The component is as follows:
```
import { Component, AfterViewInit, Input,
ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';
declare var Prism: any;
@Component({
selector: 'prism',
template: `
`
})
export class PrismComponent implements AfterViewInit {
@Input() language: string;
@ViewChild('rawContent') rawContent: ElementRef;
content: string;
constructor(public cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.content = Prism.highlight(this.rawContent.nativeElement.textContent.trim(),
Prism.languages[this.language]);
this.cdr.detectChanges();
}
}
```
The issue is that when I use it, I have to manually escape any invalid HTML characters.
I've tried using [`DomSanitizer`](https://angular.io/api/platform-browser/DomSanitizer).sanitize() on both the component element reference value and the `rawContent` reference value in the following locations in order to try to circumvent this:
* constructor
* `ngOnChanges()`
* `ngOnInit()`
* `ngAfterViewInit()`
Angular throws invalid character errors before any of these events take place when the code block contains invalid HTML characters.
How would I go about sanitizing the code block specified in `rawContent` in order to prevent manually escaping invalid HTML characters?
Example [StackBlitz Solution](https://stackblitz.com/edit/ng-content-sanitize?file=app%2Fapp.component.html)<issue_comment>username_1: Use CDATA ([Character Data](https://en.wikipedia.org/wiki/CDATA)):
```
export class Demo { id: number; name: string; }
```
Upvotes: 2 <issue_comment>username_2: As of angular 5.2, this is currently not possible because of the way single brackets are interpreted. Using `ngNonBindable` does not work with single brackets
<https://github.com/angular/angular/issues/11859>
This will fail
```
Test content with a bracket {
```
To include strings with backets in your template, you need to assign the string to a component's variable
```
//component.ts
snippet = `export class Demo {
id: number;
name: string;
}`;
//component.html
```
### SanitizePrismComponent
```
import {
Component,
AfterViewInit,
Input,
ChangeDetectorRef,
SecurityContext
} from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
declare var Prism: any;
@Component({
selector: 'sanitize-prism',
template: `
`
})
export class SanitizePrismComponent implements AfterViewInit {
@Input() snippet: string;
@Input() language: string;
content: SafeHtml;
constructor(public cdr: ChangeDetectorRef, public sanitizer: DomSanitizer) { }
ngAfterViewInit() {
this.content = this.sanitizer.bypassSecurityTrustHtml(
this.sanitizer.sanitize(
SecurityContext.HTML,
Prism.highlight(this.snippet, Prism.languages[this.language])));
this.cdr.detectChanges();
}
}
```
If you really want to hard code strings with brackets in your template file, then you can use of these solutions:
**Encode brackets**
```
export class Demo { id: number; name: string; }
```
(which is what you already had)
**Wrap everything in an interpolated expression**
```
{{"export class Demo { id: number; name: string; } }"}
```
Note: if the string contains douoble quotes, you need to escape them with `\"`
```
{{" let: str = \"string\"; "}}
```
**Escape brackets** (as suggested by angular's error message)
```
export class Demo {{'{' }} id: number; name: string; {{ '}'}
```
**Wrap your code in CDATA** (@username_1's suggestion)
```
export class Demo { id: number; name: string; }
```
The last one if the cleanest way IMHO
Upvotes: 1 [selected_answer]
|
2018/03/19
| 2,118 | 4,430 |
<issue_start>username_0: I have following array of objects:
```
[{
id: 1,
amount: 2000,
date: "2018-01-31T00:00:00.000Z"
},{
id: 2,
amount: 3000,
date: "2017-07-31T00:00:00.000Z"
},{
id: 3,
amount: 6000,
date: "2018-01-31T00:00:00.000Z"
},{
id: 4,
amount: 7000,
date: "2017-01-31T00:00:00.000Z"
},{
id: 5,
amount: 5000,
date: "2017-03-31T00:00:00.000Z"
},{
id: 6,
amount: 3000,
date: "2018-02-22T00:00:00.000Z"
},{
id: 7,
amount: 4500,
date: "2017-01-31T00:00:00.000Z"
}]
```
I am calling following command to group objects by year and date:
```
_(data)
.groupBy(o => new Date(o.date).getFullYear() + '-' + new Date(o.date).getMonth())
.map(o1 => _(o1).map(o2 => o2.amount).sum())
```
Code above give me array of sums like [xx, yy, aaa, bbb, ...]
Now I need ensure that these values in array will be ordered (sum of 2018-2 will be first, and sum of 2017-1 will be on the end).
Also will be nice when result will be contains array of sorted objects as I describe above, where each object will be contains also period key "year-month" to detect what current value is. Expected output will be something like this:
```
[
{period: "2018-2", amount:3000}, // sum of 2018-2
{period: "2018-1", amount: 8000 }, // sum of 2018-1
{period: "2017-7", amount: 3000} // sum of 2017-7
{period: "2017-3", amount: 5000} // sum of 2017-3
{period: "2017-1" amount: 11500} // sum of 2017-1
]
```
Is possible edit this chain to get required result please? Thanks!<issue_comment>username_1: You can use the function `reduce` along with the function `Object.values`
*Just vanilla javascript*
```js
var data = [{ id: 1, amount: 2000, date: "2018-01-31T00:00:00.000Z"},{ id: 2, amount: 3000, date: "2017-07-31T00:00:00.000Z"},{ id: 3, amount: 6000, date: "2018-01-31T00:00:00.000Z"},{ id: 4, amount: 7000, date: "2017-01-31T00:00:00.000Z"},{ id: 5, amount: 5000, date: "2017-03-31T00:00:00.000Z"},{ id: 6, amount: 3000, date: "2018-02-22T00:00:00.000Z"},{ id: 7, amount: 4500, date: "2017-01-31T00:00:00.000Z"}];
var result = Object.values(data.reduce((a, c) => {
var [year, month] = c.date.split('-');
var key = `${year}-${+month}`;
(a[key] || (a[key] = {period: key, amount: 0})).amount += c.amount;
return a;
}, {})).sort((a, b) => b.period.localeCompare(a.period));
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 <issue_comment>username_2: With lodash you could first `groupBy`, then sort entries and then `map` those entries to get objects with `period` and sum of `amount` for each period.
```js
const data = [{"id":1,"amount":2000,"date":"2018-01-31T00:00:00.000Z"},{"id":2,"amount":3000,"date":"2017-07-31T00:00:00.000Z"},{"id":3,"amount":6000,"date":"2018-01-31T00:00:00.000Z"},{"id":4,"amount":7000,"date":"2017-01-31T00:00:00.000Z"},{"id":5,"amount":5000,"date":"2017-03-31T00:00:00.000Z"},{"id":6,"amount":3000,"date":"2018-02-22T00:00:00.000Z"},{"id":7,"amount":4500,"date":"2017-01-31T00:00:00.000Z"}]
const result = _.chain(data)
.groupBy(({date}) => {
const d = new Date(date)
return d.getFullYear() + '-' + (d.getMonth() + 1)
})
.entries()
.sort(([a], [b]) => b.localeCompare(a))
.map(([period, arr]) => ({period, amount: _.sumBy(arr, ({amount}) => amount)}))
console.log(result)
```
Upvotes: 1 <issue_comment>username_3: You could get the grouped data and sort it ascending (the only possible way with lodash) and reverse the order.
```js
var data = [{ id: 1, amount: 2000, date: "2018-01-31T00:00:00.000Z" }, { id: 2, amount: 3000, date: "2017-07-31T00:00:00.000Z" },{ id: 3, amount: 6000, date: "2018-01-31T00:00:00.000Z" }, { id: 4, amount: 7000, date: "2017-01-31T00:00:00.000Z" }, { id: 5, amount: 5000, date: "2017-03-31T00:00:00.000Z" }, { id: 6, amount: 3000, date: "2018-02-22T00:00:00.000Z" }, { id: 7, amount: 4500, date: "2017-01-31T00:00:00.000Z" }],
result = _(data)
.groupBy(o => o.date.slice(0, 7))
.map((array, sort) => ({ sort, date: sort.split('-').map(Number).join('-'), amount: _.sumBy(array, 'amount') }))
.sortBy('sort')
.reverse()
.map(({ date, amount }) => ({ date, amount }))
.value();
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 1,677 | 3,673 |
<issue_start>username_0: to find and plot a minium in an X,Y-plot I made below, working code.
However I find it ugly and would expect something more elegant. The tibble, cf, contains in reality more then two variable. I reduced it to two only.
Who can provide me with more elegant code?
thx!!
=========
```
cf <- tibble(x = seq(0,pi,0.1), y = abs(cos(x)))
xlim <- cf %>% filter(y < 0.5) %>%
arrange(desc(y)) %>%
top_n(1) %>%
select(x)
ggplot(cf, aes(x, y) ) +
geom_point(size = 1, colour = "blue") +
geom_hline(colour = "red", size = 1.2, yintercept = 0.5) +
geom_vline(colour = "#99CCFF", size = 1, xintercept = as.numeric(xlim[1])) +
labs(title = paste0("Y < 0.5 for X > ", as.numeric(xlim[1])))
```<issue_comment>username_1: You can use the function `reduce` along with the function `Object.values`
*Just vanilla javascript*
```js
var data = [{ id: 1, amount: 2000, date: "2018-01-31T00:00:00.000Z"},{ id: 2, amount: 3000, date: "2017-07-31T00:00:00.000Z"},{ id: 3, amount: 6000, date: "2018-01-31T00:00:00.000Z"},{ id: 4, amount: 7000, date: "2017-01-31T00:00:00.000Z"},{ id: 5, amount: 5000, date: "2017-03-31T00:00:00.000Z"},{ id: 6, amount: 3000, date: "2018-02-22T00:00:00.000Z"},{ id: 7, amount: 4500, date: "2017-01-31T00:00:00.000Z"}];
var result = Object.values(data.reduce((a, c) => {
var [year, month] = c.date.split('-');
var key = `${year}-${+month}`;
(a[key] || (a[key] = {period: key, amount: 0})).amount += c.amount;
return a;
}, {})).sort((a, b) => b.period.localeCompare(a.period));
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 <issue_comment>username_2: With lodash you could first `groupBy`, then sort entries and then `map` those entries to get objects with `period` and sum of `amount` for each period.
```js
const data = [{"id":1,"amount":2000,"date":"2018-01-31T00:00:00.000Z"},{"id":2,"amount":3000,"date":"2017-07-31T00:00:00.000Z"},{"id":3,"amount":6000,"date":"2018-01-31T00:00:00.000Z"},{"id":4,"amount":7000,"date":"2017-01-31T00:00:00.000Z"},{"id":5,"amount":5000,"date":"2017-03-31T00:00:00.000Z"},{"id":6,"amount":3000,"date":"2018-02-22T00:00:00.000Z"},{"id":7,"amount":4500,"date":"2017-01-31T00:00:00.000Z"}]
const result = _.chain(data)
.groupBy(({date}) => {
const d = new Date(date)
return d.getFullYear() + '-' + (d.getMonth() + 1)
})
.entries()
.sort(([a], [b]) => b.localeCompare(a))
.map(([period, arr]) => ({period, amount: _.sumBy(arr, ({amount}) => amount)}))
console.log(result)
```
Upvotes: 1 <issue_comment>username_3: You could get the grouped data and sort it ascending (the only possible way with lodash) and reverse the order.
```js
var data = [{ id: 1, amount: 2000, date: "2018-01-31T00:00:00.000Z" }, { id: 2, amount: 3000, date: "2017-07-31T00:00:00.000Z" },{ id: 3, amount: 6000, date: "2018-01-31T00:00:00.000Z" }, { id: 4, amount: 7000, date: "2017-01-31T00:00:00.000Z" }, { id: 5, amount: 5000, date: "2017-03-31T00:00:00.000Z" }, { id: 6, amount: 3000, date: "2018-02-22T00:00:00.000Z" }, { id: 7, amount: 4500, date: "2017-01-31T00:00:00.000Z" }],
result = _(data)
.groupBy(o => o.date.slice(0, 7))
.map((array, sort) => ({ sort, date: sort.split('-').map(Number).join('-'), amount: _.sumBy(array, 'amount') }))
.sortBy('sort')
.reverse()
.map(({ date, amount }) => ({ date, amount }))
.value();
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 780 | 2,481 |
<issue_start>username_0: I have a WP site which uses a calendaring plugin - currently the url the calendar system creates to change the month view of the calendar is hitting a url which fails to advance the month view of the calendar... I have worked out what the correct url should be - but need a way of redirecting from the incorrect url to the correct one...
So...
The incorrect url is: **/calendar/?date=2018-04**
The correct url is **/calendar/?tribe-bar-date=2018-04**
So, I am basically looking for a way to redirect / rewrite the url so that "?date=2018-04" becomes "?tribe-bar-date=2018-04" bearing in mind the year-month after the "=" element in the parameter will change all the time. So need to change "**?date**" to become "**?tribe-bar-date**"...
I have had a go using the redirection WP plugin with a rule as below:
`/calendar/?date=(.*)`
`/calendar/?tribe-bar-date=(.*)`
but it doesn't work... not sure why... I thought it would but I don't know regex very well!
Any ideas?<issue_comment>username_1: Try:
```
RewriteCond %{QUERY_STRING} (?:^|&)date=(.*)$
RewriteRule ^calendar/(.*)$ /calendar/$1?tribe-bar-date=%1 [L,R]
```
This assumes that the "date" parameter will be the first in the query string, otherwise you can add an additional grouping in front to try to capture that as well. This is doing a 302 (not permanent) redirect, you can change that if you want by changing the `R` to `R=301`.
Make sure this rule is before any wordpress rules.
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want to redirect externally only , do this :
```
RewriteEngine On
RewriteCond %{QUERY_STRING} ^date=(.+)$
RewriteRule ^calendar/$ /calendar/?tribe-bar-date=%1 [QSD,R=301,L,NE]
```
Or this :
```
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(/calendar/)\?date=(.+)\sHTTP.*$
RewriteRule ^ %1?tribe-bar-date=%2 [QSD,R=301,L,NE]
```
If it is externally for that target then internally to same path , do this :
```
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(/calendar/)\?date=(.+)\sHTTP.*$
RewriteRule ^ %1?tribe-bar-date=%2 [QSD,R=301,L,NE]
RewriteCond %{QUERY_STRING} ^tribe-bar-date=(.+)$
RewriteRule ^calendar/$ /calendar/?date=%1 [L,NE]
```
To prevent query string from being appended you should put `?` at the end of `RewriteRule` substitution
In apache 2.4 and later you could discard query string by this flag `[QSD]` <https://httpd.apache.org/docs/2.4/rewrite/flags.html>
Upvotes: 1
|
2018/03/19
| 1,606 | 5,759 |
<issue_start>username_0: I have users take a quiz. After each question, I want to show them whether their answer was correct or incorrect. The correct answer should be highlighted in green, and their answer (if incorrect) should be highlighted in red (using Twitter Bootstrap styles).
I am currently rendering the quiz results page in Django and HTML like so:
```
{{ player.question }}
{{q1}}
{{q2}}
{{q3}}
{{q4}}
**Correct Answer: {{solution}}**
Total Score: {{total_score}}
```
I am storing the solution to the question in `{{solution}}`. I have been trying to figure out how to selectively apply CSS filters if, for example, `{{q1}} == {{solution}}` that should be highlighted green. I can grab the participant's answer with `{{player.submitted_answer}}`, and so want to highlight a div element red if `{{player.submitted_answer}} != {{solution}}`.
I have tried messing around with if statement blocks, but can't seem to get it right. Any ideas?
@cezar, a snippet of pages.py and models.py
In pages.py I have the following class
```
class Question(Page):
timeout_seconds = 120
template_name = 'quiz/Question.html'
form_model = 'player'
form_fields = ['submitted_answer', 'confidence']
def submitted_answer_choices(self):
qd = self.player.current_question()
return [
qd['choice1'],
qd['choice2'],
qd['choice3'],
qd['choice4'],
]
def confidence_error_message(self, value):
if value == 50:
return 'Please indicate your confidence in your answer. It is important you answer accurately.'
def before_next_page(self):
self.player.check_correct()
```
In models.py, the relevant class is Player and Subsession:
```
class Player(BasePlayer):
trial_counter = models.IntegerField(initial=0)
question_id = models.IntegerField()
confidence = models.FloatField(widget=widgets.Slider(attrs={'step': '0.01'}))
confidence_private = models.FloatField(widget=widgets.Slider(attrs={'step': '0.01'}))
question = models.StringField()
solution = models.StringField()
submitted_answer = models.StringField(widget=widgets.RadioSelect)
submitted_answer_private = models.StringField(widget=widgets.RadioSelect)
is_correct = models.BooleanField()
total_score = models.IntegerField(initial = 0)
def other_player(self):
return self.get_others_in_group()[0]
def current_question(self):
return self.session.vars['questions'][self.round_number - 1]
def check_correct(self):
self.is_correct = self.submitted_answer == self.solution
def check_partner_correspondence(self):
self.submitted_answer == self.get_others_in_group()[0].submitted_answer
def check_partner_correct(self):
self.get_others_in_group()[0].submitted_answer == self.solution
def check_if_awarded_points(self):
self.get_others_in_group()[0].submitted_answer == self.submitted_answer == self.solution
def score_points(self):
if self.get_others_in_group()[0].submitted_answer == self.submitted_answer == self.solution:
self.total_score +=1
else:
self.total_score -=1
def set_payoff(self):
if(self.check_if_awarded_points()):
self.total_score +=1
class Subsession(BaseSubsession):
def creating_session(self):
if self.round_number == 1:
self.session.vars['questions'] = Constants.questions
## ALTERNATIVE DESIGN:
## to randomize the order of the questions, you could instead do:
# import random
# randomized_questions = random.sample(Constants.questions, len(Constants.questions))
# self.session.vars['questions'] = randomized_questions
## and to randomize differently for each participant, you could use
## the random.sample technique, but assign into participant.vars
## instead of session.vars.
for p in self.get_players():
question_data = p.current_question()
p.question_id = question_data['id']
p.question = question_data['question']
p.solution = question_data['solution']
```<issue_comment>username_1: I agree with @Sapna-Sharma and @albar comment.
You may use a simple CSS class to set the color to green and use a `{% if [...] %}` template filter to add the the CSS class only to the good answer
You may refer to [Django official documentation](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/) to know how to handle template filter.
Upvotes: 2 <issue_comment>username_2: I ended up solving my own problem:
I am not sure what to do as Albar's answer helped the most.
```
{{q1}}
{{q2}}
{{q3}}
{{q4}}
```
And then the CSS:
```
.green {
color: #00FF00;
}
.red {
color: red;
}
```
Upvotes: 0 <issue_comment>username_3: You can accmoplish this with some CSS and minimal templating.
Consider the following HTML template
The key here is `class="answer{% if answer == solution %} solution{% endif %}"`
```
{{ question }}
--------------
{% for answer in answers %}
{{ answer }}
{% endfor %}
Sorry, that was not correct. The solution was {{ solution }}
Correct! Answer: {{ solution }}
```
With the Following CSS
```
.result {
display: none;
}
.answer:checked ~ .result.incorrect{
display: block;
color: red;
}
.answer.solution:checked ~ p.result.correct {
display: block;
color: green;
}
.answer.solution:checked ~ p.result.incorrect {
display: none;
}
```
And the following route
```
def quiz(request):
question = "What is 2 + 2?"
solution = "4"
answers = [solution, "22", "NaN", "0"]
random.shuffle(answers)
return render(request, 'foobar/quiz.html', context=locals())
```
You would get a result like [this jsfiddle](https://jsfiddle.net/p1rcdmgs/2/)
Upvotes: 3 [selected_answer]
|
2018/03/19
| 262 | 933 |
<issue_start>username_0: For example I have a module like
```
defmodule Foo do
@type bar :: string
end
```
But I don't want to generate doc for `bar` because it's meant to use internal implementation.<issue_comment>username_1: I believe that you can use the flag
```
@doc false
```
on top of the code you dont want docs for.
As shown in the docs:
[](https://i.stack.imgur.com/Kwk0r.png)
Upvotes: -1 <issue_comment>username_2: There's `@typedoc` for types like `@doc` for functions, but unlike `@doc false`, `@typedoc false` doesn't seem to hide the type from the documentation. Since this is for internal use, I'm assuming you don't want to export it out of the module either, so you can use `@typep` to declare it private, which will also remove it from the documentation:
```
defmodule Foo do
@typep bar :: string
end
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 565 | 2,363 |
<issue_start>username_0: I stumbled upon the following piece of code:
```
public static final Map> fooCacheMap = new ConcurrentHashMap<>();
```
this cache is accessed from rest controller method:
```
public void fooMethod(String fooId) {
Set fooSet = cacheMap.computeIfAbsent(fooId, k -> new ConcurrentSet<>());
//operations with fooSet
}
```
Is `ConcurrentSet` really necessary? when I know for sure that the set is accessed only in this method?<issue_comment>username_1: As you use it in the controller then multiple threads can call your method simultaneously (ex. multiple parallel requests can call your method)
As this method does not look like synchronized in any way then ConcurrentSet is probably necessary here.
Upvotes: 2 <issue_comment>username_2: >
> Is ConcurrentSet really necessary?
>
>
>
Possibly, possibly not. We don't know how this code is being used.
However, assuming that it is being used in a multithreaded way (specifically: that two threads can invoke `fooMethod` concurrently), yes.
The atomicity in `ConcurrentHashMap` is only guaranteed for each invocation of `computeIfAbsent`. Once this completes, the lock is released, and other threads are able to invoke the method. As such, access to the return value is not atomic, and so you can get thread inference when accessing that value.
In terms of the question "do I need `ConcurrentSet"? No: you can do it so that accesses to the set are atomic:
```
cacheMap.compute(fooId, (k, fooSet) -> {
if (fooSet == null) fooSet = new HashSet<>();
// Operations with fooSet
return v;
});
```
Upvotes: 0 <issue_comment>username_3: Using a concurrent map will not guarantee thread safety. Additions to the Map need to be performed in a synchronized block to ensure that two threads don't attempt to add the same key to the map. Therefore, the concurrent map is not really needed, especially because the Map itself is static and final. Furthermore, if the code modifies the Set inside the Map, which appears likely, that needs to be synchronized as well.
The correct approach is to the Map is to check for the key. If it does not exist, enter a synchronized block and check the key again. This guarantees that the key does not exist without entering a synchronized block every time.
Set modifications should typically occur in a synchronized block as well.
Upvotes: 0
|
2018/03/19
| 1,134 | 2,912 |
<issue_start>username_0: I have a file with the following format:
```
Barcelona 2015,2016,2017
Real Madrid 2010
Napoli 2007,2009
Bayern Munich 2008,2009,2010,2011,2012,2013
```
I want to save this to a dictionary having the team and next a list with the numbers. How can I make this? I have some difficulties in splitting because some teams have bigger names.<issue_comment>username_1: You can use `re` to split each line at space spanning the team name and the first digit:
```
import re
final_d = {a:map(int, b.split(',')) for a, b in map(lambda x:re.split('\s+(?=\d)', x.strip('\n')), open('filename.txt').readlines())}
```
Output:
```
{'Real Madrid': [2010], 'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013], 'Barcelona': [2015, 2016, 2017], 'Napoli': [2007, 2009]}
```
Upvotes: 1 <issue_comment>username_2: This is the Pandas solution, assuming 4-space delimiter.
```
import pandas as pd
from io import StringIO
mystr = StringIO("""Barcelona 2015,2016,2017
Real Madrid 2010
Napoli 2007,2009
Bayern Munich 2008,2009,2010,2011,2012,2013""")
df = pd.read_csv(mystr, delimiter=' ', header=None, names=['Club', 'Years'])
df['Years'] = [list(map(int, x)) for x in df['Years'].str.split(',')]
d = df.set_index('Club')['Years'].to_dict()
```
**Result**
```
{'Barcelona': [2015, 2016, 2017],
'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013],
'Napoli': [2007, 2009],
'Real Madrid': [2010]}
```
**Explanation**
* Read file with appropriate delimiter and name columns.
* Split by comma and map each element to integer type via list comprehension.
* Create series indexed by Club and use `.to_dict()` to output dictionary.
Upvotes: 2 <issue_comment>username_3: try with this,
```
file = open('file_name')
d = {}
for line in file.readlines():
try:
key, value = line.replace('\n','').split('\t') ##if your sep == '\t'
except ValueError:
pass ### if line is empty
else: ### if all is ok
d[key] = value
print(d)
```
Upvotes: 1 <issue_comment>username_4: This works, I don't know if it's what you want though.
```
file=open("info.txt", "r")
lines1=file.readlines()
lines=[]
for i in lines1:
lines.append(i.split(" "))
output={}
for i in lines:
key=i[0]
exec("item=("+i[1]+")")
output[key]=item
```
Upvotes: 0 <issue_comment>username_5: As requested, pure-python solution, which is
* non-regex
* not a one liner
* *very* readable
```
data = {}
with open('file.txt') as f:
for line in f:
city, dates = line.rstrip().rsplit(None, 1)
data[city] = [int(d) for d in dates.split(',')]
```
```
data
{
"Barcelona": [
2015,
2016,
2017
],
"Real Madrid": [
2010
],
"Napoli": [
2007,
2009
],
"Bayern Munich": [
2008,
2009,
2010,
2011,
2012,
2013
]
}
```
Upvotes: 2 [selected_answer]
|
2018/03/19
| 618 | 2,350 |
<issue_start>username_0: I have a scenario where there will be two fields of each item. One field is a checkbox and another is dropdown but the point is to get a pair of data from this and I am mapping this based on the item(they have category too). And the dropdown depends on checkbox(when unchecked the dropdown is disabled and value is reset to none or zero)
I tried
```
```
what happens is each of them have unique `name` and I cant do anything when I need to update the values depending on the checkbox selections.
I have tried putting the two inputs in one `Field` but I can't get it to work. Help would be much appreciated<issue_comment>username_1: Probably, this is what are you looking for - `formValues` decorator.
Just wrap your dropdown with this decorator and pass the name into it of your checkbox so you will have access inside of the `MyDropDownComponent`.
For example:
```
import { formValues } from 'redux-form';
```
So then `myCheckBox` value will be passed as a prop.
Performance note:
>
> This decorator causes the component to render() every time one of the selected values changes.
>
>
>
Use this sparingly.
See more here - <https://redux-form.com/7.3.0/docs/api/formvalues.md/>
Upvotes: 0 <issue_comment>username_2: You need to use Redux Fields (<https://redux-form.com/6.0.4/docs/api/fields.md/>) not Redux Field.
You can create a separate component which wraps your check-box component and your drop-down component.
This is how you use it
```
```
And the props that you get in your **MyMultiFieldComponent**
```
{
checkboxFieldName: { input: { ... }, meta: { ... } },
dropDownFieldName: { input: { ... }, meta: { ... } },
anotherCustomProp: 'Some other information'
}
```
The input property has a onChange property (which is a method), you can call it to update the respective field value.
For example in onChange method of check-box
```
onChangeCheckbox (event) {
const checked = event.target.checked;
if (checked) {
// write your code when checkbox is selected
} else {
const { checkboxFieldName, dropDownFieldName } = props;
checkboxFieldName.input.onChange('Set it to something');
dropDownFieldName.input.onChange('set to zero or none');
}
}
```
This way you can update multiple field values at the same time.
Hope this helps.
Upvotes: 3 [selected_answer]
|
2018/03/19
| 707 | 1,983 |
<issue_start>username_0: Why I'm getting the following error when I try to use an const int std::array?
I had to replace "<" for "<\" in the error message to show it correctly:
```
#include
#include
using namespace std;
int main() {
array vals;
return 0;
}
```
>
> test.cpp: In function ‘int main()’:
>
>
> test.cpp:7:22: error: use of deleted function ‘std::array::array()’
>
>
> array<\const int, 4> vals;
> ^~~~
>
>
> In file included from test.cpp:1:0:
> /usr/include/c++/7.3.0/array:94:12: note: ‘std::array<\const int, 4>::array()’ is implicitly deleted because the default definition would be ill-formed:
> struct array
> ^~~~~
>
>
> /usr/include/c++/7.3.0/array:94:12: error: uninitialized const member in ‘struct std::array<\const int, 4>’
>
>
> /usr/include/c++/7.3.0/array:110:56: note: ‘const int std::array<\const int, 4>::\_M\_elems [4]’ should be initialized
> typename \_AT\_Type::\_Type \_M\_elems;
> ^~~~~~~~
>
>
><issue_comment>username_1: How are you going to assign array values to `const int` elements? You should initialize them during declaration.
```
#include
using namespace std;
int main() {
array vals{1, 2, 3, 4};
return 0;
}
```
Without any initialization, your sample is similar to invalid const declaration:
```
const int a;
```
Since `std::array` itself can not be updated, I suppose the below code would be clearer for understanding.
```
#include
using namespace std;
int main() {
const array vals{1, 2, 3, 4};
return 0;
}
```
Upvotes: 3 <issue_comment>username_2: It is due to the fact that a constant object must be initialized when it is defined. However using this declaration
```
array vals;
```
you did not provide an initializer.
Consider the following program
```
#include
#include
int main()
{
int x = 42;
std::array vals = { { 1, 2, 3, 4 } };
for ( int x : vals ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
```
Its output is
```
1 2 3 4
```
Upvotes: 2
|
2018/03/19
| 499 | 1,486 |
<issue_start>username_0: I need to have a working remote IMG display using PHP, let's say like this:
```

```
And I need to fetch the remote URL based on $id, where
```
php
$id = "brown_fox";
$url = "http://exampl.com/$id";
get_remote_img($url) {
// some code to get image which SRC is dynamic:
<img id="pic" src="sjf5d85v258d.jpg" /
$src="sjf5d85v258d.jpg";
return $src
}
?>
```
I hope I explained it understandably.<issue_comment>username_1: How are you going to assign array values to `const int` elements? You should initialize them during declaration.
```
#include
using namespace std;
int main() {
array vals{1, 2, 3, 4};
return 0;
}
```
Without any initialization, your sample is similar to invalid const declaration:
```
const int a;
```
Since `std::array` itself can not be updated, I suppose the below code would be clearer for understanding.
```
#include
using namespace std;
int main() {
const array vals{1, 2, 3, 4};
return 0;
}
```
Upvotes: 3 <issue_comment>username_2: It is due to the fact that a constant object must be initialized when it is defined. However using this declaration
```
array vals;
```
you did not provide an initializer.
Consider the following program
```
#include
#include
int main()
{
int x = 42;
std::array vals = { { 1, 2, 3, 4 } };
for ( int x : vals ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
```
Its output is
```
1 2 3 4
```
Upvotes: 2
|
2018/03/19
| 5,608 | 12,075 |
<issue_start>username_0: I have a json as follows:
```
[{
"Domain": "google.com",
"A": ["172.16.17.32"],
"AAAA": ["fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b"],
"CAA": ["0 issue \"pki.goog\""],
"MX": ["20 alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.", "10 aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com."],
"NS": ["ns1.google.com.", "ns3.google.com.", "ns2.google.com.", "ns4.google.com."],
"SOA": ["ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60"],
"TXT": ["\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\"", "\"v=spf1 include:_spf.google.com ~all\""],
"Country": ["United States"],
"Hostname": ["'fra15s16-in-f46.1e100.net'"],
"SSL": ["Google Internet Authority G2"],
"WHOIS": [8400],
"TTL": ["24"]
}, {
"Domain": "",
"NS": ["a.root-servers.net.", "h.root-servers.net.", "g.root-servers.net.", "i.root-servers.net.", "d.root-servers.net.", "k.root-servers.net.", "c.root-servers.net.", "l.root-servers.net.", "e.root-servers.net.", "m.root-servers.net.", "f.root-servers.net.", "j.root-servers.net.", "b.root-servers.net."],
"SOA": ["a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400"],
"A": [],
"SSL": ["None"],
"WHOIS": [0],
"TTL": [null]
}, {
"Domain": "facebook.com",
"A": ["192.168.127.12"],
"AAAA": ["fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"],
"MX": ["10 msgin.vvv.facebook.com."],
"NS": ["a.ns.facebook.com.", "b.ns.facebook.com."],
"SOA": ["a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300"],
"TXT": ["\"v=spf1 redirect=_spf.facebook.com\""],
"Country": ["United States"],
"Hostname": ["'edge-star-mini-shv-02-frt3.facebook.com'"],
"SSL": ["DigiCert SHA2 High Assurance Server CA"],
"WHOIS": [10227],
"TTL": ["173"]
}]
```
Please note the second element, the one that has `"Domain" : ""`, which I want to remove(there maybe multiple instances where `"Domain" : ""` is like that, this is only partial JSON) and return a valid json devoid of that whole object, so the output must look like:
```
[{
"Domain": "google.com",
"A": ["172.16.17.32"],
"AAAA": ["fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b"],
"CAA": ["0 issue \"pki.goog\""],
"MX": ["20 alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.", "10 aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com."],
"NS": ["ns1.google.com.", "ns3.google.com.", "ns2.google.com.", "ns4.google.com."],
"SOA": ["ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60"],
"TXT": ["\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\"", "\"v=spf1 include:_spf.google.com ~all\""],
"Country": ["United States"],
"Hostname": ["'fra15s16-in-f46.1e100.net'"],
"SSL": ["Google Internet Authority G2"],
"WHOIS": [8400],
"TTL": ["24"]
}, {
"Domain": "facebook.com",
"A": ["192.168.127.12"],
"AAAA": ["fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"],
"MX": ["10 msgin.vvv.facebook.com."],
"NS": ["a.ns.facebook.com.", "b.ns.facebook.com."],
"SOA": ["a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300"],
"TXT": ["\"v=spf1 redirect=_spf.facebook.com\""],
"Country": ["United States"],
"Hostname": ["'edge-star-mini-shv-02-frt3.facebook.com'"],
"SSL": ["DigiCert SHA2 High Assurance Server CA"],
"WHOIS": [10227],
"TTL": ["173"]
}]
```
Here is what I tried (the example is executable as is):
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.16.17.32\"],\r\n\t\t\"AAAA\": [\"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"192.168.127.12\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = json.loads(json_data)
# cleaning empty entries
for item in ds:
try:
if item["Domain"]:
del item["Domain"]
except KeyError:
print("Key doesn't exist")
print(ds)
```
However, I could not achieve my target. How to achieve this?
Thanks!<issue_comment>username_1: The process of ***creating a new object*** by selectively choosing the required elements is better and less error prone than deleting elements and modifying the object.
Since you got `json` part covered, let me show you how to get the required `dict`. Its as simple as doing :
```
>>> [ele for ele in d if ele['Domain']]
```
Where `d` is the dictionary obtained from the input `json`.
#driver values :
```
IN : d = [{'Domain':'A', 'xyz':'abc'}, {'Domain':'', 'xyz':'bcd'},
{'Domain':'C', 'xyz':'cde'}]
OUT : [{'Domain': 'A', 'xyz': 'abc'}, {'Domain': 'C', 'xyz': 'cde'}]
```
Upvotes: 2 <issue_comment>username_2: Your issue is that you are deleting keys from the objects and not the whole objects.
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.16.17.32\"],\r\n\t\t\"AAAA\": [\"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"192.168.127.12\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = [d
for d in json.loads(json_data)
if d.get("Domain")
]
```
Upvotes: 1 <issue_comment>username_3: Try this:
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.16.17.32\"],\r\n\t\t\"AAAA\": [\"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"192.168.127.12\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = json.loads(json_data)
keep = []
for item in ds:
if item.get("Domain"):
keep.append(item)
print(json.dumps(keep))
```
This code builds a *new* list of the items to keep.
Upvotes: 2 [selected_answer]<issue_comment>username_4: ```
[dom for dom in ds if dom.get('Domain')]
```
Uses a list comprehension to select all the dictionaries which have a non-falsey value for "Domain".
Upvotes: 2 <issue_comment>username_5: Try the following:
```
for k in ds:
if not ds[k]:
ds.remove(k)
```
This way you're going to have `k` removed from `ds` if the value for `k` is either `0`, `None`, `False`, empty list or empty string and it would work for any given key.
Upvotes: 1
|
2018/03/19
| 3,056 | 6,812 |
<issue_start>username_0: I'm working in a wordpress template, and I want to set my dropdown menu value to usa as default value when the index page is completely loaded using jQuery to activate an other dropdown menu; this my function code:
```
jQuery(document).ready(function() {
if (jQuery('.car_form_search').length) {
/* load locations 0 level */
var loc_0 = jQuery('.qs_carlocation0');
if (loc_0.length) {
var data = {
action: "app_cardealer_draw_quicksearch_locations",
parent_id: 0,
level: 0,
selected_region: loc_0.eq(0).data('location0')
};
jQuery.post(ajaxurl, data, function(response) {
if (response && response != '0') {
loc_0.append(response);
}
});
}
}
```
This the form's screenshoot:
[](https://i.stack.imgur.com/ZYoGf.png)<issue_comment>username_1: The process of ***creating a new object*** by selectively choosing the required elements is better and less error prone than deleting elements and modifying the object.
Since you got `json` part covered, let me show you how to get the required `dict`. Its as simple as doing :
```
>>> [ele for ele in d if ele['Domain']]
```
Where `d` is the dictionary obtained from the input `json`.
#driver values :
```
IN : d = [{'Domain':'A', 'xyz':'abc'}, {'Domain':'', 'xyz':'bcd'},
{'Domain':'C', 'xyz':'cde'}]
OUT : [{'Domain': 'A', 'xyz': 'abc'}, {'Domain': 'C', 'xyz': 'cde'}]
```
Upvotes: 2 <issue_comment>username_2: Your issue is that you are deleting keys from the objects and not the whole objects.
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"192.168.3.11\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"192.168.3.11\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = [d
for d in json.loads(json_data)
if d.get("Domain")
]
```
Upvotes: 1 <issue_comment>username_3: Try this:
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"192.168.3.11\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"192.168.3.11\"],\r\n\t\t\"AAAA\": [\"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b5de\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = json.loads(json_data)
keep = []
for item in ds:
if item.get("Domain"):
keep.append(item)
print(json.dumps(keep))
```
This code builds a *new* list of the items to keep.
Upvotes: 2 [selected_answer]<issue_comment>username_4: ```
[dom for dom in ds if dom.get('Domain')]
```
Uses a list comprehension to select all the dictionaries which have a non-falsey value for "Domain".
Upvotes: 2 <issue_comment>username_5: Try the following:
```
for k in ds:
if not ds[k]:
ds.remove(k)
```
This way you're going to have `k` removed from `ds` if the value for `k` is either `0`, `None`, `False`, empty list or empty string and it would work for any given key.
Upvotes: 1
|
2018/03/19
| 2,957 | 6,628 |
<issue_start>username_0: I am having trouble in using git on android studio. I know there may be many related questions asked on this topic But I could not find any relevant answer.
I can use git normally but with android studio i am facing many problems. I am working on a project with my friend. The main project is on his repository. I have forked his repo. And cloned the project on my machine. Then using imported the project on my Android Studio. Till here things are fine but after this everything messes up when i try to use git.
Do i have to use git in the terminal inside android studio itself, or in normal terminal in file manager?
Can anyone give me a proper guide of how to collaborate on Android Studio using Git.<issue_comment>username_1: The process of ***creating a new object*** by selectively choosing the required elements is better and less error prone than deleting elements and modifying the object.
Since you got `json` part covered, let me show you how to get the required `dict`. Its as simple as doing :
```
>>> [ele for ele in d if ele['Domain']]
```
Where `d` is the dictionary obtained from the input `json`.
#driver values :
```
IN : d = [{'Domain':'A', 'xyz':'abc'}, {'Domain':'', 'xyz':'bcd'},
{'Domain':'C', 'xyz':'cde'}]
OUT : [{'Domain': 'A', 'xyz': 'abc'}, {'Domain': 'C', 'xyz': 'cde'}]
```
Upvotes: 2 <issue_comment>username_2: Your issue is that you are deleting keys from the objects and not the whole objects.
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.16.58.3\"],\r\n\t\t\"AAAA\": [\"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"172.16.17.32\"],\r\n\t\t\"AAAA\": [\"fc00:db20:35b:7399::5\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = [d
for d in json.loads(json_data)
if d.get("Domain")
]
```
Upvotes: 1 <issue_comment>username_3: Try this:
```
import json
if __name__ == "__main__":
json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.16.58.3\"],\r\n\t\t\"AAAA\": [\"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"172.16.17.32\"],\r\n\t\t\"AAAA\": [\"fc00:db20:35b:7399::5\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'edge-star-mini-shv-02-frt3.facebook.com'\"],\r\n\t\t\"SSL\": [\"DigiCert SHA2 High Assurance Server CA\"],\r\n\t\t\"WHOIS\": [10227],\r\n\t\t\"TTL\": [\"173\"]\r\n\t}]"
ds = json.loads(json_data)
keep = []
for item in ds:
if item.get("Domain"):
keep.append(item)
print(json.dumps(keep))
```
This code builds a *new* list of the items to keep.
Upvotes: 2 [selected_answer]<issue_comment>username_4: ```
[dom for dom in ds if dom.get('Domain')]
```
Uses a list comprehension to select all the dictionaries which have a non-falsey value for "Domain".
Upvotes: 2 <issue_comment>username_5: Try the following:
```
for k in ds:
if not ds[k]:
ds.remove(k)
```
This way you're going to have `k` removed from `ds` if the value for `k` is either `0`, `None`, `False`, empty list or empty string and it would work for any given key.
Upvotes: 1
|
2018/03/19
| 521 | 1,816 |
<issue_start>username_0: I am trying to create a game like rock, paper, scissors except with four different moves instead of three. The moves are all represented by K, G, B, V. For the computer to make a move, I need to generate a random letter to play against the human. I also need it to be a string so that I can compare it with the string that the human answers. Here is what I have but it only works with chars:
```
public static String computerMove() {
String move = "";
Random rand = new Random();
String abc = "KGBV";
char letter = abc.charAt(rand.nextInt(abc.length()));
if (letter == 'K') {
move = K;
} else if (letter == 'B') {
move = B;
} else if (letter == 'G') {
move = G;
} else if (letter == 'V') {
move = V;
}
return move;
}
```<issue_comment>username_1: Try to initialize an array with strings and take a random index within that array.
Something like this:
```
String[] moves = {"one", "two", "three", "four"};
int index = rand.nextInt(moves.length);
String move = moves[index];
```
Upvotes: 1 <issue_comment>username_2: You could do this:
```
Random rand = new Random();
String[] moves = {"G","K","N","V"};
return moves[rand.nextInt(moves.length)];
```
Upvotes: 1 <issue_comment>username_3: If you want to get a random single-character string from a string:
```
int r = rand.nextInt(string.length());
return string.substring(r, r + 1);
```
Upvotes: 0 <issue_comment>username_4: try this
```
public static string computerMove() {
String move;
Random rand = new Random();
int randNum = rand.nextInt();
if (randNum == 0)
move = "k";
else if (randNum == 1)
move = "B";
else if (randNum == 2)
move = "G";
else
move = "V";
return move;
}
```
Upvotes: 0
|
2018/03/19
| 865 | 2,823 |
<issue_start>username_0: I created a PHP function that will convert an array:
```
[
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
]
```
Into the following JSON string:
```
{
"one":
{
"two": 3,
"four": [ 5,6,7]
},
"eight":
{
"nine":
{
"ten":11
}
}
}
```
Here is the function:
```
php
function toJsonStr($array) {
$final_array = [];
foreach ($array as $key = $value) {
$key_exploded = explode("/", $key);
$array_index_at_end = is_numeric(end($key_exploded)) ? true : false ;
if ($array_index_at_end === true) {
$array_index = array_pop($key_exploded);
}
$ref = &$final_array;
foreach ($key_exploded as $value2) {
if (!isset($ref[$value2])) {
$ref[$value2] = [];
}
$ref = &$ref[$value2];
}
if ($array_index_at_end === true) {
$ref[$array_index]=$value;
} else {
$ref=$value;
}
}
return json_encode($final_array);
}
$array = [
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
];
$json_str = toJsonStr($array);
echo "\n";
print_r($json_str);
echo "\n\n";
```
I'm almost positive that this can also be done recursively. I am new to recursion and am having trouble structuring an approach when creating a recursive version.
Would it even be worthwhile to create a recursive version? Maybe it would be too difficult to understand compared to the simple foreach within a foreach I have implemented above?
I know that recursive algorithms simplify and make code more compact but in this case would it be worth it?<issue_comment>username_1: Try to initialize an array with strings and take a random index within that array.
Something like this:
```
String[] moves = {"one", "two", "three", "four"};
int index = rand.nextInt(moves.length);
String move = moves[index];
```
Upvotes: 1 <issue_comment>username_2: You could do this:
```
Random rand = new Random();
String[] moves = {"G","K","N","V"};
return moves[rand.nextInt(moves.length)];
```
Upvotes: 1 <issue_comment>username_3: If you want to get a random single-character string from a string:
```
int r = rand.nextInt(string.length());
return string.substring(r, r + 1);
```
Upvotes: 0 <issue_comment>username_4: try this
```
public static string computerMove() {
String move;
Random rand = new Random();
int randNum = rand.nextInt();
if (randNum == 0)
move = "k";
else if (randNum == 1)
move = "B";
else if (randNum == 2)
move = "G";
else
move = "V";
return move;
}
```
Upvotes: 0
|
2018/03/19
| 710 | 1,854 |
<issue_start>username_0: I have a dataframe:
```
d = {'col1':['2q','48', '48-49']}
test = pd.DataFrame(d)
col1
0 2q
1 48
2 48-49
```
And a dictionary for mapping:
```
mupcs_to_pc_mapping = {'24': ['48-49', '48', '49'], #M2
'23': ['50-51', '50', '51'], #M3
'22': ['52-53', '52', '53'], #M4
'21': ['54-55', '54', '55'], #M5
}
```
I would like to test each value of the test dataframe to see if it exists in the mupcs\_to\_pc\_mapping dict values.
So the final result is something like:
```
0 False
1 True
2 True
```
I tried a variation of:
```
test['col1'].isin(mupcs_to_pc_mapping.values())
```
and
```
test['col1'].any(value for value in mupcs_to_pc_mapping.values())
```
but both of them result in an error.
Does anyone know what is wrong with my code?<issue_comment>username_1: I think you need
```
test.col1.isin(sum(mupcs_to_pc_mapping.values(),[]))
Out[477]:
0 False
1 True
2 True
Name: col1, dtype: bool
```
Mentioned by cold in the comment `itertools.chain`
```
list(itertools.chain.from_iterable(mupcs_to_pc_mapping.values()))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First, invert your mapping:
```
m = {v : k for k in mupcs_to_pc_mapping for v in mupcs_to_pc_mapping[k]}
```
Now, use `map` and test for `NaN`s.
```
test.col1.map(m).notnull()
0 False
1 True
2 True
Name: col1, dtype: bool
```
Upvotes: 2 <issue_comment>username_3: You can also do :
```
test.isin(pd.DataFrame(mupcs_to_pc_mapping).stack().values)
col1
0 False
1 True
2 True
```
Upvotes: 3 <issue_comment>username_4: Create a set that is the union of all dictionary values
```
test.col1.isin(set.union(*map(set, mupcs_to_pc_mapping.values())))
0 False
1 True
2 True
Name: col1, dtype: bool
```
Upvotes: 2
|
2018/03/19
| 517 | 1,862 |
<issue_start>username_0: Please help me, I really dont get it when the value of this.state.isX printed console is always true. Why setState not work in this case. Here is my source code?`
```
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
isX: true
};
}
handle(){
this.setState({value: 'X',isX:!this.state.isX});
console.log(this.state.isX)
}
render() {
return (
{this.handle()}}>
{this.state.value}
);
}
}
```<issue_comment>username_1: setState is asynchronous; you can't immediately read back the value set. If you just wait a tick with a timer or something before logging, you'll see everything is fine. At least, I think so.
Reference: [setState() does not always immediately update the component. It may batch or defer the update until later.](https://reactjs.org/docs/react-component.html#setstate)
Also, minor performance nit: don't use arrow functions in render() to bind; instead, always define the handler itself as an arrow function.
Upvotes: 0 <issue_comment>username_2: It's because `setState` is asynchronous. Think of it as of Promise:
```
handle(){
new Promise((resolve) => {
setTimeout(() => {
resolve("success")
}, 1000)
}).then(result => {
console.log(result);
})
console.log('this will be printed before "success"')
}
```
You know that a code declared after the Promise, will execute immediately. The same is with `setState`.
If you want to be sure code executes after the state was updated use callback function:
```
handle(){
this.setState({value: 'X',isX:!this.state.isX}, () => {
console.log(this.state.isX)
});
}
```
Links:
[Why setState isn't synchronous.](https://reactjs.org/docs/faq-state.html#why-doesnt-react-update-thisstate-synchronously)
Upvotes: 2 [selected_answer]
|
2018/03/19
| 221 | 926 |
<issue_start>username_0: ```
public async Task Method(string value, [FromBody] Person person)
```
Can `person` ever be null here?
UPDATE: Forgot to mention that the person object has alteast one property marked with `[Required]` attribute, and that i'm receiving `A non-empty request body is required`<issue_comment>username_1: It can still be null. Example, if your person has an int Age parameter and somehow you pass a string to it that doesn't parse to an integer, it will be null.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Yes, of course it can be. If no property on person is submitted, it will be null. The modelbinder only instantiates an instance of the action parameter class if it has something to bind to it. If it has nothing to bind (either because nothing was posted or posted values were invalid (submitting an empty string for an int, for example), then the parameter will be null.
Upvotes: 2
|
2018/03/19
| 989 | 3,560 |
<issue_start>username_0: I have a code in Lua. In the first function, I get a JSON data and put it in a variable (item1), and am able to print it. In the second function, I would like to use this variable to show the image (because item1 is an image URL). I tried a forward declaration like this and put it in the second function, but it does not work. How can this be solved?
```
local item1
local function networkListener( event )
local res = json.prettify( event.response )
local decoded = json.decode( res )
if ( event.isError ) then
print( "--Network error-- ", ( res ) )
else
print( "Results: " .. ( res ) )
item1 = decoded.results.bindings[0].image.value
print(item1)
local myText = display.newText(sceneGroup, item1, 10, 100, native.systemFont, 26 )
myText:setFillColor( 1, 1, 1 )
end
end
params.body = body
network.request("http://example.com/data.json", "GET", networkListener, params)
local function networkListener2( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
print ( "event.response.fullPath: ", event.response.fullPath )
print ( "event.response.filename: ", event.response.filename )
print ( "event.response.baseDirectory: ", event.response.baseDirectory )
end
display.loadRemoteImage(item1, "GET", networkListener2, "item1.png", system.TemporaryDirectory, 50, 50 )
```
Thank you very much for your help in advance!<issue_comment>username_1: In your code the `display.loadRemoteImage()` is called before previous `network.request()` has finished its job. Callback `networkListener` wasn't triggered yet, so `item1` variable is not assigned.
You should schedule `loadRemoteImage()` from within within `networkListener`, or anywhere else where you will know that the url was successfully read, i.e. previous request has finished.
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
local function networkListener2( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
print ( "event.response.fullPath: ", event.response.fullPath )
print ( "event.response.filename: ", event.response.filename )
print ( "event.response.baseDirectory: ", event.response.baseDirectory )
end
local function networkListener( event )
local res = json.prettify( event.response )
local decoded = json.decode( res )
if ( event.isError ) then
print( "--Network error-- ", ( res ) )
else
print( "Results: " .. ( res ) )
item1 = decoded.results.bindings[0].image.value
print(item1)
local myText = display.newText(sceneGroup, item1, 10, 100, native.systemFont, 26 )
myText:setFillColor( 1, 1, 1 )
display.loadRemoteImage(item1, "GET", networkListener2, "item1.png", system.TemporaryDirectory, 50, 50 )
-- Position should be set by the center of the text object
local myText = display.newText(sceneGroup, item1, 10, 300, native.systemFont, 26 )
myText:setFillColor( 1, 1, 1 )
local myText2 = display.newText(sceneGroup, item2, 10, 500, native.systemFont, 26 )
myText:setFillColor( 1, 1, 1 )
end
end
params.body = body
network.request("http://example.com/data.json", "GET", networkListener, params)
```
Upvotes: 0
|
2018/03/19
| 461 | 1,601 |
<issue_start>username_0: I am a newbie. I need to create wordlist with specified pattern. The pattern will look like *XXXXX00000* where X are 5 english characters (different, but can be same, small from alphabet) and 00000 are 5 numbers (0-9). (There will not be some special characters like &, $, \_, -...)
Can someone help me?
It will be nice, if someone will post Terminal command. For example using **crunch**.
Thank you.
Examples:
* aklmj98765
* kjgfk11137
* hhhhd00110<issue_comment>username_1: I made a program for you, save this as anyname.py and run. copy the output.
```
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
for a in range(len(letters)):
for b in range(len(letters)):
for c in range(len(letters)):
for d in range(len(letters)):
for e in range(len(letters)):
for f in range(len(numbers)):
for g in range(len(numbers)):
for h in range(len(numbers)):
for i in range(len(numbers)):
for j in range(len(numbers)):
print(letters[a] + letters[b] + letters[c] + letters[d] + letters[e] + numbers[f] + numbers[g] + numbers[h] + numbers[i] + numbers[j])
```
Upvotes: 2 <issue_comment>username_2: ```
crunch 10 10 -t @@@@@%%%%% -o result.txt
```
Upvotes: 2 <issue_comment>username_3: github.com/adaywithtape/wlm does just about anything you want easy to use.I answered in the wrong place see description below.
Upvotes: -1
|
2018/03/19
| 502 | 1,636 |
<issue_start>username_0: I use Create-React-App to build a small React application. The full code is stored in [github](https://github.com/juan-coding/score-board-app)
My file structure:
```
src
components
Players.js
Player.js
App.css
App.js
index.css
index.js
...
```
*App.js:*
```
import React from 'react';
import './App.css';
import PropTypes from 'prop-types';// used to fix the error: 'PropTypes' is not defined
import Header from './components/Header';
import Players from './components/Players';
const App = (props) => (
);
App.propTypes = {
title: PropTypes.string.isRequired
};
export default App;
```
*Player.js:*
```
import React from 'react';
const Player = (props) => (
<NAME>
-
31
+
);
export default Player;
```
*Players.js:*
```
import React from 'react';
import Player from './components/Player';
const Players = () => (
<NAME>
-
31
+
<NAME>
-
30
+
)
export default Players;
```
And the line `import Player from './components/Player';` leads to this error:
[](https://i.stack.imgur.com/cEIJH.png)
But if I put this line on top of `App.js` file, it doesn't report such compiling error. I really want to know what's the issue indeed with my code?<issue_comment>username_1: Your file path is wrong. `Player` is in the same folder as `Players`, so you need to just say `import Player from './Player'`
Upvotes: 4 [selected_answer]<issue_comment>username_2: * Delete the node\_modules directory
* Delete the package-lock.json file
* Run npm install
* Run npm start
Upvotes: 0
|
2018/03/19
| 148 | 536 |
<issue_start>username_0: got something like:
```
var asd = $('');
```
I want to get the div with id = 1. .find is not working. How do I get the element to change some values or to append stuff to it?
Thanks<issue_comment>username_1: Your file path is wrong. `Player` is in the same folder as `Players`, so you need to just say `import Player from './Player'`
Upvotes: 4 [selected_answer]<issue_comment>username_2: * Delete the node\_modules directory
* Delete the package-lock.json file
* Run npm install
* Run npm start
Upvotes: 0
|
2018/03/19
| 702 | 1,973 |
<issue_start>username_0: I'm trying to install Xamarin.Android.Support.v7.CardView package via NuGet, but it fails with this error in Error list window:
```
При попытке установить необходимые компоненты Android для проекта "App1" произошла ошибка.
Для проекта "App1" на вашем компьютере должны быть установлены следующие компоненты:
Xamarin.Android.Support.v7.CardView
JavaLibraryReference: https://dl-ssl.google.com/android/repository/android_m2repository_r32.zip-m2repository/com/android/support/cardview-v7/23.4.0/cardview-v7-23.4.0.aar-23.4.0.0
AndroidResources: https://dl-ssl.google.com/android/repository/android_m2repository_r32.zip-m2repository/com/android/support/cardview-v7/23.4.0/cardview-v7-23.4.0.aar-23.4.0.0
Дважды щелкните здесь, чтобы установить их.
Ошибки установки: XA5209 Сбой распаковки. Скачайте "https://dl-ssl.google.com/android/repository/android_m2repository_r32.zip" и извлеките его в каталог
"C:\Users\User\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.4.0.0\content".
XA5209 Причина: Не удалось найти часть пути "C:\Users\User\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.4.0.0\content\m2repository\".
XA5207 Установите пакет: "Xamarin.Android.Support.v7.CardView" доступен в установщике пакета SDK.. Файл библиотеки Java "C:\Users\User\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.4.0.0\content\classes.jar" не существует.
```
Double click on this error shows a little window that is trying to dowload these packages and disappers through second and that's all, error still there. I've tried to delete AppData\Local\Xamarin\zips folder, but it didn't helped.<issue_comment>username_1: Your file path is wrong. `Player` is in the same folder as `Players`, so you need to just say `import Player from './Player'`
Upvotes: 4 [selected_answer]<issue_comment>username_2: * Delete the node\_modules directory
* Delete the package-lock.json file
* Run npm install
* Run npm start
Upvotes: 0
|
2018/03/19
| 288 | 1,186 |
<issue_start>username_0: I have a front end application communicating with a database. Via front end you can modify the database, so I need to authorize users.
I setup authentication via google to enter the application, however I also want to check if user is logged in and authorised BEFORE every action that would involve database.
However I don't know what would be the best approach. My pseudocode would be something like:
```
handleSubmit = () =>{
this.props.checkUser();
this.props.dbAction();
}
```
However, obviously before checkUser resolves dbAction will fire. Settimeout also doesnt seem to do the trick. So how should I tackle this?
I'm using React with Redux on frontend and node.js + passport + mongoDB on backend.
If community finds that currently I am too vague I can provide some of my code that would revolve around this issue.<issue_comment>username_1: Your file path is wrong. `Player` is in the same folder as `Players`, so you need to just say `import Player from './Player'`
Upvotes: 4 [selected_answer]<issue_comment>username_2: * Delete the node\_modules directory
* Delete the package-lock.json file
* Run npm install
* Run npm start
Upvotes: 0
|
2018/03/19
| 414 | 1,596 |
<issue_start>username_0: I have a **users** table and **user\_followings** table. The tables have the basic structure:
```
users: id, name, email
users_followings: following_user_id, follower_user_id
```
* follower\_user\_id is someone who is following some other person.
* following\_user\_id is someone who is being followed by some other
person
I want that one can click on a particular user to see all the information like who are following him/her and who are the people that he/she is follwing.
```
SELECT
users.id,
users.name,
users.email
from users
JOIN user_followings ON
user_followings.follower_user_id = users.id
WHERE user_followings.following_user_id = 1
```
This query basically joins two table and fetches desired result.
Now suppose a user named 'A' is logged in and he is looking at user X's profile. There are many people who have followed user X.
Let's say John, Mike, Rusev, Jack etc
How can write a query that tells whether logged in User 'A' is following John, Mike, Rusev, Jack etc or not along with the query that is above there.
So user A should be able to know whether he is following John, Mike, Rusev, Jack etc or not<issue_comment>username_1: Your file path is wrong. `Player` is in the same folder as `Players`, so you need to just say `import Player from './Player'`
Upvotes: 4 [selected_answer]<issue_comment>username_2: * Delete the node\_modules directory
* Delete the package-lock.json file
* Run npm install
* Run npm start
Upvotes: 0
|
2018/03/19
| 1,366 | 5,397 |
<issue_start>username_0: Testing my web API (nuget package Microsoft.AspNetCoreAll 2.0.5) I run into strange issues with the model validation using annotations.
I have (for example) this controller:
```
[HttpPost]
public IActionResult Create([FromBody] RequestModel request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// create
request.Name.DoSomething();
return Created(...);
}
```
I defined my RequestModel as follows:
```
public class RequestModel
{
[Required]
public string Name {get; set};
}
```
My problem although I defined RequestModel.Name as [Required] it is null (if Name is not present in the json from the body. Which I thought should not happen since it is marked as [Required] and be automatically appear as ModelState error.
Given [this link to the specs](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation) they use Bind(....).
So my question?
Do I have to enable it everytime or should it work out of the box or how is it intended to be used?
If I annotate it with [Required] I would assume that at least ModelState.IsValid returns false if it is not present.
Using Bind in the link seems a bit complicated for me in cases where I have multiple objects nested into each other.
---
**Edit 1: created a MVC data validation test bed**
To better visualize what I mean and so everyone can easily experiment on their own I created the small demo [.NET Core MVC data validation test bed](https://github.com/MontyGvMC/.NET-Core-MVC-data-validation-test-bed) on GitHub.
You can download the code, start it with VS 2017 and try it out your own using the swagger ui.
Having this model:
```
public class StringTestModel2
{
[Required]
public string RequiredStringValue { get; set; }
}
```
And testing it with that controller:
```
[HttpPost("stringValidationTest2")]
[SwaggerOperation("StringValidationTest2")]
public IActionResult StringValidationTest2([FromBody] StringTestModel2 request)
{
LogRequestModel("StringValidationTest2", request);
if (!ModelState.IsValid)
{
LogBadRequest(ModelState);
return BadRequest(ModelState);
}
LogPassedModelValidation("StringValidationTest2");
return Ok(request);
}
```
The results are far way from expected:
1. Giving a null (not the string "null") is allowed and return 200 OK
2. Giving an int is allowed an returns 200 OK (it gets converted to a string)
3. Giving a double is allowed and returns 200 OK (if possible it gets converted to string, if not convertible (mixing points and semicolons return 400 Bad Request)
4. if you just send empty curly brackets and leave RequiredStringValue undefined it passes and returns 200 OK (with the string as null).
Leaving me (for now) with one of the follwoing conclusions:
1. either MVC data validation does not work out of the box
2. either does not work as expected (if one marks a property as required it should be made sure it is there)
3. either MVC data validation is broken
4. either MVC data validation is completly useless
5. we are missing some important point (like the Bind[])<issue_comment>username_1: You get ModelValidation automatically as part of using/deriving from controller (I believe it is in the MVC middleware) but, unfortunately, this does not include null checks. So you need to explicitly check the parameter is NULL as well as the ModelState check.
```
[HttpPost]
public IActionResult Create([FromBody] RequestModel request)
{
if (request == null || !ModelState.IsValid)
{
return BadRequest(ModelState);
}
...
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: After further experimenting around I found the answer.
>
> Does the data validation need to be activated?
>
>
>
Answer: it depends on your configure services method:
No, it does not need to be activated if you use
```
services.AddMvc();
```
Yes, it needs to be activated if you use
```
services.AddMvcCore()
.AddDataAnnotations(); //this line activates it
```
This [article](https://offering.solutions/blog/articles/2017/02/07/difference-between-addmvc-addmvcore/) brought me to the answer.
Upvotes: 0 <issue_comment>username_3: I assume you use
```
services.AddMvc();
```
so it should work by default.
But it doesn't work just as you expect: instead of returning 400 status code it invalidates model state and lets you manage action result.
You can create an attribute class to automatically return "Bad request"
```
internal class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(
new ApiError(
string.Join(" ",
context.ModelState.Values
.SelectMany(e => e.Errors)
.Select(e => e.ErrorMessage))));
}
}
}
```
where `ApiError` is a custom ViewModel for error results.
Now you can mark controllers or actions with this attribute to achieve a behavior you expect to have by default.
If you want this behavior for all methods just change your `AddMvc` line to something like this:
```
services.AddMvc(config => config.Filters.Add(new ValidateModelAttribute()));
```
Upvotes: 1
|
2018/03/19
| 445 | 1,164 |
<issue_start>username_0: I have a file having many lines of data separated by comma like
```
Mary,F,6919
Anna,F,2698
Emma,F,2034
Elizabeth,F,1852
Margaret,F,1658
Minnie,F,1653
```
I am reading the text file and trying to split the words
```
filename = 1880.txt
with open(filename) as f:
content = f.readlines()
content = [x.split() for x in content]
```
It gives the result as
```
['Mary,F,9889', 'Anna,F,4283', 'Emma,F,2764', 'Elizabeth,F,2680', 'Minnie,F,2372']
```
I expect the content variable should return each line with data split at comma like
```
[('Mary','F','9889'), ('Anna','F','4283'), ('Emma','F','2764'), ('Elizabeth','F','2680'), ('Minnie,'F','2372')]
```
where is my mistake using the split function?<issue_comment>username_1: The answer should be
```
filename = 1880.txt
with open(filename) as f:
content = f.readlines()
content = [x.strip().split(',') for x in content]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can iterate over the file object once, applying `str.strip` to remove the trailing `'\n'`:
```
new_data = [tuple(i.strip('\n').split(',')) for i in open('filename.txt')]
```
Upvotes: 1
|
2018/03/19
| 383 | 1,545 |
<issue_start>username_0: I want to configure packages.config to download the available highest version of a package. How can I do that?
Something like:
```
```
I saw attr "allowedVersions", but it always download the version configured in "version" attr.<issue_comment>username_1: Unfortunately, this isn't possible with NuGet it only allows specific versions. The `allowedVersions` is used to block someone from going beyond *or below* a specific version. i.e. version 1.\* is fine but you cannot go to version 2.0.
A typical workaround for something like this is a batch/powershells script which updates the package you want. You could then hook this into a pre-build.
Upvotes: 2 <issue_comment>username_2: >
> How configure packages.config to download the highest version
>
>
>
Just as Ashley and Matt said, it is impossible to do that, because `packages.config` only allows a single version of a package to be specified.
The simple workaround is using nuget cli to update that package in the pre-build event:
```
$(YourNuGetPath)\nuget.exe update "$(ProjectDir)packages.config" -Id ""
```
With this build event, Visual Studio will update that package to the latest version before you build your project.
Upvotes: 4 [selected_answer]<issue_comment>username_3: I think you can use PackageReference node directly in the project file now.
By doing so you can define a floating version that will select the highest stable version.
See <https://learn.microsoft.com/en-us/nuget/concepts/package-versioning#version-ranges>
Upvotes: 0
|
2018/03/19
| 440 | 1,409 |
<issue_start>username_0: How to make individual cells in a table a hyperlink in html?
This is how I tried to make it and it did not work:
```html
| | | | | |
| --- | --- | --- | --- | --- |
| Home
| Locations
| Accomodation
| Transport
| Contact Us
|
```<issue_comment>username_1: The problem is not the table, it's that there is no content in the tag, so, there's nowhere to click to trigger the link. Try this:
```html
| | | | | |
| --- | --- | --- | --- | --- |
| [Home](Home.html) | [Locations](Locations.html) | [Accomodation](Accomodation.html) | [Transport](Transport.html) | [Contact Us](Contact Us.html) |
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The reason it didn't work because you didn't write home inside the tag.
To make any text hyperlink, you have to put that text inside the tag.
In your case, you can make hyperlinks easily by putting Home, Location etc inside the the a tag like this:
```html
| | | | | |
| --- | --- | --- | --- | --- |
| [Home](Home.html) | [Locations](Locations.html) | [Accomodation](Accomodation.html) | [Transport](Transport.html) | [Contact Us](Contact Us.html) |
```
Upvotes: 0 <issue_comment>username_3: I think the problem here is that your tags actually does not show anything, so have 0px width tags. you can put test inside the tags, which will work. Example:
```
[Home](Home.html)
```
Upvotes: 0
|
2018/03/19
| 920 | 2,981 |
<issue_start>username_0: my project is in Laravel 5.5
i have the table **wposts** for a multilevel menu in laravel and posts in the same time. The fields of the table are:
```
- id
- parentpost (id of parent post)
- title
- porder (order of posts in the same menu)
```
In the Controller i have the function **getwposts** to get the posts using recursion to have a multilevel menu.
```
private function getwposts($parentid = 0,$wposts = []){
foreach(Wpost::where('parentpost', $parentid)->orderby('porder')->get() as $pwpost)
{
echo $pwpost->id.'-' ;
$wposts[$pwpost->id] = $this->getwposts($pwpost->id,$wposts);
}
return $wposts;
}
```
In the same Controller after that, i have a function called **preview** that renders the view
```
public function preview($templ){
$pwposts = \App\Wpost::with('parent')->get();
$pwposts= $this->getwposts(0,[]);
dd($pwposts);
return view('templates.$templ1,compact('pwposts'));
}
```
I am almost there. The wright order of the tabble is
[](https://i.stack.imgur.com/nOw5S.jpg)
but the results are
[](https://i.stack.imgur.com/r7e3g.jpg)
Although with echo i see the correct order of the records in the tree view there isn't ok.
My model is
```
namespace App;
use Illuminate\Database\Eloquent\Model;
class Wpost extends Model
{
protected $fillable =
['parentpost','title','body','author','storeid','porder','haskids'];
protected $table = 'wposts';
public function children(){
return $this->hasmany(Wpost::class, 'parentpost');
}
public function parent(){
return $this->belongsTo(Wpost::class, 'parentpost');
}
}
```
I am stacked. Can you help me?
thanks in advance<issue_comment>username_1: The problem is not the table, it's that there is no content in the tag, so, there's nowhere to click to trigger the link. Try this:
```html
| | | | | |
| --- | --- | --- | --- | --- |
| [Home](Home.html) | [Locations](Locations.html) | [Accomodation](Accomodation.html) | [Transport](Transport.html) | [Contact Us](Contact Us.html) |
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The reason it didn't work because you didn't write home inside the tag.
To make any text hyperlink, you have to put that text inside the tag.
In your case, you can make hyperlinks easily by putting Home, Location etc inside the the a tag like this:
```html
| | | | | |
| --- | --- | --- | --- | --- |
| [Home](Home.html) | [Locations](Locations.html) | [Accomodation](Accomodation.html) | [Transport](Transport.html) | [Contact Us](Contact Us.html) |
```
Upvotes: 0 <issue_comment>username_3: I think the problem here is that your tags actually does not show anything, so have 0px width tags. you can put test inside the tags, which will work. Example:
```
[Home](Home.html)
```
Upvotes: 0
|
2018/03/19
| 908 | 3,035 |
<issue_start>username_0: I'm switching my old datalayer (using Queues) to the "new" and recommended Dataset API. I'm using it for the first time, so I'm providing code examples in case I got something fundamentally wrong.
I create my Dataset from a generator (that will read a file, and provide n samples). It's a small dataset and n\_iterations >> n\_samples, so I simply want to read this dataset over and over again, ideally shuffled.
```
sample_set = tf.data.Dataset.from_generator( data_generator(filename),
(tf.uint8, tf.uint8), (tf.TensorShape([256,256,4]), tf.TensorShape([256,256,1]))
)
```
with datagenerator:
```
class data_generator:
def __init__(self, filename):
self.filename= filename
def __call__(self):
with filename.open() as f:
for idx in f: yield img[idx], label[idx]
```
To actually use the data, I got that I need to define an `Iterator`
```
sample = sample_set.make_one_shot_iterator().get_next()
```
and then we are set to read data
```
while True:
try: my_sample = sess.run(sample)
except tf.errors.OutOfRangeError: break # this happens after dset is read once
```
But all available Iterators seem to be "finite", in the way that they read a dataset only once.
Is there a simple way to make reading from the Dataset endless?<issue_comment>username_1: The **reinitializable Iterator** will work with reinitializing on the same dataset, so this code will read the same dataset over and over again:
```
sample = tf.data.Iterator.from_structure(sample_set.output_types,
sample_set.output_shapes).get_next()
sample_it.make_initializer(sample_set) # create initialize op
with tf.Session(config=config) as sess:
sess.run(sample_set_init_op) # initialize in the beginning
while True:
try:
my_sample = sess.run(sample)
except tf.errors.OutOfRangeError:
sess.run(sample_set_init_op) # re-initialize on same dataset
```
Upvotes: 0 <issue_comment>username_2: Datasets have [`repeat`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#repeat) and [`shuffle`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle) methods.
```py
BUF_SIZE = 100 # choose it depending on your data
sample_set = tf.data.Dataset.from_generator( data_generator(filename),
(tf.uint8, tf.uint8), (tf.TensorShape([256,256,4]),
tf.TensorShape([256,256,1]))
).repeat().shuffle(BUF_SIZE)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: The [`Dataset.repeat()`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#repeat) transformation will repeat a dataset endlessly if you don't pass an explicit `count` to it:
```
sample_set = tf.data.Dataset.from_generator(
data_generator(filename), (tf.uint8, tf.uint8),
(tf.TensorShape([256,256,4]), tf.TensorShape([256,256,1])))
# Repeats `sample_set` endlessly.
sample_set = sample_set.repeat()
sample = sample_set.make_one_shot_iterator().get_next()
```
Upvotes: 1
|
2018/03/19
| 1,262 | 4,648 |
<issue_start>username_0: I have a List of objects each of which has a method getNumOrder that returns a string. The objects in the list are sorted in lexicographical order.
Most of the times all the objects in the list have getNumOrder that return an integer (but not always).
If all the elements in the lists have NumOrders that are integers I would like to sort them using integer sort order. Otherwise they will remain sorted lexicographically.
I have tried this using Java 8 Lambdas
```
try {
results.sort((r1,r2)-> {
Integer seq1= new Integer(r1.getNumOrder());
Integer seq2= new Integer(r2.getNumOrder());
seq1.compareTo(seq2);
});
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
```
There are 2 issues:
1. Because I dont know Lambda expressions very well the syntax is
incorrect
2. I am not sure if this will work if the sorting by integer order
fails, i.e. whether it will leave the list sorted lexicographically.<issue_comment>username_1: In order to make your code work, just return "seq1.compareTo(seq2);" like this:
```
try {
results.sort((r1,r2)-> {
Integer seq1= new Integer(r1.getNumOrder());
Integer seq2= new Integer(r2.getNumOrder());
return seq1.compareTo(seq2);
});
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
```
As @username_2 pointed out in the comments, it shouldn't be done that way (with boxing and with using the constructor to parse a String to an integer), there is a cleaner and "not so wastful" way to accomplish that.
Here's the code:
```
try {
results.sort((r1,r2)->
Integer.compare(Integer.parseInt(r1.getNumOrder()),
Integer.parseInt(r2.getNumOrder()))
);
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
```
Remember here that you only need to (explicitly) return a value in lambdas when you use brackets, as its then handled like a method which - in the case of "sort" - should return an Integer.
Upvotes: 2 <issue_comment>username_2: Do not use `new Integer(String)` to parse a number. It has been [deprecated in Java 9](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#Integer-java.lang.String-). Use [`Integer.parseInt(String s)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#parseInt-java.lang.String-) instead, or [`Integer.valueOf(String s)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#valueOf-java.lang.String-) if you insists on boxing the value (a waste in this case).
The lambda you're after would be:
```
results.sort((r1,r2) -> Integer.compare(Integer.parseInt(r1.getNumOrder()),
Integer.parseInt(r2.getNumOrder())));
```
This leaves `results` unmodified if the sort fails, because the [`sort()`](https://docs.oracle.com/javase/9/docs/api/java/util/List.html#sort-java.util.Comparator-) method copies the list elements to an array, sorts the array, then copies the elements back.
If you prefer to store intermediate values in variables, e.g. so you can see them when debugging, you will be using a lambda *block* and it needs a `return` statement. That's what is missing in your code.
```
results.sort((r1,r2) -> {
int i1 = Integer.parseInt(r1.getNumOrder());
int i2 = Integer.parseInt(r2.getNumOrder());
return Integer.compare(i1, i2);
});
```
---
*The below part of the answer was based on misunderstanding that input was list of strings, which it's not, so it doesn't apply to question, but I'm leaving it for others who might have similar problems where input is a list of strings.*
But it's not good performance. If strings don't have leading zeroes that need to be retained, it'd be better to parse to `int`, sort the `int` values, then format back to string.
Using streams (Java 8+):
```
results = results.stream()
.mapToInt(Integer::parseInt)
.sorted()
.mapToObj(Integer::toString)
.collect(Collectors.toList());
```
Or this non-stream version (Java 1.2+):
```
int[] arr = new int[results.size()];
int i = 0;
for (String s : results)
arr[i++] = Integer.parseInt(s);
Arrays.sort(arr);
results.clear();
for (int v : arr)
results.add(Integer.toString(v));
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You just forgot a "return" in your lambda :
```
return seq1.compareTo(seq2);
```
Other than that, seems fine, even if it fails
Upvotes: 1
|
2018/03/19
| 1,996 | 6,264 |
<issue_start>username_0: I have this database:
```
[{"cliente": {"nombre": "<NAME>"},
"mercancia": {"envio": "Normal", "tipo": "Gaseoso", "fecha": "24/12/2003", "peso": 21, "volumen": 43, "origen": "Cadiz", "destino": "Castellon"},
"vagon": {"id": 1330, "volumen": 202, "peso": 433 }},{"cliente": {"nombre": "<NAME>"}, "mercancia": {"envio": "Normal", "tipo": "Liquido", "fecha": "08/02/2005", "peso": 17, "volumen": 24, "origen": "<NAME>", "destino": "Orense"}, "vagon": {"id": 1290, "volumen": 111, "peso": 464 }},{"cliente": {"nombre": "<NAME>"}, "mercancia": {"envio": "Economico", "tipo": "Contaminante", "fecha": "14/03/2003", "peso": 2, "volumen": 49, "origen": "Santander", "destino": "Burgos"}, "vagon": {"id": 1100, "volumen": 323, "peso": 258 }},{"cliente": {"nombre": "<NAME>"}, "mercancia": {"envio": "Normal", "tipo": "Explosivo", "fecha": "11/07/2002", "peso": 23, "volumen": 51, "origen": "Avila", "destino": "Santa Cruz de Tenerife"}, "vagon": {"id": 1183, "volumen": 171, "peso": 439 }},{"cliente": {"nombre": "Infraestructuras Fracturas"}, "mercancia": {"envio": "Urgente primera hora", "tipo": "Fragil", "fecha": "07/08/2000", "peso": 53, "volumen": 3, "origen": "Tarragona", "destino": "Soria"}, "vagon": {"id": 1454, "volumen": 408, "peso": 101 }}]
```
There are more data but to solve this, it will do. So I am trying to look for 2 things(queries):
The 1st one: A list with the 3 "destinos" with most sent "mercancias" and the number of those, for an "origen" and "fecha", in this case, the one I use in the query:
```
db.mercancias.aggregate(['$project':{origen:'origen', destino:'destino', anio:'fecha'},
{$match: 'origen':'San Sebastian', $year:{'fecha':08/02/2005}},
{$group:{'_id':{'$destino', '$anio'}}},{ maximo:{$max:{$count:{'_id':'envio'}}},{$limit:3}}])
```
I am not sure where I am failing with the query or if it really is something related with syntax.
In the second one, I am trying to get a list of "mercancias" with "destino" close to some coordenates (100km max), ordered by order of distance(I am quite lost with this one, I am not sure how to determine the coordenates, but I have programmed in python the geoNear, so the problem is mainly in the query). I also want to be it an aggregate query, but as I have said, I am quite lost at how I am getting it wrong.
```
db.mercancias.find([{$geoNear:{'near:{'type':'Point', 'coordinates':coordinates}maxDistance':100,'distanceField':'dist.calculated'}}])
```
Anything you think I need to add the question to make it clearer, I will happily edit it.<issue_comment>username_1: In order to make your code work, just return "seq1.compareTo(seq2);" like this:
```
try {
results.sort((r1,r2)-> {
Integer seq1= new Integer(r1.getNumOrder());
Integer seq2= new Integer(r2.getNumOrder());
return seq1.compareTo(seq2);
});
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
```
As @username_2 pointed out in the comments, it shouldn't be done that way (with boxing and with using the constructor to parse a String to an integer), there is a cleaner and "not so wastful" way to accomplish that.
Here's the code:
```
try {
results.sort((r1,r2)->
Integer.compare(Integer.parseInt(r1.getNumOrder()),
Integer.parseInt(r2.getNumOrder()))
);
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
```
Remember here that you only need to (explicitly) return a value in lambdas when you use brackets, as its then handled like a method which - in the case of "sort" - should return an Integer.
Upvotes: 2 <issue_comment>username_2: Do not use `new Integer(String)` to parse a number. It has been [deprecated in Java 9](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#Integer-java.lang.String-). Use [`Integer.parseInt(String s)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#parseInt-java.lang.String-) instead, or [`Integer.valueOf(String s)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#valueOf-java.lang.String-) if you insists on boxing the value (a waste in this case).
The lambda you're after would be:
```
results.sort((r1,r2) -> Integer.compare(Integer.parseInt(r1.getNumOrder()),
Integer.parseInt(r2.getNumOrder())));
```
This leaves `results` unmodified if the sort fails, because the [`sort()`](https://docs.oracle.com/javase/9/docs/api/java/util/List.html#sort-java.util.Comparator-) method copies the list elements to an array, sorts the array, then copies the elements back.
If you prefer to store intermediate values in variables, e.g. so you can see them when debugging, you will be using a lambda *block* and it needs a `return` statement. That's what is missing in your code.
```
results.sort((r1,r2) -> {
int i1 = Integer.parseInt(r1.getNumOrder());
int i2 = Integer.parseInt(r2.getNumOrder());
return Integer.compare(i1, i2);
});
```
---
*The below part of the answer was based on misunderstanding that input was list of strings, which it's not, so it doesn't apply to question, but I'm leaving it for others who might have similar problems where input is a list of strings.*
But it's not good performance. If strings don't have leading zeroes that need to be retained, it'd be better to parse to `int`, sort the `int` values, then format back to string.
Using streams (Java 8+):
```
results = results.stream()
.mapToInt(Integer::parseInt)
.sorted()
.mapToObj(Integer::toString)
.collect(Collectors.toList());
```
Or this non-stream version (Java 1.2+):
```
int[] arr = new int[results.size()];
int i = 0;
for (String s : results)
arr[i++] = Integer.parseInt(s);
Arrays.sort(arr);
results.clear();
for (int v : arr)
results.add(Integer.toString(v));
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You just forgot a "return" in your lambda :
```
return seq1.compareTo(seq2);
```
Other than that, seems fine, even if it fails
Upvotes: 1
|
2018/03/19
| 459 | 1,572 |
<issue_start>username_0: I would like to query all columns and their description in a table/dataset. I'm looking similar metadata tables like `__TABLES_SUMMARY__` and `__TABLES__`.
The goal is to build a data dictionary report in Data Studio for the BigQuery tables.<issue_comment>username_1: You can use [`bq show`](https://cloud.google.com/bigquery/docs/reference/bq-cli-reference#bq_show) in CLI
[`For example`](https://cloud.google.com/bigquery/docs/tables#getting_information_about_tables),
>
> Issue the bq show command to display all table information. Use the --schema flag to display only table schema information. The --format flag can be used to control the output.
>
>
> If you are getting information about a table in a project other than your default project, add the project ID to the dataset in the following format: [PROJECT\_ID]:[DATASET].
>
>
>
```
bq show --schema --format=prettyjson [PROJECT_ID]:[DATASET].[TABLE]
```
>
> Where:
>
>
> [PROJECT\_ID] is your project ID.
>
> [DATASET] is the name of the dataset.
>
> [TABLE] is the name of the table.
>
>
>
Similarly for [`dataset`](https://cloud.google.com/bigquery/docs/datasets#getting_information_about_datasets) :
```
bq show --format=prettyjson [PROJECT_ID]:[DATASET]
```
Upvotes: 1 <issue_comment>username_2: You can now query the list of columns that way:
```
SELECT column_name, data_type
FROM `myproject`.mydataset.INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'mytable'
```
You need to replace myproject, mydataset, mytable by your values.
Upvotes: 3
|
2018/03/19
| 494 | 1,819 |
<issue_start>username_0: I'm looking to copy my SQL Developer preferences across to multiple devices and I'm wondering where I'd find the file/files to copy across.
When referring to preferences in particular, I'm talking about the preferences accessed through Tools -> Preferences. I would like an exact copy of all preferences saved here (down the table filters and startup script location) with the intention of applying them to other PC's.
Another preference that I would like to transfer is the filter i've applied to 'Other Users' to filter out certain Schemas. I hope this is possible.
Thanks<issue_comment>username_1: The default locations are :
Windows.... AppData\Roaming\SQL Developer
Linux/Mac.. ~/.sqldeveloper
*Note 1: the AppData folder is frequently 'hidden' in Windows by default.*
*Note 2: each version of SQL Developer gets its own directory, although certain things are shared such as reports, connections, sqlhistory*
[](https://i.stack.imgur.com/zB6P1.png)
The easiest way to 'copy' across machines is to use a dropbox/GDrive/.. type thing that will sync.
Regardless of that you can tell sqldev where to store preferences with the following setting.
```
edit sqldeveloper/bin/sqldeveloper.conf
- add the path to the Dropbox or where ever location
AddVMOption -Duser.home=/Users/klrice/Dropbox/sqldev
```
If you do this on N devices, it should all just sync and work seamless.
Ref: my blog on this from '12
<http://krisrice.io/2012-05-12-sql-developer-shared-setup-from-any/>
Upvotes: 3 <issue_comment>username_2: For Sql developer 18.2.0, product-preferences.xml is in C:\Documents and Settings\userid\AppData\Roaming\SQL Developer\system192.168.3.11.1748\o.sqldeveloper
Upvotes: 0
|
2018/03/19
| 657 | 2,310 |
<issue_start>username_0: For some reason, the `onReceive()` method of my `BroadcastReceiver` class is not always called. It is usually called, but sometimes it is not.
More specifically, I am receiving `android.intent.action.PHONE_STATE`. Most of the time, when a call comes in, the `onRecieve()` method is called as it should be for changes to RINGING, IDLE, and OFFHOOK. However, there are some occasion when the method is NOT called for RINGING (when a call is incoming) but it is still called for IDLE (when I hang up the call).
From the manifest:
```
```
The onReceive method itself is pretty simple:
```
public void onReceive(Context voCtx, Intent voIntent)
{
Log(voCtx, "onReceive: " + voIntent.getAction());
if(voIntent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED))
{
HandleCallStateChanged(voCtx, voIntent);
}
}
```
Log just outputs to my log file, so I can see what's happening. I'm not sure why `onReceive()` is only called sometimes. Could some other app be intercepting the broadcasts and cancelling them before my app gets them?<issue_comment>username_1: The default locations are :
Windows.... AppData\Roaming\SQL Developer
Linux/Mac.. ~/.sqldeveloper
*Note 1: the AppData folder is frequently 'hidden' in Windows by default.*
*Note 2: each version of SQL Developer gets its own directory, although certain things are shared such as reports, connections, sqlhistory*
[](https://i.stack.imgur.com/zB6P1.png)
The easiest way to 'copy' across machines is to use a dropbox/GDrive/.. type thing that will sync.
Regardless of that you can tell sqldev where to store preferences with the following setting.
```
edit sqldeveloper/bin/sqldeveloper.conf
- add the path to the Dropbox or where ever location
AddVMOption -Duser.home=/Users/klrice/Dropbox/sqldev
```
If you do this on N devices, it should all just sync and work seamless.
Ref: my blog on this from '12
<http://krisrice.io/2012-05-12-sql-developer-shared-setup-from-any/>
Upvotes: 3 <issue_comment>username_2: For Sql developer 18.2.0, product-preferences.xml is in C:\Documents and Settings\userid\AppData\Roaming\SQL Developer\system172.16.17.32.1748\o.sqldeveloper
Upvotes: 0
|
2018/03/19
| 468 | 1,582 |
<issue_start>username_0: I am using google finance api for conversion of currency based on real rate conversion,
The API what I am using is given below:
**<https://finance.google.com/finance/converter?a=1&from=USD&to=INR>**
It was working till yesterday but from today it's throwing 403 response code.
Can anyone help me on that or Is this url changed??
Thanks<issue_comment>username_1: The default locations are :
Windows.... AppData\Roaming\SQL Developer
Linux/Mac.. ~/.sqldeveloper
*Note 1: the AppData folder is frequently 'hidden' in Windows by default.*
*Note 2: each version of SQL Developer gets its own directory, although certain things are shared such as reports, connections, sqlhistory*
[](https://i.stack.imgur.com/zB6P1.png)
The easiest way to 'copy' across machines is to use a dropbox/GDrive/.. type thing that will sync.
Regardless of that you can tell sqldev where to store preferences with the following setting.
```
edit sqldeveloper/bin/sqldeveloper.conf
- add the path to the Dropbox or where ever location
AddVMOption -Duser.home=/Users/klrice/Dropbox/sqldev
```
If you do this on N devices, it should all just sync and work seamless.
Ref: my blog on this from '12
<http://krisrice.io/2012-05-12-sql-developer-shared-setup-from-any/>
Upvotes: 3 <issue_comment>username_2: For Sql developer 18.2.0, product-preferences.xml is in C:\Documents and Settings\userid\AppData\Roaming\SQL Developer\system192.168.3.11.1748\o.sqldeveloper
Upvotes: 0
|
2018/03/19
| 1,718 | 6,403 |
<issue_start>username_0: I'm trying to write a script to connect to TFS using powershell, however I'm stuck on the part of actually connecting
```
$credentialProvider = new-object Microsoft.TeamFoundation.Client.UICredentialsProvider
$collection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($uri, $credentialProvider)
```
It gives an error that says it cannot find the type
>
> [ERROR] New-object : Cannot find type [ERROR]
> [Microsoft.TeamFoundation.Client.UICredentialsProvider]: verify that
> the [ERROR] assembly containing this type is loaded.
>
>
>
Well I tried to do this first, but it did not help
```
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.WorkItemTracking.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Build.Client")
```
I only have Visual Studio 2015 installed on my development environment. Is there some component that I'm missing that is a requirement for interfacing with TFS using powershell?
Furthermore I don't know where this script will be run from (it wont be from a development machine), presumably from a machine that has access to TFS server directly maybe using Team Explorer.<issue_comment>username_1: Here is what I used to pull in the dll's for 2013,2015 tfs
```
function Connect-ToTfs
{
Param([string] $Collectionurl)
#the collection url will be cast as a uri to the getteamproject collection.
Write-Verbose $Collectionurl
if ($CollectionUrl -ne '')
{
#if collection is passed then use it and select all projects
$tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection([uri]$CollectionUrl)
}
else
{
#if no collection specified, open project picker to select it via gui
$picker = New-Object Microsoft.TeamFoundation.Client.TeamProjectPicker([Microsoft.TeamFoundation.Client.TeamProjectPickerMode]::NoProject, $false)
$dialogResult = $picker.ShowDialog()
if ($dialogResult -ne 'OK')
{
#exit
}
$tfs = $picker.SelectedTeamProjectCollection
}
$tfs
}
function Invoke-VisualStudioDlls
{
if (Test-Path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer')
{
Write-Verbose "importing Visual Studio 2015 Dll's"
Invoke-Visual15StudioDlls
}
elseif (Test-Path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0')
{
Write-Verbose "importing Visual Studio 2013 Dll's"
Invoke-Visual13StudioDlls
}
}
function Invoke-Visual15StudioDlls
{
$visualStudiopath = 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer'
#$visualStudiopath45 = 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer'
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Client.dll"
Add-type -path "$visualStudiopath\Microsoft.TeamFoundation.ProjectManagement.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Build.Common.dll"
}
function Invoke-Visual13StudioDlls
{
$visualStudiopath = 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0'
$visualStudiopath45 = 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\ide\ReferenceAssemblies\v4.5'
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Client.dll"
Add-type -path "$visualStudiopath45\Microsoft.TeamFoundation.ProjectManagement.dll"
}
```
Upvotes: 1 <issue_comment>username_2: The Team Foundation Server Client Object Model used to be installed to the Global Assembly Cache when you installed Team Explorer 2013 or below. Because of that, they were always easy to load from any script.
With Team Explorer and Visual Studio 2015 and up, the packages are no longer registered globally. At the same time, Microsoft changed the license and made these assemblies distributable with your application and released a NuGet package to make distribution easier.
The proper way to handle scenarios where you need the TFS Client Object Model is to package them with your script or the download them on-demand using Nuget.
There are a number of packages that you may or may not need depending on what you are doing from your scripts:
Traditional Client Object Model:
* <https://www.nuget.org/packages/Microsoft.TeamFoundationServer.Client/>
* <https://www.nuget.org/packages/Microsoft.TeamFoundationServer.ExtendedClient/>
New-style REST API object model:
* <https://www.nuget.org/packages/Microsoft.VisualStudio.Services.Client/>
* <https://www.nuget.org/packages/Microsoft.VisualStudio.Services.InteractiveClient/>
You can use this little snippet to fetch nuget.exe and the dependencies on the fly: <https://stackoverflow.com/a/26421187/736079> or use the `install-package` that was introduced in powershell v5.
**Note**: If you're updating or creating new scripts, it's recommended to switch to [the new-style REST API's and the object model](https://learn.microsoft.com/en-us/vsts/integrate/get-started/client-libraries/samples) that goes along with that.
Upvotes: 2 <issue_comment>username_3: In Visual Studio 2015, the object model client libraries are removed from GAC. In order to load them you need to point the Add-Type cmdlet to a path, for example:
```
Add-Type -Path "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.Client.dll"
```
Otherwise, you could install package from Nuget as @Jessehouwing mentioned.
Upvotes: 0
|
2018/03/19
| 745 | 2,815 |
<issue_start>username_0: I have done some research and got a specific problem with facebook login SDK. I use the PHP SDK.
So, as from march 2018 all facebook developers will be seing "Use Strict Mode for Redirect URIs" turned on (and cannot turn it off).
My website was working fine before the latesr API update. The basic login logic was this:
Users go to <https://my-website.com/take.php?someGetParam=here-goes-the-parameter>.
If there is no facebook user logged in, the current user will be redirected to the facebook login dialog, will check the permissions and on success the user will be redirected back to the URL above, and then will be redirected to another page.
As from now, with the newest changes, in order for the login flow with this GET Parameters to work, I have to manually insert them in the "Valid OAuth redirect URIs" field in the facebook developers dashboard of my API like this:
<https://my-website.com/take.php?someGetParam=parameter-1>
<https://my-website.com/take.php?someGetParam=parameter-2>
<https://my-website.com/take.php?someGetParam=parameter-3>
and so on...
otherwise I get the error:The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
Is there a way not to include manually this URLs (because there are many) but to insert only one and get the login flow to work.
PS: I am trying to insert:
<https://my-website.com/take.php>
OR
<https://my-website.com/take.php?someGetParam=>
but no effect<issue_comment>username_1: You can add any value that you want in the `state` parameter. The most frequent usage for this parameter is to prevent [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery), but you can pass anything you would want to be sent back, even an encoded JSON.
This parameter will be returned to you and is exempted on the strict URL matching.
This is documented in [Invoking the Login Dialog and Setting the Redirect URL](https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#logindialog)
>
> state. A string value created by your app to maintain state between the request and callback. This parameter should be used for preventing Cross-site Request Forgery and will be passed back to you, unchanged, in your redirect URI.
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: I encountered a similar situation, I manged to solve it by setting the Valid "**OAuth redirect URIs**" as follows:
```
https://localhost/FacebookLogin/fb-callback.php?client_id=&return\_scopes=true
```
**Please note the following**
* Insert you facebook app id in the place holder in the sample url
above.
* Make sure you use the latest version of the SDK which is 5.6.2
Upvotes: 0
|
2018/03/19
| 442 | 1,532 |
<issue_start>username_0: I am struggling in obtaining both of the behaviors requested in the title.
1) I have a property file like this:
```
my.list=a,b,c
```
2) If that property is not present I want an empty list
Why the following is throwing me syntax error?
```
@Value("#{'${my.list}'.split(',') : T(java.util.Collections).emptyList()}")
```<issue_comment>username_1: I don't think you can use nested SPEL. one way to achieve this is
```
@Value("${server.name:#{null}}")
private String someString;
private List someList;
@PostConstruct
public void setList() {
someList = someString == null ? Collections.emptyList() : Arrays.asList(someString.split(","));
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: There is a way to get it working:
```
@Value("#{T(java.util.Arrays).asList('${my.list:}')}")
private List list;
```
After the colon at `my.list:` you can set the default value. For now its emtpy.
Upvotes: 4 <issue_comment>username_3: Did came across similar requirement. Below is one of the possible way of doing this :
```
@Value("#{'${some.key:}'.split(',')}")
Set someKeySet;
```
I think similar should apply for List as well.
Pay attention to ":" after property name. It defaults to blank string which in turn would give empty list or set.
Upvotes: 2 <issue_comment>username_4: The best way to achieve this will be
```
@Value("#{'${my.list:}'.split(',')}")
private List myList;
```
If key is not present in application.properties, we are initialising with a empty list.
Upvotes: -1
|
2018/03/19
| 526 | 2,005 |
<issue_start>username_0: I'm having a lot of difficulty installing matplotlib in my pipenv, I believe due to the non-python dependencies.
The error I am getting is
`Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.`
This is on MacOS X (High Sierra). I have installed `libpng` `freetype` and `pkg-config` via brew, but this does not seem to resolve the issue.
My hope for this pipenv is for it to be deployed to Heroku, if that makes any difference.<issue_comment>username_1: I resolved this error by following the instructions in [this answer](https://stackoverflow.com/questions/34977388/matplotlib-runtimeerror-python-is-not-installed-as-a-framework#40147524) while also using [this document](https://matplotlib.org/users/customizing.html#the-matplotlibrc-file) to find where the `matplotlibrc` file is located.
To do this inside my pipenv I ran the following code:
```
python
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
```
Using the output I navigated to the matplotlibrc file within my virtual environment and added `backend: TkAgg` to the file.
This resolved my issue. Hopefully this question can be of help to others!
Upvotes: 4 <issue_comment>username_2: Before trying as @brian suggested, for me, it worked by just adding `matplotlib.use('TkAgg')` after `import matplotlib` and before `from matplotlib import pyplot`
```
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot
```
Environment
-----------
* This is on MacOS X (High Sierra)
* Python 3.7 version
* pipenv, version 2018.7.1
Upvotes: 3
|
2018/03/19
| 573 | 2,228 |
<issue_start>username_0: I was editing an HTML page and had some issue in replacing image. It didn't displayed anything.
Then I tried making a simple HTML program just to test
```

```
but it still doesnot work.
I tried Everything Including but not limited to
1. Giving local links in same directory in which my page is.
2. Creating a subDirectory and giving its link.(as shown above)
3. Giving full path
4. using (proper reference methods `./` `../` etc)
5. Using an Online Link
the above code is working fine
after watching it working , i tried to
7.remove extension of file if it is effecting somehow but that also didn't helped
Can anyone help me with this problem.<issue_comment>username_1: The above html structure should be fine. I'd recommend checking the following:
* Whether the server has altered your code and replaced the URL of the image in the html.
* Is the image itself in a folder on the server that is publicly accessible? What happens if you just type the complete URL of image to the location bar of your browser?
* Confirm that the name of the file and filename in the "src" tag are the same. I misspelled filenames more times than I would like to admit (first capital letter vs. all smallcaps).
* Check the file type. Even if the extension says "jpg", it might have a different format, and some browsers may fail to recognize it.
Anyway, if you could provide the url of your site, it would be helpful.
Upvotes: 0 <issue_comment>username_2: Open your image in a browser and you can see real path in address bar, if you testing in localhost... and tell us about your path for a help you.
Upvotes: 2 [selected_answer]<issue_comment>username_3: You are missing . Before the /image.
It's leads to the subfolder where your image is kept.
```
![]() src="./images/Kanhaji.jpg" alt="HTML5 Icon" width="128" height="128"/>
```
Upvotes: 0 <issue_comment>username_4: Okk guys i Think There was a problem with my browser.. when i tried [this](https://stackoverflow.com/a/49410018/8543493) answer ... it failed to open directly as well.. i reinstalled Firefox and its working now.. but was not able to found the cause of problem
Upvotes: 0
|
2018/03/19
| 653 | 2,540 |
<issue_start>username_0: I need to map all urls in the / which otherwise would give 404 so they get served by a specific servlet. How do I do that?
so /unknownUrl1 and /unknownUrl2 should be shown using my UnhandledUrlsServlet while /unknown/somethingElse should just give the normal 404 error page.
In case this is not possible, something which also catch /unknown/somethingElse would be my fallback. (Then my servlet will just have to look at the url, to decide what to
Using Apache tomcat 8.5
Updated:
The use case is that users on our website need to be able to select a username, and then their personal page should be accessable at example.com/coolusername
I tried to use
```
CatchAll
/\*
```
But that catches all urls even in folders. So it also catches example.com/folder/staticImage.jpg making servering any static resources impossible.
Using the solution would work perfectly, if only I could got the real url the user typed. I can then use that to lookup the name to see if it's a username, and then change the response code to 200.<issue_comment>username_1: The above html structure should be fine. I'd recommend checking the following:
* Whether the server has altered your code and replaced the URL of the image in the html.
* Is the image itself in a folder on the server that is publicly accessible? What happens if you just type the complete URL of image to the location bar of your browser?
* Confirm that the name of the file and filename in the "src" tag are the same. I misspelled filenames more times than I would like to admit (first capital letter vs. all smallcaps).
* Check the file type. Even if the extension says "jpg", it might have a different format, and some browsers may fail to recognize it.
Anyway, if you could provide the url of your site, it would be helpful.
Upvotes: 0 <issue_comment>username_2: Open your image in a browser and you can see real path in address bar, if you testing in localhost... and tell us about your path for a help you.
Upvotes: 2 [selected_answer]<issue_comment>username_3: You are missing . Before the /image.
It's leads to the subfolder where your image is kept.
```
![]() src="./images/Kanhaji.jpg" alt="HTML5 Icon" width="128" height="128"/>
```
Upvotes: 0 <issue_comment>username_4: Okk guys i Think There was a problem with my browser.. when i tried [this](https://stackoverflow.com/a/49410018/8543493) answer ... it failed to open directly as well.. i reinstalled Firefox and its working now.. but was not able to found the cause of problem
Upvotes: 0
|
2018/03/19
| 468 | 1,793 |
<issue_start>username_0: So basically I want to check that a setting is not set in my C# application. The code here
```
if (Default["StudentAccountTypeDefault"] is null) // Crashes after this
{
//
}
else
{
//
}
```
seems to be crashing on the null-check. I've put a breakpoint there, and it shows `Default["DefaultStudentAccountType"]` to just be a blank string. Why is it crashing with a NullReferenceException? I'm pretty sure this is where it crashes-if I comment out if statement it works as expected.
Edit: To alleviate some confusion. Sooooo, `Default` is actually `Settings.Default`, and to add to that, I was actually trying to access it inside the Settings() constructor. So, before it had been initialized, obviously. Oops. "Full"-er code below.
```
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
if (Settings.Default["DefaultStudentAccountType"] is null)
{
}
else
{
}
}
```<issue_comment>username_1: You should be checking with `==` not with `is`, also depending on your data type you may need to check if `Default` is null too. Try this:
```
if(Default == null || Default["StudentAccountTypeDefault"] == null)
{
}
else
{
}
```
Upvotes: 2 <issue_comment>username_2: `Default` is a variable, so if it is null, accessing the indexer `["StudentAccountTypeDefault"]` will throw a null reference exception.
If you're using a new enough .NET version, you can use:
`if (Default?["StudentAccountTypeDefault"] is null)`
(the null-coalescing operator). Otherwise, just check `Default` for null before using its indexer.
Upvotes: 1
|
2018/03/19
| 285 | 1,167 |
<issue_start>username_0: I have a console application written in C# that runs as a service each hour. The application has a Data Access Layer (DAL) to connect to the database with a Db Context. This context is a property of the DAL and is created each time the DAL is created. I believe this has lead to errors when updating various elements.
Question: Should the application create a Db Context when it runs and use this throughout the application so that all objects are being worked on with the same context?<issue_comment>username_1: You should be checking with `==` not with `is`, also depending on your data type you may need to check if `Default` is null too. Try this:
```
if(Default == null || Default["StudentAccountTypeDefault"] == null)
{
}
else
{
}
```
Upvotes: 2 <issue_comment>username_2: `Default` is a variable, so if it is null, accessing the indexer `["StudentAccountTypeDefault"]` will throw a null reference exception.
If you're using a new enough .NET version, you can use:
`if (Default?["StudentAccountTypeDefault"] is null)`
(the null-coalescing operator). Otherwise, just check `Default` for null before using its indexer.
Upvotes: 1
|
2018/03/19
| 1,287 | 4,704 |
<issue_start>username_0: I am trying to validate integer input from a string, I just need a boolean result if the input string correctly changes types to an integer. I tried this method from another question:
<https://stackoverflow.com/a/30030649/3339668>
This is the relevant code along with my imports:
```
import Data.Char
import Data.List
import Text.Read
checkValidInt :: String -> Bool
checkValidInt strInt
| readMaybe strInt :: Maybe Int == Nothing = False
| readMaybe strInt :: Maybe Int /= Nothing = True
```
However, I receive the following errors on loading the script:
```
Illegal operator ‘==’ in type ‘Maybe Int == Nothing’
Use TypeOperators to allow operators in types
main.hs:350:38:
Not in scope: type constructor or class ‘Nothing’
A data constructor of that name is in scope; did you mean DataKinds?
main.hs:351:35:
Illegal operator ‘/=’ in type ‘Maybe Int /= Nothing’
Use TypeOperators to allow operators in types
main.hs:351:38:
Not in scope: type constructor or class ‘Nothing’
A data constructor of that name is in scope; did you mean DataKinds?
```
So what kind of data type is Nothing? How do I check if Nothing is the result of readMaybe properly?<issue_comment>username_1: You could rewrite this as
```
import Data.Char
import Data.List
import Text.Read
checkValidInt :: String -> Bool
checkValidInt strInt =
case (readMaybe strInt :: Maybe Int) of
Nothing -> False
Just _ -> True
```
Upvotes: 2 <issue_comment>username_2: This is due to the fact that Haskell interprets your
```
readMaybe strInt :: (Maybe Int == Nothing = False)
```
as:
```
readMaybe strInt :: (Maybe Int == Nothing = False)
```
It can make no sense out of this. So you can help Haskell by using some brackets:
```
(readMaybe strInt :: Maybe Int) == Nothing = False
```
You also better do not repeat the condition, but use `otherwise`, since if you repeat it, the program will - unless optimized - do the parsing twice, so:
```
checkValidInt :: String -> Bool
checkValidInt strInt
| (readMaybe strInt :: Maybe Int) == Nothing = False
| otherwise = True
```
Since you check for a condition such that the result is `True` if the condition is `False`, and vice versa, it is no use to use guards, we can write it as:
```
checkValidInt :: String -> Bool
checkValidInt strInt = Nothing /= (readMaybe strInt :: Maybe Int)
```
Or we can use a *pattern guard*, this can be used in case we can not perform equality checks on the type of value that is wrapped in the `Maybe`, so:
```
checkValidInt :: String -> Bool
checkValidInt strInt | Just _ <- (readMaybe strInt :: Maybe Int) = True
| otherwise = False
```
Or we can use the [**`isJust :: Maybe a -> Bool`**](https://www.haskell.org/hoogle/?hoogle=isJust) function:
```
checkValidInt :: String -> Bool
checkValidInt strInt = isJust (readMaybe strInt :: Maybe Int)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: >
> I just need a boolean result
>
>
>
Probably not. You need a `Maybe Int` to pattern match on, and `readMaybe` already gives you that without any further processing.
Instead of this
```
if checkValidInt s -- try reading an Int, but throw it away
then foo (read s) -- now really read an Int and use it
else bar -- fall back
```
you do this
```
case readMaybe s of -- try reading an Int
Just i -> foo i -- use it
Nothing -> bar -- fall back
```
Normally an explicit type annotation should not be needed, if `foo` is of the right type; but see below.
If you, for some unfathomable reason, really need `checkValidInt`, you base it on the above pattern
```
case (readMaybe s) :: Maybe Int of
Just _ -> True
Nothing -> False
```
As noted in another answer, the `maybe` function abstracts this pattern match away, but I would recommend using explicit pattern matches whenever you can as an exercise, to get the hang of it.
Upvotes: 2 <issue_comment>username_4: The algorithm you need here has already been abstracted behind the `maybe` function:
```
checkValidInt :: String -> Bool
checkValidInt = maybe False (const True) . (readMaybe :: String -> Maybe Int)
```
If `readMaybe` returns `Nothing`, then `maybe` returns `False`. Otherwise, it just applies `const True` to the resulting `Just` value, which returns `True` without caring about just what is wrapped by `Just`. Note that you are specializing the type of `readMaybe` *itself*, not the type of its return value.
Or, even simpler with an import,
```
import Data.Maybe
checkValidInt :: String -> Bool
checkValidInt = isJust . (readMaybe :: String -> Maybe Int)
```
Upvotes: 1
|
2018/03/19
| 712 | 2,186 |
<issue_start>username_0: I'm using Ionic 3 with Angular 5 and I want to handle the click event of an element returned by Pipes. I've the following code:
`linkify.ts`:
```
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'linkify',
})
export class LinkifyPipe implements PipeTransform {
transform(value: string) {
return value.replace(/@([a-z0-9_.]+)/gi, "@$1");
}
}
```
`post.html`:
```
```
So, when `post.content` has this content:
```
Hello, @StackOverflow! I'm @Igor
```
Turns to:
```
Hello, @StackOverflow! I'm @Igor
```
However, I want to handle the click event in `span` element, so, I tried:
```
return value.replace(/@([a-z0-9_.]+)/gi, "@$1");
```
But I get the following message on console:
>
> WARNING: sanitizing HTML stripped some content (see
> <http://g.co/ng/security#xss>).
>
>
>
I've added `DomSanitizer` on `linkify.ts`:
```
return this.sanitizer.bypassSecurityTrustHtml(value.replace(/@([a-z0-9_.]+)/gi, "@$1"));
```
And I've added too the `openPage` function in both the `post.ts` and the `linkify.ts` (in both to check if event is fired):
```
openPage(link) {
console.log(link);
}
```
But nothing happens. The only thing I noticed is that when I click on the element it receives the class "activated", that is, the Angular is detecting the event, but it is not firing the function.
How can I handle this?<issue_comment>username_1: Why not simplify the solution? Keep the click where it belongs, and only pipe the small thing. Pipe:
```
@Pipe({name: 'myPipe'})
export class MyPipe {
transform(value: string) {
return `@${value}`;
}
}
```
Gets a string, retuns a string.
And your component template:
```
```
And the component also implements the `go()` method so everything is in it's place. [Here](https://stackblitz.com/edit/angular-49367076?file=app/hello.component.ts)'s how it works.
Upvotes: 0 <issue_comment>username_2: Finnally I found a way to get it work. Kept the Pipe and created a `HostListener` on my component:
```
@HostListener("click", ["$event"])
onClick(e) {
if (e.target.classList.contains("link")) console.log(e.target);
}
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 539 | 1,848 |
<issue_start>username_0: I write slides in RMarkdown and compile them into Beamer presentations. I want to incrementally reveal bullets and subbullets on slides. Below is a `.Rmd` file showing some of my failed attempts. In these attempts, I insert 4 spaces before the subbullet lines. I want to control the incrementing on a slide-by-slide (or even list-by-list) basis.
```
---
title: "My Title"
author: "RTM"
output: beamer_presentation
---
## This works, incremental bullets
>- Bullet 1
>- Bullet 2
## This nests, but does not increment
- Bullet 1
- Bullet 2
+ subbullet 1
+ subbullet 2
## This increments, but fails to nest
>- Bullet 1
>- Bullet 2
> - subbullet 1
> - subbullet 2
## This increments, but fails to nest
>- Bullet 1
>- Bullet 2
> + subbullet 1
> + subbullet 2
## This increments, but fails to nest
>- Bullet 1
>- Bullet 2
+ subbullet 1
+ subbullet 2
## This increments, but fails to nest and ignores subbullet status
>- Bullet 1
>- Bullet 2
>+ subbullet 1
>+ subbullet 2
```<issue_comment>username_1: This problem is solved by updating `pandoc`. This works using `pandoc 2.1.3`
I updated my `pandoc` at the Terminal with `brew install pandoc`, which threw an error suggesting I run `brew link --overwrite pandoc`. I did so, and my pandoc version was updated. I recompile the `.Rmd` file and the first two *but fails to nest* cases increment and nest.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Kumar's answer at [Incremental nested lists in rmarkdown](https://stackoverflow.com/questions/36866916/incremental-nested-lists-in-rmarkdown) is useful and shows how to increment and nest by adding an extra space at the bullet level.
I am not sure how to create slides where the nested bullets appear at the same time as the bullet under which they are nested.
Upvotes: 0
|
2018/03/19
| 716 | 2,810 |
<issue_start>username_0: When I pass self as an argument to a function, does it make any difference if I weakify it first?
For example:
```
__weak __typeof(self) weakSelf = self;
[self.someObject doWorkWithDelegate: weakSelf];
```
In the body of the doWork function it assigns it to a strong property
```
@property (strong) Foo* fooDelegate;
```
(I know this is terrible, don't get sidetracked).
This will still be a strong reference and cause a memory cycle despite theh fact that I "weakified" the reference first, correct?
Bonus Question: How can I check this myself?<issue_comment>username_1: It is the variable `weakSelf` which is weak. That is, ARC does not emit a retain when a value is assigned to it, nor a release when it goes out of scope (or is assigned a different value).
Since the `fooDelegate` property is strong, assigning to it releases any old value it may have had and retains the newly-assigned value.
So, yes, that will be a strong reference. It's not clear from what you posted whether it will constitute a retain cycle. The name of the method suggests that the delegate will be cleared (thus released) after the work has been completed. In that case, it's not a problem. It would only be a problem if `self.someObject` maintained the strong reference until it itself was released and `self` maintained a strong reference to `someObject` until `self` was released.
Upvotes: 3 [selected_answer]<issue_comment>username_2: An important aspect of the original question could be further clarified. "When I pass `self` as an argument to a function, does it make any difference if I weakify it first?"
Note that in the example code block:
```
__weak __typeof(self) weakSelf = self;
[self.someObject doWorkWithDelegate: weakSelf];
```
ARC will perform a retain on each of the objects passed, including the receiver (i.e. `self.someObject` and `weakSelf`), and then a release on each when complete, allowing weak objects to be safely used for the lifetime of the called method. So the answer would be no, it doesn't make a difference to make it weak first because it will be strong for the duration of the call.
If the weak variable was simply referenced within a code block callback from the method, then it will still be weak within that scope.
So this is a common pattern to use a `weakSelf` variable within a block callback to call another method, `foo`, which then can safely use `self` because it is no longer weak during that execution of `foo`. But if `self` goes away before the callback is executed, then `[weakSelf foo]` will simply never be called because `weakSelf` has gone nil.
```
__weak __typeof(self) weakSelf = self;
[self.someObject doWorkWithCallback:^{
[weakSelf foo];
}];
- (void)foo
{
// Safely use self here.
[self doMoreWork];
}
```
Upvotes: 0
|
2018/03/19
| 1,680 | 6,080 |
<issue_start>username_0: I'm trying the **Wikipedia** client login flow depicted in the [API:Login](https://www.mediawiki.org/wiki/API:Login) docs, but something wrong happens:
1) I correctly get a token raised with the HTTP GET `https://en.wikipedia.org/w/api.php?action=query&meta=tokens&type=login&format=json`
and I get a valid `logintoken` string.
2.1) I then try the `clientlogin` like:
HTTP POST `/w/api.php?action=clientlogin&format=json&lgname=xxxx&lgtoken=xxxx%2B%5C`
and the POST BODY was
```
{
"lgpassword" : "<PASSWORD>",
"lgtoken" : "<PASSWORD>"
}
```
But I get an error:
```
{
"error": {
"code": "notoken",
"info": "The \"token\" parameter must be set."
},
"servedby": "mw1228"
}
```
If I try to change `lgtoken` to `token` I get the same result.
2.2) I have then tried the old method i.e. `action=login` and passing the body, but it does not work, since it gives me back another login token: HTTP POST `https://en.wikipedia.org/w/api.php?action=login&format=json&lgname=xxxx`
and the same POST BODY
I then get
```
{
"warnings": {}
},
"login": {
"result": "NeedToken",
"token": "xxxxx+\\"
```
}
where the docs [here](https://www.mediawiki.org/wiki/API:Login) states that
`NeedToken if the lgtoken parameter was not provided or no session was active (e.g. your cookie handling is broken).`
but I have passed the `lgtoken` in the json body as showed.
I'm using **Node.js** and the built-in `http` module, that is supposed to pass and keep session `Cookies` in the right way (with other api it works ok).
I have found a similar issue on a the LrMediaWiki client [here](https://github.com/robinkrahl/LrMediaWiki/issues/65).
**[UPDATE]**
This is my current implementation:
```
Wikipedia.prototype.loginUser = function (username, password) {
var self = this;
return new Promise((resolve, reject) => {
var cookies = self.cookies({});
var headers = {
'Cookie': cookies.join(';'),
'Accept': '*/*',
'User-Agent': self.browser.userAgent()
};
// fetch login token
self.api.RequestGetP('/w/api.php', headers, {
action: 'query',
meta: 'tokens',
type: 'login',
format: 'json'
})
.then(response => { // success
if (response.query && response.query.tokens && response.query.tokens['logintoken']) {
self.login.logintoken = response.query.tokens['logintoken'];
self.logger.info("Wikipedia.login token:%s", self.login);
return self.api.RequestPostP('/w/api.php', headers, {
action: 'login',
format: 'json',
lgname: username
},
{
lgpassword: <PASSWORD>,
lgtoken: self.login.logintoken
});
} else {
var error = new Error('no logintoken');
return reject(error);
}
})
.then(response => { // success
return resolve(response);
})
.catch(error => { // error
self.logger.error("Wikipedia.login error%s\n%@", error.message, error.stack);
return reject(error);
});
});
}//loginUser
```
where `this.api` is a simple wrapper of the Node.js http, the source code is available [here](https://github.com/loretoparisi/audionamix.js/blob/master/lib/api.js) and the api signatures are like:
```
Promise:API.RequestGetP(url,headers,querystring)
Promise:API.RequestPostP(url,headers,querystring,body)
```<issue_comment>username_1: I *think* from what you are saying you have `lgtoken` and `lgname` in the URL you are using, and then `lgpassword` and `lgtoken` (again!) in a JSON-encoded POST body.
This is not how the Mediawiki API works.
You submit it *all* as POST parameters. JSON is never involved, except when you ask for the result to come back in that format. I can't help you fix your code as you don't provide it, but that's what you need to do. (If you edit your question with your code, I'll do my best to help you.)
After seeing your code, I'll presume (without knowing the detail of your code) that you want something like this:
```
return self.api.RequestPostP('/w/api.php', headers, {
action: 'login',
format: 'json',
lgname: username,
lgpassword: <PASSWORD>,
lgtoken: self.login.logintoken
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If the currently accepted answer isn't working for someone, the following method will definitely work. I've used the axios library to send requests. Any library can be used but the key lies in formatting the body and headers correctly.
```
let url = "https://test.wikipedia.org/w/api.php";
let params = {
action: "query",
meta: "tokens",
type: "login",
format: "json"
};
axios.get(url, { params: params }).then(resp => {
let loginToken = resp.data.query.tokens.logintoken
let cookie = resp.headers["set-cookie"].join(';');
let body = {
action: 'login',
lgname: 'user_name',
lgpassword: '<PASSWORD>',
lgtoken: loginToken,
format: 'json'
}
let bodyData = new URLSearchParams(body).toString();
axios.post(url, bodyData, {
headers: {
Cookie: cookie,
}
}).then(resp => {
// You're now logged in!
// You'll have to add the following cookie in the headers again for any further requests that you might make
let cookie = resp.headers["set-cookie"].join(';')
console.log(resp.data)
})
})
```
And you should be seeing a response like
```
{
login: { result: 'Success', lguserid: 0000000, lgusername: 'Username' }
}
```
The second post request was where I got stuck for several hours, trying to figure out what was wrong. You need to send the data in an encoded form by using an API like URLSearchParams, or by just typing up the body as a string manually yourself.
Upvotes: 2
|
2018/03/19
| 795 | 2,662 |
<issue_start>username_0: I wrote this code for like and dislike for my posts in my blog:
```
$(".p_like").each(function() {
$(this).click(function() {
ids = $(this).find(".pl_id").val();
t = $(this);
if ($(this).find(".bi").hasClass("bi-heart-o")) {
gfd = 'p';
$(this).find(".bi").addClass("bi-heart");
$(this).find(".bi").removeClass("bi-heart-o");
} else {
gfd = 'm';
$(this).find(".bi").addClass("bi-heart-o");
$(this).find(".bi").removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
t.find(".nol").html(result);
}
});
});
});
```
And when I use the code, in some of the post it likes the post and then dislike it.
What is the problem of the code and how can I fix it?<issue_comment>username_1: Jquery by default query all given selectors ( here `.p_like` ). It's not needed to iterate over them explicitly.
Jquery methods are chanable. after you select one element you could call methods one after another: `$element.addClass(...).removeClass().css(...)`
Also you've leaked three variables: `ids`, `t`, `gfd`. maybe they're got overriten before you send em out to server so declare them to make em private to your event handler function.
```
$('.p_like').click(function() {
var $t = $(this),
$bi = $t.find('.bi'),
$nol = $t.find('.nol'),
ids = $t.find('.pl_id').val(),
gfd;
if ( $bi.hasClass('bi-heart-o') ) {
gfd = 'p';
$bi.addClass('bi-heart').removeClass('bi-heart-o');
} else {
gfd = 'm';
$bi.addClass('bi-heart-o').removeClass('bi-heart');
}
$.ajax({
type: 'POST',
url: 'likes.php',
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
$nol.html(result);
}
});
});
```
Upvotes: 0 <issue_comment>username_2: use this :
```
$(".p_like").find(".bi").click(function(){
ids = $(this).siblings(".pl_id").val();
t = $(this);
if($(this).hasClass("bi-heart-o")){
gfd='p';
$(this).addClass("bi-heart");
$(this).removeClass("bi-heart-o");
}else{
gfd='m';
$(this).addClass("bi-heart-o");
$(this).removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {ids:ids,k:gfd},
cache: false,
success: function (result) {
t.siblings(".nol").html(result);
}
});
});
```
and you maybe used this file two time!
Upvotes: 2 [selected_answer]
|
2018/03/19
| 1,185 | 4,017 |
<issue_start>username_0: I have an object that contains multiple datasets objects that can contain an array of items or multiple arrays within this object. Without knowing whether it is a multiple object array, how can I pass it to function, that is expecting to 'forEach' depending on the amount of the arrays?
To make it more clear see data within storage:
```
var storage = {
dataset1: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{ // two objects here
data: [2, 4, 5, 6, 10]
},
{
data: [200, 100, 300, 600]
}
]
},
dataset2: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{ // one object here
data: [200, 100, 300, 600]
}]
}
};
```
with above I am trying to pass them as parameters:
```
$(".change").click(function() {
var temp = $(this).text();
addChartData(myChart, storage[temp].labels, storage[temp].storageDatasets.data); // how to get last parameter correctly, based on the amount of data objects?
});
```
and process using this function:
```
function addChartData(chart, labels, data) {
chart.data.labels = labels;
chart.data.datasets.forEach(dataset => {
dataset.data = data;
});
chart.update();
}
```
The problem is with the amount of data objects within storageDatasets in var storage. Some will have multiple, some one. How can I loop through them to pass them as argument so addChartData function will run correctly.
```js
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 0, 80, 81, 56, 85, 40],
fill: false
}]
}
};
var storage = {
dataset1: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{
data: [2, 4, 5, 6, 10]
},
{
data: [200, 100, 300, 600]
}
]
},
dataset2: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{
data: [200, 100, 300, 600]
}]
}
};
function addChartData(chart, labels, data) {
chart.data.labels = labels;
chart.data.datasets.forEach(dataset => {
dataset.data = data;
});
chart.update();
}
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, config);
$(".change").click(function() {
var temp = $(this).text();
addChartData(myChart, storage[temp].labels, storage[temp].storageDatasets.data);
console.log(temp);
});
```
```css
.chart-container {
height: 300px;
width: 500px;
position: relative;
}
canvas {
position: absolute;
}
```
```html
dataset1
dataset2
```<issue_comment>username_1: Javascript has a built in object called arguments...
It is avavilable in every function...It is actually a list....
So you can loop through it to get you job done....
```
function name (arg1,arg2,.....) {
for (var i=0;i
```
Upvotes: 0 <issue_comment>username_2: Instead of dealing with a variable number of parameters, it may be easier to pass the whole of `storageDatasets` to your function as a single param:
```js
$(".change").click(function() {
var temp = $(this).text();
addChartData(
myChart,
storage[temp].labels,
storage[temp].storageDatasets
);
});
function addChartData(chart, labels, datasets) {
chart.labels = labels;
chart.datasets = datasets; // per comments below, this is a direct assignment, no iteration necessary
chart.update();
}
```
But if you needed to merge two datasets into one, for example, then you would need to iterate through storageDatasets:
```
function addChartData(chart, labels, datasets) {
chart.labels = labels;
chart.datasets = [{data:[]}];
datasets.forEach(set=> {
chart.datasets[0].data = chart.datasets[0].data.concat(set.data);
})
// chart.datasets now contains a single object containing concatenated data from all the datasets passed in
chart.update();
}
```
Upvotes: 2 [selected_answer]
|
2018/03/19
| 288 | 1,026 |
<issue_start>username_0: Is there any reason that this attribute tag a[h2]{color:orange;} wont work in css? I Cant seem to get the attribute tag to work for any elements.<issue_comment>username_1: Did you make a reference in the html page to your stylesheet?
If this is done, check whether the element has an h2 attribute. Something like
Upvotes: 0 <issue_comment>username_2: ```
a[h2] {
color:orange;
}
```
Means that all tags that have an attribute called `h2` will be coloured orange; i.e. `hello, world!`.
This is probably not what you want, both because this would be invalid HTML (`h2` is not an attribute of , and custom attributes are only allowed if they start with `data-`), but also because I am assuming that you want to target tags that are *inside* of your tags.
To that, use the following code:
```
a h2 {
color:orange;
}
```
That will colour all tags inside of tags orange.
Read more about CSS Selectors [here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors).
Upvotes: 1
|
2018/03/19
| 524 | 1,630 |
<issue_start>username_0: I have a dictionary:
```
{'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
```
I wish to pop the list values that are outside of the UK, therefore taking the first value within the lists and comparing to see if it is equal to 'UK'.
I currently have:
```
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
k.pop(v)
```
I know after the else is wrong but need help!
I wish for the dict to look like this once finished popping values that aren't equal to "UK".
```
{'dict': [['UK', '3', '-9']]}
```<issue_comment>username_1: You can use a list comprehension to filter out based on the first element
```
>>> data = {'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
>>> {'dict': [i for i in data['dict'] if i[0] == 'UK']}
{'dict': [['UK', '3', '-9']]}
```
Upvotes: 1 <issue_comment>username_2: A nested dict and list expression can do this:
```
{k: [i for i in v if i[0] == 'UK'] for k,v in insideUK.items()}
```
If you really want to do it with a for-loop and change the list in-place, you could do something like this:
```
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
v.remove(i)
```
But it is discouraged strongly to change the list you are iterating over during the iteration
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can also do it using the `filter` function:
```
d = {'dict': list(filter(lambda i: 'UK' in i, d['dict']))}
print(d)
```
Output:
```
{'dict': [['UK', '3', '-9']]}
```
Upvotes: 1
|
2018/03/19
| 786 | 2,618 |
<issue_start>username_0: I'm trying to start writing my Qt project inside JetBrains' Clion but I need to link some libraries in my Cmake file first. There's no problem when trying to find packages like Qt5Core, Qt5Widgets, Qt5Gui but when it come to finding Qt5Charts an error is thrown:
>
>
> >
> > By not providing "FindQt5Charts.cmake" in CMAKE\_MODULE\_PATH this project has asked CMake to find a package configuration file
> > provided by "Qt5Charts", but CMake did not find one.
> >
> >
> >
>
>
> Could not find a package configuration file provided by "Qt5Charts"
> with any of the following names:
>
>
>
> ```
> Qt5ChartsConfig.cmake
> qt5charts-config.cmake
>
> ```
>
> Add the installation prefix of "Qt5Charts" to CMAKE\_PREFIX\_PATH or
> set "Qt5Charts\_DIR" to a directory containing one of the above
> files. If "Qt5Charts" provides a separate development package or
> SDK, be sure it has been installed.
>
>
>
[This is my CMake file right now.](https://pastebin.com/ZbRJtLT2)
All packages are installed via the Qt's Linux(ubuntu) maintanence tool.
Any ideas how to help Cmake find the Charts module ?<issue_comment>username_1: Typically when including Qt5 in a project I use the follow basic script for CMake, though I should note I haven't tested this on Linux.
```
cmake_minimum_required(VERSION 3.10.0 FATAL_ERROR)
project()
find\_package(Qt5 REQUIRED COMPONENTS Core Gui Widgets Charts)
# set your project sources and headers
set(project\_sources src/blah.cpp)
set(project\_headers include/headers/blah.h)
# wrap your qt based classes with qmoc
qt5\_wrap\_cpp(project\_source\_moc ${project\_headers})
# add your build target
add\_executable(${PROJECT\_NAME} ${project\_sources} ${project\_headers} ${project\_source\_moc})
# link to Qt5
target\_link\_libraries(${PROJECT\_NAME}
PUBLIC
Qt5::Core
Qt5::Gui
Qt5::Widgets
Qt5::Charts)
# require C++ 14
target\_compile\_features(${PROJECT\_NAME} PUBLIC cxx\_std\_14)
```
When configuring your project via cmake, you just need to pass in the path to you qt5 installation directory (cmake variable name is `Qt5_DIR`) that contains the `Qt5Config.cmake` file and then cmake should be able to find the rest of the components that you request.
Also double check that `Qt5Charts` was installed, not sure if it's installed by default.
Upvotes: 1 <issue_comment>username_2: Using the following and see if it helps:
>
> sudo apt install libqt5charts5-dev
>
>
>
Src: <https://stackoverflow.com/a/46765025>
Upvotes: 2 <issue_comment>username_3: Maybe try this?
```
sudo apt install libqt5charts5-dev
```
Upvotes: 0
|
2018/03/19
| 960 | 4,056 |
<issue_start>username_0: So far I've seen how to set expiration for the client webapp's cookie (thank you v0id): [IdentityServer4 cookie expiration](https://stackoverflow.com/questions/49325793/identityserver4-cookie-expiration)
There are actually two cookies used by IdentityServer4 - the client cookie and server cookie ("idsrv").
If I set the client cookie expiration as given here:
[IdentityServer4 cookie expiration](https://stackoverflow.com/questions/49325793/identityserver4-cookie-expiration/49337801#49337801)
then when I close the browser and go back to a client webapp page where I need to be authorized, I get access denied because the browser session no longer has the server cookie.
So I need a way to set the "idsrv" cookie expiration to be the same as the client.
Currently, the best way I see to set the server cookie (it is being ignored or dropped somehow) is the following code block in the IdentityServer4 host Startup.cs / ConfigureServices() method:
```
services.AddIdentityServer(options =>
{
options.Authentication.CookieLifetime = new TimeSpan(365, 0, 0, 0);
options.Authentication.CookieSlidingExpiration = true;
})
```
That should set the cookie's expiration to one year later. However, in Chrome developer tools under the Application tab, cookies, I see that it still has an expired expiration default date in 1969.
I downloaded the IdentityServer4 project source, removed the nuget package, and added the source project to my solution so I could debug through it.
I see that it gets the expiration I gave it in the ConfigureInternalCookieOptions.cs / Configure() method. It's matching the DefaultCookieAuthenticationScheme inside as well / applying the properties. I haven't found anything specific to IdentityServer that would ignore the expiration date I've set, but it still has the 1969 expiration.
Edit: I've attempted to set the cookie persistent in the IdentityServer host's AccountController as follows (interestingly enough, Microsoft has a good article around using authenticationproperties without using AspNet Identity here: <https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x> - it is sending information in a cookie, "scheme" is just the cookie name):
In the ExternalLoginCallback():
```
if (id_token != null)
{
props = new AuthenticationProperties();
props.ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration);
props.IsPersistent = true;
props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
```
None of the server side cookies have their expiration set (the AccountOptions RememberMeLoginDuration is also set to 365 days). Both "idsrv" and "idsrv.session" still have a 1969 expiration.<issue_comment>username_1: You can configure Identity Server's authentication cookie lifetime when you register Identity Server in your `Startup.cs`, like this:
```
services.AddIdentityServer(options =>
{
options.Authentication.CookieLifetime = TimeSpan.FromHours(10);
})
```
Note: you also need to indicate that the cookie should be persistent when logging the user in. If you're using the Quickstart UI, then you have to tick the "Remember me" checkbox on the login screen to get a persistent cookie. Or you can modify the code to always issue a persistent cookie - something like this:
```
HttpContext.SignInAsync(subject, name, new AuthenticationProperties{ IsPersistent = true});
```
Upvotes: 3 <issue_comment>username_2: I set the IdentityServer cookie configuration by using the following code. When I then store the cookie via (rememeber me) option in IdentityServ
```
// Set identity cookie options
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest;
});
```
Upvotes: 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.