date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/16
| 403 | 1,495 |
<issue_start>username_0: I know there had already been similar discussions on such naming conventions. However, I'm having problem with plural acronyms.
```
public List findAllDvds(DiscHolder holder) {}
public List findAllDvd(DiscHolder holder) {}
```
Assuming that I have decided to use CamelCase for acronyms, which of the two is generally more acceptable?
Edit
----
I am aware this will invite opinion-based answers, but sometimes when you are in doubt, you just need people to give advises and feedbacks.
To add on, the confusing part here is that `findAllDvds` can imply a new acronym `DVDS`, and it can be considered confusing.<issue_comment>username_1: The first (`findAllDvds`). The second (`findAllDvd`) is simply incorrect, "all" implies more than one, but "Dvd" is singular in English.
Re your edit:
>
> the confusing part here is that `findAllDvds` can imply a new acronym `DVDS`, and it can be considered confusing
>
>
>
Since the "all" implies multiple, the "s" on "Dvds" reads as a plural, not part of the acronym. If it really were DVDS, the name would be `findAllDvdss` or similar.
It's said that in computer science, there are three hard problems: Cache invalidation, and naming things. (Off-by-one errors are just common, not hard.)
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is a really opinion based question and could be closed.
However, this should be the correct version:
```
public List findAllDvds(DiscHolder holder) {}
```
Upvotes: 2
|
2018/03/16
| 841 | 3,443 |
<issue_start>username_0: I'm a newbie in C# and would like to know if, having two classes in the same namespace, I can call a constructor of one in a constructor of the other one?
For example:
```
class Company
{
// COMPANY DETAILS
Person owner;
string name, website;
Company()
{
this.owner = new Person();
}
}
```
The above returns "Person.Person()" is inaccessible due to its protection level. Person class looks like this:
```
class Person
{
// PERSONAL INFO
private string name, surname;
// DEFAULT CONSTRUCTOR
Person()
{
this.name = "";
this.surname = "";
}
}
```
Is there anything I'm missing here? Shouldn't the constructor be accessible from wherever in the same namespace?<issue_comment>username_1: You defined the constructor as **private** hence you cannot access it.
The compiler even gives you a [hint](https://learn.microsoft.com/dotnet/csharp/language-reference/compiler-messages/cs0122):
```
error CS0122: 'Person.Person()' is inaccessible due to its protection level
```
The [C# 6.0 specification](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/) state for [access modifiers](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/classes#access-modifiers):
>
> When a *class\_member\_declaration* does not include any access modifiers, **private** is assumed.
>
>
>
whereas a [*class\_member\_declaration*](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/classes#class-members) is specified as
```
class_member_declaration
: ...
| constructor_declaration
| ...
;
```
Only [default constructors](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/classes#default-constructors) are public by default when the class is **not** defined as abstract.
Therefore change
```
Person() { }
```
to
```
public Person() { }
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: In C# we have access modifiers. The current options are
```
Public - everyone has access
Internal - can only access from same assemnly
Protected - only the class and classes derived from the class can access members marked as protected
Protected Internal - accessible from any class in the same assembly or from any class derived from this class in any assembly
Private protected - only accessible from a class that is derived from this class AND in the same assembly
Private - only accessible in the declaring class
```
There's a new one coming but let's leave that out.
What is important for your question is what things defualt to in code. A class with no access modifiers specified will default to internal. So anyone in the same assembly can see it. A class member, so a field, property, method, or **constructor** will default to private meaning only that class has access to it.
So for you you can leave your class declaration as it is if both your classes are in the same assembly (not Namespace those don't matter to access modifiers) so the default Internal access modifier is fine.
You need to change your Constructor to have an explicit internal or public modifier so you can access it. Just a note if you class is internal you can mark methods etc as public but they will still only be able to accessed from inside that assembly as the encapsulatong class is internal.
Upvotes: 2
|
2018/03/16
| 545 | 1,947 |
<issue_start>username_0: I have a `Model` I need to get the next record id which is going to be create before create that object in my model like:
```
MyModel.last.id #=> 10
MyModel.last.destroy
MyModel.last.id #=> 9, so (Model.last.id + 1) would be 10... but...
MyModel.create #=> 11, my next id was actually 11
```
Can you please suggest a better way to solve my problem?
Thanks<issue_comment>username_1: You are looking for the table's AUTO\_INCREMENT value. MySQL stores such metadata in the [INFORMATION\_SCHEMA](https://dev.mysql.com/doc/refman/5.7/en/information-schema.html) database. The AUTO\_INCREMENT values can be found in the [TABLES](https://dev.mysql.com/doc/refman/5.7/en/tables-table.html) table. The table contains one entry for each database and table.
I don't think Rails or the MySQL gem provide any built-in method for fetching it.
I have used something like this in one of my previous projects:
```
# config/initializers/auto_increment.rb
module AutoIncrement
def auto_increment_value
connection.execute(<<-SQL.squish).first[0]
SELECT `AUTO_INCREMENT`
FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE `TABLE_SCHEMA` = '#{connection.current_database}'
AND `TABLE_NAME` = '#{table_name}'
SQL
end
end
ActiveRecord::Base.extend(AutoIncrement)
```
You can then execute:
```
MyModel.auto_increment_value
```
and it will return the current value for the table's AUTO\_INCREMENT value, e.g. `11`.
Note that it is not safe to use that value as an explicit ID for your record. You should let MySQL handle the assignment of new IDs – that's what AUTO\_INCREMENT is for.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Why worry about the id? If you have some other reasons for a contiguous number, use another field and do some select max on a before\_create.
FWIW, MySQL, and Mariadb auto increment only resets on a database restart, which avoids race situations.
Upvotes: 1
|
2018/03/16
| 1,668 | 5,571 |
<issue_start>username_0: I have to work using binary formated numbers and I'm wondering if there's a simple and easy built in way to use them. I am aware of the `bytearray` but it works with byte type and it is absolutely not intuitive (at least for me).
So, is there any way of handling binary numbers (assign them to a variable, perform bit operations, transform to ASCII, etc.) easily? If not built in, at least a nice and understandable module.
Just in case what I'm asking is not clear enough, here is an example of what I picture a nice way for handling binary would be:
```
bin_num1 = Binary('100')
bin_num2 = Binary(0)
print(bin_num1.and(bin_num2)) # Prints 000
```
I'm using Python 3.6 but any solution in any version would do the job.
**Edit 1:**
As pointed out in the comments, `0bXXX` could work to get a `type int` from a binary just as `bin()` would do the opossite. Still, this would be working with integers, the result returned would be an integer and character conversion (e.g. `bin('a')`) would be an error and require further conversions (from str to int and then to binary).<issue_comment>username_1: **Assign binary numbers to a variable:** You can use integer variables to hold the binary values. They can be created from the binary representation using the `0b` prefix.
```
x = 0b110 # assigns the integer 6
```
**Perform bit operations:** The bit operations `&` (*and*), `|` (*or*), `^` (*xor*), `~` (*not*) can be used on integers and perform the respective binary operations.
```
x = 0b110
y = 0b011
z = x & y # assigns the integer 0b010 (2)
```
**Transform them to ASCII:** To convert a number to ASCII you can use `chr`.
```
x = 0b1100001 # assigns 97
print(chr(x)) # prints 'a'
```
**Transform from ASCII:** If you use integers to represent the binary values you can use `ord` to convert ASCII values.
```
s = 'a'
x = ord(a) # assigns the integer 0b1100001 (97)
```
**Print integer in binary:** An integer can be printed in binary using the string format method on the string `"{0:b}"`.
```
x = 0b1100001
s = "{0:b}".format(x)
print(s) # prints '1100001'
```
If you do not mind the `0b` prefix you can also use `bin`.
```
x = 0b1100001
s = bin(x)
print(s) # prints '0b1100001'
```
**Read integer from binary string:** The `int` function allows you to specify a base that is used when parsing strings.
```
x = int("1100001", 2) # assigns the integer 0b1100001 (97)
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can subclass int and write a `__new__` to parse desired input as a binary to the integer. I currently have char and a string with zeros and ones as supported.
You can now just use it as an integer with all its methods for binary operations. It only keeps converting to integer if you use these methods. Therefore you have to override all these methods with magic functions (the double underscores, or dunders) to keep returning your Binary class. This can be repetitive, but with some other python magic it can be done quite concise.
NB. I might have missed some dunders (intentially or not), this is a good reference if you want to know more: <https://www.python-course.eu/python3_magic_methods.php>
```
class Binary(int):
def __new__(self, val):
if type(val) is str:
if len(val) > 1:
val = int(val, 2)
else:
val = ord(val)
return super().__new__(self, val)
dunders_binary = "and rand add radd sub rsub mul rmul lshift rlshift " + \
"rshift rrshift and rand or ror xor rxor"
for dunder in ("__%s__" % s for s in dunders_binary.split()):
locals()[dunder] = lambda self, other, __f=dunder: \
self.__class__(getattr(super(), __f)(other))
dunders_unary = "neg pos invert"
for dunder in ("__%s__" % s for s in dunders_unary.split()):
locals()[dunder] = lambda self, __f=dunder: \
self.__class__(getattr(super(), __f)())
def __repr__(self):
return bin(self)
def __str__(self):
return bin(self)
```
Upvotes: 1 <issue_comment>username_3: It is amusing to ponder how integral binary/bytes were to programmers of yesteryear. Today's 'tangential' programmers using Python can go really far without worrying too much about what is happening inside the computers. Assembler code? Nah!
I am new to Python and found it interesting that it does not support unsigned integers.
It might be useful for the OP to learn or recall that a hexadecimal byte is made up of two 'nibbles'.
The Python documentation contains a section "[Bitwise Operations on Integer Types](https://docs.python.org/3.6/library/stdtypes.html#bitwise-operations-on-integer-types)".
The following program might be of interest to the OP and others new Python programmers:
```
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: bits and bytes and ascii
#--------*---------*---------*---------*---------*---------*---------*---------*
import sys
while True:
for i in range(0, 16):
print(i, i.bit_length())
print(255, (255).bit_length())
print(256, (256).bit_length())
print((16).to_bytes(1, byteorder='big',signed=False))
print((255).to_bytes(1, byteorder='big',signed=False))
b = (255).to_bytes(1, byteorder='big',signed=False)
print(b)
print(b[0])
print("\nAscii Table")
for i in range(0, 256):
b = (i).to_bytes(1, byteorder='big',signed=False)
print(b[0], b, ord(b), chr(ord(b)))
sys.exit()
```
Upvotes: 1
|
2018/03/16
| 1,047 | 3,495 |
<issue_start>username_0: I am trying to get the weight matrix of my hidden\_layer2 and print it.
It seems like I am able to get the weight matrix, but I am not able to print it.
When using `tf.Print(w, [w])` it prints nothing.
When using `print(tf.Print(w,[w])` it prints at least the info about the tensor:
```
Tensor("hidden_layer2_2/Print:0", shape=(3, 2), dtype=float32)
```
I also tried to use `tf.Print()` outside of the **with**-Statement, same result.
Full code is here, I am just processing random data in a feed-forward NN: <https://pastebin.com/KiQUBqK4>
A part of my Code:
```
hidden_layer2 = tf.layers.dense(
inputs=hidden_layer1,
units=2,
activation=tf.nn.relu,
name="hidden_layer2")
with tf.variable_scope("hidden_layer2", reuse=True):
w = tf.get_variable("kernel")
tf.Print(w, [w])
# Also tried tf.Print(hidden_layer2, [w])
```<issue_comment>username_1: Try to do this,
```
w = tf.get_variable("kernel")
print(w.eval())
```
Upvotes: 0 <issue_comment>username_2: I believe there are multiple issues to be tackled here.
1. Running eval() should be accompanied by a session. As suggested in [In TensorFlow, what is the difference between Session.run() and Tensor.eval()?](https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval), `.eval()` expects a default session to be running which was not likely in your case earlier. So, the best option here was to precede the code with a session. From your comment, we can see that this is done.
2. The variables in the hidden layers (i.e. weights/kernels) need to be initialized once the graph is complete. Hence, you might want to use something similar to this:
```
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
with tf.variable_scope("hidden_layer2", reuse=True):
w = tf.get_variable("kernel")
print(w.eval(session=sess))
```
Upvotes: 2 <issue_comment>username_3: I took a different approach. First I list all the trainable variables and use the index of the required variable and run it using the current session. The code is attached below:
```py
variables = tf.trainable_variables()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
print("Weight matrix: {0}".format(sess.run(variables[0]))) # For me the variable at the 0th index was the one I required
```
Upvotes: 0 <issue_comment>username_4: An example on how to print weights per layer in `tensorflow.js`:
```
//
const model = tf.sequential();
...
// kernel:
model.layers[0].getWeights()[0].print()
// bias:
model.layers[0].getWeights()[1].print()
```
Upvotes: 0 <issue_comment>username_5: **UPDATED FOR TENSORFLOW 2.X**
Starting from TensorFlow 2.0 (>= 2.0), since the `Session` object has been removed and the recommended high-level backend is Keras, the way to do get the weights is:
```
from tensorflow.keras.applications import MobileNetV2
model = MobileNetV2(input_shape=[128, 128, 3], include_top=False) #or whatever model
print(model.layers[0].get_weights()[0])
```
Upvotes: 3 <issue_comment>username_6: As an update to username_5 answer in Tensorflow 2, biases can be accessed also using `get_weights()`, specifically `get_weights()[1]`.
To access and print weights and biases for example in feedforward network:
```
for layer in self.model.layers:
print(layer.get_weights()[0]) # weights
print(layer.get_weights()[1]) # biases
```
Upvotes: 0
|
2018/03/16
| 1,023 | 3,732 |
<issue_start>username_0: I wanted to upload GZip compressed JSON file on S3 bucket.I am struggling with this, can someone help me on this.As, I am trying to use zlib npm module for Gzip compression of JSON file but coudn't get a method to achieve this.
Below is my upload method to upload Gzip compressed JSON file on S3 :
```
var uploadEntitlementDataOnS3 = function(next, event,
jsonFileContent, filePath, results) {
console.log("uploadEntitlementDataOnS3 function
started",jsonFileContent);
var bufferObject = new
Buffer.from(JSON.stringify(jsonFileContent));
var s3 = new AWS.S3();
var params = {
Bucket: configurationHolder.config.bucketName,
Key: filePath,
Body: bufferObject,
CacheControl: 'no-cache',
ContentType: "application/json",
ContentEncoding: 'gzip'
}
s3.putObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
next(err);
} else {
next(null, filePath);
}
});
};
```
Thanks<issue_comment>username_1: Try to do this,
```
w = tf.get_variable("kernel")
print(w.eval())
```
Upvotes: 0 <issue_comment>username_2: I believe there are multiple issues to be tackled here.
1. Running eval() should be accompanied by a session. As suggested in [In TensorFlow, what is the difference between Session.run() and Tensor.eval()?](https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval), `.eval()` expects a default session to be running which was not likely in your case earlier. So, the best option here was to precede the code with a session. From your comment, we can see that this is done.
2. The variables in the hidden layers (i.e. weights/kernels) need to be initialized once the graph is complete. Hence, you might want to use something similar to this:
```
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
with tf.variable_scope("hidden_layer2", reuse=True):
w = tf.get_variable("kernel")
print(w.eval(session=sess))
```
Upvotes: 2 <issue_comment>username_3: I took a different approach. First I list all the trainable variables and use the index of the required variable and run it using the current session. The code is attached below:
```py
variables = tf.trainable_variables()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
print("Weight matrix: {0}".format(sess.run(variables[0]))) # For me the variable at the 0th index was the one I required
```
Upvotes: 0 <issue_comment>username_4: An example on how to print weights per layer in `tensorflow.js`:
```
//
const model = tf.sequential();
...
// kernel:
model.layers[0].getWeights()[0].print()
// bias:
model.layers[0].getWeights()[1].print()
```
Upvotes: 0 <issue_comment>username_5: **UPDATED FOR TENSORFLOW 2.X**
Starting from TensorFlow 2.0 (>= 2.0), since the `Session` object has been removed and the recommended high-level backend is Keras, the way to do get the weights is:
```
from tensorflow.keras.applications import MobileNetV2
model = MobileNetV2(input_shape=[128, 128, 3], include_top=False) #or whatever model
print(model.layers[0].get_weights()[0])
```
Upvotes: 3 <issue_comment>username_6: As an update to username_5 answer in Tensorflow 2, biases can be accessed also using `get_weights()`, specifically `get_weights()[1]`.
To access and print weights and biases for example in feedforward network:
```
for layer in self.model.layers:
print(layer.get_weights()[0]) # weights
print(layer.get_weights()[1]) # biases
```
Upvotes: 0
|
2018/03/16
| 240 | 928 |
<issue_start>username_0: I haven't encountered any where in EF examples, but is it safe to update multiple tables in one go as below
```
using(var db = new MyDbContext(opts))
{
var record = db.Record.FirstOrDefault(x => x.Id == id);
if(record == null) return;
record.FieldN = ...
db.Update(record);
db.Other.RemoveRange(db.Other.Where(x => x.EntityId == id));
db.SaveChanges();
}
```<issue_comment>username_1: Yes, it is safe.
`db.SaveChanges()` will execute all your UPDATE / INSERT / DELETE queries in atomic transaction. It will use current transaction or create a new one.
Upvotes: 1 <issue_comment>username_2: Yes but sometimes EF executes what you asked in the wrong order and it explodes, for example deleting 2 things where one is Dependent on the other.
Solution is to just separate those by multiple calls to SaveChangesAsync() (which you should really be using instead of SaveChanges).
Upvotes: 0
|
2018/03/16
| 1,680 | 5,498 |
<issue_start>username_0: I am using [Ajv](http://epoberezkin.github.io/ajv/) in my project. I am trying to add a custom keyword by the help of `ajv.addKeyword` api. I am able to add keyword by doing this (borrowed from docs):
```
var ajv = new Ajv({
$data: true
});
ajv.addKeyword('range', {
type: 'number',
compile: function(sch, parentSchema) {
var min = sch[0];
var max = sch[1];
return parentSchema.exclusiveRange === true ? function(data) {
return data > min && data < max;
} : function(data, dataPath, parentData, parentDataProperty) {
return data >= min && data <= max;
}
}
});
var schema = {
"properties": {
"smaller": {
"type": "number"
},
"larger": {
"type": "number",
"range": [2, 10]
}
}
};
var validData = {
smaller: 15,
larger: 17
};
let validateData = ajv.compile(schema);
validateData(validData);
console.log('Errors after validations --> ', validateData.errors)
```
Everything is working fine. Now I need to use [`$data`](http://epoberezkin.github.io/ajv/#data-reference) cause data for my custom field will be the value of some other field. To achieve it this is what I tried with my schema:
```
var schema = {
"properties": {
"smaller": {
"type": "number"
},
"larger": {
"type": "number",
// "range": [2, 10],
"range": {
"$data": "1/myRange" // referencing to myRange
}
},
"myRange": {
type: "array",
items: {
type: "number"
}
}
}
};
```
But it looks likes custom fields are not supported with `$data` ref yet. As mentioned in the docs, only following fields are supported for $data ref.
>
> $data reference is supported in the keywords: const, enum, format,
> maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength /
> minLength, maxItems / minItems, maxProperties / minProperties,
> formatMaximum / formatMinimum, formatExclusiveMaximum /
> formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.
>
>
>
One way to get the value is, I use parameters of validate function `data, dataPath, parentData, parentDataProperty` and write logic to extract value of field defined by `$data` ref. But I am not sure this is a right way to achieve it or not. Can anyone please help me on this? Here's the [plunkr to play](http://plnkr.co/edit/fNBeJzTOHMCC7g7tgSDP). Thanks.<issue_comment>username_1: After digging [documentation](https://github.com/epoberezkin/ajv/blob/797dfc8c2b0f51aaa405342916cccb5962dd5f21/CUSTOM.md#define-keyword-with-validation-function) for a while finally I made it working. It's always good to share the solution for posterior readers. This is what I have done:
```
// Code goes here
console.clear();
var ajv = new Ajv({
$data: true
});
ajv.addKeyword('range', {
type: 'number',
errors: true,
$data: true, // important part
validate: function(schema, data, parentSchema) {
const {
exclusiveRange: isExclusive
} = parentSchema;
const [min, max] = schema;
if (isExclusive) {
return data > min && data < max;
}
return data >= min && data <= max;
}
});
var schema = {
"properties": {
"smaller": {
"type": "number",
"maximum": {
"$data": "1/larger"
}
},
"larger": {
"type": "number",
// "range": [2, 10],
"range": {
"$data": "1/myRange"
},
"exclusiveRange": true
},
"myRange": {
type: "array",
items: {
type: "number"
}
}
}
};
var validData = {
smaller: 3,
larger: 7,
myRange: [2, 10]
};
let validateData = ajv.compile(schema);
validateData(validData);
console.log(ajv);
console.log('Errors after validations --> ', validateData.errors)
```
The salient option is `$data` in definition.It needs to be set `true`. Here's the working [plunkr](http://plnkr.co/edit/1kTwtnOQaiTC05lDVogG?p=preview)
Upvotes: 3 <issue_comment>username_2: Also for anybody now finding this, just to add to @hitesh's answer if you want to add errors to the custom keyword you do so by attaching them to the validation function. I have included Hitesh's answer with the update for adding an error message
```
// Code goes here
console.clear();
var ajv = new Ajv({
$data: true
});
ajv.addKeyword('range', {
type: 'number',
errors: true,
$data: true, // important part
validate: function myCustomKeyword(schema, data, parentSchema) {
if (
myCustomKeyword["errors"] === undefined ||
myCustomKeyword["errors"] === null
)
myCustomKeyword["errors"] = [];
const {
exclusiveRange: isExclusive
} = parentSchema;
const [min, max] = schema;
if (isExclusive) {
return data > min && data < max;
} else {
myCustomKeyword["errors"].push({
keyword: "range",
message: `range message`,
params: {
keyword: "range",
},
});
}
return data >= min && data <= max;
}
});
var schema = {
"properties": {
"smaller": {
"type": "number",
"maximum": {
"$data": "1/larger"
}
},
"larger": {
"type": "number",
// "range": [2, 10],
"range": {
"$data": "1/myRange"
},
"exclusiveRange": true
},
"myRange": {
type: "array",
items: {
type: "number"
}
}
}
};
var validData = {
smaller: 3,
larger: 7,
myRange: [2, 10]
};
let validateData = ajv.compile(schema);
validateData(validData);
console.log(ajv);
console.log('Errors after validations --> ', validateData.errors)
```
Upvotes: 0
|
2018/03/16
| 533 | 2,073 |
<issue_start>username_0: I have two pages, page one is `loginPage`, another is `MainViewPage`.
I wanna transfer `userInfo` (`UserName` and `<PASSWORD>`) from page one to two, I'm using VIPER structure.
I already get the `userInfo` in the second page, but when I'm using `Presenter` function to update `UILabel` in `SecondPage`, the progress is broken, it shows following error:
>
> Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
>
>
>
```
import Foundation
import UIKit
class MainViewModuleView: UIViewController, MainViewModuleViewProtocol
{
var presenter: MainViewModulePresenterProtocol?
@IBOutlet weak var userInfo: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// print(NSHomeDirectory()as NSString)
}
func updateLabel(text:String){
print(text)
userInfo.text = text
}
}
```
Here is my `Presenter`:
```
import Foundation
class MainViewModulePresenter: MainViewModulePresenterProtocol, MainViewModuleInteractorOutputProtocol
{
weak var view: MainViewModuleViewProtocol?
var interactor: MainViewModuleInteractorInputProtocol?
var wireFrame: MainViewModuleWireFrameProtocol?
var delegate: MainModuleDelegate?
init() {}
}
extension MainViewModulePresenter: MainModuleDelegate{
func sendLoginUser(userName: String) {
print("MainViewModulePresenter?.sendLoginUser: " + userName)
let text = userName
view?.updateLabel(text: text)
}
}
```
The text in both `Presenter` and `MainView` has value, but when it call `updateLabel` function, the progress was broken. The Code of this Demo in [this repository](https://github.com/paboo199148/VIPERDemo)<issue_comment>username_1: I think it's a case of the MainViewModuleView not being loaded/instantiated from the storyboard.
It seems to lose its connection with the storyboard shortly afterwards.
Upvotes: 1 <issue_comment>username_2: Your label is uninitialized during the assignment. I think your method is being called before `viewDidLoad`.
Upvotes: 0
|
2018/03/16
| 331 | 1,045 |
<issue_start>username_0: How to change *hour* part in localdb timestamp column 4 hour back.
I have a table JOB\_MONITOR
```
JOBID JOB_TYPE JOB_STATS START_DATE
3 BIN Management SUCCESSFUL 3/15/2018 5:50:29.269000 PM
```
I want to set START\_DATE value to be 4 hr back like 3/15/2018 1:50:29.269000 PM
My server is in St. louis so when i do it with sysdate`-4/24. it update column value with respect to st louis time zone something like 3/15/2018 4:42:26.426000 AM..which i don't want. Hope now question is clear to everyone..
I want to set START\_DATE value to be 4 hr back irrespective of time zone. just subtract 4 hr. I need this condition to test data locally.<issue_comment>username_1: I think it's a case of the MainViewModuleView not being loaded/instantiated from the storyboard.
It seems to lose its connection with the storyboard shortly afterwards.
Upvotes: 1 <issue_comment>username_2: Your label is uninitialized during the assignment. I think your method is being called before `viewDidLoad`.
Upvotes: 0
|
2018/03/16
| 1,278 | 4,492 |
<issue_start>username_0: I'm trying to create a modal but I'm getting this error only when I close it:
```
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"
found in
---> at resources\assets\vue\PanelDesconectarModal.vue
at resources\assets\vue\PanelDrawer.vue
at resources\assets\vue\PanelRoot.vue
```
PanelDesconectarModal.vue
```
Desconectar
Você tem certeza que deseja desconectar-se?
Cancelar
Desconectar
export default {
name: 'panel-desconectar-modal',
props: ['value'],
methods: {
closeDialog() {
this.value = false;
},
desconectar() {
this.closeDialog();
window.location = this.$route + '/panel/desconectar';
}
}
}
```
Using ProgressDesconectarModal.vue, showDesconectar is a data variable
```
```<issue_comment>username_1: You should not mutate the props in your child component. You can only mutate the object but not primitives. So, you can use data option or a computed property:
```
data() {
return {
childValue: this.value; // initialize props value
}
}
```
Now, you can change the `childValue`:
```
closeDialog() {
this.childValue = false;
},
```
Make sure to use `childValue` everywhere inside your child component instead of `value` props.
Upvotes: 2 <issue_comment>username_2: This happens because you have props `value` in your `v-model`.
Do not do that, as that will mutate the prop(`value`) when `v-model` changes (you should only change `data` values with `v-model` afaik, but in this case, you don't even need additional `data` variable).
Since vuejs [v2.3.0, it is suggested to `emit` value to the parent](https://v2.vuejs.org/v2/guide/components.html#sync-Modifier), so that parent changes it, and it is then passed to child component.
---
So all you have to do is:
in `v-dialog` component
remove `v-model` and replace it with `:value="value" @input="$emit('input')"`
And your function:
```
closeDialog() {
this.$emit('input');
}
```
In `panel-desconectar-modal` component use `v-model="showDesconectar"`.
---
This will work [because](https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events):
>
>
> ```
> is syntactic sugar for:
>
>
> ```
>
>
```
v-bind:value="something"
v-on:input="something = $event.target.value">
```
Here is [working example pen](https://codepen.io/anon/pen/XZWRJY) which I provided in an [answer](https://stackoverflow.com/a/48503369/1981247) to [similar question](https://stackoverflow.com/q/48490440/1981247).
Upvotes: 6 [selected_answer]<issue_comment>username_3: This is really the moment to ask yourself ***"Do I really need a prop? Can I do this with data? Am I here because I mistakenly put some state in Vue component?"***
If you're the author of the page and the component, and the component only appears once on the page, there is **no good reason to use props.** If you need props because the component is repeated for all the lines in an array, make the prop just the array index, so the component can directly modify the source array in the store. Vue components should not contain state, especially state that needs to be shared, and do not enjoy being tightly bound *to each other*. The parent-child relationship arises out of the chance of their placement in the DOM tree, (children occur inside the markup of parents). This is like a chance meeting in a nightclub. The child may have nothing else to do with the parent. The hierarchy of your source data should be expressed, independently of your markup, in the structure of your store. Your Vue components, where possible, should have an intimate two way relationship with the store, and **not talk much to each other :-)**
Upvotes: 1 <issue_comment>username_4: In the [relevant Vue doc](https://v2.vuejs.org/v2/guide/forms.html) they don't have examples with default values, so these answers are to be found elsewhere. I needed a solution to create a component with a default value, but the input would always spring back to what it was before when it loses focus, or it gave the "avoid mutating a prop directly" error. Creating a mutable property and setting its value in the `created` event solved it for me:
```js
data()
{
return {
text: null
};
},
props: {
properties: Object,
value: String
},
created()
{
this.text = this.value;
}
```
Upvotes: -1
|
2018/03/16
| 1,285 | 4,396 |
<issue_start>username_0: I was trying some things with references and pointers, and I found something that I do not understand at all.
Here is my code:
```
#include
using namespace std;
class A
{
public:
A() { cout << "con\n"; }
~A() { cout << "des\n"; }
void f() { cout << "bla" << endl; }
};
A &createA()
{
A \*a = nullptr;
{
A b;
a = &b
cout << \*&a << endl;
}
return \*a;
}
int main()
{
A &b(createA());
cout << &b << endl;
b.f();
system("pause");
return 0;
}
```
The output:
```
con
des
0058FE0B
0058FE0B
bla
Press any key to continue . . .
```
As you can see the member function f() still gets called, even after the object itself has been destroyed. Why? I thought there should be some error, but the function f() does get called and it event does everything correctly, why?<issue_comment>username_1: You should not mutate the props in your child component. You can only mutate the object but not primitives. So, you can use data option or a computed property:
```
data() {
return {
childValue: this.value; // initialize props value
}
}
```
Now, you can change the `childValue`:
```
closeDialog() {
this.childValue = false;
},
```
Make sure to use `childValue` everywhere inside your child component instead of `value` props.
Upvotes: 2 <issue_comment>username_2: This happens because you have props `value` in your `v-model`.
Do not do that, as that will mutate the prop(`value`) when `v-model` changes (you should only change `data` values with `v-model` afaik, but in this case, you don't even need additional `data` variable).
Since vuejs [v2.3.0, it is suggested to `emit` value to the parent](https://v2.vuejs.org/v2/guide/components.html#sync-Modifier), so that parent changes it, and it is then passed to child component.
---
So all you have to do is:
in `v-dialog` component
remove `v-model` and replace it with `:value="value" @input="$emit('input')"`
And your function:
```
closeDialog() {
this.$emit('input');
}
```
In `panel-desconectar-modal` component use `v-model="showDesconectar"`.
---
This will work [because](https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events):
>
>
> ```
> is syntactic sugar for:
>
>
> ```
>
>
```
v-bind:value="something"
v-on:input="something = $event.target.value">
```
Here is [working example pen](https://codepen.io/anon/pen/XZWRJY) which I provided in an [answer](https://stackoverflow.com/a/48503369/1981247) to [similar question](https://stackoverflow.com/q/48490440/1981247).
Upvotes: 6 [selected_answer]<issue_comment>username_3: This is really the moment to ask yourself ***"Do I really need a prop? Can I do this with data? Am I here because I mistakenly put some state in Vue component?"***
If you're the author of the page and the component, and the component only appears once on the page, there is **no good reason to use props.** If you need props because the component is repeated for all the lines in an array, make the prop just the array index, so the component can directly modify the source array in the store. Vue components should not contain state, especially state that needs to be shared, and do not enjoy being tightly bound *to each other*. The parent-child relationship arises out of the chance of their placement in the DOM tree, (children occur inside the markup of parents). This is like a chance meeting in a nightclub. The child may have nothing else to do with the parent. The hierarchy of your source data should be expressed, independently of your markup, in the structure of your store. Your Vue components, where possible, should have an intimate two way relationship with the store, and **not talk much to each other :-)**
Upvotes: 1 <issue_comment>username_4: In the [relevant Vue doc](https://v2.vuejs.org/v2/guide/forms.html) they don't have examples with default values, so these answers are to be found elsewhere. I needed a solution to create a component with a default value, but the input would always spring back to what it was before when it loses focus, or it gave the "avoid mutating a prop directly" error. Creating a mutable property and setting its value in the `created` event solved it for me:
```js
data()
{
return {
text: null
};
},
props: {
properties: Object,
value: String
},
created()
{
this.text = this.value;
}
```
Upvotes: -1
|
2018/03/16
| 595 | 2,001 |
<issue_start>username_0: In the `console.log`, I can see that `this.id` is `undefined` after the Ajax call. I would still like to use the `id` of `.home` after that. I know I can again still perform `$('.home').attr('id')` in the `.done` section but that would be repeating the same code again. Is there a better/more efficient way of calling `this.id` (the `id` of `.home`) inside `.done`? I have placed the JavaScript file at the bottom of the tag.
**JQuery**
```
$(".home").submit(function(e) {
e.preventDefault();
e.stopPropagation();
var sendData = {
//Some data
};
var url = "/home" + this.id;
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(sendData)
}).done(function(result){
//This shows undefined.
console.log(this.id)
})
});
```<issue_comment>username_1: You need to store your id before the ajax request like :
```
$(".home").submit(function(e) {
e.preventDefault();
e.stopPropagation();
var sendData = {};
var id = this.id;
var url = "/home" + id;
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(sendData)
}).done(function(result){
console.log(id)
})
});
```
Upvotes: 2 <issue_comment>username_2: Problem is that `this` behaves little bit [differently](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) than in other languages. You have two options:
Either you can put `id` into variable
```
var id = this.id;
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(sendData)
}).done(function(result){
console.log(id)
})
```
or you can bind `this`
```
var onDone = function(result) {
console.log(this.id)
}
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(sendData)
}).done(onDone.bind(this));
```
this way your `this` will stay the same
Upvotes: 3 [selected_answer]
|
2018/03/16
| 488 | 1,814 |
<issue_start>username_0: This is the structure of my app's data in which user can log in and post the image with image's detail in the database.
I want that if a user post image, every user can see the notification **Seth Post Something**
I cannot find any link how to send a notification to all users when new data is added.
Can anyone specify the roadmap, code snippet how to do this after configuration of FCM
[](https://i.stack.imgur.com/X1GDv.png)<issue_comment>username_1: First thing to do is registering your users to one topic.
```
FirebaseMessaging.getInstance().subscribeToTopic("MySampleApp");
```
Then send a post request to fcm api <https://fcm.googleapis.com/fcm/send>
```
//HEADERS
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GB,./,Udno5aA
//BODY
{
"to": "/topics/MySampleApp",
"data": {
"message": "Hello Everyone!",
}
}
```
Then handle the notification in your FirebaseMessagingService. Hope this helps
Upvotes: 0 <issue_comment>username_2: To achieve your requirement you can use cloud function to send messages to all devices and the steps to achieve this.
1. take device access token for all user and save it in your database because without access token you can't send the message to devices never forget to update this toke whenever it changed.
2. cloud message will trigger always whenever any event occurs in a targeted part of the database.
3. For cloud message link of tutorials are here
[Fcm Tutorial](https://firebase.google.com/docs/cloud-messaging/http-server-ref),
[cloud function Tutorial](https://firebase.google.com/docs/reference/functions/functions) and [this tutorial](https://aaronczichon.de/2017/03/13/firebase-cloud-functions/) is very helpful for me.
Upvotes: 1
|
2018/03/16
| 685 | 2,676 |
<issue_start>username_0: **EDIT:** Looks like [this bug](https://stackoverflow.com/a/7509285/6683139) is the main problem here
-----------------------------------------------------------------------------------------------------
In my application's **MainActivity** I have a **custom bottom navigation** which is a horizontal recyclerview. I have an access to this recyclerview in all of my Fragments for navigation. The thing is when I focus on an **edittext inside my fragment**, soft input method moves that recyclerview up, how can I force the screen to pan just for the items in my Fragment's layout.
[![here is my fragment with activity's bottom navigation][2]][2]
[![enter image description here][3]][3]
I tried to put `android:windowSoftInputMode="adjustPan"` and then `android:windowSoftInputMode="adjustNothing"` to my activity in my Manifest.
then I tried to do those programatically **inside my Activity**.
then I tried to do the same **inside my Fragment** this time, nothing helped. Literally no way to make the keyboard ignore the activity.
Main Activity layout:
```
xml version="1.0" encoding="utf-8"?
```
Edit: I already tried possible solutions like `android:windowSoftInputMode="adjustPan"` the problem is when the edittext inside fragment gain focus, Recyclerview in my activity moves up and I lost pan
**FYI: my fragment's root layout is `ScrollView`**<issue_comment>username_1: First thing to do is registering your users to one topic.
```
FirebaseMessaging.getInstance().subscribeToTopic("MySampleApp");
```
Then send a post request to fcm api <https://fcm.googleapis.com/fcm/send>
```
//HEADERS
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GB,./,Udno5aA
//BODY
{
"to": "/topics/MySampleApp",
"data": {
"message": "Hello Everyone!",
}
}
```
Then handle the notification in your FirebaseMessagingService. Hope this helps
Upvotes: 0 <issue_comment>username_2: To achieve your requirement you can use cloud function to send messages to all devices and the steps to achieve this.
1. take device access token for all user and save it in your database because without access token you can't send the message to devices never forget to update this toke whenever it changed.
2. cloud message will trigger always whenever any event occurs in a targeted part of the database.
3. For cloud message link of tutorials are here
[Fcm Tutorial](https://firebase.google.com/docs/cloud-messaging/http-server-ref),
[cloud function Tutorial](https://firebase.google.com/docs/reference/functions/functions) and [this tutorial](https://aaronczichon.de/2017/03/13/firebase-cloud-functions/) is very helpful for me.
Upvotes: 1
|
2018/03/16
| 1,310 | 5,225 |
<issue_start>username_0: I followed the Spring Security 5.0 official reference documentation and sample codes [oauth2login](https://github.com/spring-projects/spring-security/tree/master/samples/boot/oauth2login) to setup OAuth2/OIDC authentication in my project, but it failed and I got the following exception when I booted up my application by `mvn spring-boot:run`.
```sh
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository'
defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]:
Factory method 'clientRegistrationRepository' threw exception;
nested exception is java.lang.IllegalArgumentException: authorizationGrantType cannot be null
```
I was using the default configuration provided by Spring Boot and just added some basic dependencies into projects, such as `spring-security-config`, `spring-security-oauth2-client`, `spring-security-oauth2-jsoe` etc.
**Updated:**
**I've found the reason**, for custom OAuth2 providers, such as **Gitlab**, I have to add **grant type**, **redirectUritemplate**, **scope**, **clientName** etc, but OpenID Connect specification has a configuration endpoint protocol, eg: <https://gitlab.com/.well-known/openid-configuration> , is there possible to make Spring Security read this info automatically?
**Update(5/15/2021):** in the latest Spring Security 5.4 and Spring Boot 2.4, the OpenId configuration(`.well-known/openid-configuration`) is discovered by default, for most oauth2/oidc authorization servers, configure a
`issuer_uri` is enough.<issue_comment>username_1: To elaborate on [username_3's answer](https://stackoverflow.com/a/59173235/1389817), the properties you need to include in your `application.yaml` to resolve the original error are as shown below, in this case for Azure AD (note this ONLY works with Spring Security 5, NOT Spring Security OAuth2 2.x whose functionality is [being merged](https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Features-Matrix) directly into Spring Security 5):
```
spring:
security:
oauth2:
client:
registration:
microsoft:
client-id: a935ba7b-6aa4-4b0c-9e84-04f9acaa477b
client-secret: redacted
authorization-grant-type: authorization_code
redirect-uri-template: '{baseUrl}/login/oauth2/code/{registrationId}'
scope: User.Read
client-name: Microsoft
client-alias: microsoft
provider:
microsoft:
authorization-uri: https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/
token-uri: https://login.microsoftonline.com/common/oauth2/token
user-info-uri: https://graph.microsoft.com/v1.0/me
user-name-attribute: sub
jwk-set-uri: https://login.microsoftonline.com/common/discovery/keys
```
Upvotes: 4 <issue_comment>username_2: redirect-uri-template -> redirect-uri
it works SpringBoot 2.2.0.RELEASE
but it works spring 2.1.x with redirect-uri-template
Upvotes: 3 <issue_comment>username_3: use redirect-uri instead of redirect-uri-template if use SpringBoot v2.2.1 RELEASE
Upvotes: 4 <issue_comment>username_4: ```
org.springframework.security.oauth.boot
spring-security-oauth2-autoconfigure
2.4.5
```
Add this dependency in your pom and check
Upvotes: -1 <issue_comment>username_5: I had to add the following property to my `application.properties`:
`spring.security.oauth2.client.registration.azure.authorization_grant_type=authorization_code`
After which it started complaining that "Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'oidcUserService'"
At which point I had to add the following to the `WebSecurityConfig`:
```
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers()
.httpStrictTransportSecurity()
.includeSubDomains(includeSubDomains)
.maxAgeInSeconds(31536000);
http.requestCache()
.requestCache(new NullRequestCache())
.and()
.authorizeRequests()
.antMatchers("Our permitted end points")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService());
}
private OAuth2UserService oidcUserService() {
final OidcUserService delegate = new OidcUserService();
return userRequest -> {
OidcUser oidcUser = delegate.loadUser(userRequest);
Set mappedAuthorities = new HashSet<>();
oidcUser =
new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
return oidcUser;
};
}
```
Then is started working...
Reference: <https://docs.spring.io/spring-security/site/docs/5.2.12.RELEASE/reference/html/oauth2.html>
Upvotes: 0
|
2018/03/16
| 1,526 | 5,237 |
<issue_start>username_0: My application uses the unicode character \u2192 to display a right arrow within a TextView element. However, the arrow is shown at the very bottom line, but should be centered vertically:
[](https://i.stack.imgur.com/phIQv.png)
However, if I print the unicode character using the standard output, everything is fine:
```
public class Main {
public static void main(String[] args) {
System.out.println("A" + Character.toString("\u2192".toCharArray()[0]));
}
}
```
[](https://i.stack.imgur.com/2g6mD.png)
How I can enforce the right arrow to be centered in the TextView, too? My TextView already uses `android:gravity="center_vertical|left"`.
**Update**: I use Android Studio 3.0.1 and Android SDK 26. The XML code of the TextView:
```
```
Filling the TextView in the code:
```
TextView textView = findViewById(R.id.my_text_view);
textView.setText("A" + Character.toString("\u2192".toCharArray()[0]) + "B");
```<issue_comment>username_1: Try another symbols with html entity encodings. Look at this [link](http://www.fileformat.info/info/unicode/char/a.htm), maybe you find here more convenient *right arrow* for you but I chose this for example : `➔`
```
String formula = "A ➔ B";
textView.setText(Html.fromHtml(formula));
```
also this third party [lib](https://github.com/kexanie/MathView) maybe appropriate for you
Upvotes: 1 <issue_comment>username_2: Try that:
```
SpannableString st = new SpannableString("A" + "\u2192" + "B");
st.setSpan(new RelativeSizeSpan(2f), 1, 2, 0);
textView.setText(st);
```
I know that however this doesn't completely answer.
Upvotes: 1 <issue_comment>username_3: Since [Android's Roboto font doesn't seem to contain arrow glyphs](http://www.fontspace.com/google/roboto/21071/charmap), this would cause it to display a character from a fallback font if possible (though I couldn't find the documentation of this behavior). I'm guessing that the "fallback" arrow on your device is lying on the baseline for some reason.
However, there's a trick that might help you: You can include an image of the special character and insert the image into your output text.
First, add a new Drawable resource file (`ic_arrow.xml`) in `res/drawable`, and copy-paste this into it:
```
```
Now, we'll need to embed the arrow image into a SpannableString that you can display in your TextView. I'll walk you through the (surprisingly many) lines of code that we'll need to accomplish this:
* Get the Drawable resource so that we can make it the correct size before displaying it.
`Drawable arrow = ContextCompat.getDrawable(this, R.drawable.ic_arrow);`
* Figure out what size the arrow needs to be, [based on the font
metrics](https://stackoverflow.com/questions/9879233/explain-the-meaning-of-span-flags-like-span-exclusive-exclusive).
`Float ascent = textView.getPaint().getFontMetrics().ascent;`
* This is negative ([for reasons](https://stackoverflow.com/questions/9879233/explain-the-meaning-of-span-flags-like-span-exclusive-exclusive)), so make it positive.
`int h = (int) -ascent;`
* Finally, we can set the bounds of the Drawable to match the text
size.
`arrow.setBounds(0,0,h,h);`
* Next, create a SpannableString initialized with our text. I just used `*` for a placeholder here, but it could be any character (or a blank space). If you're planning to concatenate different bits together along with multiple arrow images, use a `SpannableStringBuilder` for this.
`SpannableString stringWithImage = new SpannableString("A*B");`
* Now, we can finally insert the image into the span (using a new
ImageSpan with our "arrow" image, [aligned with the baseline](https://stackoverflow.com/questions/9879233/explain-the-meaning-of-span-flags-like-span-exclusive-exclusive)).
The `1` and `2` are zero-based start and end indices (telling where
to insert the image), and `SPAN_EXCLUSIVE_EXCLUSIVE` indicates that
[the span doesn't expand to include inserted text](https://stackoverflow.com/questions/9879233/explain-the-meaning-of-span-flags-like-span-exclusive-exclusive).
`stringWithImage.setSpan(new ImageSpan(arrow, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);`
* Finally, we can display the text (including the custom arrow image):
`textView.setText(stringWithImage);`
Altogether, the code should look like this.
```
TextView textView = findViewById(R.id.my_text_view);
Drawable arrow = ContextCompat.getDrawable(this, R.drawable.ic_arrow);
Float ascent = textView.getPaint().getFontMetrics().ascent;
int h = (int) -ascent;
arrow.setBounds(0,0,h,h);
SpannableString stringWithImage = new SpannableString("A*B");
stringWithImage.setSpan(new ImageSpan(arrow, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(stringWithImage);
```
I wish Android had a better way to do this sort of thing, but at least it can be done somehow. The resulting TextView should look like this:
[](https://i.stack.imgur.com/ZS6dl.png)
Upvotes: 4 [selected_answer]
|
2018/03/16
| 1,166 | 4,417 |
<issue_start>username_0: I'm working on a simple software in c# that read bytes from a named pipe (client) and forward it to a serial port (with some processing on the data) and vice-versa. It look like:
```
if(data available on the named pipe)
write on com port (the data read from the named pipe)
if(data available on the com port)
write on named pipe (the data read from the com port)
repeat endlessly
```
The problem is that read from the named pipe get blocked if their is no data to read, until a data comes. So the other side communication (com port to pipe) is also blocked.
I have tried running both direction communication in it's own thread, but the write operation on the pipe is blocked while a read operation is performed (or waiting for data) on the other thread.
I've tried stopping the blocked thread and cancelling the read operation without success.
The simplest way to deal with this kind of thing would be to either:
* get the number of byte available to read on the pipe, and skip reading if 0
* or have a timeout on the read operation, so write could occur after the timeout (timing is not that critical in this application).
This work great with the com port part as a comPort.BytesToRead variable containing the number of byte in the read buffer exist.
The named pipe is a client (server created by another software), but could also be a server if this is more convenient.
Any ideas ?!?
Thank you in advance !<issue_comment>username_1: >
> I have tried running both direction communication in it's own thread, but the write operation on the pipe is blocked while a read operation is performed (or waiting for data) on the other thread
>
>
>
Pipes can be used to both read and write at the same time, provided the right options are used. Here's a toy sample that demonstrates the client and the server disagreeing on which order they'll be performing operations and it just working:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.IO.Pipes;
using System.Text;
using System.Threading;
public class Bob
{
static void Main()
{
var svr = new NamedPipeServerStream("boris", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte);
var helper = Task.Run(() =>
{
var clt = new NamedPipeClientStream("localhost", "boris", PipeDirection.InOut, PipeOptions.Asynchronous);
clt.Connect();
var inBuff = new byte[256];
var read = clt.ReadAsync(inBuff, 0, inBuff.Length);
var msg = Encoding.UTF8.GetBytes("Hello!");
var write = clt.WriteAsync(msg, 0, msg.Length);
Task.WaitAll(read, write);
var cltMsg = Encoding.UTF8.GetString(inBuff, 0, read.Result);
Console.WriteLine("Client got message: {0}", cltMsg);
});
svr.WaitForConnection();
var srvBuff = new byte[256];
var srvL = svr.Read(srvBuff, 0, srvBuff.Length);
var svrMsg = Encoding.UTF8.GetString(srvBuff, 0, srvL);
Console.WriteLine("Server got message: {0}", svrMsg);
var response = Encoding.UTF8.GetBytes("We're done now");
svr.Write(response, 0, response.Length);
helper.Wait();
Console.WriteLine("It's all over");
Console.ReadLine();
}
}
```
(In real world usage, we'd use some `async` methods to launch the read and write "threads" rather than manually managing either threads or tasks)
Upvotes: 2 <issue_comment>username_2: Thank's Damien, your answer doesn't help me a lot, but I figured it out myself:
I've tried working around with readAsync but it wasn't working great because my pipe wasn't opened as Asynchronous:
```
pipe = new NamedPipeClientStream(".", "thePipe", PipeDirection.InOut, PipeOptions.Asynchronous);
```
Then, to read the pipe without blocking:
```
pipe.ReadAsync (buffer, 0, buffer.Lenght).ContinueWith (t=>
{
//called when read is finished (data available).
});
```
And finally, as the read is called in a while(1) loop, I need to prevent the read async to be lunched multiple times :
```
if (readFinished) {
readFinished = false;
pipe.ReadAsync (buffer, 0, buffer.Length).ContinueWith (t => {
//called when read is finished (data available).
//TODO: deal with the data (stored in 'buffer').
readFinished = true;
});
}
```
(with 'readFinished' a boolean initialised to true).
Hope it will help someone else.
Upvotes: 1
|
2018/03/16
| 462 | 1,647 |
<issue_start>username_0: Abstract Class:
```
public abstract class absclass {
private int x,y;
public absclass(int x,int y) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return new String(x+" --------- "+y);
}
```
Subclass:
```
public class pc extends absclass {
public pc(int x,int y) {
// TODO Auto-generated constructor stub
super(x, y);
// x=x;
// y=y;
}
public void compute()
{
System.out.println("well this is pc");
System.out.println(this);
//for y=1;
}
```
Main:
```
public static void main(String[] args) {
// TODO Auto-generated method stub
new pc(0, 2).compute();
}
```
Why does the **subclass** **pc** have access to the private members **x,y** of the **abstract class**? Based on inheritance rules any private members in the parent class are not inherited into the childclass so the childclass shouldn't have any members x,y. Yet the output is:
>
> 0 --------- 2
>
>
><issue_comment>username_1: It does not. `toString()` is inherited from the parent class. Since you have not overriden this method in the sub class and as it has access to the private variables of parent class, when println is called, it simply prints the the output from parent class `toString()`.
Upvotes: 2 <issue_comment>username_2: `pc` doesn't have access to `x` and `y`. It has access to `toString()`, because that's a public method. And `toString()` has access to `x` and `y`, because it's defined in `absclass`.
Upvotes: 3 [selected_answer]
|
2018/03/16
| 785 | 2,874 |
<issue_start>username_0: I have got a function which should accept either an array, or a string and another string. Other operand types are to be declined.
How do I do that?<issue_comment>username_1: You can use the is\_array() function of php to check if the given option in an array or string.
[Check it here is\_array()](http://php.net/manual/en/function.is-array.php)
Upvotes: 0 <issue_comment>username_2: You can define your function such a way that it should only accept arrays or string and if it's find another operand then It will be automatically exit from the php function.
Below is just PHP script that you can identify manually into your PHP function.
Sample of PHP Function:
```
function testStringAndArray($arg) {
if(is_array($arg)|| is_string($arg)) {
//Do Processing
} else {
return false;
}
}
```
Upvotes: 1 <issue_comment>username_3: If you already have any code you can put in the question.
As I understood from the requirement your function should look something like below
```
function($arrayOrString, $string){
if((is_array($arrayOrString) || is_string($arrayOrString)) && is_string($string)){
// do something here
}else{
return false;
}
}
```
Ref: [is\_string](http://php.net/manual/en/function.is-string.php)
& [is\_array](http://php.net/manual/en/function.is-array.php)
Upvotes: 0 <issue_comment>username_4: Attached, functional sample with "No param", string param and array param.
```
php
class Speaker {
public function sayHello($person = null)
{
// I will display hello something base on parameter type.
$this-render(
$this->prepareParams($person);
);
}
private function prepareParams($param = null) {
//Default value
if(is_null($param)) {
$param = 'World';
}
else if(is_array($param)) {
//Merge all item to one string with coma separator
$param = implode(', ', $param);
}
return $param;
}
private function render(string $target) {
echo "Hello ".$target;
}
}
$tester = new Speaker();
$this->sayHello();
$this->sayHello('Yanis');
$this->sayHello(['Yanis', 'thomas','roman']);
```
You can deal with default parameter to manage your second optional parameter such as :
```
if(!is_null($mySecondParameter)) // I can use it Because he is defined.
```
Upvotes: 0 <issue_comment>username_5: Okay, I just thought too complicated.
I wanted something like
```
public myFunction(array $arg1) {
...
}
public myFunction(string $arg1, string $arg2) extends myFunction {
...
}
```
But it's much easier with something like
```
public myFunction($arg1, $arg2 = null) {
if(is_array($arg1)) {
...
}
if(is_string($arg1) && is_string($arg2)) {
...
}
```
Upvotes: 0
|
2018/03/16
| 508 | 1,581 |
<issue_start>username_0: I am facing problem, when i am trying to load this type of `html` string
```
(Identify the arrow-marked structures in the images<\/p>\r\n)
```
in `webview`.
problem is raised due to backward slaces.
Any Help will Appreciated<issue_comment>username_1: If the back-slashes are your problem, you should remove them:
```
let origString = ...
let unescapedString = origString.replacingOccurrences(of: "\\", with: "")
webview.loadHTMLString(unescapedString, baseURL:nil)
```
Upvotes: 1 <issue_comment>username_2: URL string has a problem with forward slash(es) `/` in your html string.
[](https://i.stack.imgur.com/GaZXk.png)
Correct url string is: <https://dams-apps-production.s3.ap-south-1.amazonaws.com/course_file_meta/73857742.PNG>
Here I tried this and its working:
```
class WebKitController: UIViewController {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
loadHTMLStringImage()
}
func loadHTMLStringImage() -> Void {
let htmlString = "Identify the arrow-marked structures in the images
"
webView.loadHTMLString(htmlString, baseURL: nil)
}
}
```
Result:
[](https://i.stack.imgur.com/TXH9F.png)
Upvotes: 3
|
2018/03/16
| 1,199 | 4,326 |
<issue_start>username_0: **The code**
```
import whois
domains = ['google.com', 'stackoverflow.com', 'hdtrcs.com' , 'facebook.com' ]
w = []
i = 0
for data in domains:
n = domains[i]
print(n)
i = i+1
data = whois.whois(n)
if data != None:
w.append(data['domain_name'])
else:
w.append('none')
print (w)
```
Expected to store `w = ['GOOGLE.COM', 'STACKOVERFLOW.COM', 'none', 'facebook.com' ]`
The error is it cant find the domain and it stops checking next domains
***The output this code gives***
```
google.com
stackoverflow.com
hdtrcs.com
Traceback (most recent call last):
File "who.py", line 9, in
data = whois.whois(n)
File "/usr/local/lib/python3.5/dist-packages/whois/\_\_init\_\_.py", line 41, in whois
return WhoisEntry.load(domain, text)
File "/usr/local/lib/python3.5/dist-packages/whois/parser.py", line 185, in load
return WhoisCom(domain, text)
File "/usr/local/lib/python3.5/dist-packages/whois/parser.py", line 283, in \_\_init\_\_
raise PywhoisError(text)
whois.parser.PywhoisError: No match for "HDTRCS.COM".
>>> Last update of whois database: 2018-03-16T09:41:06Z <<<
NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar. Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.
TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability. VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.
The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.
```
How to get rid of this error or to add some default value like none and store it in the list and when this error arises or domain not found and continue to check for rest of the domains.<issue_comment>username_1: You can use `dict.get`
**Ex:**
```
import whois
domains = ['google.com', 'stackoverflow.com', 'hdtrcs.com' , 'facebook.com' ]
result = []
for dom in domains:
w = whois.whois(dom)
if w:
result.append(w.get('domain_name', 'none'))
print (result)
```
Upvotes: 1 <issue_comment>username_2: The library you use generates an exception (`whois.parser.PywhoisError`) when the domain name is not found.
Hence, you need to capture this exception and deal with it.
Replace the end of your loop by something like:
```
try:
data = whois.whois(n)
w.append(data['domain_name'])
except whois.parser.PywhoisError:
w.append('none')
```
You may need an `import whois.parser` at top of your file, so that the exception is known (symbol resolved) in your program.
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,137 | 3,969 |
<issue_start>username_0: I'm using mat-table in my angular 5 project.
the current result is as follows :
[](https://i.stack.imgur.com/tOrrn.gif)
I'd like to be able to "pin" a column.
you'd click on these pins and "pinned" columns would come to the leftmost and stay above others when you **scroll-x** (as you can see me do in the gif above).
the css allowing scroll-x is (for example, mine is much bigger and dynamic) :
```
.mat-header-row, .mat-row {
width: 1500px;
}
```
Much the way excel locked columns/rows do.
(I scroll X ALOT since my column numbers are in the high 80's to hundreds and some of them need to be quite wide.)
I've made a photoshop mockup to give you an idea what I'm talking about :
[](https://i.stack.imgur.com/noxPf.png)
For example the select checkboxes should always be "pinned". That is, they remain visible when you horizontally scroll.
here's my code :
```
{{ startCase(col) }}
{{row[col]}}
```
And I'm persuaded, but I may be wrong, that there's a hurdle thrown at me by me iterating over the array elements and their objects (like I do), rather than declaring each column in the DOM.
However, this is a functionality I cannot forgo.
I'd love to just say : "ok your `pinned` var is set to true so you get the `[ngClass]` 'pinned' which in css translate to you being `position: absolute` and `left: 0`"
ok but that's no help if I want to pin several. they'll just end up one on top of one another.
The other issue I see is once I've done that haven't I lost the "pin header" functionality I added for those pinned columns?<issue_comment>username_1: Your columns order if defined by your displayedColumnsWSelect variable. Change the values order in that array and your columns order will change.
Here is a stackblitz demonstrating that:
<https://stackblitz.com/edit/angular-q7nibn>
Click on the top button "Put last column first" and the last column becomes the first.
That's for moving the columns. Now if you want to keep track of what columns have been pinned so you can set the order right, your just need another object/array containing that information.
Upvotes: 1 <issue_comment>username_2: So I've since implemented my own idea for a solution : simply having two mat tables.
that process was easy enough and uninteresting but I though you might be interested by the code I wrote to sync both tables :
ts :
```
leftS;
rightS;
leftTimeout;
rightTimeout;
syncScrollRightBeingCalled = false;
syncScrollLeftBeingCalled = false;
constructor(
private element: ElementRef) {
this.dataSource = new MatTableDataSource();
}
ngAfterViewInit() {
this.leftS = this.element.nativeElement.querySelector('.catching-scrolling-left');
this.rightS = this.element.nativeElement.querySelector('.catching-scrolling-right');
}
syncScrollLeft(div){
clearTimeout(this.leftTimeout);
if(!this.syncScrollRightBeingCalled){
this.syncScrollLeftBeingCalled = true;
this.leftS.scrollTop = div.scrollTop;
}
this.leftTimeout = setTimeout(() => this.syncScrollLeftBeingCalled = false, 25);
}
syncScrollRight(div){
clearTimeout(this.rightTimeout);
if(!this.syncScrollLeftBeingCalled) {
this.syncScrollRightBeingCalled = true;
this.rightS.scrollTop = div.scrollTop;
}
this.rightTimeout = setTimeout(() => this.syncScrollRightBeingCalled = false, 25);
}
```
html :
```
```
css :
```
.unpinned{
height: calc(100vh - 430px);
}
.pinned{
height: calc(100vh - 447px);
}
.pinned{
-ms-overflow-style: none;
overflow: auto;
width: 560px;
}
.unpinned{
overflow: scroll;
flex: 1;
}
/deep/ .pinned::-webkit-scrollbar {
width: 0;
}
```
this has relatively satisfactory results. I'll have to figure out one day why it doesn't work under firefox, though.
Upvotes: 1 [selected_answer]
|
2018/03/16
| 677 | 2,474 |
<issue_start>username_0: can an entity exist in isolation in ER diagram? When this entity has no relation ship with other entities (they have relationship with others) in the diagram?
Will this diagram be a valid ER diagram?<issue_comment>username_1: Your columns order if defined by your displayedColumnsWSelect variable. Change the values order in that array and your columns order will change.
Here is a stackblitz demonstrating that:
<https://stackblitz.com/edit/angular-q7nibn>
Click on the top button "Put last column first" and the last column becomes the first.
That's for moving the columns. Now if you want to keep track of what columns have been pinned so you can set the order right, your just need another object/array containing that information.
Upvotes: 1 <issue_comment>username_2: So I've since implemented my own idea for a solution : simply having two mat tables.
that process was easy enough and uninteresting but I though you might be interested by the code I wrote to sync both tables :
ts :
```
leftS;
rightS;
leftTimeout;
rightTimeout;
syncScrollRightBeingCalled = false;
syncScrollLeftBeingCalled = false;
constructor(
private element: ElementRef) {
this.dataSource = new MatTableDataSource();
}
ngAfterViewInit() {
this.leftS = this.element.nativeElement.querySelector('.catching-scrolling-left');
this.rightS = this.element.nativeElement.querySelector('.catching-scrolling-right');
}
syncScrollLeft(div){
clearTimeout(this.leftTimeout);
if(!this.syncScrollRightBeingCalled){
this.syncScrollLeftBeingCalled = true;
this.leftS.scrollTop = div.scrollTop;
}
this.leftTimeout = setTimeout(() => this.syncScrollLeftBeingCalled = false, 25);
}
syncScrollRight(div){
clearTimeout(this.rightTimeout);
if(!this.syncScrollLeftBeingCalled) {
this.syncScrollRightBeingCalled = true;
this.rightS.scrollTop = div.scrollTop;
}
this.rightTimeout = setTimeout(() => this.syncScrollRightBeingCalled = false, 25);
}
```
html :
```
```
css :
```
.unpinned{
height: calc(100vh - 430px);
}
.pinned{
height: calc(100vh - 447px);
}
.pinned{
-ms-overflow-style: none;
overflow: auto;
width: 560px;
}
.unpinned{
overflow: scroll;
flex: 1;
}
/deep/ .pinned::-webkit-scrollbar {
width: 0;
}
```
this has relatively satisfactory results. I'll have to figure out one day why it doesn't work under firefox, though.
Upvotes: 1 [selected_answer]
|
2018/03/16
| 1,126 | 4,133 |
<issue_start>username_0: Trying to send info in JSON format using Retrofit, but it enters into Retrofit's `onFailure` method and throws the following error:
```
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
```
So far I have tried to solve it by using the answers from the following links:
1) [MalformedJsonException with Retrofit API?](https://stackoverflow.com/questions/27485346/malformedjsonexception-with-retrofit-api)
2) [Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $](https://stackoverflow.com/questions/39918814/use-jsonreader-setlenienttrue-to-accept-malformed-json-at-line-1-column-1-path)
Here is my code:
Retrofit interface:
```
public interface ServerApi {
@POST("/register/test")
Call createAccount(@Body User user);
}
```
MainActivity with connection stuff:
```
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
User user= new User("<EMAIL>","vercode100");
sendNetworkRequest(user);
}
private void sendNetworkRequest(User user){
//create Retrofit instance
Retrofit.Builder builder= new Retrofit.Builder()
.baseUrl("http://localhost:8080")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit= builder.build();
//Get client and call object for the request
ServerApi client= retrofit.create(ServerApi.class);
Call call= client.createAccount(user);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
```
User class:
```
public class User {
private String email;
private String verificationCode;
public User(String email, String verificationCode) {
this.email = email;
this.verificationCode = verificationCode;
}
}
```
The server side expects JSON like this:
```
{
"email" : "user.email",
"verificationCode" : "<PASSWORD>"
}
```
**I know that there are some common questions in stackoverflow, but neither of them fully solves my problem.**<issue_comment>username_1: The exception is not thrown when sending your data, but it's thrown when gson tries to parse the server response. According to your code you are expecting the server to respond with a **User** object but you're also sending a User object.
Does your server respond with the following? Because that's what you're telling retrofit with `Call createAccount(@Body User user)`
>
> {
> "email" : "user.email",
> "verificationCode" : "<PASSWORD>" }
>
>
>
Upvotes: 1 <issue_comment>username_2: ```
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLenient();
Gson gson = gsonBuilder.create();
// and in you adapter set this instance
GsonConverterFactory.create(gson)
```
Upvotes: 2 <issue_comment>username_3: Make sure that your header are correct.
In my case I send `Accept-Encoding: gzip` and so the server return the value with gzip. So I remove it and it works well now.
Hope helpfull...
Upvotes: 0 <issue_comment>username_4: Remove the Accept-Encoding header. OkHttp will take care of gzip for you, but only if you aren't setting up gzip yourself.
Upvotes: 1 <issue_comment>username_5: may be in your metadata you have to properly write the JSON file. for example if it is array or two objects make sure not to miss the square bracket.
```
[
{
"email" : "user.email", "verification" : "<PASSWORD>"
},
{
"email" : "user.email", "verification" : "<PASSWORD>"
}
]
```
Upvotes: 0 <issue_comment>username_6: In my case it was caused by BASE\_URL
when I changed this
private const val BASE\_URL = "https://api.airvisual.com/v2"
to
```
private const val BASE_URL = "https://api.airvisual.com/"
```
and then added "/v2" to
```
@GET("/v2/nearest_city")
```
It worked just fine!
Upvotes: 0
|
2018/03/16
| 560 | 1,435 |
<issue_start>username_0: I have an array that looks like this:
```
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
```
I want to get the most frequent item followed by the next most frequent item until I get to the least frequent item and then create another array with this information that looks like this:
```
$frequencies=array("1"=>4,"4"=>3,"5"=>2,"6"=>1,"7"=>1)
```
How can I achieve this, please help.<issue_comment>username_1: You have to Use [array\_count\_values()](http://php.net/manual/en/function.array-count-values.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
print_r($recs1);
</code
```
<https://eval.in/973006>
Or if you want numbers need to be ascending order(which are keys in your final array) then use [ksort()](http://php.net/manual/en/function.ksort.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
ksort($recs1);
print_r($recs1);
</code
```
<https://eval.in/973163>
Upvotes: 2 <issue_comment>username_2: ```
$recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
//array_count_values — Counts all the values of an array
$recs1 = array_count_values($recs);
//to get the most frequent item followed by the next most
//frequent item until I get to the least frequent item
//use `arsort` — Sort an array in reverse order and maintain index association
arsort($recs1);
print_r($recs1);
```
[Demo](https://3v4l.org/gbtJP)
Upvotes: 0
|
2018/03/16
| 591 | 1,555 |
<issue_start>username_0: ```
xml version="1.0" encoding="utf-8"?
```
[](https://i.stack.imgur.com/zN1fO.png)
Screen is not scrolling. The screen contains Swipe refresh also.
I have tried different solutions and added this line
>
> `android:fillViewport="true"`
> and removed orientation for relative layout.
>
>
>
Why scroll view not working here?
But screen is not scrolling. I am new to android.
Please help me. Any help would be appreciated.
Thank you.<issue_comment>username_1: You have to Use [array\_count\_values()](http://php.net/manual/en/function.array-count-values.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
print_r($recs1);
</code
```
<https://eval.in/973006>
Or if you want numbers need to be ascending order(which are keys in your final array) then use [ksort()](http://php.net/manual/en/function.ksort.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
ksort($recs1);
print_r($recs1);
</code
```
<https://eval.in/973163>
Upvotes: 2 <issue_comment>username_2: ```
$recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
//array_count_values — Counts all the values of an array
$recs1 = array_count_values($recs);
//to get the most frequent item followed by the next most
//frequent item until I get to the least frequent item
//use `arsort` — Sort an array in reverse order and maintain index association
arsort($recs1);
print_r($recs1);
```
[Demo](https://3v4l.org/gbtJP)
Upvotes: 0
|
2018/03/16
| 715 | 2,100 |
<issue_start>username_0: I need send a JSONObject to server and get other JSONObject from it. but I can not send JSONObject to server, in the other words my JSONObject is sent to server with null value.
Android Code:
```
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
getUrl(), new JSONObject("{\"command\":\"get_ad_list\"}"), new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
Log.e("xxxxxxxxx-result ", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("xxxxxxxxx-error ", error.toString());
}
});
request.setRetryPolicy(new DefaultRetryPolicy(8000,
DefaultRetryPolicy.DEFAULT\_MAX\_RETRIES, DefaultRetryPolicy.DEFAULT\_BACKOFF\_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
```
PHP Code:
```
php
$post_data=@$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
echo $command; //$command is null!
?
```<issue_comment>username_1: You have to Use [array\_count\_values()](http://php.net/manual/en/function.array-count-values.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
print_r($recs1);
</code
```
<https://eval.in/973006>
Or if you want numbers need to be ascending order(which are keys in your final array) then use [ksort()](http://php.net/manual/en/function.ksort.php)
```
php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
ksort($recs1);
print_r($recs1);
</code
```
<https://eval.in/973163>
Upvotes: 2 <issue_comment>username_2: ```
$recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
//array_count_values — Counts all the values of an array
$recs1 = array_count_values($recs);
//to get the most frequent item followed by the next most
//frequent item until I get to the least frequent item
//use `arsort` — Sort an array in reverse order and maintain index association
arsort($recs1);
print_r($recs1);
```
[Demo](https://3v4l.org/gbtJP)
Upvotes: 0
|
2018/03/16
| 706 | 3,028 |
<issue_start>username_0: Theoretically speaking, if we implement optimistic concurrency on Aggregate Root level (changing entities in AR changes version on AR) and lets say we use timestamp for version property (just for simplicity) - should timeline ever be a property on AR or should it be a part of read model on one side and on other (for example, updates) be a separate argument to application service like:
[pseudo]
```
public class AppService{
.
.
.
public void UpdateSomething(UpdateModelDTO model, int timestamp)
{
repository.GetModel(model.Identifier);
model.UpdateSomething(model.something);
repository.ConcurrencySafeModelUpdate(model, timestamp);
}
}
```
I see pros/cons for both but wondering which is by-the-book solution?
[UPDATE]
To answer question from @guillaume31, i expect usual scenario:
1. On read, version identifier is read and sent to client
2. On update, client sends back the identifier and repository returns some kind of an error if version identifier is not the same.
I don't know if its important but i want to leave responsibility for creating/updating version identifiers themselves to my database system.<issue_comment>username_1: I assume, else you won't be asking this question, you are using your Domain model as Data model (i.e. Hibernate entity), then you have already introduced infrastructural concerns into your domain model, so I would suggest to go ahead and add the timestamp to AR.
Upvotes: 1 <issue_comment>username_2: The Aggregate should not care about anything else but business related concerns. It should be pure, without any infrastructure concerns.
The `version` column in the database/persistence is an infrastructure concern so it should not be reflected in the Aggregate class from the Domain layer.
P.S. using timestamps for optimistic locking is weird; you would better use an integer that is incremented every time an Aggregate is mutated and that is expected to have the (loaded-version + 1) when a `save` is executed.
```
public void UpdateSomething(UpdateModelDTO model)
{
(model, version) = repository.GetModel(model.Identifier);
model.UpdateSomething(something);
repository.ConcurrencySafeModelUpdate(model, version + 1);
}
```
Update: here is an [implementation example](https://github.com/xprt64/cqrs-java/blob/master/src/main/java/com/cqrs/aggregates/EventSourcedAggregateRepository.java) in java.
Upvotes: 0 <issue_comment>username_3: There's no by-the-book solution. Sometimes you'll already have a field in your aggregate that fits the role nicely (e.g. `LastUpdatedOn`), sometimes you can make it non-domain data. For performance reasons, it may be a good idea to select the field as part of the same query that fetches the aggregate though.
Some ORMs provide facilities to detect concurrency conflicts. Some DBMS's can create and update a version column automatically for you. You should probably look for guidelines about optimistic concurrency in your specific stack.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 482 | 1,430 |
<issue_start>username_0: I have 3 tables
Table 1 (tickets):
```
id | name
---------------
1 | Ticket 1
2 | Ticket 2
3 | Ticket 3
```
Table 2 (ticket\_field):
```
id | name
------------
1 | Field 1
2 | Field 2
3 | Field 3
```
Table 3 (ticket\_field\_map):
```
id | ticket_id | field_id | value
------------------------------------
1 | 1 | 1 | Value 1
2 | 1 | 2 | Value 2
3 | 1 | 3 | Value 3
4 | 2 | 1 | Value 4
5 | 2 | 2 | Value 5
6 | 2 | 3 | Value 6
7 | 3 | 1 | Value 7
8 | 3 | 2 | Value 8
9 | 3 | 3 | Value 9
```
The final Table on which sorting is to be done:
```
ticket_id | ticket_name | Field 1 | Field 2 | Field 3
-----------------------------------------------------
1 | Ticket 1 | Value 1 | Value 2 | Value 3
2 | Ticket 2 | Value 4 | Value 5 | Value 6
3 | Ticket 3 | Value 7 | Value 8 | Value 9
```
On this table, I have to give the user option to sort on each field value.<issue_comment>username_1: I think a simple two step ordering should work:
```
SELECT *
FROM yourTable
ORDER BY
`key`, value;
```
By the way, `KEY` is a reserved MySQL keyword, and you should avoid naming your columns and tables using it.
Upvotes: 2 <issue_comment>username_2: Use Order by key asc or desc whatever order you want
Upvotes: 0
|
2018/03/16
| 523 | 2,022 |
<issue_start>username_0: I have following code and try to use $index in delete function but it gives incorrect value of it.
```
- ![{{joinMember.member.screenName ? joinMember.member.screenName : joinMember.member.fname + ' ' + joinMember.member.lname }}]()
####
{{joinMember.member.screenName ? joinMember.member.screenName : joinMember.member.fname + ' ' + joinMember.member.lname }}
{{joinMember.created | date : "MMMM d, y"}}
```<issue_comment>username_1: As you can see in the official documentation of angularjs you should get a zero-based index via $index within a ng-repeat. Try the example by angularjs [here](https://docs.angularjs.org/api/ng/directive/ngRepeat#examples). Try to debug `data.teamMember` in your controller to make sure that this is the correct array you'd like to iterate.
Upvotes: 0 <issue_comment>username_2: That's because the directive ng-if creates a new scope for itself, when you refer to $parent, it access the immediate $parent's scope, i.e., the inner repeat expression's scope.
So if you want to achieve something you wanted like in the former, you may use this:
```
({{$parent.$parent.$index}} {{$parent.$index}})
```
if you have more than one inner directives, you can use ng-init for storing $index in a variable for references in child scopes.
```
({{outerIndex}} {{innerIndex}})
```
So try $parent.$parent.$index in your example and please check [understanding the scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
Upvotes: 1 <issue_comment>username_3: You are using $parent.$index in a div that have ng-if tag. which delete dom element(div) if condition is fall so that case you will receive incorrect $index value. but with ng-show it only add hide class to that div.
So try to ng-show if it is not important to remove div element instead just hide it.
Note:- You are also using orderBy filter in ng-repeat which will sort in only your DOM so if you will find incorrect object value in your controller.
Upvotes: 1 [selected_answer]
|
2018/03/16
| 1,236 | 4,541 |
<issue_start>username_0: I have a RoR Rest API and I want to emit a metric with the status of each response of my API. I managed to do that for all the cases except from those where the controller is crashing.
For example with the following code in the ApplicationController:
```
require 'statsd-ruby'
class ApplicationController < ActionController::API
after_action :push_status_metric
def push_status_metric
statsd = Statsd.new ENV['STATSD_LOCATION'], ENV['STATSD_PORT']
puts normalize_status_metric(response.status)
statsd.increment('ds.status.' + normalize_status_metric(response.status).to_s + '.int') unless request.fullpath == '/health'
end
private
def normalize_status_metric(status)
return 100 if status >= 100 && status < 200
return 200 if status >= 200 && status < 300
return 300 if status >= 300 && status < 400
return 400 if status >= 400 && status < 500
return 500 if status >= 500 && status < 600
0
end
end
```
But this solution doesn't capture errors such as ActionController::RoutingError and ActiveRecord::RecordNotFound.
I tried the following code:
```
rescue_from StandardError do |exception|
statsd = Statsd.new ENV['STATSD_LOCATION'], ENV['STATSD_PORT']
statsd.increment('ds.status.' + normalize_status_metric(response.status).to_s + '.int') unless request.fullpath == '/health'
raise exception
end
```
But when this callback is executed, the response.status value is always 200 (seems like it's not set yet by the framework up to this point).<issue_comment>username_1: >
> But when this callback is executed, the response.status value is always 200 (seems like it's not set yet by the framework up to this point).
>
>
>
Correct, it's not yet set (application didn't attempt to render). Normally, it's the `rescue_from` handler that will render the "error" response, with code and everything.
Upvotes: 2 <issue_comment>username_2: Knowing the the rails logger manages to do this, we can take a look at its class, [`ActionController::LogSubscriber`](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/log_subscriber.rb) and that `process_action` method. So, the status in that event could be `nil`, and we can see how they then convert an exception to a status, if an exception exists:
```
status = payload[:status]
if status.nil? && payload[:exception].present?
exception_class_name = payload[:exception].first
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
end
```
So now, we can do something similar by subscribing to this event on our own, with [Active Support Instrumentation](http://guides.rubyonrails.org/active_support_instrumentation.html#subscribing-to-an-event), by creating an initializer:
```
ActiveSupport::Notifications.subscribe 'process_action.action_controller' do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
# opening a file here is probably a performance nightmare, but you'd be doing something with statsd, not a file, anyway
open('metrics.txt', 'a') do |f|
# get the action status, this code is from the ActionController::LogSubscriber
status = event.payload[:status]
if status.nil? && event.payload[:exception].present?
exception_class_name = event.payload[:exception].first
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
end
f.puts "process_action.action_controller controller: #{event.payload[:controller]} - action: #{event.payload[:action]} - path: #{event.payload[:path]} - status: #{status}"
end
end
```
and hitting it a few times with a simple controller:
```
class HomeController < ApplicationController
def non_standard_status
render html: 'This is not fine', status: :forbidden
end
def error
raise ActiveRecord::RecordNotFound, 'No Records Found'
end
def another_error
raise ArgumentError, 'Some Argument is wrong'
end
def this_is_fine
render html: 'This is fine'
end
end
```
yields a file:
```
process_action.action_controller controller: HomeController - action: non_standard_status - path: /forbidden - status: 403
process_action.action_controller controller: HomeController - action: error - path: /error - status: 404
process_action.action_controller controller: HomeController - action: another_error - path: /error2 - status: 500
process_action.action_controller controller: HomeController - action: this_is_fine - path: /fine - status: 200
```
Upvotes: 4 [selected_answer]
|
2018/03/16
| 991 | 2,126 |
<issue_start>username_0: ```
a = np.array(5)
result = np.array([a-2, a-1, a, a+1, a+2])
print result
array([3, 4, 5, 6, 7])
```
correct!
But what would be a better way to get this with out manually writing `+- 2 a-2, a-1, a, a+1, a+2`
EDIT: second problem:
```
a = np.array([5,16,27])
res = np.concatenate([a-2, a-1, a, a+1, a+2])
print res
array([ 3, 14, 25, 4, 15, 26, 5, 16, 27, 6, 17, 28, 7, 18, 29])
```
Ok
but how to do this with out writing `+-`?<issue_comment>username_1: Did you consider this method ?
```
result = [a+i for i in range(-2,3)]
```
for the second problem, just use a loop (using my method)
```
a, result = np.array([5,6,7]), []
for k in a: result.append([k+i for i in range(-2,3)])
```
or
```
results = [k+i for k in a for i in range(-2,3)]
```
Upvotes: 1 <issue_comment>username_2: Maybe [arange](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.arange.html)?
```
np.arange(a-2, a+3)
#=> array([3, 4, 5, 6, 7])
```
Note that I had to use a+3 for the upper bound since the arguments specify a half-open interval.
**Update** One possible solution for the updated question:
```
np.transpose([np.arange(n-2, n+3) for n in a]).flatten()
#=> array([ 3, 14, 25, 4, 15, 26, 5, 16, 27, 6, 17, 28, 7, 18, 29])
```
As a function:
```
def ranges(a, x):
return np.transpose([np.arange(n-x, n+x+1) for n in a]).flatten()
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: How about:
```
>>> import numpy as np
>>> np.add.outer(np.r_[-2:3], [5,16,27]).ravel()
array([ 3, 14, 25, 4, 15, 26, 5, 16, 27, 6, 17, 28, 7, 18, 29])
```
Upvotes: 0 <issue_comment>username_4: Since you are using `numpy`, take advantage of its vectorisation.
You can also wrap your logic in a function to make it adaptable.
**Problem 1**
```
a = np.array(5)
def ranger(a, n):
return np.arange(a-n, a+n+1)
ranger(a, 2) # array([3, 4, 5, 6, 7])
```
**Problem 2**
```
a = np.array([5, 16, 27])
def ranger(a, n):
return np.hstack([a+i for i in range(-n, n+1)])
ranger(a, 2) # array([ 3, 14, 25, 4, 15, 26, 5, 16, 27, 6, 17, 28, 7, 18, 29])
```
Upvotes: 1
|
2018/03/16
| 1,531 | 5,501 |
<issue_start>username_0: Hi I am trying to add text entered in an field to the end of a list using Jquery . This is my HTML .
```js
$(function() {
var $newitem = $('#newItemButton');
var $text = $('#itemDescription');
$newitem.show();
$('#newItemForm').hide();
$('#showForm').on('click', function(){
$newitem.hide();
$('#newItemForm').show();
});
$('#addButton').on('submit', function(e){
e.preventDefault();
var text = $text.val();
console.log(text); //Why is this not working
$('li:last').after('- '+ text +'
');
$newItemForm.hide();
$newitem.show();
});
});
```
```html
JavaScript
List
====
Buy groceries
-------------
* *fresh* figs
* pine nuts
* honey
* balsamic vinegar
new item
```
While other things are working the user input is not getting added to the end of the li . I tried console logging the user input value but nothing is showing up . Could someone please tell me what I am doing wrong ?
Also could someone let me know how do they debug Jquery efficiently ? I tried to trace in chrome inspector but it goes to the Jquery file unlike when using vanilla JS and tracking the program execution and variable assignment seems to be all most impossible with so much Jquery code being run .<issue_comment>username_1: ```js
$(function() {
var $newitem = $('#newItemButton');
var $text = $('#itemDescription');
$newitem.show();
$('#newItemForm').hide();
$('#showForm').on('click', function(){
$newitem.hide();
$('#newItemForm').show();
});
$('#addButton').on('click', function(e){
e.preventDefault();
var text = $text.val();
$('ul').append('- '+ text +'
');
$('#newItemForm').hide();
$newitem.show();
$text.val('');
});
});
```
```html
JavaScript
List
====
Buy groceries
-------------
* *fresh* figs
* pine nuts
* honey
* balsamic vinegar
new item
```
Upvotes: 2 <issue_comment>username_2: Try using
```
$(function() {
var $newitem = $('#newItemButton');
var $text = $('#itemDescription');
$newitem.show();
$('#newItemForm').hide();
$('#showForm').on('click', function(){
$newitem.hide();
$('#newItemForm').show();
});
$('#addButton').on('click', function(e){
e.preventDefault();
var text = $text.val();
console.log(text);
$('li:last').after('- '+ text +'
');
$newItemForm.hide();
$newitem.show();
});
});
```
You should be using `click`, not `submit`.
How to debug JavaScript / jQuery
--------------------------------
Your `console.log` approach is not bad. Since you've noticed it doesn't get executed, you should ask yourself, *why* it is not getting executed. In this case it was the wrong listener tag (`submit` instead of `click`).
Another approach is, as you've mentioned, to use the Chrome debugger. You can set a breakpoint by clicking on a line number. This way you skip all irrelevant code.
[](https://i.stack.imgur.com/cDt5r.png)
Also you should probably always also use "Step over" (or `F10`) to go forward in debug mode, to not unnecessarily see the jQuery code.
[](https://i.stack.imgur.com/sz36P.png)
Upvotes: 3 [selected_answer]<issue_comment>username_3: Here is an updated javascript that works:
```
$(function() {
var $newitem = $('#newItemButton');
var $text = $('#itemDescription');
$newitem.show();
$('#newItemForm').hide();
$('#showForm').on('click', function(){
$newitem.hide();
$('#newItemForm').show();
});
$('#newItemForm').on('submit', function(e){
e.preventDefault();
var text = $('#itemDescription').val();
console.log(text); //Why is this not working
$('li:last').after('- '+ text +'
');
$('#newItemForm').hide();
$newitem.show();
});
});
```
**More explanations**
The `submit` event must be binded on a `form` element. See JQuery documentation: <https://api.jquery.com/submit/>
In your code, you misuse the `$()` function. It should take a selector as parameter. Basically, you can use the `id` of the element.
Upvotes: 2 <issue_comment>username_4: `e.preventDefault` will prevent the current behavior. Look at your code.
```
$('#addButton').on('submit', function(e) {
e.preventDefault();
```
You have added the `preventDefault`, which means you are not preventing the submission of the form. This code should changed to
```
$('#newItemForm').on('submit', function(e) {
e.preventDefault();
```
Now whenever the form is trying to submit you are preventing it. This should work as you expected. Look at the snippet below.
```js
$(function() {
var $newitem = $('#newItemButton');
var $text = $('#itemDescription');
$newitem.show();
$('#newItemForm').hide();
$('#showForm').on('click', function(){
$newitem.hide();
$('#newItemForm').show();
});
$('#newItemForm').on('submit', function(e){
e.preventDefault();
var text = $text.val();
console.log(text); //Why is this not working
$('li:last').after('- '+ text +'
');
$('#newItemForm').hide();
$newitem.show();
});
});
```
```html
List
====
Buy groceries
-------------
* *fresh* figs
* pine nuts
* honey
* balsamic vinegar
new item
```
Upvotes: 2
|
2018/03/16
| 344 | 1,373 |
<issue_start>username_0: I am using ag-Grid **onCellEditingStopped** event handler to get the changed value of a grid cell.
```
onCellEditingStopped: function(event) {
// event.value present the current cell value
console.log('cellEditingStopped');
}
```
But it does not provide the previous value (the value before the change happens). Is there anyway to get the previous value ?
My current solution:
I am using **onCellEditingStarted** event to store the current cell value in a separate variable and use that variable inside the **onCellEditingStopped** event handler function. But it is not a clear solution.
Thanks<issue_comment>username_1: you can use value Setter function for that column as below.
```
valueSetter: function (params) {
console.log(params.oldValue);
console.log(params.newValue);
if (params.oldValue !== params.newValue) {
//params.data["comments"] = params.newValue;
return true;
}
else {
return false;
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm using `onCellEditingStopped` in my Angular application, with agGrid v24.1... and it does have an `oldValue` and a `newValue` value in there.
```
onCellEditingStopped = (_params) => {
if (_params.newValue != _params.oldValue) {
// Do something...
}
}
```
Upvotes: 0
|
2018/03/16
| 994 | 3,507 |
<issue_start>username_0: Am developing a application using swift,in my am integrating cometchat following the link <https://docs.cometchat.com/ios-sdk/quick-start/>. So am fetching chat history from the server.
Now I got two(sender messages and receiver messages) nsmutablearray value from the server.
i.e., `var firstArr = response!["history"]! as! NSMutableArray`
```
var secondArr = response!["history"]! as! NSMutableArray
```
I merged two nsmuatblearray values and the result i got is:
```
[
{
from = 1;
id = 68;
localmessageid = "46A9A5E5-FEEC-4588-B7D6-18E88BA68393_2";
message = "ckeck messages";
"message_type" = 10;
old = 1;
self = 1;
sent = 1521185409000;
},
{
from = 2;
id = 69;
localmessageid = "46A9A5E5-FEEC-4588-B7D6-18E88BA68393_1";
message = "sent to thiyakarajan";
"message_type" = 10;
old = 1;
self = 1;
sent = 1521185410000;
}
]
```
In the responses key value sent is refered as timestamp.
using that sent key(timestamp) help me to sort array in ascending
order.
And also me to load message value in table view.
Thanks<issue_comment>username_1: It's a very bad practice working with network data like that. Especially if you want to use this data further inside of your app.
1. You need to parse the data received either in `Dictionary` or in your own data structure to work with it safely. There're plenty of ways to do that including `JSONSerialization`, `Codable Protocol` or even external libraries like `SwiftyJSON`
2. After parsing you will have your objects that you can work with without necessity of casting `Any` type to expected types, which brings a lot of optional checks. So let's say you have your structure called `Message` that contains all the data from JSON, after getting all the objects you'll have your neat `[Message]` array that you can pass around the application.
3. To sort array by some of the properties you simply use function `sorted(by:)` that is default for any collection. In your case: `sortedArray = myArray.sorted(by: {$0.sent < $1.sent})`
4. Now you can use this array as a dataSource for your tableView using `UITableViewDataSource` protocol
It's obvious that you're pretty new to iOS programming, so I'd recommend to look up for some tutorials on working with networking data. You can watch this [video](https://www.youtube.com/watch?v=_c0pAz3UPEs) for example, it pretty much sums up everything mentioned above.
Upvotes: 0 <issue_comment>username_2: Do code like this
```
Save Swift Array
var firstArr : Array> = response!["history"]! as! Array>
Access valus
let strMessage : String = fistArr[index]["message"] as! String
```
Will works..!
Upvotes: 0 <issue_comment>username_3: You can access the Array in `cellforrowatindexpath` method of your TableView by using code like `[[yourarray objectAtIndex:indexPath.row]objectForKey:@"message"]`. By using this line you can access the value of message of the array at indexPath 0. Also for sorting the Array depending on timestamp please refer the below code:
```
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"sent" ascending: YES];
return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
```
We have used the same in our ReadyUI code. Please refer our ReadyUI source code and email us at <EMAIL> if you need additional assistance.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 864 | 3,237 |
<issue_start>username_0: ```
php
include_once 'config.php';
$query = $config - prepare("SELECT `edit`, `user_banned`, `ban_reason`, `ban_time`, `user_banner`, `ban_timestamp` FROM `samp_ban` ORDER BY `edit` ASC LIMIT 10");
if($query -> execute())
{
$query_results = $query->fetchAll();
if($ban_time == 0) { $query_result["ban_time"] = "Permanent"; }
}
?>
```
code edidetcode edidetcode edidetcode edidet
ERROR: Undefined variable: ban\_time<issue_comment>username_1: You need to change
```
php
include_once 'config.php';
$query = $config - prepare("SELECT `Username`, `Headshots`, `ForumName` FROM `users` ORDER BY `Headshots` DESC LIMIT 10");
if($query -> execute())
{
$row_count = $query -> rowCount();
if($row_count)
{
while($query_result = $query -> fetch())
$Username = $query_result['Username'];
$Headshots = $query_result['Headshots'];
$ForumName = $query_result['ForumName'] ;
}
}
?>
```
into
```
php
include_once 'config.php';
$query = $config - prepare("SELECT `Username`, `Headshots`, `ForumName` FROM `users` ORDER BY `Headshots` DESC LIMIT 10");
if($query -> execute())
{
$row_count = $query -> rowCount();
if($row_count)
{
while($query_result = $query -> fetch())
{
$Username = $query_result['Username'];
$Headshots = $query_result['Headshots'];
$ForumName = $query_result['ForumName'] ;
echo '';
echo '';
echo $Username;
echo '';
echo '';
echo $Headshots;
echo '';
echo '';
echo $ForumName;
echo '';
echo '';
}
}
}
?>
```
You forgot the { } arround the while loop
Upvotes: 0 <issue_comment>username_2: You have to combine and html and php for getting all data from query
```
if($row_count)
{
while($query_result = $query -> fetch()){
$Username = $query_result['Username'];
$Headshots = $query_result['Headshots'];
$ForumName = $query_result['ForumName'] ;
?>
php echo $Username ?
php echo $Headshots ?
php echo $ForumName ?
php
}
}
</code
```
Upvotes: 1 <issue_comment>username_3: The issue is that you are trying to output same variables on both rows. As a result you get two rows with same results. You have to store rows from database to array and then make a for loop to output your html with data from that array.
PHP code
```
php
include_once 'config.php';
$query = $config - prepare("SELECT `Username`, `Headshots`, `ForumName` FROM `users` ORDER BY `Headshots` DESC LIMIT 10");
if($query -> execute())
{
$query_results = $query->fetchAll();
}
?>
```
HTML code
```
Nickname
Headshots
Forum Name
php foreach( $query\_results as $query\_result ) { ?
php echo $query\_result["Username"]; ?
php echo $query\_result["Headshots"]; ?
php echo $query\_result["ForumName"]; ?
php } ?
```
Upvotes: 1 [selected_answer]
|
2018/03/16
| 637 | 2,395 |
<issue_start>username_0: Trying to practice Java by doing basic functionality like reading input.
I am trying to parse `movies-sample.txt` found in:
```
C:\University\BigDataManagement\Data-Mining\hw1\src\main\resources\movies-sample.txt
```
Trying to reach `movies-sample.txt` from
```
C:\University\BigDataManagement\Data-Mining\hw1\src\main\java
\univ\bigdata\course\MoviesReviewsQueryRunner.java
```
Using the answer found [here](https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) on how to parse a large file line by line.
```
File file = new File("../../../../../resources/movies-sample.txt");
```
I am getting the following error:
>
> The system cannot find the path specified
>
>
>
Given the above two paths, what am I doing incorrect?<issue_comment>username_1: If it's a web app then the `resources` folder is your root element, otherwise it will be the `src` folder as mentioned in comments.
In your case here as you are writing a standalone Java program and as your file is loacted in the `resources` folder, you can use **[`CLassLoader`](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html)** to read the file as a stream.
This is how should be your code:
```
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("movies-sample.txt");
```
Then you will be able to read the `is` stream line by line.
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you run your program directly from command line, then the path must be related to your current directory.
If you run your program from an IDE, then the current directory of the runnin program depends on the IDE and the way it is configured.
You can determine what is the current directory with `System.getProperty("user.dir")`
Whatever, hard coding a path in an application is always a bad thing because you cannot ensure where the run was launched from. Either:
* it is a user resource, then its path must be input in some way (*open...* in GUIs apps)
* it is a resource needed by the app to run correctly and it should be embedded in some way into the app itself (look for Resource Bundle)
* it is a kind of *optional* external resource (config file for example, or path specified in a config file) and its location should be computed in some way.
Upvotes: 0
|
2018/03/16
| 584 | 2,251 |
<issue_start>username_0: I'm new to ActivePerl. However, I need to using it on my new Windows 8.1.
I try to download both 5.26.1.2601 and 5.24.3.2404 (x64) to installed.
But when I run with file.pl and file.bat, it would be suddenly closed in few second.
Then I need to test with different Windows OS. I saved these files to my daughter's computer that is Windows 7 32-bit and surprise that all works very well just clicking.
I already set PATH to C:\Perl64\bin and C:\Perl64\site\bin but it still not working.
So, I doubt why problem occured on my Windows 8.1 and how to solved its?
Thank<issue_comment>username_1: I suspect you are running them by double-clicking them. This runs the program and immediately exits (losing all output) as soon as the program is done. For toy programs that's practically immediately.
What happens when you run the programs from a Command Prompt (or PowerShell) window?
Upvotes: 2 <issue_comment>username_2: I suggest username_1's response is on target, but there's more. The windows OS needs to be CAREFULLY APPENDED include the path to the perl interpreter in the [system environment variable](https://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows) PLUS the computer might need a RE-BOOT, or the command window in use will need a PATH revision to update the path to include that same directory location for the perl interpreter. You stated that the path was set, but not clearly; was that in the command prompt window or via the system environment variable? I suggest updating the PATH environment variable in the system via the Windows control panel.
The call to run the perl script could be made from the directory containing the perl script, or the path to the script needs to precede the call, such as: c:\directory-a\dirctory-b\file.pl ---running file.pl from c:\users\mysuername isn't going to cut it, unless that just happens to be where the perl script lives.
A debugging suggestion, add the following statements to your perl script:
```
print "my script runs!";
sleep 4;
```
and see if anything shows on the screen. If you run from the command window rather than double-clicking the file in File Explorer, the window shouldn't disappear.
Upvotes: 0
|
2018/03/16
| 607 | 2,374 |
<issue_start>username_0: I'm trying to write a program which compares specific parameters of INI Files.
The problem is that there are some Strings in those files which are marked with an apostrophe and some other which are marked with quote marks.
What I am trying to do is to convert either every quotation mark to an apostrophe or to convert every apostrophe to a quotation mark.
I've tried it with *replace* but the string won't change in either way.
Here is a simple test I made to See if it works, the string is part of an INI File:
```
e = "'03:SUN/05:00:00'"
e.replace("'",'"')
print (e)
```
But the console output is just the same string:
```
'03:SUN/05:00:00'
```
Is there another way to replace them?<issue_comment>username_1: I suspect you are running them by double-clicking them. This runs the program and immediately exits (losing all output) as soon as the program is done. For toy programs that's practically immediately.
What happens when you run the programs from a Command Prompt (or PowerShell) window?
Upvotes: 2 <issue_comment>username_2: I suggest username_1's response is on target, but there's more. The windows OS needs to be CAREFULLY APPENDED include the path to the perl interpreter in the [system environment variable](https://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows) PLUS the computer might need a RE-BOOT, or the command window in use will need a PATH revision to update the path to include that same directory location for the perl interpreter. You stated that the path was set, but not clearly; was that in the command prompt window or via the system environment variable? I suggest updating the PATH environment variable in the system via the Windows control panel.
The call to run the perl script could be made from the directory containing the perl script, or the path to the script needs to precede the call, such as: c:\directory-a\dirctory-b\file.pl ---running file.pl from c:\users\mysuername isn't going to cut it, unless that just happens to be where the perl script lives.
A debugging suggestion, add the following statements to your perl script:
```
print "my script runs!";
sleep 4;
```
and see if anything shows on the screen. If you run from the command window rather than double-clicking the file in File Explorer, the window shouldn't disappear.
Upvotes: 0
|
2018/03/16
| 481 | 1,668 |
<issue_start>username_0: I'm trying to avoid jQuery, simply needing to clone an element, *e.g.*
```
var table: Node = document.querySelector('#myTable').cloneNode(false);
```
Later, I need to
```
return table.outerHTML;
```
but I'm getting the error
```
ERROR in [at-loader] ./src/components/overworld-component.tsx:24:43
TS2339: Property 'outerHTML' does not exist on type 'Node'.
```
Which, makes sense. Only `Element`s have `outerHTML`.
What am I supposed to do here?
* Somehow cast `Node` to `Element` since I know it's definitely an `Element`?
* Find some other way to clone the element (without children), but as an element?
* Or, am I doing something wrong further upstream? Maybe I don't need to use `outerHTML` at all? I thought I needed the `outerHTML` in React for `dangerouslySetInnerHTML`ing:
```
export class OverworldComponent extends React.Component {
render() {
var table: Node = document.querySelector('div.file div.data table').cloneNode(false);
return ;
}
}
```<issue_comment>username_1: Don't specify the datatype, Just use 'any'
```
var table: any = document.querySelector('#myTable').cloneNode(false);
```
Or
```
var table: HTMLElement = document.querySelector('#myTable').cloneNode(false);
```
Upvotes: 1 <issue_comment>username_2: What about saving the outerHTML directly ?
```
export class OverworldComponent extends React.Component {
render() {
var outerHTML: string = document.querySelector('div.file div.data table').outerHTML;
return ;
}
}
```
or you can cast `cloneNode`:
`var table: Element = document.querySelector('div.file div.data table').cloneNode(false) as Element;`
Upvotes: 3 [selected_answer]
|
2018/03/16
| 889 | 3,206 |
<issue_start>username_0: This question has been [asked](https://stackoverflow.com/questions/21817340/jquery-slidetoggle-displaynone) a [few](https://stackoverflow.com/questions/22384461/trouble-with-a-responsive-menu-and-jquerys-slidetoggle) times before years ago. I am basically asking if there is a more up to date 'cleaner' way of handling this problem.
I am using `slideToggle` on a button to show and hide a menu div when the screen is small. However, the style is added inline.
Without clicking the button
```
...
```
Toggling the button once
```
...
```
Toggling the button twice
```
...
```
So this leads to a situation where after toggling the button twice the in-line style of `display: none` remains on the div. So if I then change the width of the screen so that the button disappears the menu is still hidden when it should be visible.
Is there a clean way of dealing with this issue?<issue_comment>username_1: As said in the comments, you could stop using `slideToggle` and use `toggleClass` instead.
Here, I emulate the `slideToggle` effect with a combination of `max-height` and `transition` :
```js
$('button').on('click',function(){
$('.test').toggleClass('shown');
});
```
```css
.test{
max-height: 0;
overflow: hidden;
transition: all .5s;
background-color: blue;
height: 200px;
}
.shown{
max-height: 200px;
}
```
```html
Toggle !
```
Upvotes: 1 <issue_comment>username_2: You can use Bootstrap library for toggling options and many more functionalities.
You can see example here, [Bootstrap collapse.](https://getbootstrap.com/docs/4.0/components/collapse/#example)
Upvotes: 0 <issue_comment>username_3: jQuery solution that doesn't require `refresh()` on a predefined screen width
```
$(document).ready(function() {
$('#navbar-toggle').click(function() {
// Toggle navbar button animation
$(this).toggleClass('active');
// Toggle navbar menu
$('.site-nav-container').slideToggle(500, function() {
if ($(this).css('display') == 'none') {
// Remove inline class
$(this).css('display', '');
}
});
});
});
```
Upvotes: 1 [selected_answer]<issue_comment>username_4: Run into this situation today and I fixed it using `$(window).resize` event. My case was similar to yours: I had a jQuery function that `slideToggle()` my `ul` containing the menu but, when my nav was toggled off and I resized the window back to desktop-size, I couldn't see the nav bar anymore because I had in-line style `style="display: block;"`.
So, my solution was listening for window resize and check if the `ul` was hidden (my `ul` has a class called `nav` and my breakpoint is 667 px).
```
$(window).resize(function () {
if ($(this).width() > 667 && $(".nav").is(":hidden")) {
$(".nav").removeAttr("style");
}
});
```
Upvotes: 0 <issue_comment>username_5: Replace slideToggle code with below piece of code:
```
var sel = $('.nav');
if(sel[0].style.display === 'block') {
sel[0].style.display = 'none';
sel[0].style.display = '';
} else {
sel[0].style.display = 'block';
}
```
Upvotes: 0
|
2018/03/16
| 677 | 2,388 |
<issue_start>username_0: I installed a Joomla 3.6.5 and now I cannot install any packages.
And this is the error I've got :
>
> Unable to find install package
>
>
>
[](https://i.stack.imgur.com/W43M5.jpg)
This happens when I click on '*Add "Install from Web" tab*' button too!
I tried reinstalling and upgrading to 3.8.5 but nothing changed! I can install nothing!
Update:
Folder permissions:
[](https://i.stack.imgur.com/H5x8B.jpg)<issue_comment>username_1: Anything related to installation error, you should check
1. Your temp file location is correct or not
2. Your temp folder has appropriate permission or not.
You can attach screenshot of your folder permissions here.
Upvotes: 1 <issue_comment>username_2: I have two suggestions.
(1) The problem may be because **upload\_tmp\_dir** isn't set in your PHP config.
Look in SYSTEM > SYSTEM INFORMATION > PHP INFORMATION and check if upload\_tmp\_dir has been set. If not, you need to edit php.ini
On our servers (which use open base dir), the setting is:
```
upload_tmp_dir=/tmp
```
Depending on your server configuration, this value could be different for you.
(2) The other place to check is the value in SYSTEM > GLOBAL CONFIGURATION > SERVER
If you haven't already done so, try using the full server path to the tmp directory, rather than say a path relative to your home directory.
Good luck!
Upvotes: 1 <issue_comment>username_3: The temp folder is not where you have told Joomla it is.
Upvotes: 1 <issue_comment>username_4: I know this is an old topic, but maybe my solution might be helpful for someone...
>
> Error: Unable to find install package (and other errors like that)
>
>
>
is nothing more than permissions error check... So, you have to give right permissions to yourself for:
* /var/www/html/nameofyoursite/languages,
* /var/www/html/nameofyoursite/tmp,
* /var/www/html/nameofyoursite/administrator/languages,
* /var/www/html/nameofyoursite/administrator/manifest/everythinginmanifestfolder,
* /var/www/html/nameofyoursite/administrator/modules,
* /var/www/html/nameofyoursite/administrator/logs.
That's it! Now you can install languages and everything else...
(I found this solution yesterday, and cp my answer from joomla's forum)
Upvotes: -1
|
2018/03/16
| 496 | 1,448 |
<issue_start>username_0: ```
select count(*)
from siebel.s_srv_req
where trunc(created)>='25-Sep-2017'
and trunc(created)<='25-Sep-2017'
and X_MBL_AREA_LIC is not null
and sr_cat_type_cd <> 'Trouble Ticket';
```
I'm trying to execute above sql in my oracle db and its not giving results.
If i execute this as below it works fine. Created is an indexed column.
```
select count(*)
from siebel.s_srv_req
where trunc(created)>='25-Sep-2017'
and trunc(created)<='25-Sep-2017'
```
when i see the execution plan it gives below error
[](https://i.stack.imgur.com/OKfCd.jpg)
What should i need to be done to work this fine. This is working fine in my test environment<issue_comment>username_1: Please check if `X_MBL_AREA_LIC` and `sr_cat_type_cd` fields are indexed.
Also if you can change the values of sr\_cat\_type\_cd column to integer values it could work faster. Now you make a string comparison for every record.
Upvotes: 1 <issue_comment>username_2: If you use `TRUNC`, the index may not be used by optimizer. If you are sure that you don't have data in the table for dates beyond `'25-Sep-2017'`,
you may use
```
WHERE created >= DATE '2017-09-25'
```
Otherwise use,
```
WHERE created >= DATE '2017-09-25' AND created < DATE '2017-09-26'
```
or if you are using `SYSDATE`,
`created >= TRUNC(SYSDATE) and created < TRUNC(SYSDATE) + 1`
Upvotes: 2
|
2018/03/16
| 751 | 2,849 |
<issue_start>username_0: I am trying to send sftp call through endpoint and need to pass header as one of the parameters. Can some on help me out on this.
My route will be looking like this
```
```
Another route will be like
```
20170512
```
Thanks,,<issue_comment>username_1: Your setup has multiple issues. Where to begin best?
* The first route is an **SFTP poller**. That means it receives a message whenever a **new file is available** on the sftp server in the given directory. That's fine, but...
* Your SFTP poller has a dynamic expression as subdirectory (`${header.date}`). As far as I know you **cannot have a dynamic `from` address** in a Camel route. Because this would mean that you could consume from multiple endpoints.
* In your example the SFTP poller would have to scan whatever subdirectories on the server. To achieve that you have to remove the part `${header.date}` and set the **`recursive` option**.
* The second route is timer based a sends messages to `direct:sftpCall`. This means to a route that begins with `from uri="direct:sftpCall"`. But **you don't have such a route**.
I guess that with you want to call the SFTP route that has `sftpCall` as route id. But that does not match the destination route at all.
* `direct` is the "protocol" (synchronous in-memory call). But your destination route uses the protocol `sftp`
* `sftpCall` is a route id. You cannot call a route by its ID (as far as I know)
If my guess is correct and you want that **your timer route triggers your sftp route**, the timer route has to **upload a file** to the sftp-server/directory the sftp route consumes. That would simply look somehow like this.
```
```
Upvotes: 2 <issue_comment>username_2: You have 2 misconception
>
> 1. Use of header in from endpoint definition
>
>
>
* In/Out header is a part of exchange object and exchange object is create by existing route (naturally)
* The `from` endpoint definition is fixed once the route is created
For your route definition, `${header.date}` will be use as a hard code string path because there is no exchange object when the spring create the route.
>
> 2. Use of direct component
>
>
>
The [direct](http://camel.apache.org/direct.html) component is used to connect existing routes in the same camel context, not to kick start/build another route.
---
**If you are uploading files to sftp server**, then you only need the timer route and paste your `sftp` component string in the `to` endpoint definition and use [toD](http://camel.apache.org/message-endpoint.html) or [Recipient List](http://camel.apache.org/recipient-list.html) instead of `to`.
**If you are downloading files from sftp server**, then you need to use RouteBuilder to create route and [ControlBus](http://camel.apache.org/controlbus-component.html) to start/stop created route.
Upvotes: 0
|
2018/03/16
| 1,040 | 3,546 |
<issue_start>username_0: I am having memory leaks with Unity with the following code:
Behavior: in runtime, Unity eventually uses > 64GB of RAM and crashes (Thats all this machine has)
Scene: I only have one plane in my scene with the below code.
How do I fix this? I dont think I want a weak reference here, (or at least in C++ I wont use a weak\_ptr in this scenario, maybe a unique\_ptr). I just want the memory to be deallocated when objects fall out of scope.
```
void Start () {
frameNumber_ = 0;
// commented code leaks memory even if update() is empty
//WebCamDevice[] devices = WebCamTexture.devices;
//deviceName = devices[0].name;
//wct = new WebCamTexture(deviceName, 1280, 720, 30);
//GetComponent().material.mainTexture = wct;
//wct.Play();
wct = new WebCamTexture(WebCamTexture.devices[0].name, 1280, 720, 30);
Renderer renderer = GetComponent();
renderer.material.mainTexture = wct;
wct.Play();
}
// Update is called once per frame
// This code in update() also leaks memory
void Update () {
if (wct.didUpdateThisFrame == false)
return;
++frameNumber\_;
Texture2D frame = new Texture2D(wct.width, wct.height);
frame.SetPixels(wct.GetPixels());
frame.Apply();
return;
```<issue_comment>username_1: See this:
```
Texture2D frame = new Texture2D(wct.width, wct.height);
```
You are crating new `Texture2D` almost every frame or when `didUpdateThisFrame` is true. This is **very expensive** and most of the time is not even freed by Unity. You only need to create one `Texture2D` then re-use it in the `Update` function. Make the `frame` variable a global variable then initialize it **once** in the `Start` function.
---
By doing this, you will likely run into new problem when camera image height/width changes causing `frame.SetPixels(wct.GetPixels());` to fail with an exception. To fix this, check when the camera texture size changes then automatically resize your `frame` Texture. This check should be done in the Update function before `frame.SetPixels(wct.GetPixels());`.
```
if (frame.width != wct.width || frame.height != wct.height)
{
frame.Resize(wct.width, wct.height);
}
```
Your final code should looks something like this:
```
int frameNumber_ = 0;
WebCamTexture wct;
Texture2D frame;
void Start()
{
frameNumber_ = 0;
wct = new WebCamTexture(WebCamTexture.devices[0].name, 1280, 720, 30);
Renderer renderer = GetComponent();
renderer.material.mainTexture = wct;
wct.Play();
frame = new Texture2D(wct.width, wct.height);
}
// Update is called once per frame
// This code in update() also leaks memory
void Update()
{
if (wct.didUpdateThisFrame == false)
return;
++frameNumber\_;
//Check when camera texture size changes then resize your frame too
if (frame.width != wct.width || frame.height != wct.height)
{
frame.Resize(wct.width, wct.height);
}
frame.SetPixels(wct.GetPixels());
frame.Apply();
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Archaic topic but I found something interesting. I used to have this in my code:
```
downloadedTexture = DownloadHandlerTexture.GetContent(www);
m_PictureScreen.GetComponent().texture = downloadedTexture;
```
this caused huge problems with memory leaks, app went over 8gb with every iteration of that. I my case that could ramp up to thousands of files per day.
I solved it by using this line before:
```
Texture2D.Destroy(m_PictureScreen.GetComponent().texture);
```
Not sure how but it worked and memory leaks do not exist now.
Upvotes: 1
|
2018/03/16
| 5,340 | 9,596 |
<issue_start>username_0: I've been trying to finish <NAME>'s Machine Learning course, I am at the part about logistic regression now. I am trying to discover the parameters and also calculate the cost without using the MATLAB function `fminunc`. However, I am not converging to the correct results as posted by other students who have finished the assignment using `fminunc`. Specifically, my problems are:
* the parameters `theta` are incorrect
* my cost seems to be blowing up
* I get many `NaN`s in my cost vector (I just create a vector of the costs to keep track)
I attempted to discover the parameters via Gradient Descent as how I understood the content. However, my implementation still seems to be giving me incorrect results.
```
dataset = load('dataStuds.txt');
x = dataset(:,1:end-1);
y = dataset(:,end);
m = length(x);
% Padding the the 1's (intercept term, the call it?)
x = [ones(length(x),1), x];
thetas = zeros(size(x,2),1);
% Setting the learning rate to 0.1
alpha = 0.1;
for i = 1:100000
% theta transpose x (tho why in MATLAB it needs to be done the other way
% round? :)
ttrx = x * thetas;
% the hypothesis function h_x = g(z) = sigmoid(-z)
h_x = 1 ./ (1 + exp(-ttrx));
error = h_x - y;
% the gradient (aka the derivative of J(\theta) aka the derivative
% term)
for j = 1:length(thetas)
gradient = 1/m * (h_x - y)' * x(:,j);
% Updating the parameters theta
thetas(j) = thetas(j) - alpha * gradient;
end
% Calculating the cost, just to keep track...
cost(i) = 1/m * ( -y' * log(h_x) - (1-y)' * log(1-h_x) );
end
% Displaying the final theta's that I obtained
thetas
```
The parameters `theta` that I get are:
```
thetas =
-482.8509
3.7457
2.6976
```
The results below is from one example that I downloaded, but the author used **fminunc** for this one.
```
Cost at theta found by fminunc: 0.203506
theta:
-24.932760
0.204406
0.199616
```
The data:
```
34.6236596245170 78.0246928153624 0
30.2867107682261 43.8949975240010 0
35.8474087699387 72.9021980270836 0
60.1825993862098 86.3085520954683 1
79.0327360507101 75.3443764369103 1
45.0832774766834 56.3163717815305 0
61.1066645368477 96.5114258848962 1
75.0247455673889 46.5540135411654 1
76.0987867022626 87.4205697192680 1
84.4328199612004 43.5333933107211 1
95.8615550709357 38.2252780579509 0
75.0136583895825 30.6032632342801 0
82.3070533739948 76.4819633023560 1
69.3645887597094 97.7186919618861 1
39.5383391436722 76.0368108511588 0
53.9710521485623 89.2073501375021 1
69.0701440628303 52.7404697301677 1
67.9468554771162 46.6785741067313 0
70.6615095549944 92.9271378936483 1
76.9787837274750 47.5759636497553 1
67.3720275457088 42.8384383202918 0
89.6767757507208 65.7993659274524 1
50.5347882898830 48.8558115276421 0
34.2120609778679 44.2095285986629 0
77.9240914545704 68.9723599933059 1
62.2710136700463 69.9544579544759 1
80.1901807509566 44.8216289321835 1
93.1143887974420 38.8006703371321 0
61.8302060231260 50.2561078924462 0
38.7858037967942 64.9956809553958 0
61.3792894474250 72.8078873131710 1
85.4045193941165 57.0519839762712 1
52.1079797319398 63.1276237688172 0
52.0454047683183 69.4328601204522 1
40.2368937354511 71.1677480218488 0
54.6351055542482 52.2138858806112 0
33.9155001090689 98.8694357422061 0
64.1769888749449 80.9080605867082 1
74.7892529594154 41.5734152282443 0
34.1836400264419 75.2377203360134 0
83.9023936624916 56.3080462160533 1
51.5477202690618 46.8562902634998 0
94.4433677691785 65.5689216055905 1
82.3687537571392 40.6182551597062 0
51.0477517712887 45.8227014577600 0
62.2226757612019 52.0609919483668 0
77.1930349260136 70.4582000018096 1
97.7715992800023 86.7278223300282 1
62.0730637966765 96.7688241241398 1
91.5649744980744 88.6962925454660 1
79.9448179406693 74.1631193504376 1
99.2725269292572 60.9990309984499 1
90.5467141139985 43.3906018065003 1
34.5245138532001 60.3963424583717 0
50.2864961189907 49.8045388132306 0
49.5866772163203 59.8089509945327 0
97.6456339600777 68.8615727242060 1
32.5772001680931 95.5985476138788 0
74.2486913672160 69.8245712265719 1
71.7964620586338 78.4535622451505 1
75.3956114656803 85.7599366733162 1
35.2861128152619 47.0205139472342 0
56.2538174971162 39.2614725105802 0
30.0588224466980 49.5929738672369 0
44.6682617248089 66.4500861455891 0
66.5608944724295 41.0920980793697 0
40.4575509837516 97.5351854890994 1
49.0725632190884 51.8832118207397 0
80.2795740146700 92.1160608134408 1
66.7467185694404 60.9913940274099 1
32.7228330406032 43.3071730643006 0
64.0393204150601 78.0316880201823 1
72.3464942257992 96.2275929676140 1
60.4578857391896 73.0949980975804 1
58.8409562172680 75.8584483127904 1
99.8278577969213 72.3692519338389 1
47.2642691084817 88.4758649955978 1
50.4581598028599 75.8098595298246 1
60.4555562927153 42.5084094357222 0
82.2266615778557 42.7198785371646 0
88.9138964166533 69.8037888983547 1
94.8345067243020 45.6943068025075 1
67.3192574691753 66.5893531774792 1
57.2387063156986 59.5142819801296 1
80.3667560017127 90.9601478974695 1
68.4685217859111 85.5943071045201 1
42.0754545384731 78.8447860014804 0
75.4777020053391 90.4245389975396 1
78.6354243489802 96.6474271688564 1
52.3480039879411 60.7695052560259 0
94.0943311251679 77.1591050907389 1
90.4485509709636 87.5087917648470 1
55.4821611406959 35.5707034722887 0
74.4926924184304 84.8451368493014 1
89.8458067072098 45.3582836109166 1
83.4891627449824 48.3802857972818 1
42.2617008099817 87.1038509402546 1
99.3150088051039 68.7754094720662 1
55.3400175600370 64.9319380069486 1
74.7758930009277 89.5298128951328 1
```<issue_comment>username_1: I ran your code and it does work fine. However, the tricky thing about gradient descent is ensuring that your costs don't diverge to infinity. If you look at your costs array, you will see that the costs definitely diverge and this is why you are not getting the correct results.
The best way to eliminate this in your case is to **reduce** the learning rate. Through experimentation, I have found that a learning rate of `alpha = 0.003` is the best for your problem. I've also increased the number of iterations to `200000`. Changing these two things gives me the following parameters and associated cost:
```
>> format long g;
>> thetas
thetas =
-17.6287417780435
0.146062780453677
0.140513170941357
>> cost(end)
ans =
0.214821863463963
```
This is more or less in line with the magnitudes of the parameters you see when you are using `fminunc`. However, they get slightly different parameters as well as different costs because of the actual minimization method itself. `fminunc` uses a variant of [L-BFGS](https://en.wikipedia.org/wiki/Limited-memory_BFGS) which finds the solution in a much faster way.
What is most important is the actual accuracy itself. Remember that to classify whether an example belongs to label 0 or 1, you take the weighted sum of the parameters and examples, run it through the sigmoid function and threshold at 0.5. We find what the average amount of times each expected label and predicted label match.
Using the parameters we found with gradient descent gives us the following accuracy:
```
>> ttrx = x * thetas;
>> h_x = 1 ./ (1 + exp(-ttrx)) >= 0.5;
>> mean(h_x == y)
ans =
0.89
```
This means that we've achieved an 89% classification accuracy. Using the labels provided by `fminunc` also gives:
```
>> thetas2 = [-24.932760; 0.204406; 0.199616];
>> ttrx = x * thetas2;
>> h_x = 1 ./ (1 + exp(-ttrx)) >= 0.5;
>> mean(h_x == y)
ans =
0.89
```
So we can see that the accuracy is the same so I wouldn't worry too much about the magnitude of the parameters but it's more in line with what we see when we compare the costs between the two implementations.
As a final note to you, I would suggest looking at this post of mine for some tips on how to make logistic regression work over long-term. I would definitely recommend normalizing your features prior to finding the parameters to make the algorithm run faster. It also addresses why you were finding the wrong parameters (namely the cost blowing up): [Cost function in logistic regression gives NaN as a result](https://stackoverflow.com/questions/35419882/cost-function-in-logistic-regression-gives-nan-as-a-result/35422981#35422981).
Upvotes: 3 <issue_comment>username_2: normalizing the data using mean and standard deviation as follows enables you to use large learning rate and get a similar answer
```
clear; clc
data = load('ex2data1.txt');
m = length(data);
alpha = 0.1;
theta = [0; 0; 0];
y = data(:,3);
% Normalizing the data
xm1 = mean(data(:,1)); xm2 = mean(data(:,2));
xs1 = std(data(:,1)); xs2 = std(data(:,2));
x1 = (data(:,1)-xm1)./xs1; x2 = (data(:,2)-xm2)./xs2;
X = [ones(m, 1) x1 x2];
for i=1:10000
h = 1./(1+exp(-(X*theta)));
theta = theta - (alpha/m)* (X'*(h-y));
J(i) = (1/m)*(-y'*log(h)-(1-y)'*log(1-h));
end
theta
J(end)
figure
plot(J)
```
Upvotes: 0
|
2018/03/16
| 724 | 2,083 |
<issue_start>username_0: Hi I am trying to write css classes as per the specification given. For example, If i am designing a button they have given specification as below.
Normal:-
[](https://i.stack.imgur.com/WRfo4.png)
Hover:-
[](https://i.stack.imgur.com/cm9wi.png)
Below is my html code which displays button.
```
```
I want to write classes for the above button as per the specification provided. May i know how to write this? I have tried something below but correct me if i am wrong.
```
.btn {
background: rgb(12,116,218);
border: rgb(12,116,218);
border-bottom: rgb(0,76,151);
}
```
Also how can I write css for the hover as per the above specification provided? Any help would be appreciated. Thank you<issue_comment>username_1: Create another rule with `:hover` selector
```css
.btn {
background: rgb(12,116,218);
border: rgb(12,116,218);
border-bottom: rgb(0,76,151);
}
.btn:hover {
background: rgb(46,146,250);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Use CSS pseudo-selectors, also you can combine styles for multiple selectors (separated by coma)
```css
/* styles for the element */
.btn {
background: rgb(12,116,218);
border: 1px solid #0C74Da;
border-bottom: rgb(0,76,151);
}
/* styling when on hover */
.btn:hover {
background: rgb(46,146,250);
border: 1px solid #2E92FA;
}
/* styles for both cases */
.btn, .btn:hover{
font-size: 13px;
color: white;
}
```
Upvotes: 0 <issue_comment>username_3: You can write css as per below:
```css
.btn {
background: rgb(12,116,218);
border: rgb(12,116,218);
border-bottom: rgb(0,76,151);
}
.btn:hover{
background: rgb(255,0,0);
}
.btn:active {
background-color: yellow;
}
.btn:visited {
color: black;
}
```
For better documentation [check this](https://www.w3schools.com/css/css_pseudo_classes.asp)
Upvotes: 0
|
2018/03/16
| 1,768 | 5,956 |
<issue_start>username_0: i need to convert an xml to array.
I get the xml from an online api.
My code so far:
```
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_page('https://url/api/user/distgroup/domain/user?t=ticketofuser');
echo "xml start: ". htmlentities($sXML);
$oXML = new SimpleXMLElement($sXML);
echo "xml: ". $oXML;
foreach($oXML["distributionGroups"] as $key=>$value)
{
$groups[$key]["group"]["id"]=$value["id"];
$groups[$key]["group"]["domain"]=$value["domain"];
$groups[$key]["group"]["name"]=$value["name"];
$groups[$key]["group"]["type"]=$value["type"];
$groups[$key]["group"]["loggedIn"]=$value["loggedIn"];
$groups[$key]["group"]["nightMode"]=$value["nightMode"];
$groups[$key]["group"]["loggedInAgents"]=$value["loggedInAgents"];
$groups[$key]["group"]["freeAgents"]=$value["freeAgents"];
$groups[$key]["group"]["callsWaiting"]=$value["callsWaiting"];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
$_SESSION["groups"]=$groups;
echo "groups: ". $groups;
```
Afterdownloaded the xml it looks like this when i echo it with htmlentities($sXML);
```
xml version="1.0" encoding="UTF-8" standalone="yes"?
33247
soluno.se
Kamoda Support
ATTENDANT
true
false
1
1
0
33257
soluno.se
Test 5
ATTENDANT
false
false
0
0
0
```
My problem is that my array is empty after my try to foreach fill the array.
What am i doing wrong?<issue_comment>username_1: In your second foreach, you are missing the key `group`. Also, you could use `$oXML->group` to iterator over the XML elements:
```
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[]["group"] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row['group']["id"]; // missing 'group' in $row['group']
}
array_multisort($temp, SORT_ASC, $groups);
print_r($temp);
print_r($groups);
```
Output of `$temp`:
```
Array
(
[0] => 33247
[1] => 33257
)
```
Output of `$groups`:
```
Array
(
[0] => Array
(
[group] => Array
(
[id] => 33247
[domain] => soluno.se
[name] => Kamoda Support
[type] => ATTENDANT
[loggedIn] => true
[nightMode] => false
[loggedInAgents] => 1
[freeAgents] => 1
[callsWaiting] => 0
)
)
[1] => Array
(
[group] => Array
(
[id] => 33257
[domain] => soluno.se
[name] => Test 5
[type] => ATTENDANT
[loggedIn] => false
[nightMode] => false
[loggedInAgents] => 0
[freeAgents] => 0
[callsWaiting] => 0
)
)
)
```
Or you could remove `"group"` in your first array :
```
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: `new SimpleXMLElement($sXML)` creates an object (not an array) of an XML element. So in your case, this `$oXML = new SimpleXMLElement($sXML);` gives you the distributionGroups element. From there you can access its child elements like `foreach($oXML->group as $group)`, but remember that `$group` would also be an instance of `SimpleXMLElement()`. To access the content of the element you actually need to cast the object, i.e. `(int) $group->loggedInAgents`, to get an integer value. Otherwise `$group-> loggedInAgents` will actually give you another `SimpleXMLElement()` object, rather than a variable.
read more in the [docs](http://php.net/manual/en/class.simplexmlelement.php)
Upvotes: 0 <issue_comment>username_3: You could make it more flexible by getting the code to copy across each element within the group, adding an element to the array with the element name. This means that as the XML changes (or if) then the code will still retain all of the data being passed over.
I've also merged the two loops, so that $temp is set in the same loop as the main data.
```
$oXML = new SimpleXMLElement($sXML);
$groups = array();
$temp=array();
foreach ( $oXML->group as $group ) {
$data = array();
foreach ( $group as $element ) {
$data[ $element->getName() ] = (string)$element;
}
$groups[]["group"] = $data;
$temp[] = $data["id"];
}
print_r($temp);
print_r($groups);
```
Upvotes: 1
|
2018/03/16
| 1,250 | 4,363 |
<issue_start>username_0: I would like to have VB code in excel. If cell "A1:A200 is blank then concananet cells B1:C1.
[enter image description here](https://i.stack.imgur.com/PI0DC.jpg)<issue_comment>username_1: In your second foreach, you are missing the key `group`. Also, you could use `$oXML->group` to iterator over the XML elements:
```
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[]["group"] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row['group']["id"]; // missing 'group' in $row['group']
}
array_multisort($temp, SORT_ASC, $groups);
print_r($temp);
print_r($groups);
```
Output of `$temp`:
```
Array
(
[0] => 33247
[1] => 33257
)
```
Output of `$groups`:
```
Array
(
[0] => Array
(
[group] => Array
(
[id] => 33247
[domain] => soluno.se
[name] => Kamoda Support
[type] => ATTENDANT
[loggedIn] => true
[nightMode] => false
[loggedInAgents] => 1
[freeAgents] => 1
[callsWaiting] => 0
)
)
[1] => Array
(
[group] => Array
(
[id] => 33257
[domain] => soluno.se
[name] => Test 5
[type] => ATTENDANT
[loggedIn] => false
[nightMode] => false
[loggedInAgents] => 0
[freeAgents] => 0
[callsWaiting] => 0
)
)
)
```
Or you could remove `"group"` in your first array :
```
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: `new SimpleXMLElement($sXML)` creates an object (not an array) of an XML element. So in your case, this `$oXML = new SimpleXMLElement($sXML);` gives you the distributionGroups element. From there you can access its child elements like `foreach($oXML->group as $group)`, but remember that `$group` would also be an instance of `SimpleXMLElement()`. To access the content of the element you actually need to cast the object, i.e. `(int) $group->loggedInAgents`, to get an integer value. Otherwise `$group-> loggedInAgents` will actually give you another `SimpleXMLElement()` object, rather than a variable.
read more in the [docs](http://php.net/manual/en/class.simplexmlelement.php)
Upvotes: 0 <issue_comment>username_3: You could make it more flexible by getting the code to copy across each element within the group, adding an element to the array with the element name. This means that as the XML changes (or if) then the code will still retain all of the data being passed over.
I've also merged the two loops, so that $temp is set in the same loop as the main data.
```
$oXML = new SimpleXMLElement($sXML);
$groups = array();
$temp=array();
foreach ( $oXML->group as $group ) {
$data = array();
foreach ( $group as $element ) {
$data[ $element->getName() ] = (string)$element;
}
$groups[]["group"] = $data;
$temp[] = $data["id"];
}
print_r($temp);
print_r($groups);
```
Upvotes: 1
|
2018/03/16
| 680 | 2,457 |
<issue_start>username_0: ```vbs
SystemUtil.Run "iexplore.exe", "https://www.jetairways.com/EN/IN/Home.aspx"
wait (7)
Set traverse=Browser("Jet Airways: Airlines").Page("Jet Airways: Airlines")
traverse.WebEdit("placeholder:=From").Click
traverse.Link("acc_name:= This link will open Popup window for airport selection. ").WebElement("innerhtml:=All Airports","innertext:=All Airports","outerhtml:=**All Airports** ").Click
traverse.WebTabStrip("html id:=ToC").Link("innerhtml:=Africa","innertext:=Africa").Click
Set oDesc = Description.Create
oDesc( "micclass" ).value = "Link"
oDesc( "href" ).value = "https://www.jetairways.com/EN/IN/Home.aspx#"
Set rc=Browser("creationtime:=0").Page("micClass:=page").ChildObjects(oDesc)
msgbox rc.count
```
UFT is not bale to identify the link, lets say, **Johanesber** or **Port Elizabeth**,etc
This is actually not working. Have tried many ways .
Can some one help me fix this?<issue_comment>username_1: Try to write the link object and the pop up window object in two different lines
`traverse.Link("acc_name:= This link will open Popup window for airport selection. ")`
```
traverse.WebElement("innerhtml:=All Airports","innertext:=All Airports","outerhtml:=**All Airports** ").Click
```
also try to use Regex if the property values contains spaces or symbols.
Upvotes: 1 <issue_comment>username_2: The following code works for me, I cleaned up some of the spaces (and simplified the description a bit). I don't understand what you were trying to accomplish with the last lines of your script (counting the links).
I think the problem you were facing was probably to do with the fact that when you use descriptive programming (either inline with `:=` or using a `Description` object), the values are used as regular expressions and not as plain strings. This means you have to [escape regular expression characters](https://www.regular-expressions.info/characters.html) (in this case `(` and `)`) or else the values won't match.
```vbs
Set traverse=Browser("Jet Airways: Airlines").Page("Jet Airways: Airlines")
traverse.WebEdit("placeholder:=From").Click
traverse.Link("acc_name:=This link will open Popup window for airport selection.").WebElement("html tag:=strong").Click
traverse.WebTabStrip("html id:=ToC").Link("innerhtml:=Africa","innertext:=Africa").Click
traverse.Link("innertext:=Port Elizabeth \(PLZ\)").Click ' Note \( and \)
```
Upvotes: 2
|
2018/03/16
| 262 | 882 |
<issue_start>username_0: I have a problem to process the data from my html form with jQuery. I have this simple form:
```
Create account now
```
Now I want to get the value of the inputs with jQuery.
```
$("#singup").submit(function (e) {
var email = $('#singup-email').val();
console.log(email);
e.preventDefault(e);
});
```
But the browser console tells me the var `email` is undefined. Why?
Thanks for help!<issue_comment>username_1: Typo mistake. use `signup-email` not `singup-email`
```
$("#singup").submit(function (e) {
var email = $('#signup-email').val();
console.log(email);
e.preventDefault(e);
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```js
$("#signup-submit").on('click', function (e) {
var email = $('#signup-email').val();
console.log(email);
});
```
```html
Create account now
```
Upvotes: 1
|
2018/03/16
| 719 | 3,113 |
<issue_start>username_0: I'm beginning on Jenkins in my work place. We use semantic versioning with Teamcity and I want to implement the same on Jenkins. My problem appears when I store the artifacts in builds folder ($JENKINS\_HOME/jobs/$JOB\_NAME/builds/$BUILD\_NUMBER) because Jenkins use only the build\_number to create the folder for build so when I have to reset de Build\_number the future artifacts will be stored in the folder of previous builds.
>
> For example:
>
>
> *I have build 1.3.1\_develop.1 stored, when I reset Build\_Number the next build should be 1.3.2\_develop.1 and it should be stored in the
> folder 1 of build 1.3.1\_develop.1*
>
>
>
My question is if someone could explain me how to deal with automatic semantic versioning on jenkins because we reset the build number we increase the mayor, minor and patch number.
Jenkins Version: 2.89.4
Jobs--> We use jobs to compile Vuejs for front and to deploy back with python (If this helps)
Thanks for any help.<issue_comment>username_1: First thing I notice is you are not using semantic versioning correctly. `1.3.1_develop.1` should be `1.3.1-develop+1`. Build metadata should always be preceded by the plus '+' symbol and is not factored into the SemVer sort order.
Second, build number is never "reset", it might roll-over eventually, but it should never be reset. A build number that does not indicate the machine performing the build is also generally useless unless there can only ever be one.
Basically, there's no concept of a build number in semantic versioning. The standard specifies the syntax for build meta data, but is completely neutral on what might be included. Build numbers are generally useless at the level of semantic versioning. They have their uses for preventing directory collisions in CI build systems and even provide a unique identifier for some product lines (Windows for instance), particularly where semantic versioning is not in use (Windows again).
I recommend using a SHA-1 or better hash of the build inputs (Git commit Id for instance) in the build meta tag in addition to any build counter, and use that for your output directory name. You can still use a monotonic counter on your prerelease tags as well, but you would have to create a build output directory name that includes the entire semver string in order to maintain uniqueness.
Third, your build machine is the worst place to archive your build artifacts! Build automation can and does go horribly wrong from time to time. Your build system should not have access to your archive of build artifacts. When your build and initial smoke testing is completed, it should signal a process running on a completely different machine to move the artifacts off the build machine to a more secure location. No process running on the build system should have write access to your archive of build artifacts.
Upvotes: 3 <issue_comment>username_2: There is a tool `GitVersion` which does what you want and it can be integrated with Jenkins or other CI providers.
<https://gitversion.net/docs/reference/build-servers/jenkins>
Upvotes: 2
|
2018/03/16
| 2,050 | 7,529 |
<issue_start>username_0: I'm having an issue where when I'm selecting the cell for e.g at index 3 , it selecting cells below also at random indexes. Check and Uncheck cell is working but for some reasons when selecting a cell it is selecting other cells as well. **My array is returning 120 rows in total.** I have selected multiple touch. Thank you for the help.
```
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return arrayVerbCount.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MesTalentsChoixCell
cell.verb!.text = arrayVerbCount[indexPath.row].verb
if cell.isSelected
{
cell.isSelected = false
if cell.accessoryType == UITableViewCellAccessoryType.none
{
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.none
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath)
if cell!.isSelected
{
cell!.isSelected = false
if cell!.accessoryType == UITableViewCellAccessoryType.none
{
cell!.accessoryType = UITableViewCellAccessoryType.checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.none
}
}
}
```
My custom cell class:
```
class MesTalentsChoixCell: UITableViewCell {
@IBOutlet weak var verb: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
```<issue_comment>username_1: You should do like this way, this is very much easy solution if there is only one section.
Initialize `selectedItems` array like this,
```
var selectedItems: [Int] = []
```
Find `UITableViewDataSource` method below
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
cell.tmpValue.text = data[indexPath.row]
if selectedItems.contains(indexPath.row) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
```
Find `UITableViewDelegate` Method below.
```
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if selectedItems.contains(indexPath.row) {
let index = selectedItems.index(of: indexPath.row)
selectedItems.remove(at: index!)
} else {
selectedItems.append(indexPath.row)
}
tableView.reloadRows(at: [indexPath], with: .none)
}
```
Code will be changed depending on your requirement and custom cell. Hope you can do it your way. Thank you.
**UPDATE**
You can even use `Set` also like this way,
```
var setSelectedItems: Set = []
```
`UITableViewDataSource` method,
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
cell.tmpValue.text = data[indexPath.row]
if setSelectedItems.contains(indexPath.row) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
```
`UITableViewDelegate` method,
```
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if setSelectedItems.contains(indexPath.row) {
setSelectedItems.remove(indexPath.row)
} else {
setSelectedItems.insert(indexPath.row)
}
tableView.reloadRows(at: [indexPath], with: .none)
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: For multiple selection you should track selected cells in a `Dictionary` for convenience faster access to selected and unselected indexPaths allowing you use multiple sections because the key value of our Dictionary is a string formed by (IndexPath.section)+(IndexPath.row) which is always unique combination
```
var selectedIndexPaths : [String:Bool] = [:]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentIndexPathStr = "\(indexPath.section)\(indexPath.row)"
if(self.selectedIndexPaths[currentIndexPathStr] == nil || !self.selectedIndexPaths[currentIndexPathStr]!) {
self.selectedIndexPaths[currentIndexPathStr] = true
}else{
self.selectedIndexPaths[currentIndexPathStr] = false
}
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "npCell", for: indexPath) as! NewPlaylistTableViewCell
cell.mTitle.text = musics[indexPath.row]["title"] as! String?
cell.mArtist.text = musics[indexPath.row]["artist"] as! String?
cell.accessoryType = .checkmark
let currentIndexPathStr = "\(indexPath.section)\(indexPath.row)"
if(self.selectedIndexPaths[currentIndexPathStr] == nil || !self.selectedIndexPaths[currentIndexPathStr]!) {
cell.accessoryType = .none
}
return cell
}
```
**Results**
[](https://i.stack.imgur.com/Cccbe.gif)
Upvotes: 0 <issue_comment>username_3: Just a minor change
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MesTalentsChoixCell
cell.verb!.text = arrayVerbCount[indexPath.row].verb
if cell.isSelected
{
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath)
//toggle the state
cell!.isSelected = !cell!.isSelected
if cell!.isSelected
{
cell!.accessoryType = UITableViewCellAccessoryType.checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.none
}
}
```
>
> Note: you should also create method for common code :-)
>
>
>
Upvotes: 0 <issue_comment>username_4: Make bool array for stability while scrolling i.e.
```
var arrStatusBool = [Bool]()
```
Now set value at indexPath.row in **didSelectRowAt**
```
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if self.arrStatusBool[indexPath.row]
{
self.arrStatusBool[indexPath.row] = false
}
else
{
self.arrStatusBool[indexPath.row] = true
}
}
```
And also put this in **cellForRowAt** to avoid scrolling issue.
```
if self.arrStatusBool[indexPath.row]
{
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
else
{
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
```
hope this help!
Upvotes: 1
|
2018/03/16
| 2,559 | 7,133 |
<issue_start>username_0: So, implementing a brush behaviour inspired from [M Bostock example](https://gist.github.com/mbostock/6498580) I came across something I did not quite understand.
If set a callback for the 'end' event of the brush, this gets called as expected whenever you're interacting directly with the brush.
But whenever I recenter the brush, it seems that the end event is fired twice.
Why is that the case? Or, is it something I'm doing wrong here?
```html
.selected {
fill: red;
stroke: brown;
}
Event fired
var fired=0;
var randomX = d3.randomUniform(0, 10),
randomY = d3.randomNormal(0.5, 0.12),
data = d3.range(800).map(function() { return [randomX(), randomY()]; });
var svg = d3.select("svg"),
margin = {top: 10, right: 50, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush", brushed)
.on("end", brushend);
var dot = g.append("g")
.attr("fill-opacity", 0.2)
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + x(d[0]) + "," + y(d[1]) + ")"; })
.attr("r", 3.5);
g.append("g")
.call(brush)
.call(brush.move, [3, 5].map(x))
.selectAll(".overlay")
.each(function(d) { d.type = "selection"; }) // Treat overlay interaction as move.
.on("mousedown touchstart", brushcentered); // Recenter before brushing.
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
function brushcentered() {
var dx = x(1) - x(0), // Use a fixed width when recentering.
cx = d3.mouse(this)[0],
x0 = cx - dx / 2,
x1 = cx + dx / 2;
d3.select(this.parentNode).call(brush.move, x1 > width ? [width - dx, width] : x0 < 0 ? [0, dx] : [x0, x1]);
}
function brushed() {
var extent = d3.event.selection.map(x.invert, x);
dot.classed("selected", function(d) { return extent[0] <= d[0] && d[0] <= extent[1]; });
}
function brushend() {
document.getElementById('test').innerHTML = ++fired;
// console.log('end fired - ' + (++fired));
}
```<issue_comment>username_1: Whenever you want to stop an event from triggering multiple layers of actions, you can use:
```
d3.event.stopPropagation();
```
Here you can include it at the end of the `brushcentered` function:
```
function brushcentered() {
var dx = x(1) - x(0), // Use a fixed width when recentering.
cx = d3.mouse(this)[0],
x0 = cx - dx / 2,
x1 = cx + dx / 2;
d3.select(this.parentNode).call(brush.move, x1 > width ? [width - dx, width] : x0 < 0 ? [0, dx] : [x0, x1]);
d3.event.stopPropagation();
}
```
And the demo:
```html
.selected {
fill: red;
stroke: brown;
}
Event fired
var fired=0;
var randomX = d3.randomUniform(0, 10),
randomY = d3.randomNormal(0.5, 0.12),
data = d3.range(800).map(function() { return [randomX(), randomY()]; });
var svg = d3.select("svg"),
margin = {top: 10, right: 50, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush", brushed)
.on("end", brushend);
var dot = g.append("g")
.attr("fill-opacity", 0.2)
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + x(d[0]) + "," + y(d[1]) + ")"; })
.attr("r", 3.5);
g.append("g")
.call(brush)
.call(brush.move, [3, 5].map(x))
.selectAll(".overlay")
.each(function(d) { d.type = "selection"; }) // Treat overlay interaction as move.
.on("mousedown touchstart", brushcentered); // Recenter before brushing.
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
function brushcentered() {
var dx = x(1) - x(0), // Use a fixed width when recentering.
cx = d3.mouse(this)[0],
x0 = cx - dx / 2,
x1 = cx + dx / 2;
d3.select(this.parentNode).call(brush.move, x1 > width ? [width - dx, width] : x0 < 0 ? [0, dx] : [x0, x1]);
d3.event.stopPropagation();
}
function brushed() {
var extent = d3.event.selection.map(x.invert, x);
dot.classed("selected", function(d) { return extent[0] <= d[0] && d[0] <= extent[1]; });
}
function brushend() {
document.getElementById('test').innerHTML = ++fired;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: **-UPDATE-**
For the purpose of this snippet, I can use a boolean flag to stop the first event and let the second go through. This means that I am still able to drag the brush after recentering, all in one go.
```html
.selected {
fill: red;
stroke: brown;
}
Event fired
var fired=0;
var justcentered = false;
var randomX = d3.randomUniform(0, 10),
randomY = d3.randomNormal(0.5, 0.12),
data = d3.range(800).map(function() {
return [randomX(), randomY()];
});
var svg = d3.select("svg"),
margin = { top: 10, right: 50, bottom: 30, left: 50 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush", brushed)
.on("end", brushend);
var dot = g.append("g")
.attr("fill-opacity", 0.2)
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("transform", function(d) {
return "translate(" + x(d[0]) + "," + y(d[1]) + ")";
})
.attr("r", 3.5);
g.append("g")
.call(brush)
.call(brush.move, [3, 5].map(x))
.selectAll(".overlay")
.each(function(d) { d.type = "selection"; }) // Treat overlay interaction as move.
.on("mousedown touchstart", brushcentered); // Recenter before brushing.
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
function brushcentered() {
var dx = x(1) - x(0), // Use a fixed width when recentering.
cx = d3.mouse(this)[0],
x0 = cx - dx / 2,
x1 = cx + dx / 2;
justcentered = true;
d3.select(this.parentNode)
.call(brush.move, x1 > width ? [width - dx, width] : x0 < 0 ? [0, dx] : [x0, x1]);
}
function brushed() {
var extent = d3.event.selection.map(x.invert, x);
dot.classed("selected", function(d) { return extent[0] <= d[0] && d[0] <= extent[1]; });
}
function brushend() {
if(justcentered) {
justcentered = false;
return;
}
document.getElementById('test').innerHTML = ++fired;
}
```
Upvotes: 1
|
2018/03/16
| 1,513 | 5,481 |
<issue_start>username_0: I know that I can find a word in a text/array with this:
```
if word in text:
print 'success'
```
What I want to do is read a word in a text, and keep counting as many times as the word is found (it is a simple counter task). But the thing is I do not really know how to `read` words that have already been read. In the end: count the number occurrences of each word?
I have thought of saving in an array (or even multidimensional array, so save the word and the number of times it appears, or in two arrays), summing 1 every time it appears a word in that array.
So then, when I read a word, can I NOT read it with something similar to this:
```
if word not in wordsInText:
print 'success'
```<issue_comment>username_1: What I understand is that you want to keep words already read so as you can detect if you encounter a new word. Is that OK ? The easiest solution for that is to use a set, as it automatically removes duplicates. For instance:
```
known_words = set()
for word in text:
if word not in known_words:
print 'found new word:', word
known_word.add(word)
```
On the other hand, if you need the exact number of occurrences for each word (this is called "histogram" in maths), you have to replace the set by a dictionary:
```
histo = {}
for word in text:
histo[word] = histo.get(word, 0) + 1
print histo
```
Note: In both solutions, I suppose that text contains an iterable structure of words. As said by other comments, `str.split()` is not totally safe for this.
Upvotes: 1 <issue_comment>username_2: I would use one of these methods:
1) If the word doesn't contain spaces, but the text does, use
```
for piece in text.split(" "):
...
```
Then your word should occur at most once in each piece, and be counted correctly. This fails if you for example want to count "Baden" twice in "Baden-Baden".
2) Use the string method 'find' to get not only whether the word is there, but where it is. Count it, and then continue searching from beyond that point.
text.find(word) returns either a position, or -1.
Upvotes: 1 <issue_comment>username_3: Now that we established what you're trying to achieve, I can give you an answer. Now the first thing you need to do is convert the text into a list of words. While the `split` method might look like a good solution, it will create a problem in the actual counting when sentences end with a word, followed by a full stop, commas or any other characters. So a good solution for this problem would be [NLTK](http://www.nltk.org). Assume that the text you have is stored in a variable called `text`. The code you are looking for would look something like this:
```
from itertools import chain
from collections import Counter
from nltk.tokenize import sent_tokenize, word_tokenize
text = "This is an example text. Let us use two sentences, so that it is more logical."
wordlist = list(chain(*[word_tokenize(s) for s in sent_tokenize(text)]))
print(Counter(wordlist))
# Counter({'.': 2, 'is': 2, 'us': 1, 'more': 1, ',': 1, 'sentences': 1, 'so': 1, 'This': 1, 'an': 1, 'two': 1, 'it': 1, 'example': 1, 'text': 1, 'logical': 1, 'Let': 1, 'that': 1, 'use': 1})
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Several options can be used but I suggest you do the following :
* Replace special characters in your text in order to uniformize it.
* Split the cleared sentence.
* Use `collections.Counter`
And the code will look like...
```
from collections import Counter
my_text = "Lorem ipsum; dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut. labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
special_characters = ',.;'
for char in special_characters:
my_text = my_text.replace(char, ' ')
print Counter(my_text.split())
```
I believe the safer approach would be to use the answer with NLTK, but sometimes, understanding what you are doing feels great.
Upvotes: 1 <issue_comment>username_5: ```
sentence = 'a quick brown fox jumped a another fox'
words = sentence.split(' ')
```
solution 1:
```
result = {i:words.count(i) for i in set(words)}
```
solution 2:
```
result = {}
for word in words:
result[word] = result.get(word, 0) + 1
```
solution 3:
```
from collections import Counter
result = dict(Counter(words))
```
Upvotes: 3 <issue_comment>username_6: There is no need to tokenize sentence. Answer from [username_3](https://stackoverflow.com/users/3197668/alexander-ejbekov) could be simplified as:
```
from itertools import chain
from collections import Counter
from nltk.tokenize import sent_tokenize, word_tokenize
text = "This is an example text. Let us use two sentences, so that it is more logical."
wordlist = word_tokenize(text)
print(Counter(wordlist))
# Counter({'is': 2, '.': 2, 'This': 1, 'an': 1, 'example': 1, 'text': 1, 'Let': 1, 'us': 1, 'use': 1, 'two': 1, 'sentences': 1, ',': 1, 'so': 1, 'that': 1, 'it': 1, 'more': 1, 'logical': 1})
```
Upvotes: 1
|
2018/03/16
| 358 | 1,233 |
<issue_start>username_0: I am trying to get the string between parentheses but i am getting always getting empty value.
```
String_Input: select sum(OUTPUT_VALUE) from table_name
Output : OUTPUT_VALUE
```
What I tried here:
```
select regexp_extract(String_Input,"/\\(([^)]+)\\)/") from table_name;
```
any suggestion to get the value ?<issue_comment>username_1: Try this:
```
\((.*?)\)
```
In Hive:
```
select regexp_extract(String_input,'\\((.*?)\\)')
from table_name
```
Upvotes: 0 <issue_comment>username_2: If you need to get the value without the parentheses, you should indicate that you need to extract Captturing group 1 value in the third argument to `regexp_extract` function. Besides, you should remove `/` delimiters, they are parsed as literal symbols.
```
select regexp_extract(String_Input,"\\(([^)]+)\\)", 1) from table_name;
^ ^ ^
```
From the [Hive documentation](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF):
>
> The *'index'* parameter is the Java regex *`Matcher group()`* method index. See *docs/api/java/util/regex/Matcher.html* for more information on the 'index' or Java regex *`group()`* method.
>
>
>
Upvotes: 2
|
2018/03/16
| 3,031 | 9,568 |
<issue_start>username_0: I have binary relation on some type `T` induced by a function `equivalent`:
```
bool equivalent(T const& a, T const& b); // returns true if a and b are equivalent
```
It has the properties that
```
equivalent(a, a) == true
```
and
```
equivalent(a, b) == equivalent(b, a)
```
for all `a`, `b`.
For a given collection of elements of type `T`, I want to remove all but the first occurrence of each equivalence class. I have come up with the following Code but was wandering:
**Is there is a solution without an explicit loop?**
```
std::vector filter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_T(std::vector const& ts) {
std::vector result;
for (auto iter = ts.begin(); iter != ts.end(); ++iter) {
auto const& elem = \*iter;
bool has\_equivalent\_element\_at\_earlier\_position = std::any\_of(
ts.begin(),
iter,
&equivalent
);
if (not has\_equivalent\_element\_at\_earlier\_position) {
result.push\_back(routing\_pin);
}
}
return result;
}
```
Update
======
As far as I understand `std::unique` won't do because my type `T` is not sortable. And because I only have C++11 in my case, but I would be interested in other options too for education.<issue_comment>username_1: ```
struct S {
int eq;
int value;
bool operator==(const S& other) const { return eq == other.eq; }
};
namespace std {
template <> struct hash~~{
size\_t operator()(const S &s) const
{
return hash()(s.eq);
}
};
}
array as{ { {1,0},{2,0},{3,0},{ 1,1 },{ 2,1 },{ 3,1 } } };
unordered\_set ~~us(as.cbegin(), as.cend());~~~~
```
Upvotes: 0 <issue_comment>username_2: First coming up with another *loop* version, in contrast to your own, it unifies *in place*, you might find it interesting:
```
std::vector v({1, 7, 1, 8, 9, 8, 9, 1, 1, 7});
auto retained = v.begin();
for(auto i = v.begin(); i != v.end(); ++i)
{
bool isFirst = true;
for(auto j = v.begin(); j != retained; ++j)
{
if(\*i == \*j)
{
isFirst = false;
break;
}
}
if(isFirst)
{
\*retained++ = \*i;
}
}
v.erase(retained, v.end());
```
This was the base for a version using `std::remove_if` and `std::find_if`:
```
auto retained = v.begin();
auto c = [&v, &retained](int n)
{
if(std::find_if(v.begin(), retained, [n](int m) { return m == n; }) != retained)
return true;
// element remains, so we need to increase!!!
++retained;
return false;
};
v.erase(std::remove_if(v.begin(), v.end(), c), v.end());
```
You need the lambda in this case, as we need a unique-predicate, whereas equivalent (in my int example represented by `operator==`) is a binary one...
Upvotes: 1 <issue_comment>username_3: Expanding on my comment in username_4's answer:
```
template
auto deduplicated2(std::vector vec, Equivalent&& equivalent) -> std::vector
{
auto current = std::begin(vec);
// current 'last of retained sequence'
auto last = std::end(vec);
while (current != last)
{
// define a predicate which checks for equivalence to current
auto same = [&](T const& x) -> bool
{
return equivalent(\*current, x);
};
// move non-equivalent items to end of sequence
// return new 'end of valid sequence'
last = std::remove\_if(std::next(current), last, same);
}
// erase all items beyond the 'end of valid sequence'
vec.erase(last, std::end(vec));
return vec;
}
```
Credit to username_4 please.
For very large vectors where T is hashable, we can aim for an O(n) solution:
```
template
auto deduplicated(std::vector const& vec, Equivalent&& equivalent) -> std::vector
{
auto seen = std::unordered\_set, Equivalent>(vec.size(), std::hash(), std::forward(equivalent));
auto result = std::vector();
result.resize(vec.size());
auto current = std::begin(vec);
while (current != std::end(vec))
{
if (seen.insert(\*current).second)
{
result.push\_back(\*current);
}
}
return result;
}
```
Finally, revisiting the first solution and refactoring into sub-concerns (I can't help myself):
```
// in-place de-duplication of sequence, similar interface to remove_if
template
Iter inplace\_deduplicate\_sequence(Iter first, Iter last, Equivalent&& equivalent)
{
while (first != last)
{
// define a predicate which checks for equivalence to current
using value\_type = typename std::iterator\_traits::value\_type;
auto same = [&](value\_type const& x) -> bool
{
return equivalent(\*first, x);
};
// move non-equivalent items to end of sequence
// return new 'end of valid sequence'
last = std::remove\_if(std::next(first), last, same);
}
return last;
}
// in-place de-duplication on while vector, including container truncation
template
void inplace\_deduplicate(std::vector& vec, Equivalent&& equivalent)
{
vec.erase(inplace\_deduplicate\_sequence(vec.begin(),
vec.end(),
std::forward(equivalent)),
vec.end());
}
// non-destructive version
template
auto deduplicated2(std::vector vec, Equivalent&& equivalent) -> std::vector
{
inplace\_deduplicate(vec, std::forward(equivalent));
return vec;
}
```
Upvotes: 2 <issue_comment>username_4: Here's a way that only has one very simple loop:
First define our class, which I'll call `A` instead of `T` because `T` is typically used for templates:
```
class A{
public:
explicit A(int _i) : i(_i){};
int get() const{return i;}
private:
int i;
};
```
And then our `equivalent` function just compares the integers for equality:
```
bool equivalent(A const& a, A const& b){return a.get() == b.get();}
```
next I'll define the filtering function.
The idea here is to take advantage of [`std::remove`](http://en.cppreference.com/w/cpp/algorithm/remove) to do the looping and erasing efficiently for us (it typically swaps elements to the end so that you are not shifting the vector for each removal).
We start by removing everything that matches the first element, then afterwards remove everything that matches the second element (which is guaranteed != to the first element now), and so on.
```
std::vectorfilter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_A(std::vectoras) {
for(size\_t i = 1; i < as.size(); ++i){
as.erase(std::remove\_if(as.begin() + i, as.end(), [&as, i](const A& next){return equivalent(as[i-1], next);}), as.end());
}
return as;
}
```
[Demo](https://wandbox.org/permlink/IbwgfSWuxML601IQ)
-----------------------------------------------------
---
Edit: As username_3 mentioned, it is possible to delay any erasing until the very end. I couldn't make it look as beautiful though:
```
std::vectorfilter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_A(std::vectoras) {
auto end = as.end();
for(size\_t i = 1; i < std::distance(as.begin(), end); ++i){
end = std::remove\_if(as.begin() + i, end, [&as, i](const A& next){return equivalent(as[i-1], next);});
}
as.erase(end, as.end());
return as;
}
```
[Demo 2](https://wandbox.org/permlink/XEf1DDLmUlaCZbBF)
Upvotes: 2 <issue_comment>username_5: You can try this one. The trick here is to obtain the index while inside predicate.
```
std::vector output;
std::copy\_if(
input.begin(), input.end(),
std::back\_inserter(output),
[&](const T& x) {
size\_t index = &x - &input[0];
return find\_if(
input.begin(), input.begin() + index, x,
[&x](const T& y) {
return equivalent(x, y);
}) == input.begin() + index;
});
```
Upvotes: 2 <issue_comment>username_6: Since performance is not an issue, you can use `std::accumulate` to scan through the elements and add them to an accumulator vector `xs` if there is not already
an equaivalent element in `xs`.
With this you don't need any hand-written raw loops at all.
```
std::vectorfilter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_A(std::vectoras) {
return std::accumulate(as.begin(), as.end(),
std::vector{}, [](std::vectorxs, A const& x) {
if ( std::find\_if(xs.begin(), xs.end(), [x](A const& y) {return equivalent(x,y);}) == xs.end() ) {
xs.push\_back(x);
}
return xs;
});
}
```
With two helper functions this becomes actually readable:
```
bool contains_equivalent(std::vectorconst& xs, A const& x) {
return std::find\_if(xs.begin(), xs.end(),
[x](A const& y) {return equivalent(x,y);}) != xs.end();
};
std::vectorpush\_back\_if(std::vectorxs, A const& x) {
if ( !contains\_equivalent(xs, x) ) {
xs.push\_back(x);
}
return xs;
};
```
The function itself is just a call to `std::accumulate`:
```
std::vectorfilter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_A(std::vectoras) {
return std::accumulate(as.begin(), as.end(), std::vector{}, push\_back\_if);
}
```
[I've modified username_4's example code with my proposed function.](https://wandbox.org/permlink/aRnHWu0OPeGpRvb7)
As defined above, `std::accumulate` calls `push_back_if` with a copy of the accumulator variable, and the return value is move-assigned to the accumulator again. This is very inefficient, but can be optimized by changing `push_back_if` to take a reference so that the vector is modified in-place. The initial value needs to be passed as a reference wrapper with `std::ref` to eliminate remaining copies.
```
std::vector& push\_back\_if(std::vector& xs, A const& x) {
if ( !contains\_equivalent(xs, x) ) {
xs.push\_back(x);
}
return xs;
};
std::vectorfilter\_all\_but\_one\_for\_each\_set\_of\_equivalent\_A(std::vectorconst& as) {
std::vectoracc;
return std::accumulate(as.begin(), as.end(), std::ref(acc), push\_back\_if);
}
```
[You can see in the example that the copy-constructor is almost completely eliminated.](https://wandbox.org/permlink/vt6QHIG37iY9Wh04)
Upvotes: 2 [selected_answer]
|
2018/03/16
| 326 | 1,078 |
<issue_start>username_0: Hi I am using using Angular 5 and I am trying to import bootstrap in my code but unable to do so. I have installed bootstrap using:
```
npm install --save bootstrap
```
I have also add the css file to the .angular-cli.json as:
```
"styles": ["../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/bootstrap/dist/css/bootstrap.css",
"styles.css"
],
```
But when I inspect my code in google chrome what I get is this,
```
MyFirstApp
```
There is no styles for bootstrap in the header section. Please help me. I am stuck<issue_comment>username_1: "./../node\_modules/bootstrap/dist/css/bootstrap.css",
./../node\_modules/bootstrap/dist/css/bootstrap.min.css",
use same like this
Upvotes: 1 [selected_answer]<issue_comment>username_2: Add your style `bootstrap.min.css` to `style.css` main:
```
@import "../src/css/bootstrap.min.css";
```
Upvotes: 0 <issue_comment>username_3: Try This, add your style `bootstrap.min.css` to `style.css`
`@import "../node_modules/bootstrap/dist/css/bootstrap.min.css";`
Upvotes: 1
|
2018/03/16
| 377 | 1,228 |
<issue_start>username_0: My use case is something like this.
1. I stored images names in an array called **imagesFolder**
2. then I retrieve names from that array and display on my vue component.
This is my code
```
![]()
export default {
data(){
return{
imagesFolder:['src/assets/mickey.png','src/assets/logo.png']
}
}
}
```
My question is every time I have to store the static location part **src/assets/** instead of doing this. Is there a way to attach this **src/assets/** part to the `img` tag. I hope you understand my question.<issue_comment>username_1: You can provide just the filename of the images in an array in your `data`.
```
export default {
data() {
return{
images: ['mickey', 'logo']
}
}
}
```
Then, you can loop through and use only the filename of the image as the dynamic value.
```
![]()
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use a [directive](https://v2.vuejs.org/v2/guide/custom-directive.html):
```
Vue.directive('src', function (el, binding) {
el.src = 'src/assets/' + binding.value
})
```
Then you can use `v-src`:
```
![]()
```
Now, you are safe to use just file name:
```
imagesFolder:['mickey.png','logo.png']
```
Upvotes: 0
|
2018/03/16
| 320 | 1,298 |
<issue_start>username_0: I know this probably isn't applied way for declaring variable but I'm curious it is possible or not
```
#define paste(front,back) front ## back
int main(int argc,int *argv[]){
int i=0;
for(i=0;i<10;i++){
int paste(var,i) = i;
}
return 0;
}
```
I know arrays but as I said I'm curious :)<issue_comment>username_1: This macro will indeed declare a variable, but with fixed name `vari` because macros are evaluated as a first step of compilation and do not exists at runtime. And it will be destroyed at each iteration of the loop because it immediately goes out of scope.
Declaring variables at runtime is not possible because C is a compiled language and variables (and macros) only really exists in source code. It is possible to write a fancy macro that will expand into several variables but their names and count will be still fixed at compile time.
Upvotes: 1 <issue_comment>username_2: You have 2 misunderstandings.
* macro is just doing text substitution, nothing magic. in your case, the line with macro will be literally `int vari = i;`. Thus you can always predict its effect.
* Declaring variable is a compile time action, `for` loop execution is at runtime. Declaring multiple variables with a `for` loop is impossible.
Upvotes: 2
|
2018/03/16
| 909 | 3,135 |
<issue_start>username_0: How can I produce an html document from a .Rmd file, with self-contained images? I am using the `bsplus` package along with `rmarkdown` to create a carousel of images. It works perfectly when I open the `.html` output within the `.Rproj` working directory, but the images are no longer displayed when I send the file to someone.
Would it be possible to get a "self-contained" .html file output with the corresponding images? or should I send also all folder dependencies?
Example of how the code looks like...
```
---
title: "test"
author: "me"
date: "today"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see .
When you click the \*\*Knit\*\* button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r carousel}
bs\_carousel(id = "the\_beatles", use\_indicators = TRUE) %>%
bs\_append(
content = bs\_carousel\_image(src = image\_uri("img/john.jpg")),
caption = bs\_carousel\_caption("<NAME>", "Rhythm guitar, vocals")
) %>%
bs\_append(
content = bs\_carousel\_image(src = image\_uri("img/paul.jpg")),
caption = bs\_carousel\_caption("<NAME>", "Bass guitar, vocals")
) %>%
bs\_append(
content = bs\_carousel\_image(src = image\_uri("img/george.jpg")),
caption = bs\_carousel\_caption("<NAME>", "Lead guitar, vocals")
) %>%
bs\_append(
content = bs\_carousel\_image(src = image\_uri("img/ringo.jpg")),
caption = bs\_carousel\_caption("<NAME>", "Drums, vocals")
)
```
```<issue_comment>username_1: This is not an R/Rmarkdown problem - it's an HTML one. Most HTML files read images from files, not from within the code.
If you absolutely need to do this, see [this question](https://stackoverflow.com/questions/2807251/can-i-embed-a-png-image-into-an-html-page) and/or [this website](http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/).
However, I would instead suggest gzipping the directory in which images are stored + your .html file, and sending that archive via email.
Upvotes: -1 <issue_comment>username_2: Assuming that the file shown in the question is in the current directory and called `caro.Rmd` and the `*.jpg` files are all present at the appropriate location and you are able to run pandoc then this works for me:
```
library(knitr)
library(rmarkdown)
render("caro.Rmd", html_document(pandoc_args = "--self-contained"))
browseURL("caro.html")
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
To post the report on sharepoint:
setwd("C:/Users/...")
#render table
rmarkdown::render("tablename.rmd") #run the rmd file in the extracts folder
file.remove("tablename.aspx") #remove the current aspx sharepoint from previous render
file.rename("tablename.html",`enter code here`"tablename.aspx") #rename the html to be the new one
```
Upvotes: 0
|
2018/03/16
| 536 | 1,977 |
<issue_start>username_0: I have came accross a concept in java or selenium stating that we use `this` before a global variable. This is done when the global variable and local varibale both have the same name.
This is because if we do not use the `this` keyword then a compile run time error would be generated when we call the variable in a method.
My query is:
Can we not use different name for local and global variable always?
Is there any specific advantage of using same name for local and global variable and then using the `this` keyword.
I am very new to java and selenium so this concept might be very basic.
Thanks.<issue_comment>username_1: This is not an R/Rmarkdown problem - it's an HTML one. Most HTML files read images from files, not from within the code.
If you absolutely need to do this, see [this question](https://stackoverflow.com/questions/2807251/can-i-embed-a-png-image-into-an-html-page) and/or [this website](http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/).
However, I would instead suggest gzipping the directory in which images are stored + your .html file, and sending that archive via email.
Upvotes: -1 <issue_comment>username_2: Assuming that the file shown in the question is in the current directory and called `caro.Rmd` and the `*.jpg` files are all present at the appropriate location and you are able to run pandoc then this works for me:
```
library(knitr)
library(rmarkdown)
render("caro.Rmd", html_document(pandoc_args = "--self-contained"))
browseURL("caro.html")
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
To post the report on sharepoint:
setwd("C:/Users/...")
#render table
rmarkdown::render("tablename.rmd") #run the rmd file in the extracts folder
file.remove("tablename.aspx") #remove the current aspx sharepoint from previous render
file.rename("tablename.html",`enter code here`"tablename.aspx") #rename the html to be the new one
```
Upvotes: 0
|
2018/03/16
| 621 | 2,054 |
<issue_start>username_0: I would like to rename the beginning of different files.
input:
```
myfilename abc yeswithspaces.abc
myfilename def yeswithspaces.abc
myfilename_abc_nospaces.abc
myfilename def blabla.def
myfilename_abc_mainfile.ok
```
output wanted:
```
newfilename abc yeswithspaces.abc
newfilename def yeswithspaces.abc
newfilename_abc_nospaces.abc
myfilename def blabla.def
myfilename_abc_mainfile.ok
```
I have this code which works ok, if I have only one file .abc but not if there is more:
```
if [ -e "${DOSSIER}/${OLD_NAME}"*.abc ];
then
for i in "${DOSSIER}/$OLD_NAME"*.abc; do
[ -f "$i" ] || continue
mv "$i" "${i/$OLD_NAME/$NEW_NAME}"
done
fi
```<issue_comment>username_1: This is not an R/Rmarkdown problem - it's an HTML one. Most HTML files read images from files, not from within the code.
If you absolutely need to do this, see [this question](https://stackoverflow.com/questions/2807251/can-i-embed-a-png-image-into-an-html-page) and/or [this website](http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/).
However, I would instead suggest gzipping the directory in which images are stored + your .html file, and sending that archive via email.
Upvotes: -1 <issue_comment>username_2: Assuming that the file shown in the question is in the current directory and called `caro.Rmd` and the `*.jpg` files are all present at the appropriate location and you are able to run pandoc then this works for me:
```
library(knitr)
library(rmarkdown)
render("caro.Rmd", html_document(pandoc_args = "--self-contained"))
browseURL("caro.html")
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
To post the report on sharepoint:
setwd("C:/Users/...")
#render table
rmarkdown::render("tablename.rmd") #run the rmd file in the extracts folder
file.remove("tablename.aspx") #remove the current aspx sharepoint from previous render
file.rename("tablename.html",`enter code here`"tablename.aspx") #rename the html to be the new one
```
Upvotes: 0
|
2018/03/16
| 750 | 2,273 |
<issue_start>username_0: **[This is a sample image]**

I want to crop out the header Text for several other similar colored images like this for OCR. what are the most effective steps to preprocess the image for better recognition only for the header text.<issue_comment>username_1: May be you can try to detect text first then can get maximum row index from detected area and cut it. There are multiple way to detect text using opencv. You may try [this question here](https://stackoverflow.com/questions/23506105/extracting-text-opencv).
Upvotes: 0 <issue_comment>username_2: [](https://i.stack.imgur.com/d4srK.jpg)
**ATTENTION**
To all who want to copy the code and want to use it in other projects: you will have to tweak and adapt it (especially threshold/kernel/iterations values).
This version works at it's best on the user provided image.
```
import cv2
image = cv2.imread("image.jpg")
image_c = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale
cv2.imshow('gray', gray)
cv2.waitKey(0)
_, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) # threshold
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
dilated = cv2.dilate(thresh, kernel, iterations=13) # dilate
cv2.imshow('dilated', dilated)
cv2.waitKey(0)
image, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # get contours
# for each contour found, draw a rectangle around it on original image
for i, contour in enumerate(contours):
# get rectangle bounding contour
x, y, w, h = cv2.boundingRect(contour)
roi = image_c[y:y + h, x:x + w]
if 50 < h < 100 or 200 < w < 420: # these values are specific for this example
# draw rectangle around contour on original image
rect = cv2.rectangle(image_c, (x, y), (x + w, y + h), (255, 255, 255), 1)
cv2.imshow('rectangles', rect)
cv2.waitKey(0)
cv2.imwrite('extracted{}.png'.format(i), roi)
# write original image with added contours to disk - change values above to (255,0,255) to see clearly the contours
cv2.imwrite("contoured.jpg", image_c)
```
Upvotes: 2
|
2018/03/16
| 791 | 3,230 |
<issue_start>username_0: I am developing a web application and maintaining the data in Firebase in the following way.
[](https://i.stack.imgur.com/1aaD7.png)
There can be several nodes under the "Users" node and in each of those nodes, I am storing users information such as name, gender etc.
Now I am trying to retrieve names of all users using the following Javascript function.
```
function getList(){
var nameList = new Array();
var uidList = new Array();
var query = firebase.database().ref('Users');
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var name = childSnapshot.val().Name;
var uid = childSnapshot.key;
alert(name); //first alert
nameList.push(name);
uidList.push(uid);
});
});
var len = nameList.length;
alert(len); //second alert
}
```
When I run this on my browser, at first it shows the length of the array is 0 (in the second alert) and then it shows the name which is being retrieved from the database (in the first alert).
Why is the second alert executing before the first alert? What is the appropriate way to retrieve data from Firebase, so that I can detect that data is retrieved and then execute further code to get the length of `namelist` array?
I have tried using a while loop while "name" and "uid" are null, but that didn't work.<issue_comment>username_1: You are trying to populate an array from a callback function, the callback function happens sometime in the future. So you are alerting before the callback executes
I suggest you use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) or [async](https://github.com/caolan/async)
Upvotes: 0 <issue_comment>username_2: Promises are the way to handle such situations.
Use promises for asynchronous call to handle the execution of result after the function for pushing the data into firebase completes that way the alert will show the length of `namelist`.
```
function getList(){
var nameList = new Array();
var uidList = new Array();
var query = firebase.database().ref('Users');
let getData = new Promise((resolve, reject) => {
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var name = childSnapshot.val().Name;
var uid = childSnapshot.key;
alert(name); //first alert
nameList.push(name);
uidList.push(uid);
});
resolve(nameList)
})
});
getData.then((nameList) => {
alert(nameList.length)
})
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: Try this:
```
function getList() {
var query = firebase.database().ref('Users');
query.once("value").then(snapshots => snapshots.map(snapshot => ({
name: snapshot.val().Name,
uid: snapshot.key
}))).then(result => {
console.log(result);
});
}
```
The queried array is remapped to an array of `{ name: "name", uid: "key" }` objects.
Upvotes: 1
|
2018/03/16
| 646 | 2,092 |
<issue_start>username_0: In a react webapp, I have a form with .
The value returned in chrome version 64 on Windows is in the following format:
```
2018-03-08T07:00
```
I assume that in other browsers it will be different.
I want to write this value in firestore, in the same format that is generated when I create, using the firestore admin GUI, a field of type 'timestamp', which is the following:
```
March 8, 2018 at 7:00:00 AM UTC+2
```
Any idea how to do this so that it works on all browsers?<issue_comment>username_1: Cloud Firestore stores timestamps in ISO8601 format. If you use the console to add a timestamp and then `get` the document, the following is returned.
```
{"timestamp":"2018-03-16T15:45:36.000Z"}
```
I would recommend that you convert all times to a common format, so you don't have different time formats in your database. A great tool for this, is [moment.js](http://momentjs.com/). I would recommend [ISO8601](http://momentjs.com/docs/#/displaying/) format, as this is universally readable by most (if not all) browsers, apps, databases,etc.
Upvotes: 1 <issue_comment>username_2: I set a default/initial value in state:
```
this.state={
datetime: `${new Date().getFullYear()}-${`${new Date().getMonth()+1}`.padStart(2,0)}-${`${new Date().getDay() + 1}`.padStart(2,0)}T${`${new Date().getHours()}`.padStart(2,0)}:${`${new Date().getMinutes()}`.padStart(2, 0)}`
}
```
Then I create a controlled input that used the state value above...
```
this.setState({datetime: e.target.value})}
/>
```
A little verbose, but it worked for me.
Upvotes: 1 <issue_comment>username_3: To format the date, you should use this:
```
this.state={
datetime: `${new Date().getFullYear()}-${`${new Date().getMonth()+1}`.padStart(2,0)}-${`${new Date().getDate()}`.padStart(2,0)}T${`${new Date().getHours()}`.padStart(2,0)}:${`${new Date().getMinutes()}`.padStart(2, 0)}`
}
```
Note: From Josh's answer I changed getDay() to getDate(), because the first one returns the day of the week (0 -6), I don't have the sufficient reputation to comment it
Upvotes: 0
|
2018/03/16
| 521 | 1,390 |
<issue_start>username_0: I would like to replace a string with another string in a single column.
Input:
```
A.a 1
A.b .
A.c 1
A.d 1
```
Desired output:
```
A.a 1
A.b -9
A.c 1
A.d 1
```
Using `sed 's/\./-9/g' input > output` it modifies all `.` by `-9`, and this is what I obtain:
```
A-9a 1
A-9b -9
A-9c 1
A-9d 1
```
How can I use `sed` on a single column ($2) only?<issue_comment>username_1: Following `awk` may help you on same.
```
awk 'FNR==2{$2="-9"} 1' OFS="\t" Input_file
```
Above will simply change `$2` value to `-9` in case you need to cross verify that 2nd line's 2nd field is a `.` and you want to do change then only then following may help you on same.
```
awk 'FNR==2 && $2=="."{$2="-9"} 1' OFS="\t" Input_file
```
OR
```
awk '$2=="."{$2="-9"} 1' OFS="\t" Input_file
```
Append `> temp_file && mv temp_file Input_file` to get the output in Input\_file itself.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use group pattern. A bit heavy in sed but in this case it is still easy.
```
sed 's/^\([^[:space:]]+[[:space:]]+\)\./\1-9/' input > output
# a more generic for the 4th column (\{3\} here mean 3 group before)
sed 's/^\(\([^[:space:]]+[[:space:]]+\)\{3\}\)\./\1-9/' input > output
```
the last `g` is not needed here because it only works for 1 element on a line
Upvotes: 0
|
2018/03/16
| 699 | 2,329 |
<issue_start>username_0: I have 6 words that is stored in a `HashSet` as below :
```
String first = jtfFirstWord.getText();
String second = jtfSecondWord.getText();
String third = jtfThirdWord.getText();
String fourth = jtfFourthWord.getText();
String fifth = jtfFifthWord.getText();
String sixth = jtfSixthWord.getText();
Set accept = new HashSet(Arrays.asList(new String[] {first,second,third,fourth,fifth,sixth}));
```
I want to check if the length of all words is not 7, 9, or 11, then I will prompt users with a message box to warn them to only enter 7, 9, or 11-characters word.
Currently, I'm using if-else statement to manually check the condition like:
```
if (first.length() != 7 || first.length() != 9 || first.length() != 11 ||
second.length() != 7 ||second.length() != 9 || second.length() != 11 ||
... and it continues until the sixth word.
```
By using this way, it reduce my code readability and its not an elegant way of checking user inputs.
My question is how do I check the length of the String element stored previously in the HashSet shown above? Or is there any other elegant and efficient way of checking the inputs?<issue_comment>username_1: If you are using Java 8 you can use [`Stream::allMatch`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#allMatch-java.util.function.Predicate-)
```
boolean check = accept.stream()
.allMatch(input -> Arrays.asList(7, 9, 11).contains(input.length()));
```
Or :
```
List acceptedLengths = Arrays.asList(7, 9, 11);
boolean check = accept.stream()
.allMatch(input -> acceptedLengths.contains(input.length()));
```
I used `Arrays.asList(7, 9, 11)` to define the accepted length, you can add what you want here, Its more easier than using condition for each length.
Upvotes: 1 <issue_comment>username_2: You can of course use a loop, checking that each element of the set has the one of the accepted lengths, and break out of the loop as soon as one string hasn't.
But you can also use [Stream's allMatch](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/stream/IntStream.html) method, which does that for you:
```
boolean allOK = accept.stream().allMatch(s ->
s.length() == 7 || s.length() == 9 || s.length() == 11);
if (!allOK) {
// display error message
}
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 970 | 3,632 |
<issue_start>username_0: **Desire Output is:**
I want to delete duplicates from a table by a group.
My tables :
**rc\_document:**
```
+----------------+-------------+----------------------+
| rc_document_id | document_id | rc_document_group_id |
+----------------+-------------+----------------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 1 | 2 |
| 6 | 3 | 2 |
+----------------+-------------+----------------------+
```
**rc\_document\_group:**
```
+----------------------+----------+
| rc_document_group_id | priority |
+----------------------+----------+
| 1 | 1 |
| 2 | 2 |
+----------------------+----------+
```
I only want to keep the rc\_documents whose rc\_document\_group has the highest priority. All other entries with the same "document\_id" should be deleted.
In other words ... document\_id should only be in the rc\_document\_group with the highest priority, the other ones should be deleted
**here is my expected result:**
```
+----------------+-------------+----------------------+
| rc_document_id | document_id | rc_document_group_id |
+----------------+-------------+----------------------+
| 2 | 2 | 1 |
| 4 | 4 | 1 |
| 5 | 1 | 2 |
| 6 | 3 | 2 |
+----------------+-------------+----------------------+
```<issue_comment>username_1: >
> For unique selection
>
>
>
```
SELECT MAX(rd.rc_document_id),rd.document_id,
rd.rc_document_group_id
FROM rc_document rd
INNER JOIN rc_document_group rdg ON
rd.rc_document_group_id = rdg.rc_document_group_id
GROUP BY rd.document_id,rd.rc_document_group_id ;
```
>
> For deletion run this query
>
>
>
```
DELETE FROM rc_document WHERE rc_document_id NOT IN (
SELECT MAX(rd.rc_document_id)
FROM rc_document rd
INNER JOIN rc_document_group rdg ON
rd.rc_document_group_id = rdg.rc_document_group_id
GROUP BY rd.document_id,rd.rc_document_group_id);
```
Upvotes: 0 <issue_comment>username_2: You can use `not exists` to check if the record has the highest priority.
```
SELECT
*
FROM
rc_document rc,
rc_document_group rcg
WHERE
NOT EXISTS (
SELECT
1
FROM
rc_document rcsub,
rc_document_group rcgsub
WHERE
rc.documetn_id == rcsub.document_id
AND rc.rc_document_id != rcsub.rc_document_id
AND rc.priority < rcsub.priority
)
```
Upvotes: 0 <issue_comment>username_3: Use `row_number` window function
```
select *
from (
select *, row_number() over (partition by document_id order by priority desc) rn
from rc_document d
join rc_document_group dg on d.rc_document_group_id = dg.rc_document_group_id
) t
where t.rn = 1
```
Upvotes: 0 <issue_comment>username_4: Use Oracle's `KEEP LAST` to find the best `rc_document_id` per `document_id`. Then delete all others.
```
delete from rc_document
where rc_document_id not in
(
select max(d.rc_document_id) keep (dense_rank last order by dg.priority)
from rc_document d
join rc_document_group dg using (rc_document_group_id)
group by d.document_id
);
```
Rextester demo: <http://rextester.com/NZVZGF52818>
Upvotes: 1
|
2018/03/16
| 466 | 1,361 |
<issue_start>username_0: How can I plot 2 density plots in one output. Here are my codes for the density plot.
```
#Density Plot
d <- density(dataS)
plot(d, main= "Density plots of Revenue")
o <- density(RemoveOutlier)
plot(o, main= "Density plots of Revenue excluding outliers")
```
So basically I want to see both plots on one output. And maybe change the color line of each plot and a legend on the top right. Attached is the picture of the 2 plots in R.
**image 1**

**image 2**
<issue_comment>username_1: Or instead of the second "plot()" function call, use "lines()", then you get two overlapping density plots.
Upvotes: 1 <issue_comment>username_2: If the support of your PDFs is quite spread apart, using `lines` will not suffice. You'll need to control the range of the calculated values to the density.
Here's an example:
```
x1 = rnorm(1e5)
x2 = rnorm(1e5, mean = 4)
#looks bad because the support has little overlap
plot(density(x1))
lines(density(x2))
```
To overcome this, leverage the `to` and `from` parameters to `density`
```
rng = range(c(x1, x2))
d1 = density(x1, from = rng[1L], to = rng[2L])
d2 = density(x2, from = rng[1L], to = rng[2L])
matplot(d1$x, cbind(d1$y, d2$y), type = 'l', lty = 1L)
```
Add bells and whistles to taste.
Upvotes: 0
|
2018/03/16
| 723 | 2,217 |
<issue_start>username_0: Why bodies seems broken on second loop example, am trying to optimize my planetary system to support more bodies.
```
for(Body body : bodies){
PVector totalForce = new PVector();
for(Body other : bodies){
if(body != other){
PVector fxy = body.attraction(other);
totalForce.x += fxy.x;
totalForce.y += fxy.y;
}
}
body.vel.x += totalForce.x / body.mass * timestep;
body.vel.y += totalForce.y / body.mass * timestep;
body.pos.x += body.vel.x * timestep;
body.pos.y += body.vel.y * timestep;
}
```
second loop where just one body is moving and it is moving in wrong directions
```
PVector totalForce = new PVector();
PVector fxy = new PVector();
for(int i = 0; i + 1 < bodies.size(); i++){
Body body = bodies.get(i);
Body other = bodies.get(i + 1);
System.out.println(body + " " + other);
fxy = body.attraction(other);
totalForce.x += fxy.x;
totalForce.y += fxy.y;
body.vel.x += totalForce.x / body.mass * timestep;
body.vel.y += totalForce.y / body.mass * timestep;
body.pos.x += body.vel.x * timestep;
body.pos.y += body.vel.y * timestep;
}
```
[gravity example](https://i.stack.imgur.com/Gqz6n.png)<issue_comment>username_1: It seems that the code is not applying every forces affecting the body.
```
Body body = bodies.get(i);
Body other = bodies.get(i + 1);
```
These two lines are suspicious, and have to be thought over more.
Mathematically [this wikipedia link](http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order) and [this SO community wiki](https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n) may help you optimizing.
So, a possible candidate is:
```
n=num_of_bodies;
for(int i=0;i
```
The point of it is reducing repetition of calc performed to body and other.
If indices are wrong please edit mine.
Upvotes: 1 <issue_comment>username_2: In your first sample you are examining every possible pair of bodies.
>
> a,b,c - (a,b),(a,c),(b,c)
>
>
>
In your second example you are examining each neighboring body.
>
> a,b,c - (a,b),(b,c)
>
>
>
Upvotes: 3 [selected_answer]
|
2018/03/16
| 300 | 847 |
<issue_start>username_0: CODE:
```
Select list (select one):
{% for i in 150 %}
{{ i + 1989 }}
{% endfor %}
```
I want to make year select form which is from 1900 to 2050.
How can I use `i` variable in django template tag?<issue_comment>username_1: You can use [Template range loop](https://djangosnippets.org/snippets/1899/) from django
**syntax**
```
{% range start:step:end as i %}
{{ i }}
{% endrange %}
```
**Example**
```
{% range 1900:1:2050 as i %}
{{ i }}
{% endrange %}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Here's a much easier solution using django template language filter.
views.py
```py
def my_view(request)
return render(request, 'my_template.html', {'my_range':range(150)})
```
my\_template.html
```
{% for i in my_range %}
{{ i|add:1990 }}
{% endfor %}
```
Upvotes: 0
|
2018/03/16
| 447 | 1,452 |
<issue_start>username_0: I need to set default Collation for MySQL tables with Django 2.\*, im using mysqlclient, my settings are:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
},
}
}
'charset': 'utf8mb4',
```
This parameter seems don't work properly and tables in DB utf8. Although i want to manually set and tables Collation to **utf8mb4\_general\_ci**
Will be appreciate for any clues.<issue_comment>username_1: ```
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': 'ALTER DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4\_general\_ci',
},
}
```
Thanks to <https://stackoverflow.com/a/6115705/2891421>
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': get_env_val('MYSQL_DB_NAME'),
'USER': get_env_val('MYSQL_DB_USER'),
'PASSWORD': get_env_val('MYSQL_DB_PASSWORD'),
'HOST': get_env_val('MYSQL_DB_HOST'),
'PORT': get_env_val('MYSQL_DB_PORT'),
'OPTIONS': {
'charset': 'utf8mb4',
}
,
}
}
```
Upvotes: 0
|
2018/03/16
| 710 | 2,583 |
<issue_start>username_0: When I fetch a small data set, say 2000 observations, in R using googleAnalyticsR from google analytics, everything works well.
```
df <- google_analytics(id=ga_id,
start="2017-12-01",
end="2017-12-31",
metrics="ga:users",
dimensions="ga:dimension1, ga:longitude, ga:latitude",
max=10000)
```
But when I needed to fetch a bigger data set with 20000 observations, the same code failed and error returned:
>
> Batching data into [2] calls.
>
> Request to profileId: ()
>
> Error in f(content, ...) : Invalid dimension or metric:
>
>
>
How can I solve this issue? Thank you.<issue_comment>username_1: There is a provision to run your code in batches. I use 'rga' library and I download huge data in batches, and data frame that comes out usually has all observations. Here is a slight modification. Please let me know if it doesn't work.
```
df <- ga$getData(id, batch =TRUE,
start="2017-01-01",
end="2017-12-31",
metrics="ga:users",
dimensions="ga:dimension1, ga:longitude,ga:latitude",
max=10000)
```
It is from a git [version](https://github.com/skardhamar/rga) of the library. Very sorry I did not mention this earlier. I use this so much, I forgot it isn't part of the CRAN version.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You need to set max to -1, then it fetches all results. You don't need to set batches or page sizes etc. , it does that for you.
Here are some examples from the [website](http://code.markedmondson.me/googleAnalyticsR/v4.html):
```
# 1000 rows only
thousand <- google_analytics(ga_id,
date_range = c("2017-01-01", "2017-03-01"),
metrics = "sessions",
dimensions = "date")
# 2000 rows
twothousand <- google_analytics(ga_id,
date_range = c("2017-01-01", "2017-03-01"),
metrics = "sessions",
dimensions = "date",
max = 2000)
# All rows
alldata <- google_analytics(ga_id,
date_range = c("2017-01-01", "2017-03-01"),
metrics = "sessions",
dimensions = "date",
max = -1)
```
Upvotes: 2
|
2018/03/16
| 744 | 2,968 |
<issue_start>username_0: I have two generic objects of class `Generic`:
```
Generic genericOne;
Generic genericTwo;
```
I have to mock:
```
when(someObject.someMethod(Matchers.>any()))
.thenReturn(responseOne());
when(someObject.someMethod(Matchers.>any()))
.thenReturn(responseTwo());
```
The problem is that mockito will not the see difference between this two method calls because of type erasure - it's both recognized as `Generic` class.
Is there any way to to distinguish between this two method calls?<issue_comment>username_1: Mockito doesn't know which generics was specified in front of `any()` invocation and anyway it doesn't matter.
The parameters expected in the recording a mock behavior has to rely on :
* value (in terms of `equals()`
* or in terms of captor if `equals()` is not adequate
* or `any()` if the value of the parameter in the mock invocation doesn't matter or is not known in the test fixture
These never have to rely on the generic specified on.
To have a good example, look at `Mockito.anyCollectionOf(Class clazz)` or `Mockito.anyMapOf(Class keyClazz, Class valueClazz)`.
These methods know the class passed but anyway, their specifications state :
>
> This method *don't do any type checks*, it is only there to avoid
> casting in your code. This might however change (type checks could be
> added) in a future major release.
>
>
>
Generally what you want to check is that the method to mock was invoked with the expected parameter and not any parameter : so `any()` will never achieve it.
**So trying to check only the generic type but accepting any values as parameters seems be an anti pattern mocking.**
In your case, if `equals()` is not convenient for the matching in the `when()` recording, use Mockito captor with `verify()` and do the check after the execution of the mock.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I don't think it's possible to differentiate between the two as generic types are arased. But there are other options.
You can couple this calls to specific order so that even if mockito cannot differentiate between them it return expected value. This is done by chaining the `thenReturn` methods. First call returns `responseOne()` and second call returns `responseTwo()`.
```
when(someObject.someMethod(Matchers.>any()))
.thenReturn(responseOne())
.thenReturn(responseTwo());
```
But this is not optimal as this test will break if your implementations changes. So here comes the second option.
You can implement custom [Fake](https://8thlight.com/blog/uncle-bob/2014/05/14/TheLittleMocker.html) for this object. So that you can bette control how this instance behaves. For example.
```
class SomeObjectFake {
private final SomeResponse response;
public SomeObject(SomeResponse response) {
this.response = response;
}
public SomeResponse someMethod(Generic arg) {
// Decide what to return
return response;
}
}
```
Upvotes: 2
|
2018/03/16
| 924 | 3,371 |
<issue_start>username_0: I need to make a method that takes as argument a multi dimensional array of integers and does the following:
* Checks if the number of rows and columns are odd, otherwise returns 0.
* If the array is odd, then the method returns the sum of the terms of the
middle line, minus those in the middle column.
**For example :**
```
2 4 6
9 10 17
1 6 18
```
This exemple should return : `(9 + 10 + 17) − (4 + 10 + 6) = 36 − 20 = 16`
This is what I did so far :
```
static int [][] sub(int i , int j) {
if (i%2 == 0 || j%2 == 0)
return 0;
else
int[][] tab = new int[i][j];
// Create array with values from 0 to 99 randomly
for (int i = 0; i < tab.length; i++) {
for (int j = 0; j < tab[i].length; j++) {
tab[i][j] = (int) (Math.random() * 99);
}
}
}
```
After that, I don't really know what to do.. Thanks for helping me out<issue_comment>username_1: Mockito doesn't know which generics was specified in front of `any()` invocation and anyway it doesn't matter.
The parameters expected in the recording a mock behavior has to rely on :
* value (in terms of `equals()`
* or in terms of captor if `equals()` is not adequate
* or `any()` if the value of the parameter in the mock invocation doesn't matter or is not known in the test fixture
These never have to rely on the generic specified on.
To have a good example, look at `Mockito.anyCollectionOf(Class clazz)` or `Mockito.anyMapOf(Class keyClazz, Class valueClazz)`.
These methods know the class passed but anyway, their specifications state :
>
> This method *don't do any type checks*, it is only there to avoid
> casting in your code. This might however change (type checks could be
> added) in a future major release.
>
>
>
Generally what you want to check is that the method to mock was invoked with the expected parameter and not any parameter : so `any()` will never achieve it.
**So trying to check only the generic type but accepting any values as parameters seems be an anti pattern mocking.**
In your case, if `equals()` is not convenient for the matching in the `when()` recording, use Mockito captor with `verify()` and do the check after the execution of the mock.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I don't think it's possible to differentiate between the two as generic types are arased. But there are other options.
You can couple this calls to specific order so that even if mockito cannot differentiate between them it return expected value. This is done by chaining the `thenReturn` methods. First call returns `responseOne()` and second call returns `responseTwo()`.
```
when(someObject.someMethod(Matchers.>any()))
.thenReturn(responseOne())
.thenReturn(responseTwo());
```
But this is not optimal as this test will break if your implementations changes. So here comes the second option.
You can implement custom [Fake](https://8thlight.com/blog/uncle-bob/2014/05/14/TheLittleMocker.html) for this object. So that you can bette control how this instance behaves. For example.
```
class SomeObjectFake {
private final SomeResponse response;
public SomeObject(SomeResponse response) {
this.response = response;
}
public SomeResponse someMethod(Generic arg) {
// Decide what to return
return response;
}
}
```
Upvotes: 2
|
2018/03/16
| 1,947 | 5,991 |
<issue_start>username_0: I had this working without jquery, but the problem was that the tooltip was appearing on the whole div rather than just the PNG.
The mouseover function worked well with jquery so I decided to switch to that, however I do not know how to trigger the CSS animation when the mouseover function runs.
```js
$('#cookie').mouseover(function() {
//$('#tooltip').removeClass('.cookieToolTip');
$('#tooltip').addClass('.cookieToolTipHovered');
});
// I also have some code to move the tooltip wherever the cursor is:
var tooltip = document.querySelectorAll('.cookieToolTip');
document.addEventListener('mousemove', fn, false);
function fn(e) {
for (var i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
}
```
```css
.cookieToolTipHovered {
visibility: visible;
opacity: 1;
}
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html

This is a picture of a cookie.
```<issue_comment>username_1: When adding and removing class do not use the `.` before the classname...as it will add a class with the name `.class` instead of `class`.
You can make your code a little bit cleaner and use ES6 variable declaration ( as a bonus :) ). If your html markup is like in your example ( tooltip exactly after the image ), you can use css selector and get rid of the mouseover/mousein/mouseout methods. See example below, when you hover out of the image the tooltip dissapears
```js
const cookie = $("#cookie"),
tooltip = $('.cookieToolTip')
cookie.on("mousemove", function(e) {
for (let i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
})
```
```css
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
#cookie:hover + .cookieToolTip{
opacity:1
}
```
```html

This is a picture of a cookie.
```
Upvotes: 2 <issue_comment>username_2: You can change the CSS - you may want to hide (display:none) instead of using visibility since moving the mouse to the edge of the screen will add scrollbars now
```js
$('#cookie').mouseover(function() {
$('#tooltip').css({"opacity":1, "visibility": "visible"})
});
$('#cookie').mouseout(function() {
$('#tooltip').css({ opacity: 0, visibility: "hidden"})
});
// I also have some code to move the tooltip wherever the cursor is:
var $tooltip = $('#tooltip');
$(document).on("mousemove",function(e) {
$tooltip.css({"left": e.pageX + 'px', "top" : e.pageY + 'px'});
})
```
```css
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html

This is a picture of a cookie.
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: when you add a class you don't need the dot before the class name because it's a declaration, not a selector
```
Wrong: $('#cookie').addClass('.cookieToolTipHovered');
Correct: $('#cookie').addClass('cookieToolTipHovered');
```
Then, you need to remove the class when you're out, if you don't the class will keep applied, by the other part, select the proper item to apply (hover / mouseover...) condition (see the example below).
```js
$('.zoomin').mouseover(function() {
$('#cookie').addClass('cookieToolTipHovered');
});
$('#cookie').mouseout(function() {
$('#cookie').removeClass('cookieToolTipHovered');
});
```
```css
.cookieToolTipHovered {
opacity: 0.35;
transition: 1s;
}
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html

This is a picture of a cookie.
```
Upvotes: 0 <issue_comment>username_4: You don't need a `mouseover` event handler.
Instead, you can handle the `opacity` toggle using pure CSS with a combination of [`:hover`](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover) and [`+`](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors) :
```css
#cookie:hover+.cookieToolTip{ //This will change the opacity
//of the tooltip when the image is hovered
opacity: 1;
}
```
**EDIT:** I added
```
.cookieToolTip:hover{
opacity: 1;
}
```
To fix a bug which toggled the opacity back off when you hovered the tooltip.
**Demo:**
```js
$(document).on('mousemove', function(e) {
$('.cookieToolTip').css({
left: e.pageX,
top: e.pageY
});
});
```
```css
.cookieToolTip {
display: block;
position: absolute;
background: #C8C8C8;
padding: 10px;
width: 200px;
height: 50px;
border: 1px solid black;
border-radius: 5px;
opacity: 0;
transition: opacity 1s;
z-index: 1000;
}
#cookie:hover+.cookieToolTip {
opacity: 1;
}
.cookieToolTip:hover{
opacity: 1;
}
```
```html

This is a picture of a cookie.
```
Upvotes: 0
|
2018/03/16
| 1,132 | 3,472 |
<issue_start>username_0: In JavaScript I have a string like
```
Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?
```
I want to format that like an object array like this
```
[
{'Package' : 'sdvasd', 'Qty' : 1, 'Price' : 34 }
{'Package' : 'sdabhjds', 'Qty' : 1, 'Price' : 234 }
]
```
The code what I have tried so far
```
let packageData = data.split('?');
let packageArr = [];
if( packageData.length > 0 ) {
for (var i = 0; i < packageData.length -1; i++) {
let str = packageData[i].split('&');
for (var j = 0; j < str.length; j++) {
let keys = str[j].split('=');
packageArr.push(keys[1])
}
}
}
console.log(packageArr);
```
But it is not giving me result like this. Can someone tell me how to make this like the desired output. Any suggestions and advice will be really appreciable.
I only want javascript method not jQuery<issue_comment>username_1: Use `split`, `map` and `reduce`
```
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
```
**Demo**
```js
var str = "Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?";
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
console.log( output );
```
Upvotes: 1 <issue_comment>username_2: You could split the string and create for the outer splitting an array and for inner splitting the object and for the most inner splitting a key/value pair.
```js
var string = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?',
result = string
.split('?')
.filter(Boolean)
.map(s => s.split('&').reduce((o, p) => {
var [k, v] = p.split('=');
return Object.assign(o, { [k]: v });
}, {}));
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can use this. Also you can check for `number` values so that the `qty` and `Price` properties has numeric values and not string:
```js
var str = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234';
var resArray = [];
str.split('?').filter((obj)=>{
var resObj = {};
obj.split('&').map((item)=>{
var itemSplit = item.split('=');
if(isNaN(itemSplit[1])){
resObj[itemSplit[0]] = itemSplit[1];
} else {
resObj[itemSplit[0]] = parseInt(itemSplit[1]);
}
});
resArray.push(resObj);
});
console.log(resArray);
```
Upvotes: 0 <issue_comment>username_4: Try the below code. Create a object and then put the key value pairs.
```
let packageArr = [];
let packageDataArr = data.split('?');
Array.prototype.forEach.call(packageDataArr,(packageData)=>{
let dataObj = {};
let str = packageData.split('&');
Array.prototype.forEach.call(str,(keyValue)=>{
let keys = keyValue.split('=');
dataObj[key[0]] = key[1];
});
packageArr.push(dataObj);
});
```
Upvotes: 0
|
2018/03/16
| 949 | 2,980 |
<issue_start>username_0: I'm finding a `sed` command in linux that can replace the following variable value to `root` in .env file
```
DB_USERNAME=123
DB_ABC_USERNAME=abc
DB_ABC_DEF_USERNAME=abcdef
```
to
```
DB_USERNAME=root
DB_ABC_USERNAME=root
DB_ABC_DEF_USERNAME=root
```
the file have another variable within such like DB\_HOST=xxx, we can not using sed change all variable<issue_comment>username_1: Use `split`, `map` and `reduce`
```
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
```
**Demo**
```js
var str = "Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?";
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
console.log( output );
```
Upvotes: 1 <issue_comment>username_2: You could split the string and create for the outer splitting an array and for inner splitting the object and for the most inner splitting a key/value pair.
```js
var string = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?',
result = string
.split('?')
.filter(Boolean)
.map(s => s.split('&').reduce((o, p) => {
var [k, v] = p.split('=');
return Object.assign(o, { [k]: v });
}, {}));
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can use this. Also you can check for `number` values so that the `qty` and `Price` properties has numeric values and not string:
```js
var str = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234';
var resArray = [];
str.split('?').filter((obj)=>{
var resObj = {};
obj.split('&').map((item)=>{
var itemSplit = item.split('=');
if(isNaN(itemSplit[1])){
resObj[itemSplit[0]] = itemSplit[1];
} else {
resObj[itemSplit[0]] = parseInt(itemSplit[1]);
}
});
resArray.push(resObj);
});
console.log(resArray);
```
Upvotes: 0 <issue_comment>username_4: Try the below code. Create a object and then put the key value pairs.
```
let packageArr = [];
let packageDataArr = data.split('?');
Array.prototype.forEach.call(packageDataArr,(packageData)=>{
let dataObj = {};
let str = packageData.split('&');
Array.prototype.forEach.call(str,(keyValue)=>{
let keys = keyValue.split('=');
dataObj[key[0]] = key[1];
});
packageArr.push(dataObj);
});
```
Upvotes: 0
|
2018/03/16
| 726 | 1,909 |
<issue_start>username_0: I have read an excel file in a pandas data frame. I am iterating over the indexed column comparing each of the element of the row with some value. When I find a match I need to find the column number in which the match is found.
Example:
```
df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4], 'C' : [5,7,2,5]})
print df
A B C
0 0 1 5
1 0 2 7
2 2 3 2
3 1 4 5
```
If i find a match for element 3, I should be able to print 'B' along with B's column number i.e. 1.
How to achieve that?
Thanks!<issue_comment>username_1: I think there should be multiple match, so is possible filter with [`any`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html) for at least one match and then get `index` of `s` for all `True`s and select first value by `[]` For positions by column name use [`Index.get_loc`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html):
```
s = (df == 3).any()
print (s)
A False
B True
C False
dtype: bool
a = s.index[s]
print (a[0])
B
print (df.columns.get_loc(a[0]))
1
```
EDIT:
```
df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4], 'C' : [5,2,3,5]})
print (df)
A B C
0 0 1 5
1 0 2 2
2 2 3 3
3 1 4 5
s = (df == 3).any()
print (s)
A False
B True
C True
dtype: bool
a = s.index[s]
print (a)
Index(['B', 'C'], dtype='object')
print (df.columns.get_indexer(a))
[1 2]
```
Upvotes: 1 <issue_comment>username_2: ```
for da in df.index.values:
for i,d in df.loc[data].items():
print i
```
Here `i` will print the column number.
Upvotes: 1 [selected_answer]<issue_comment>username_3: Use `np.where`. It'll give you the row and corresponding column positions for all matches
```
i, j = np.where(df.values == 3)
j
array([1])
```
If you want the column labels
```
df.columns[j]
Index(['B'], dtype='object')
```
Upvotes: 2
|
2018/03/16
| 659 | 1,853 |
<issue_start>username_0: I want to upload some data from a local file on my pc via SQL-manager to a sql-database on azure.
I tried
```
BULK INSERT gifts
FROM 'c:\temp\trouwpartij.txt'
WITH
(
FIELDTERMINATOR =' |',
ROWTERMINATOR =' |\n'
);
```
But unfortunatly the path is pointing to a location on the sql-server, which I cannot access.
Any suggestions how to complete this simple task whitout actually developing a small application ?<issue_comment>username_1: I think there should be multiple match, so is possible filter with [`any`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html) for at least one match and then get `index` of `s` for all `True`s and select first value by `[]` For positions by column name use [`Index.get_loc`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html):
```
s = (df == 3).any()
print (s)
A False
B True
C False
dtype: bool
a = s.index[s]
print (a[0])
B
print (df.columns.get_loc(a[0]))
1
```
EDIT:
```
df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4], 'C' : [5,2,3,5]})
print (df)
A B C
0 0 1 5
1 0 2 2
2 2 3 3
3 1 4 5
s = (df == 3).any()
print (s)
A False
B True
C True
dtype: bool
a = s.index[s]
print (a)
Index(['B', 'C'], dtype='object')
print (df.columns.get_indexer(a))
[1 2]
```
Upvotes: 1 <issue_comment>username_2: ```
for da in df.index.values:
for i,d in df.loc[data].items():
print i
```
Here `i` will print the column number.
Upvotes: 1 [selected_answer]<issue_comment>username_3: Use `np.where`. It'll give you the row and corresponding column positions for all matches
```
i, j = np.where(df.values == 3)
j
array([1])
```
If you want the column labels
```
df.columns[j]
Index(['B'], dtype='object')
```
Upvotes: 2
|
2018/03/16
| 1,057 | 3,927 |
<issue_start>username_0: I have multiple microservices and I am using docker-compose for development deployments. When there are some changes in the microservices code base, I am triggering ci job to re-deploy them. I have below script to do this. But each time I have to build all images from scratch, then run them. After all of this operation, I have `anonymous` images. So I am using the last script to remove them. What you would suggest making this process more practical? Is there any way to update an existing image without removing it with new changes?
```
- docker-compose build
- docker-compose down
- docker-compose up -d --force-recreate
- docker rmi $(docker images -f "dangling=true" -q) -f
```
Additional info: i am using `gitlab-ci`<issue_comment>username_1: Docker containers are designed to be ephemeral. To update an existing container, you remove the old one and start a new one.
Thus the process that you are following is the correct one.
You can simplify the commands to the following ones:
```
docker-compose up --force-recreate --build -d
docker image prune -f
```
Upvotes: 9 [selected_answer]<issue_comment>username_2: With docker-compose version 3 you can add tags to your images and clean up by them depends on your logic:
```
build: ./dir
image: yourapp:tag
```
It could help you to avoid anonymous images to clean up
Upvotes: 2 <issue_comment>username_3: You can update it using:
```
docker-compose pull
```
Now your image is updated. If you have the previous version of container running you should restart it to use the updated image:
```
docker-compose up --detach
```
`up` command automatically recreates container on image or configuration change.
Upvotes: 8 <issue_comment>username_4: I prefer to ensure all the images are downloaded before updating the containers with the new images to minimize the time in an intermediate state or worse being in the middle in case the download of an image fails.
1. I pull latest images:
`docker-compose pull`
2. Then I restart containers:
`docker-compose up -d --remove-orphans`
3. Optionally, I remove obsolete images:
`docker image prune`
Upvotes: 8 <issue_comment>username_5: ```
docker-compose pull
```
then
```
docker-compose up -d
```
you don't need "down" "docker-compose up -d" command will only recreate changed one
Upvotes: 6 <issue_comment>username_6: There is also a script, with which one can update many docker-compose stacks at once.
It is called [compose-update](https://github.com/FrederikRogalski/compose-update) and can be found at the following link:
<https://github.com/FrederikRogalski/compose-update>
**compose-update** a docker-compose-image-updater
=================================================
This python script updates the images of one or many docker-compose stacks automatically.
If multiple docker-compose directories are supplied, the script updates them in parallel.
Demo
----

Usage
-----
```
Usage: compose-update [OPTIONS] [UPDATE_DIRS]...
Update docker-compose images automatically.
Takes one or more directorys as input and searches for a
compose file in one of the following forms:
"compose.yaml", "compose.yml", "docker-compose.yaml",
"docker-compose.yml"
Options:
--prune / --no-prune Prune docker images after update
process if set
--help Show this message and exit.
```
Installation
------------
```
git clone https://github.com/FrederikRogalski/compose-update.git
cd compose-updater
chmod +x update-compose
```
Then add the file 'update-compose' to your path.
Upvotes: 2 <issue_comment>username_7: I've noticed above answers, but I still insist to use the following orders to make sure everything is correct:
1. `docker-compose pull`
2. `docker-compose down`
3. `docker-compose up -d`
Upvotes: 2
|
2018/03/16
| 475 | 1,986 |
<issue_start>username_0: I can't navigate through the code for an old project involving many classes. in eclipse, for example, holding Ctrl when clicking on a class/method/interface doesn't open it.
How can I define the path of this class so that I can navigate through the code in Eclipse?<issue_comment>username_1: There can be scenarios where `Ctrl` + `Click` do not work, and in order to solve that you may want to check the below options in the order mentioned as below:
1. You may just have to restart your Eclipse IDE once to check if this is solved
2. If Step-1 doesn't solve, you might want to add the `-clean` parameter to the command line argument to the `eclipse.exe` executable.
3. You need to check whether your Java project's build path is all correct without any errors/issues.
4. At times if this option is ('Project' -> 'Build Automatically') selected, you might have to do a 'Project' -> 'Clean...' to clean your projects
5. If Steps 1,2,3 and 4 do not solve your problem then you can take a backup of your project folder and then clean this `WORKSPACE_FOLDER/.metadata/.plugins/org.eclipse.jdt.core`
6. If the following didn't help then you can check for the following option to be available on your Eclipse IDE as well
```
On Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking -> Open Declaration
```
You need to check whether the `Default modifier key` is `Ctrl` and also ensure to select the checkbox for `Enable on demand hyperlink style navigation`
Hope this helps to resolve your issue!
Upvotes: 0 <issue_comment>username_2: Make you sure you have imported it as `java project` and make sure that the `java facet` is set in the project properties.
If not just remove the project from eclipse **without deleting sources from disk**, remove eclipse files (.classpath, .project, and .settings) from project directory on disk and import it again as java project. If you have a `pom.xml` import as existing maven project.
Upvotes: 2
|
2018/03/16
| 729 | 2,535 |
<issue_start>username_0: I want to skip text at the start of a string in Kotlin like the Java `Scanner.skip()`
please tell me how to do something like `string.skip("**")` to skip `**` at the start of `string`
for example `"**hello stack".skip("**") --> "hello stack"`<issue_comment>username_1: Edit: I didn't realize you wanted it at the *start* only, just use `removePrefix`:
```
"**hello stack".removePrefix("**") // "hello stack"
```
>
> If this char sequence starts with the given prefix, returns a new char sequence with the prefix removed. Otherwise, returns a new char sequence with the same characters.
>
> [kotlin.text.removePrefix](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/remove-prefix.html)
>
>
>
---
>
> I want to skip text at the start of a string
>
>
>
You can use `substringAfter`:
```
"**hello stack".substringAfter("**") // "hello stack"
```
>
> Returns a substring after the first occurrence of `delimiter`. If the string does not contain the delimiter, returns `missingDelimiterValue` which defaults to the original string.
>
> [kotlin.text.substringAfter](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/substring-after.html)
>
>
>
When the given delimiter is not present, `substringAfter` will simply return `missingDelimiterValue`, which by default is the original string:
```
"foo".substringAfter("**") // "foo"
"foo".substringAfter("**", "no match") // "no match"
```
Upvotes: 2 <issue_comment>username_2: Kotlin is fully designed with interoperability in mind. You can use all Java classes including Scanner.
What you would like to achieve is creation extenstion function
This is just unefficient draft. But you can optimize for your need.
```
fun String.skip(pattern: String): String {
val scanner = Scanner(this)
//scanner opeations
return scanner.nextLine()
}
```
Take a look here: <https://kotlinlang.org/docs/reference/extensions.html> &
<https://kotlinlang.org/docs/reference/inline-functions.html>
Upvotes: -1 <issue_comment>username_3: ```
var data = "**hi dhl**"
println(data.removePrefix("**")) // hi dhl**
println(data.removeSuffix("**")) // **hi dhl
println(data.removeSurrounding("**")) // hi dhl
println(data.substringAfter("**")) // hi dhl**
println(data.substringAfter("--")) // **hi dhl**
println(data.substringAfter("--","no match")) // no match
data = "{JAVA | KOTLIN | C++ | PYTHON}"
println(data.removeSurrounding("{", "}")) // JAVA | KOTLIN | C++ | PYTHON
```
Upvotes: 0
|
2018/03/16
| 1,171 | 3,445 |
<issue_start>username_0: I need optimization of loop (array) in loop (object). Below is my solution which is working, but if I try this with huge amount of data then is too slow.
Here is my array
```
$data = [
["PLZ", "Preis"],
["8074", "90"],
["8075", "90"],
["8076", "90"],
["8077", "90"],
["8078", "77"],
["1010", "77"],
["1020", "77"],
["1030", "77"],
["8041", "55"],
["8020", "89"],
];
```
Here is my object
```
$postal_collection = {
"1010":1,
"1020":2,
"1030":3,
"8020":1602,
"8041":1604,
"8074":1622,
"8075":1623,
"8076":1624,
"8077":1625
}
```
Here is working loop
```
$allData = [];
foreach ($data as $key => $fields) {
foreach ($postal_collection as $postal => $placeId) {
if ($fields[0] == $postal) {
$allData[$placeId] = [
'postal' => $postal,
'place_id' => $placeId,
'price' => $fields[1],
];
}
}
}
```
So how can I change this loop to make the same job but faster?<issue_comment>username_1: You could avoid one foreach by using keys of `$postal_collection`:
```
$allData = [];
foreach ($data as $key => $fields) {
$id = $fields[0] ;
// check if the key exists in $postal_collection:
if (!isset($postal_collection[$id])) continue ;
// get the value
$cp = $postal_collection[$id];
// add to $allData
$allData[$cp] = [
'postal' => $id,
'place_id' => $cp,
'price' => $fields[1],
];
}
print_r($allData);
```
Outputs:
```
Array
(
[1622] => Array
(
[postal] => 8074
[place_id] => 1622
[price] => 90
)
[1623] => Array
(
[postal] => 8075
[place_id] => 1623
[price] => 90
)
[1624] => Array
(
[postal] => 8076
[place_id] => 1624
[price] => 90
)
[1625] => Array
(
[postal] => 8077
[place_id] => 1625
[price] => 90
)
[1] => Array
(
[postal] => 1010
[place_id] => 1
[price] => 77
)
[2] => Array
(
[postal] => 1020
[place_id] => 2
[price] => 77
)
[3] => Array
(
[postal] => 1030
[place_id] => 3
[price] => 77
)
[1604] => Array
(
[postal] => 8041
[place_id] => 1604
[price] => 55
)
[1602] => Array
(
[postal] => 8020
[place_id] => 1602
[price] => 89
)
)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If $fields[0] (the first item in each $data "row") is unique you can cycle through those once and create a lookup array. The assignment of a single item from that lookup array will be fast.
Then you can cycle through $postal\_collection and create your $all\_data result in only one pass.
```
$lookup = [];
foreach ($data as $row){
$lookup[$row[0]] = $row[1];
}
$allData = [];
foreach ($postal_collection as $postal => $placeId) {
if (isset($lookup[$postal]) && !isset($allData[$placeId])){
$allData[$placeId] = [
'postal' => $postal,
'place_id' => $placeId,
'price' => $lookup[$postal]
];
}
}
```
Upvotes: 0
|
2018/03/16
| 714 | 2,535 |
<issue_start>username_0: I am using the code below to run a macro at specific time each day which works fine while I am at work but over weekends my computer goes into sleep mode and the code does not run. How do I work around this?
```
Sub Scheduler()
Application.OnTime TimeValue("12:00:00"), "TheScheduledSub"
End Sub
Sub TheScheduledSub()
MsgBox "TheScheduledSub() has run at " & Time
End Sub
```<issue_comment>username_1: You can turn off hibernation with a shell command:
```
powercfg.exe /hibernate off
```
and you can use the [`Shell` Function](https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/shell-function) to run shell commands.
For more info read: [How to disable and re-enable hibernation on a computer that is running Windows](https://support.microsoft.com/en-us/help/920730/how-to-disable-and-re-enable-hibernation-on-a-computer-that-is-running).
Of course don't forget to turn it on again when you close that file.
Upvotes: 2 <issue_comment>username_2: Configure Windows task scheduler to wake your computer as specified times (with specified frequency)
From [this](https://www.howtogeek.com/119028/how-to-make-your-pc-wake-from-sleep-automatically/) link:
* Open the Task Scheduler by typing Task Scheduler into the Start menu if you are running Windows 10 or 7 (or Start Screen if you are using Windows 8.x) and pressing Enter
* In the Task Scheduler window, click the Create Task link to create a new task.
* Name the task something like “Wake From Sleep.” You may also want to tell it to run whether a user is logged on or not and set it to run with highest privileges.
* On the Triggers tab, create a new trigger that runs the task at your desired time. This can be a repeating schedule or a single time.
* On the conditions tab, enable the Wake the computer to run this task option.
* On the actions tab, you must specify at least one action for the task – for example, you could have the task launch a file-downloading program. If you want to wake the system without running a program, you can tell the task to run cmd.exe with the /c “exit” arguments
* Save your new task after configuring it.
You can also configure a task to send your computer [back to sleep](https://www.howtogeek.com/howto/30758/make-your-pc-shut-down-at-night-but-only-when-youre-not-using-it/).
You could additionally use the Scheduler to kick off your script.
Adding cmd text
[](https://i.stack.imgur.com/5EwL7.png)
Upvotes: 2 [selected_answer]
|
2018/03/16
| 698 | 2,524 |
<issue_start>username_0: I've created an AWS EC2 instance. What I'm trying to do is to add an inbound rule for the corresponding security group to the instance. The type of connection I wish the firewall to allow is HTTPS on port 443.
Every time I save it though, it changes to a Custom TCP Rule on port 443. Does anyone know why this happens and how may I allow a HTTPS connection to the instance?<issue_comment>username_1: You can turn off hibernation with a shell command:
```
powercfg.exe /hibernate off
```
and you can use the [`Shell` Function](https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/shell-function) to run shell commands.
For more info read: [How to disable and re-enable hibernation on a computer that is running Windows](https://support.microsoft.com/en-us/help/920730/how-to-disable-and-re-enable-hibernation-on-a-computer-that-is-running).
Of course don't forget to turn it on again when you close that file.
Upvotes: 2 <issue_comment>username_2: Configure Windows task scheduler to wake your computer as specified times (with specified frequency)
From [this](https://www.howtogeek.com/119028/how-to-make-your-pc-wake-from-sleep-automatically/) link:
* Open the Task Scheduler by typing Task Scheduler into the Start menu if you are running Windows 10 or 7 (or Start Screen if you are using Windows 8.x) and pressing Enter
* In the Task Scheduler window, click the Create Task link to create a new task.
* Name the task something like “Wake From Sleep.” You may also want to tell it to run whether a user is logged on or not and set it to run with highest privileges.
* On the Triggers tab, create a new trigger that runs the task at your desired time. This can be a repeating schedule or a single time.
* On the conditions tab, enable the Wake the computer to run this task option.
* On the actions tab, you must specify at least one action for the task – for example, you could have the task launch a file-downloading program. If you want to wake the system without running a program, you can tell the task to run cmd.exe with the /c “exit” arguments
* Save your new task after configuring it.
You can also configure a task to send your computer [back to sleep](https://www.howtogeek.com/howto/30758/make-your-pc-shut-down-at-night-but-only-when-youre-not-using-it/).
You could additionally use the Scheduler to kick off your script.
Adding cmd text
[](https://i.stack.imgur.com/5EwL7.png)
Upvotes: 2 [selected_answer]
|
2018/03/16
| 498 | 1,587 |
<issue_start>username_0: I'm trying to redirect my port 80 to 8080 because the user need not type the url as webapp:8080 to access the web site.
Here's the command that I came across to redirect from port 80 to 8080 :
```
sudo iptables -A PREROUTING -t nat -i enp0s25 -p tcp --dport 80 -j REDIRECT --to-port 8080
```
I'm now able to access the page as webapp/. But the problem now I'm facing is that I'm not able to access the page if I give webapp/ after I restart the system.
How do I fix this?<issue_comment>username_1: The only thing you need is to save iptables rules permanently. It can be various depend on linux distribution.
For Debian/Ubuntu see for instance here:
<https://www.thomas-krenn.com/en/wiki/Saving_Iptables_Firewall_Rules_Permanently>
Upvotes: 0 <issue_comment>username_2: You can try this :
```
iptables-save > /etc/sysconfig/iptables
```
"/etc/sysconfig/iptables " is for centos, you need to find the same file on your linux OS :)
An other solution is to create a conf' file and use this file when the system boot :
* Create a file like "Conf\_iptables".
* Add your rules to this file.
* Add execute privilege to root
* `chkconfig Conf_iptables on`
Moreover you have to create 2 iptables rules (for IPv4 and IPv6) if you want to use IPv6 :)
If you need help use this site (sorry but it's in french) : <http://blog.sephirots.fr/?p=123>
Upvotes: 1 <issue_comment>username_3: Ubuntu:
Install `iptables-persistent`. This will create 2 files in /etc/iptables/rules.v4 and rules.v6
Run `netfilter-persistent save`.
Try rebooting the machine.
Upvotes: 0
|
2018/03/16
| 1,802 | 6,424 |
<issue_start>username_0: I am using below code to get **versionName** from **playstore** by using jsoup I am fetching details but its throwing some exception.
My code is
```
public class ForceUpdateAsync extends AsyncTask{
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
@Override
protected JSONObject doInBackground(String... params) {
try {
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+context.getPackageName()+"&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH\_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context,
R.style.DialogDark));
alertDialogBuilder.setTitle(context.getString(R.string.youAreNotUpdatedTitle));
alertDialogBuilder.setMessage(context.getString(R.string.youAreNotUpdatedMessage) + " " + latestVersion + context.getString(R.string.youAreNotUpdatedMessage1));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
context.startActivity(new Intent(Intent.ACTION\_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
dialog.cancel();
}
});
alertDialogBuilder.show();
}
}
```
but I am getting null pointer exception error
>
> FATAL EXCEPTION: AsyncTask #1
> Process: com.yabeee.yabeee, PID: 15893
> java.lang.RuntimeException: An error occured while executing
> doInBackground()
> at android.os.AsyncTask$3.done(AsyncTask.java:304)
> at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
> at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
> at java.util.concurrent.FutureTask.run(FutureTask.java:242)
> at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
> at java.lang.Thread.run(Thread.java:818)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
> 'java.lang.String org.jsoup.nodes.Element.ownText()' on a null object
> reference
> at com.yabeee.yabeee.ModelClasses.ForceUpdateAsync.doInBackground(ForceUpdateAsync.java:53)
> at com.yabeee.yabeee.ModelClasses.ForceUpdateAsync.doInBackground(ForceUpdateAsync.java:28)
> at android.os.AsyncTask$2.call(AsyncTask.java:292)
> at java.util.concurrent.FutureTask.run(FutureTask.java:237)
> at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
> at java.lang.Thread.run(Thread.java:818)
>
>
>
Please some one help me to fix this issue.<issue_comment>username_1: I used the same code and got the same error as well.
I solved this error by taking help of web developer for better understanding of google play store updated code.
use below code its working fine(code updated 10/08/2018)
public class ForceUpdateAsync extends AsyncTask {
```
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
@Override
protected JSONObject doInBackground(String... params) {
try {
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + context.getPackageName()+ "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
Log.e("latestversion","---"+latestVersion);
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
}
}
```
Upvotes: 2 <issue_comment>username_2: With updated code:
```
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + mCom.getPackageName()+ "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
```
Upvotes: 3
|
2018/03/16
| 896 | 3,506 |
<issue_start>username_0: I have installed Docker and have running some Ubuntu image with command:
```
sudo docker run ubuntu
```
I would like to create some text file on it and find it next time the same image will run. How to achieve that?
UPD.
Got problems with attaching to docker.
I have running docker
```
docker ps -a
aef01293fdc9 ubuntu "/bin/bash" 6 hours ago Up 6 hours priceless_ramanujan
```
Since it is `Up` mode, I suppose I don't need to execute command:
```
docker start priceless_ramanujan
```
So, I run command `attach`
```
docker attach priceless_ramanujan
```
And got nothing in output while command not returns.
Why I can't get to container's bash?<issue_comment>username_1: I used the same code and got the same error as well.
I solved this error by taking help of web developer for better understanding of google play store updated code.
use below code its working fine(code updated 10/08/2018)
public class ForceUpdateAsync extends AsyncTask {
```
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
@Override
protected JSONObject doInBackground(String... params) {
try {
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + context.getPackageName()+ "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
Log.e("latestversion","---"+latestVersion);
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
}
}
```
Upvotes: 2 <issue_comment>username_2: With updated code:
```
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + mCom.getPackageName()+ "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
```
Upvotes: 3
|
2018/03/16
| 607 | 2,081 |
<issue_start>username_0: As per java doc, static block is executed when the class is initialized.
Could anyone please tell me why static block is not executed when I run below code?
```
class A {
static {
System.out.println("Static Block");
}
}
public class Main {
public static void example1() {
Class class1 = A.class;
System.out.println(class1);
}
public static void example2() {
try {
Class class1 = Class.forName("ClassLoading_Interview_Example.ex1.A");
System.out.println(class1);
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
example1();
}
}
```<issue_comment>username_1: >
> A class's static initialization normally happens immediately before
> the first time one of the following events occur:
>
>
> * an instance of the class is created,
> * a static method of the class is invoked,
> * a static field of the class is assigned,
> * a non-constant static field is used, or [...]
>
>
>
You are currently not doing any of the above.
So, by replacing
```
Class class1 = A.class;
System.out.println(class1);
```
with this for example
```
A object = new A();
```
will give you your result.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Referencing `A.class` will not resulting in executing `A`'s static initializers, see [here](https://docs.oracle.com/javase/specs/jls/se9/html/jls-12.html#jls-12.4.1)
>
> Initialization of a class consists of executing its static
> initializers and the initializers for static fields (class variables)
> declared in the class.
>
>
>
And
>
> A class or interface type T will be initialized immediately before the
> first occurrence of any one of the following:
>
>
> T is a class and an instance of T is created.
>
>
> A static method declared by T is invoked.
>
>
> A static field declared by T is assigned.
>
>
> A static field declared by T is used and the field is not a constant
> variable (§4.12.4).
>
>
>
Upvotes: 2
|
2018/03/16
| 815 | 2,424 |
<issue_start>username_0: Frequently solution for this is `float`, but it will not work in my case. I tried to use flexbox, `overflow:hidden` for parent, but it didn't help either.
So I have three inline-block elements. The width of that one in the center is defined by text length in it, but others are just for drawing black line on the sides with known height. Like this:
```css
.headline {
width: 700px;
}
.headline>* {
display: inline-block;
}
.blackline {
background-color: #000;
height: 10px;
}
```
```html
blah blah blah
==============
```
Parent element width is known and constant, but that one in center is variable.
and it should look something like this:
`|---blah blah blah---|`
so that element is always in center and both have same width which takes all available space depending on the width as i can't know how many "blah" it will contain.<issue_comment>username_1: You can do with flexbox like this:
```css
.headline {
width: 500px;
display:flex;
align-items:center;
border:1px solid;
}
.blackline {
background-color: #000;
height: 10px;
flex:1;
}
```
```html
blah blah blah
==============
```
You can also simplify the markup like this:
```css
.headline {
width: 500px;
display:flex;
align-items:center;
border:1px solid;
}
.headline:before,.headline:after {
content:"";
background-color: #000;
height: 10px;
flex:1;
}
```
```html
blah blah blah
==============
```
Or like this:
```css
.headline {
width: 500px;
display:flex;
align-items:center;
justify-content:center;
border:1px solid;
background:linear-gradient(#000,#000) 0 50%/100% 10px no-repeat;
}
h1 {
background:#fff;
}
```
```html
blah blah blah
==============
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use responsive measurements to reach this, see the example below:
```css
.fullWidth{
width: 100vw;
height: 50px;
background-color: red;
}
```
```html
```
Upvotes: 0 <issue_comment>username_3: Another way to do this with fieldset and legend tag. This may not be the purpose of these tags but nothing prevents us to do things differently.
```css
div {
border-right: 1px solid #000;
border-left: 1px solid #000;
height: 20px;
}
fieldset {
border: 0px;
border-top: 1px solid #000;
}
```
```html
Blah Blah Blah
```
**Fiddle:** <https://jsfiddle.net/z364h1ar/>
Upvotes: 0
|
2018/03/16
| 387 | 1,328 |
<issue_start>username_0: Suppose i have written:
```
...
char c;
while(condition){
cin>>c;
//do stuff
...
}
...
```
If `2` characters are give in cin, the next cin will take the second character without me giving any. So, i tried this:
```
...
char c;
while(condition){
cin<
```
In this case the program will work keeping only the first input but, is there a way to check how many characters the user inputs in cin in order to print an appropriate message?
for example, if the input is `ab` it will print something like "Please type only one character".<issue_comment>username_1: Read a `std::string` and validate:
```
while(condition){
std::string s;
std::cin >> s;
if (s.length() != 1){
// oops - make sure s[0] is not taken
}
c = s[0];
// do stuff
}
```
Upvotes: 2 <issue_comment>username_2: I think what you want is `std::cin.rdbuf()->in_avail()` which will tell you how many chars are still in `std::cin` buffer. If you are going to read just 1 char, and enter 1 char, the result would be 1, because of unread `\n`. So keep this in mind when calculating.
```
#include
int main()
{
char c;
std::cin >> c;
std::cout << "cin still contains " << std::cin.rdbuf()->in\_avail() << " chars" << std::endl;
}
```
Upvotes: 1
|
2018/03/16
| 820 | 2,655 |
<issue_start>username_0: I'm having some trouble to prepare macro which would help me to pass the value to another cell if the specified cell is a part of merged cells.
[](https://i.stack.imgur.com/oqFCy.png)
As you can see, cells A1-A15 are merged, in B1 I've written =A1 in B2 I did =A2, so what I want to achieve is that whenever I assign somewhere cell which is part of merged cells(A1-A15) the 'test' value is passed so there is no difference if I write =A1 or =A15 or =A10
I would appreciate any help of advice.<issue_comment>username_1: You can detect if a Cell is part of a Merged Cell using `If Range("A1").MergeCells = True`.
Get the number of rows you have in your `MergedArea` using `Range("A" & i).MergeArea.Rows.Count`.
More explanation inside the code below.
***Code***
```
Option Explicit
Sub CheckifMergedCell()
Dim MergeRows As Long, i As Long
i = 1
While i < 100 ' 100 is just for example , change it later according to your needs
If Range("A" & i).MergeCells = True Then
MergeRows = Range("A" & i).MergeArea.Rows.Count ' number of merged cells
Else ' not merged >> single row
MergeRows = 1
End If
Range("B" & i).Resize(MergeRows, 1).Value = Range("A" & i).Value
i = i + MergeRows
Wend
End Sub
```
Upvotes: 3 <issue_comment>username_2: In B1,
```
=INDEX(A:A, MATCH("zzz", A$1:A1))
```
Fill or copy down.
[](https://i.stack.imgur.com/yluuY.png)
Upvotes: 2 <issue_comment>username_3: *what I want to achieve is that whenever I assign somewhere cell which is part of merged cells(A1-A15) the 'test' value is passed so there is no difference if I write =A1 or =A15 or =A10*
What you want to accomplish can't be done easily. You could do it with an VBA code that checks every single time you type something, **but it's not worth it.** The other answer you got here are worth it.
What you want to do is not possible because Excel works in a weird way. Let's say you have cells `A1:A15` merged. The value is ALWAYS in first cell of merged area (in this case in **A1**). So when you reference a cell inside the merged area, it will have a 0 value (a blank cell) always, unless it is the first one.
So my advice, would be:
>
> 1. Use 1 of the other answers, because both are really helpful
> 2. If you insist in using normal formulas, then instead of typing `=A1`, try with absolute references, try `=$A$1`. If you click and
> drag, that formula will work for you to complete adjacent cells to
> merged area.
> 3. I insist, use 1 of the other answers.
>
>
>
Upvotes: 0
|
2018/03/16
| 375 | 1,172 |
<issue_start>username_0: Maybe you can help on the following code please.
I have an error on the "1". I want to select all row for the previous day if I query today. The format of the date is 2018-03-16 07:22:48.377
```
SELECT object_key, audited_changes
FROM pg_audits
WHERE source_action = 'funding'
AND 'created_at' = CURDATE() - INTERVAL 1 DAY
ORDER BY created_at DESC
LIMIT 1000
```<issue_comment>username_1: If you want all records from any point yesterday, we can use `NOW()` with an appropriate range:
```
SELECT object_key, audited_changes
FROM pg_audits
WHERE
source_action = 'funding' AND
created_at >= CURRENT_DATE - 1 AND
created_at < CURRENT_DATE
ORDER BY
created_at DESC
LIMIT 1000;
```
`NOW()::date` returns the current day at midnight, so the above range targets anything on or after midnight of yesterday, but strictly earlier than midnight of today.
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> Please try it:
>
>
>
```
SELECT object_key, audited_changes
FROM pg_audits
WHERE source_action = 'funding'
AND DATE(created_at) =DATE_ADD(CURDATE(), INTERVAL -1 DAY)
ORDER BY created_at DESC
LIMIT 1000
```
Upvotes: 0
|
2018/03/16
| 904 | 3,556 |
<issue_start>username_0: I have a table which is made by `ng-repeat`. That part which doesnt get refreshed is below;
```
| | | | | | |
| --- | --- | --- | --- | --- | --- |
|
| {{activity.PlanDateTime}} / {{activity.ActivityType\_DisplayName}}
*{{activity.ActivityID}}* |
{{activity.ParentActivityDisplayName}}
*{{activity.ParentActivityID}}* | {{activity.Customer\_DisplayName}} | {{activity.ActivityStatus\_DisplayName}} |
{{activity.StatusReason}}
{{activity.StatusReasonNote}}
|
```
`$scope.activityList` is fine, it gets populated correctly. This is how I change an item in activiyList
```
$scope.UpdateActivityListItem = function (activityID, prevResponseDetail) {
var url = "/api/activity/GetActivityResponse?activityID=" + activityID;
$http({
method: 'GET',
url: url
}).then(function successCallback(result) {
var response = result.data;
if (response.Status == "SUCCESS") {
var activity = $scope.activityList.filter(activity => activity.ActivityID == activityID)[0];
var renewedAct = response.Detail[0];
activity = renewedAct;
$scope.$apply();
console.log("yenilenmiş aktivite:" +$scope.activityList)
$('#modalActivityDetail').modal('hide');
console.log(JSON.stringify($scope.activityList));
$scope.addSpinnerClass(spinner);
}
else {
console.log("fail");
}
},
function errorCallback(result) {
console.log("error");
}
);
};
```
I confirmed in debug that item gets "updated" nicely but in screen it stays same.
I thought this was kind of a problem whicj $scope.$apply() can solve but adding it (as shown in code piece above) caused this problem
```
Error: error:inprog
Action Already In Progress
$digest already in progress
```
What else can I do?
PS: This is written in Angular JS 1.0<issue_comment>username_1: Before calling $apply please check weather the digest cycle is busy or not.
```
if(!$scope.$$phase) {
//$digest or $apply
}
```
---------EDIT------
A new, powerful method has been added to any $scope: $evalAsync. Basically, it will execute its callback within the current digest cycle if one is occurring, otherwise a new digest cycle will start executing the callback.
Try this:
In these cases and all the others where you had a !$scope.$$phase, be sure to use `$scope.$evalAsync( callback )` do all related changes in callback.
Upvotes: 0 <issue_comment>username_2: check this, You are filtering activityList and updating a filtered array (result) first element not activityList array.
```
var renewedAct = response.Detail[0];
for (let index = 0; index < $scope.activityList.length; index++) {
const activity = $scope.activityList[index];
if (activity.ActivityID == activityID) {
$scope.activityList[index] = renewedAct;
break;
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can do that even without looping again using `splice` **with a single line**
Here is the code,
```
var activity = $scope.activityList.filter(activity => activity.ActivityID == activityID)[0];
var index = $scope.activityList.indexOf(activity);
var renewedAct = response.Detail[0];
activity = renewedAct;
$scope.activityList.splice(index, 1, activity)
```
**Note:** The above line removes that element at that place and adds your new element.
Upvotes: 1
|
2018/03/16
| 505 | 2,183 |
<issue_start>username_0: When I open any dialog in my Winforms application then Windows 10 behaves oddly in these ways:
1. ALT-TAB no longer displays the list of windows
2. I cannot switch to hidden applications using taskbar icons - if I select a taskbar icon of a window that is not currently visible (even if it is not hidden by the winforms app) the icon just flashes and then stays highlighted, but is not brought to the foreground. I can use other applications that are visible. As soon as I close the dialog form the other I can use the windows of other applications correctly
3. If I switch to the application window that is behind the winforms application by clicking on it, I cannot go back to the winforms app either by ALT-TAB or by clicking on the taskbar icon. I can get back to it by minimizing the other application
I'm opening the dialogs with
```
dialogFormName.ShowDialog(this);
```
TopMost is set false on all forms and is not set in the code.
I've read about 50 related articles and the only problems seem to be either TopMost is set or ShowDialog is not called with the parent form. I'm not a regular Winforms developer so I'm probably doing something stupid. This is driving me crazy, so I'd really appreciate any help!
Edit: The same issues occur with MessageBox.Show(this, "test"). The issue does not occur with a newly created app just with a single button calling MessageBox.Show(this, "test"). The problem application uses EntityFramework but no other packages and the problem existed before I added EF.<issue_comment>username_1: `Form.ShowDialog()` blocks the parent form until it's closed.
Use `Show()` to display the form separately without blocking its parent.
Upvotes: 0 <issue_comment>username_2: After trying different scenarios I eventually found the issue. In my case I was calling ShowDialog() after a user clicks an item on a ContextMenu. The blocking of ALT-TAB was caused by the following code that attached the ContextMenu to the ListView that the menu was contextually for:
```
lstList.ContextMenu = myContextMenu;
```
As soon as I removed that association, the ShowDialog no longer blocked ALT-TAB.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 667 | 2,251 |
<issue_start>username_0: ```
public static int averageInArrayList(ArrayList arrayList) {
Integer sum = 0;
if(!ArrayList.isEmpty()) {
for (Integer sum : ArrayList) {
sum += ArrayList;
}
double total = sum.doubleValue() / ArrayList.size();
}
return total;
}
```
Hi I'm having trouble returning the average of all the elements in the Arraylist
(also not quite sure if my first line is correct)<issue_comment>username_1: You have to declare `double total` outside of the condition scope otherwise it won't be available. Put it one line below `sum`. Also you have to change your return type to `double` since you are no longer returning an `int`.
Upvotes: 1 <issue_comment>username_2: ```
private double calculateAverage(List marks) {
Integer sum = 0;
if(!marks.isEmpty()) {
for (Integer mark : marks) {
sum += mark;
}
return sum.doubleValue() / marks.size();
}
return sum;
}
```
Upvotes: 0 <issue_comment>username_3: **Java 8**
```
public static double calculateAverage(List list) {
return list
.stream()
.mapToInt(number -> number)
.average().getAsDouble();
}
```
Upvotes: 2 <issue_comment>username_4: Why don't you use the lambda way?
```
List testList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
double intAverage = testList.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
System.out.println(intAverage);
```
As a method:
```
public static double averageList(List testList) {
return testList.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_5: Just change three lines and you'll be fine.
```
public static double averageInArrayList(List ArrayList) { //line 1
Integer sum = 0;
if(!ArrayList.isEmpty()) {
for (Integer element: ArrayList) { //line 2
sum += element; //line 3
}
double total = sum.doubleValue() / ArrayList.size();
}
return total;
}
```
Upvotes: -1 <issue_comment>username_6: Simply change your return type to Double (the average is not an integer) and change your stream into DoubleStream for effective computing:
```
public static double averageInArrayList(ArrayList arrayList) {
return arrayList
.stream()
.mapToDouble(Integer::doubleValue)
.average()
.orElse(0.0D);
}
```
Upvotes: 1
|
2018/03/16
| 665 | 2,308 |
<issue_start>username_0: I am starting a business and I would like to offer Paypal as a payment option, but for my business it is essential to be able to block an amount of money, just like a car rental or a hotel does on a credit card. Would it be possible to block an amount from my users PayPal account and release it or book it for good later?
My business is of course an online service, and I want to do this pragmatically in a Spring based application.<issue_comment>username_1: You have to declare `double total` outside of the condition scope otherwise it won't be available. Put it one line below `sum`. Also you have to change your return type to `double` since you are no longer returning an `int`.
Upvotes: 1 <issue_comment>username_2: ```
private double calculateAverage(List marks) {
Integer sum = 0;
if(!marks.isEmpty()) {
for (Integer mark : marks) {
sum += mark;
}
return sum.doubleValue() / marks.size();
}
return sum;
}
```
Upvotes: 0 <issue_comment>username_3: **Java 8**
```
public static double calculateAverage(List list) {
return list
.stream()
.mapToInt(number -> number)
.average().getAsDouble();
}
```
Upvotes: 2 <issue_comment>username_4: Why don't you use the lambda way?
```
List testList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
double intAverage = testList.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
System.out.println(intAverage);
```
As a method:
```
public static double averageList(List testList) {
return testList.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_5: Just change three lines and you'll be fine.
```
public static double averageInArrayList(List ArrayList) { //line 1
Integer sum = 0;
if(!ArrayList.isEmpty()) {
for (Integer element: ArrayList) { //line 2
sum += element; //line 3
}
double total = sum.doubleValue() / ArrayList.size();
}
return total;
}
```
Upvotes: -1 <issue_comment>username_6: Simply change your return type to Double (the average is not an integer) and change your stream into DoubleStream for effective computing:
```
public static double averageInArrayList(ArrayList arrayList) {
return arrayList
.stream()
.mapToDouble(Integer::doubleValue)
.average()
.orElse(0.0D);
}
```
Upvotes: 1
|