text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: how to make Angular service only module scooped if its not a lazy loaded module So i m trying to make a module have a service which is module scoped. I have implemented a shared module which i would like to have it with a utils service only singleton to its components. other modules can only have instances of the utils service.
when i import this shared module in the app module, than somehow the utils service becomes singleton eventhough its not provided inside of the app module.
what is the logic behind of it ? And how can i achieve this when its not a route module which is lazy loaded ?
@NgModule({
declarations: [FilterComponent],
imports: [
],
exports: [
FilterComponent
],
providers: [DataService]
})
export class SharedModule {
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
SharedModule,
CommonModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
@Injectable({
providedIn: SharedModule
})
export class UtilsService {
constructor() {
console.log("created")
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75422471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do I need JDK to work with Eclipse Helios and Tomcat 7.0.33? I want to develop dynamic web applications.
For this I am using Eclipse Helios and Tomcat 7.0.33. I have the JRE installed on my machine and I have provided the location of the JRE in the JAVA_HOME path.
But when I am running any servlet, I get the error:
" HTTP Status 404 " -- " The requested resource is not available
"
Do I need a JDK in place of the JRE (meaning I have to set the path of the JDK in place of the JRE)? Or could there be another other reason why this error is happening?
Looking for Help!
A: If your servlets are already compiled then JRE will serve the purpose,
But they are compiled then you will JDK and other libraries( like servlet-api.jar, etc.) to compile you servlets.
In short JDK is for development where you want to develop something using Java.
And JRE is used when you already have compiled classes and you just want to run it.
You might want to refer to this :
What is the difference between JDK and JRE?
A: In theory, compiling with Eclipse's incremental compiler is sufficient. Running the application server with a JRE should be fine as well. I suppose your error is somewhere else. Anyway, I'd strongly recommend installing a JDK for developing a Java application. It comes with some handy tools and many 3rd party tools (Maven, e.g.) also require a real JDK compiler and can't work with Eclipse's built in compiler.
A: I had the same problem. The JDK was not the issue. After you compile your servlet you have to restart your tomcat server so it can load your class files before you try to access it through the web browser. No more 404 errors after that, servlets are running fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13601478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating mapkit's showsUserLocation pin ripple animation Has any one successfully created user location pin that has a ripple like effect that 4.x (or higher) mapkit gives when we use mkMakkit.showUserLoaction = YES;
If any one has done it please guide me how to do it or past sample code that does that effect.
The user location in the mapkit is read-only property. Has anyone able to move the pin from user actual location. That is in my senario when the user location is not available for cases like iTouch user can select his location, I don't want to show user at Infinite Loop,CA but the location he prefers to choose.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3869005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to parse nested function calls using Pyparsing? I'm developing a css parser but cannot figure out how to parse nested function calls like alpha(rgb(1, 2, 3), 0.5).
Here is my code:
# -*- coding: utf-8 -*-
from pyparsing import * #, Word, alphas, OneOrMore, countedArray, And, srange, hexnums, Combine, cStyleComment
from string import punctuation
from app.utils.file_manager import loadCSSFile, writeFile
from pyparsing import OneOrMore, Optional, Word, quotedString, delimitedList, Suppress
from __builtin__ import len
# divide tudo por espaços, tabulações e novas linhas
words = ZeroOrMore(cStyleComment | Word(printables))
digit = '0123456789'; underscore = '_'; hyphen = '-'
hexDigit = 'abcdefABCDEF' + digit
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
az_AZ_underscore = underscore + letter;
az_AZ_09_underscore = az_AZ_underscore + digit;
az_AZ_hyphen = hyphen + letter;
az_AZ_09_hiphen = az_AZ_hyphen + digit;
LPAR = Suppress('('); RPAR = Suppress(')')
# identifiers
identifier = Combine(Word(az_AZ_underscore) + Optional(Word(az_AZ_09_underscore)))
# identifiers
identifier_reserved = Combine(Word(az_AZ_hyphen) + Optional(Word(az_AZ_09_hiphen)))
# numbers
hexadecimal = Word(hexnums, min=1)
integer = Word(digit, min=1)
decimal = Combine('.' + integer | integer + Optional('.' + integer))
# value values
color_hex = Combine('#' + hexadecimal )
at_identifier = Combine('@' + identifier)
arg = at_identifier | color_hex | decimal | quotedString
function_call = identifier + LPAR + Optional(delimitedList(arg)) + RPAR
value = Group(color_hex | at_identifier | function_call)
print(value.parseString('a(b())'))
I whould like to do something like arg = at_identifier | color_hex | decimal | quotedString | function_call but it's not possible because the variable is function_call is not declared yet.
How could I parse nested function calls using Pyparsing?
A: You are really very close. To define a recursive grammar like this, you need to forward-declare the nested expression.
As you have already seen, this:
arg = at_identifier | color_hex | decimal | quotedString
function_call = identifier + LPAR + Optional(delimitedList(arg)) + RPAR
only parses function calls with args that are not themselves function calls.
To define this recursively, first define an empty placeholder expression, using Forward():
function_call = Forward()
We don't know yet what will go into this expression, but we do know that it will be a valid argument type. Since it has been declared now we can use it:
arg = at_identifier | color_hex | decimal | quotedString | function_call
Now that we have arg defined, we can define what will go into a function_call. Instead of using ordinary Python assignment using '=', we have to use an operator that will modify the function_call instead of redefining it. Pyparsing allows you to use <<= or << operators (the first is preferred):
function_call <<= identifier + LPAR + Optional(delimitedList(arg)) + RPAR
This is now sufficient to parse your given sample string, but you've lost visibility to the actual nesting structure. If you group your function call like this:
function_call <<= Group(identifier + LPAR + Group(Optional(delimitedList(arg))) + RPAR)
you will always get a predictable structure from a function call (a named and the parsed args), and the function call itself will be grouped.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23331004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Gson not loading in properly - Null object reference I'm trying to load in a local file into my Android application using Gson. Loading in the file works just fine. Here is what the Json looks like:
{"heroes" : [
{
"hero": {
"name": "Hanzo",
"role": "Offense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "dragons"
},
"strongAgainst": [
"Bastion",
"Mercy"
],
"weakAgainst": [
"Genji",
"Tracer"
]
},
"hero": {
"name": "Torbjorn",
"role": "Defense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "lava bastard"
},
"strongAgainst": [
"Lucio",
"Mercy"
],
"weak_against": [
"Widowmaker",
"Junkrat"
]
}
}
]}
I have created 3 POJOs with getters and setters like so:
public final class Heroes {
private List<Hero> hero;
}
public class Hero {
private HeroAttr hero;
}
public class HeroAttr {
private String name;
private String role;
private Abilities abilities;
private List<String> strongAgainst;
private List<String> weakAgainst;
}
public class Abilities {
private String primary;
private String secondary;
private String ultimate;
}
And I load in using Gson like so:
Gson gson = new GsonBuilder().create();
Heroes h = gson.fromJson(byteArrayOutputStream.toString(), Heroes.class);
And whenever I try to get the size or print something from h it gives me a null object reference and I am unable to get anything from the arraylist.
I've even tried making the json file only an array and using
Hero[] h = gson.fromJson(byteArrayOutputStream.toString(), Hero[].class);
but I get the same issue -- null object reference.
Any ideas? Thanks.
A: UPDATED
You got a problem in your JSON:
{
"hero": {
"name": "Hanzo",
"role": "Offense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "dragons"
},
"strongAgainst": [
"Bastion",
"Mercy"
],
"weakAgainst": [
"Genji",
"Tracer"
]
},
"hero": {
"name": "Torbjorn",
"role": "Defense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "lava bastard"
},
"strongAgainst": [
"Lucio",
"Mercy"
],
"weak_against": [
"Widowmaker",
"Junkrat"
]
}
}
This is not sane. An object defining hero property twice.
The full version should be:
{
"heroes" : [
{
"name": "Hanzo",
"role": "Offense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "dragons"
},
"strongAgainst": [
"Bastion",
"Mercy"
],
"weakAgainst": [
"Genji",
"Tracer"
]
},
{
"name": "Torbjorn",
"role": "Defense",
"abilities": {
"primary": "left click",
"secondary": "right click",
"ultimate": "lava bastard"
},
"strongAgainst": [
"Lucio",
"Mercy"
],
"weak_against": [
"Widowmaker",
"Junkrat"
]
}
]
}
Full code (back to three POJOs):
import com.google.gson.Gson;
import java.util.List;
public class Test {
String json = "{\n" +
" \"heroes\" : [\n" +
" {\n" +
" \"name\": \"Hanzo\",\n" +
" \"role\": \"Offense\",\n" +
" \"abilities\": {\n" +
" \"primary\": \"left click\",\n" +
" \"secondary\": \"right click\",\n" +
" \"ultimate\": \"dragons\"\n" +
" },\n" +
" \"strongAgainst\": [\n" +
" \"Bastion\",\n" +
" \"Mercy\"\n" +
" ],\n" +
" \"weakAgainst\": [\n" +
" \"Genji\",\n" +
" \"Tracer\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"Torbjorn\",\n" +
" \"role\": \"Defense\",\n" +
" \"abilities\": {\n" +
" \"primary\": \"left click\",\n" +
" \"secondary\": \"right click\",\n" +
" \"ultimate\": \"lava bastard\"\n" +
" },\n" +
" \"strongAgainst\": [\n" +
" \"Lucio\",\n" +
" \"Mercy\"\n" +
" ],\n" +
" \"weak_against\": [\n" +
" \"Widowmaker\",\n" +
" \"Junkrat\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
static class Heroes {
public List<Hero> heroes;
}
static class Hero {
public String name;
public String role;
public Abilities abilities;
public List<String> strongAgainst;
public List<String> weakAgainst;
}
static class Abilities {
public String primary;
public String secondary;
public String ultimate;
}
void go() {
Gson gson = new Gson();
Heroes h = gson.fromJson(json, Heroes.class);
System.out.println(h.heroes.size());
System.out.println(h.heroes.get(0).name);
}
public static void main(String[] args) {
new Test().go();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37619895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to delete an existing embed in DiscordJS (v12) I'm working on a small private Discord bot (mainly for learning)
I've been working on a feature where the bot sends a message, the user sends a response and the bot will delete the initial embed and follow up with another embed. (creating a chain of embedded messages to collect user input and build a final result from it)
Thus far this is what my code consists of
const wait = 30000;
let count;
const embed = new Discord.MessageEmbed()
.setColor('#9EFF9A')
.setTitle('Question?')
.setDescription('');
message.channel.send(embed);
message.channel.awaitMessages(m => m.author.id == message.author.id,
{ max: 1, time: `${wait}` }).then(collected => {
message.delete(embed);
count = collected.first().content;
console.log(count);
}).catch(() => {
message.delete(embed);
return message.reply('No reply after ' + `${wait / 1000}` + ' seconds, operation canceled.').then(m => {
m.delete({ timeout: 15000 });
});
});
I have tried various iterations of message.delete(); with no useful results, the bot usually ends up deleting the commanding message sent by the user to start the embed chain.
I got a suggestion from a friend that I also ended up seeing online a few times which was the following:
.then(() => {
message.delete()
})
I can't come up with any way to implement this into my current code.
Is there something I am misunderstanding? I am very new to DiscordJS and Javascript and my friend did mention that .then() statements can get pretty tricky
I appreciate any help I can get!
A: Your code is very close to achieving what you want, except you are attempting to delete the Embed object that you created instead of the Message object of the embed. Here's a slight tweak that will achieve what you need:
const wait = 30000;
let count;
const embed = new Discord.MessageEmbed()
.setColor('#9EFF9A')
.setTitle('Question?')
.setDescription('');
message.channel.send(embed).then(embedMessage => {
embedMessage.channel.awaitMessages(m => m.author.id == message.author.id,
{ max: 1, time: wait }).then(collected => {
embedMessage.delete();
count = collected.first().content;
console.log(count);
}).catch(() => {
embedMessage.delete();
return message.reply('No reply after ' + (wait / 1000) + ' seconds, operation canceled.').then(m => {
m.delete({ timeout: 15000 });
});
});
})
The secret here is using .then() on the method that sends the embed. This allows you to obtain the actual Message object of the embed that was sent, which you can then interact with. Now that you have the Message object for your embed, you can directly interact with the message using its methods, such as delete() and edit().
A: .then(() => {
message.delete()
})
Is not working because you never passed in the message as a parameter, therefor your embed does not exist in the context of .then()
You can try using .then() or await to delete a send message.
then Method
// const embed = ...
message.channel.send(embed).then(msg => {
msg.delete();
});
Await Method
// Make sure you're in an async function
//const embed = ...
const msg = await message.channel.send(msg);
msg.delete();
A: I am not to familiar with discordjs but from what I understand you create a message with the bot under the variable "message" which has the properties seen here:
https://discord.js.org/#/docs/main/master/class/Message
Then you use that message to send an embed to the message's channel. The embed ask's a question and you then await for ensuing messages. You then want to take the first response and put it into the count variable. Then you want to delete the original embed. If this is all true I would suggest deleting the original message that houses the embed itself like so:
message.channel.awaitMessages(m => m.author.id == message.author.id,
{ max: 1, time: `${wait}` }).then(collected => {
message.delete();
count = collected.first().content;
console.log(count);
})
Or try this but I don't think this method will work:
message.channel.awaitMessages(m => m.author.id == message.author.id,
{ max: 1, time: `${wait}` }).then(collected => {
embed.delete();
count = collected.first().content;
console.log(count);
})
I would check out these two pages of documentation:
https://discord.js.org/#/docs/main/master/class/Message?scrollTo=delete
https://discord.js.org/#/docs/main/master/class/MessageEmbed
Welcome to Stack Overflow tell me if one of these worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64791771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache: Can't open .php files I want to start learning PHP, so I installed Apache2, MySQL and PHP5 on my Ubuntu 10.10 today. For some reason, when I try to open a file other than index.html from the default directory /var/www/, I either get a 404 error or I get a prompt to download the php file. I googl'd all over and I can't find a solution.
When I do http://localhost/index.html, it works, and displays whatever I write in index.html. When I change /index.html to /test.php, I get an error saying "The requested URL /test.php was not found on this server".
When I try /var/www/index.html or file:///var/www/index.html, again, index.html appears although it appears differently. When opened with http://localhost/index.html I only get "It works!", but with /var/www/index.html I get "It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet."
And then when I change /var/www/index.html to /test.php, I get a prompt to download test.php.
In my .conf files, the default directory is set to /var/www/, so this is very weird.
Edit:
Did some checking, and it seems that when I run http://localhost it's set to a directory in the httpd directory. I tried putting my test.php file there, and still I'm getting 404. But when I write the full path, again, I get a download prompt.
This problem is really confusing... thanks to all helpers.
A: Check to see if PHP has been enabled in the Apache httpd.conf file. See here for further details: http://www.devarticles.com/c/a/Apache/Using-Apache-and-PHP-on-Mac-OS-X/
A: Ok.. seems that I found the solution myself. For some weird reason, I have like 4 different localhost default folders. I had to search manually through each folder containing index.html and move test.php there. Eventually, I found an obscure folder somewhere in the /usr/ folder, moved test.php to there, and it worked. Apparently I have like 4 different versions for each .conf file, and each one states a different thing. Only one of them works.
Phew. What a relief.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4297513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update profile picture for existing model instance? I'm trying to update a user's profile photo after they've already created their account. I'm using an abstract user model connected to a model called Person. For additional context, I have my application connected to AWS to deploy to Heroku.
I have a form, model, url and view set up but I'm sure I'm missing some piece to the puzzle.
<form action="{% url 'update-photo' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table class="table-form">
{{ form|crispy }}
</table>
<input type="submit" class="btn btn-lg custom-bg">
<br><br>
</form>
class User(AbstractUser):
is_active = models.BooleanField(default=False)
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
upload = models.FileField(default='core/static/images/default_avatar.png')
class UpdatePhotoForm(forms.ModelForm):
class Meta:
model = Person
fields = ('upload',)
@login_required
def update_photo(request):
person = Person.objects.get(user=request.user)
from core.forms import UpdatePhotoForm
if request.method == "POST":
form = UpdatePhotoForm(data=request.POST, instance=request.user.person)
if form.is_valid():
person = form.save(commit=False)
person.save()
return redirect('profile')
else:
form = UpdatePhotoForm()
return render(request, 'core/edit_profile.html', {'form': form})
path('update_photo/', core_views.update_photo, name='update-photo'),
The form submits without any error but does not actually update the user's photo. I can change the photo in the admin site but not via the form. Any help would be greatly appreciated!
A: You will have to fetch file field from request Object with following code:
form = UpdatePhotoForm(data=request.POST, files=request.FILES, instance=request.user.person)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57454660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: node.js redis smembers synchronously I wonder if it's possible to implement synchronous retrieval of smembers of redis with node_redis.
_.each(seeds, function(subseed, key, list){
client.smembers(subseed, function (err, replies) {
retrieved = retrieved.concat(replies)
})
})
client.quit();
console.log("start")
console.log(retrieved.length)
OUTPUT:
start
0
10
So it looks like I need somehow to get to the point when smembers finishes it's run, ot alternatively to run smembers in synchronous mode.
How can I solve this problem?
A: Why do you want to make it synchronous?
If you want to do something after members, just do it in callback function.
var callback=function(res){
retrived=retrieved.concat(res);
//continue do other things
};
client.smembers("offer", function (err, replies) {
if(!err){
callback(replies);
}
})
If you want to do something after a loop,you can try _.after of underscore.js,for example:
var times=10;
var arrayOfReplies=[]; //store all replies
var callback=function(){
//do something with arrayOfReplies
}
var afterAll = _.after(times,callback); //afterAll's callback is a function which will be run after be called 10 times
for(var i=0;i<10;i++){
client.smembers("offer", function (err, replies) {
if(!err){
arrayOfReplies=arrayOfReplies.concat(replies);
afterAll();
}
})
}
see more:http://underscorejs.org/#after
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25580690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Recursive python script found = 0
def new(string):
global found
if found > len(string):
return 0
fish = string.find('x',found,len(string))
found = fish + 1
return new(string) + 1
text = 'onxonxoinxoinoxn'
final_text = text + 'x'
print new(final_text)
So I'm new to recursion and i know there is a much easier way to do this but can someone explain how to fix this.this is basically a recursive function to find the total number of times a letter 'x' can be found in the variable 'text'.
This is my error:
4
7
11
16
18
0
4
7
Traceback (most recent call last):
11
16
File "/Users/Charana/Documents/Projects/untitled/Main.py", line 18,
in
new(final_text)
RuntimeError: maximum recursion depth exceeded
so it works but it continues to loop.how do i make it stop
thankyou in advance
A: found > len(string)
This condition will never be true, because str.find will always return a result < len(s).
The correct return value to check for when there was no result is -1. But you need to be careful with the increment, since that will change the invalid result -1 to 0 continuing the loop. So you should reorder your logic a bit:
def new(string):
global found
fish = string.find('x',found,len(string))
if fish < 0:
return 0
found = fish + 1
return new(string) + 1
Note that using global variables for such a function, especially for recursive functions, is a bad idea. You don’t have full control over it, and instead, you also need to make sure that you reset its value when you call the function. Instead, you should keep all the information inside, and pass it around to the recursive calls if necessary. You could change your function like this:
def new (string, found = 0):
fish = string.find('x', found)
if fish < 0:
return 0
return new(string, fish + 1) + 1
This uses default parameter values to make sure that found starts with 0. And for the recursive call, it just passes the new found value, so the next function can start there.
Finally note, that you should try to use descriptive names for your functions and variables. The function is supposed to count the number of occurrences of 'x', so maybe count_x would be better. Also, the variable found in that context conveys a meaning that it contains the number of occurrences of x that you have already found; but instead, it’s the start offset from which to continue the search; and fish is just bad, as it’s just the index of the next 'x':
def count_x (string, offset = 0):
index = string.find('x', offset)
if index < 0:
return 0
return count_x(string, index + 1) + 1
Finally, just in case you don’t know, there is also a built-in function str.count which does the same thing :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32391740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Pandas pivot table: Aggregate function by count of a particular string I am trying to analyse a DataFrame which contains the Date as the index, and Name and Message as columns.
df.head() returns:
Name Message
Date
2020-01-01 Tom image omitted
2020-01-01 Michael image omitted
2020-01-02 James image Happy new year you wonderfully awfully people...
2020-01-02 James I was waiting for you image
2020-01-02 James QB whisperer image
This is the pivot table I was trying to call off the initial df, which the aggfunc being the count of the existence of a word (eg. image)
df_s = df.pivot_table(values='Message',index='Date',columns='Name',aggfunc=(lambda x: x.value_counts()['image']))
Which ideally would show, as an example:
Name Tom Michael James
Date
2020-01-01 1 1 0
2020-01-02 0 0 3
For instance, I've done another df.pivot_table using
df_m = df.pivot_table(values='Message',index='Date',columns='Name',aggfunc=lambda x: len(x.unique()))
Which aggregates based off the number of messages in a day and this returns the table fine.
Thanks in advance
A: Use Series.str.count for number of matched values to new column added to DataFrame by DataFrame.assign and then pivoting with sum:
df_m = (df.reset_index()
.assign(count= df['Message'].str.count('image'))
.pivot_table(index='Date',
columns='Name',
values='count' ,
aggfunc='sum',
fill_value=0))
print (df_m)
Name James Michael Tom
Date
2020-01-01 0 1 1
2020-01-02 3 0 0
A: This is for the fun of it, and an alternative to the same answer. It is just a play on the different options Pandas provides :
#or df1.groupby(['Date','Name']) if the index has a name
res = (df1.groupby([df1.index,df1.Name])
.Message.agg(','.join)
.str.count('image')
.unstack(fill_value=0)
)
res
Name James Michael Tom
Date
2020-01-01 0 1 1
2020-01-02 3 0 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61574046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why it's not possible to reach nested type, declared in interface, through inheriting type in C#? Let's say we have a situation like this:
// Declare `Nested` struct inside class and interface
class Base {
public struct Nested {}
}
interface IBase {
public struct Nested {}
}
// Inherit them
class ThroughClass: Base {}
class ThroughInterface: IBase {}
// Try reaching `Nested` class through above types
class Test {
ThroughClass.Nested c; // OK
ThroughInterface.Nested i; // Error CS0426: The type name 'Nested' does not exist in the type 'ThroughInterface'
}
Why it's not possible to reach Nested here using ThroughInterface? Is this a compiler bug, or design choice (I can't find any documentation related to that)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65126739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery '.each' and attaching '.click' event I am not a programer but I enjoy building prototypes. All of my experience comes from actionScript2.
Here is my question. To simplify my code I would like to figure out how to attach '.click' events to div's that are already existing in the HTML body.
<body>
<div id="dog-selected">dog</div>
<div id="cat-selected">cat</div>
<div id="mouse-selected">mouse</div>
<div class="dog"><img></div>
<div class="cat"><img></div>
<div class="mouse"><img></div>
</body>
My (failed) strategy was:
1) make an array of objects:
var props = {
"dog": "false",
"cat": "true",
"mouse": "false"
};
2) iterate through the array with '.each' and augment each existing div with a '.click' event. Lastly, construct a local variable.
here is a prototype:
$.each(props, function(key, value) {
$('#'+key+'-selected').click(function(){
var key = value;
});
});
A: No need to use .each. click already binds to all div occurrences.
$('div').click(function(e) {
..
});
See Demo
Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.
A: One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:
<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>
<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>
JS:
$( ".selected" ).each(function(index) {
$(this).on("click", function(){
// For the boolean value
var boolKey = $(this).data('selected');
// For the mammal value
var mammalKey = $(this).attr('id');
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18966222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
} |
Q: Spread function in R with multiple fields which constitute the key Im working to transform my table in this way so i can join it on another table. Here is a sample of what my initial table looks like:
df1 <- data.frame(ID = c(1,1,1,2,2,2,3,3,3),
date=c('2021-11-01', '2021-11-01', '2021-11-02','2021-11-01',
'2021-11-01', '2021-11-02','2021-11-01', '2021-11-01', '2021-11-02'
),
event_name = c('a', 'a', 'c', 'a', 'b', 'b','a', 'b', 'c'),
Time_duration = c(1, 3, 5, 9, 2, 4, 1, 6, 8))
And this is an example of how I'd like the data to look after spreading it:
df2 <- data.frame(ID = c(1,1, 2,2, 3,3),
date=c('2021-11-01', '2021-11-02',
'2021-11-01', '2021-11-02',
'2021-11-01', '2021-11-02'
),
event_A_duration_sum = c(4, 0,
9, 0,
1,0),
event_B_duration = c(0, 0,
2, 4,
6,0),
event_C_duration = c(0, 5,
0, 0,
0,8))
In my final table, I need to have the data grouped by (ID, Date); a unique identified for my final table would be both the ID and date. Each ID and date can have multiple events of the same type, for instance.
I hope this makes sense. Should I concatenate my identifiers and then split them back, after? Or is there a better way to do this using DPLYR?
Cheers, appreciate any help.
A: library(data.table)
dcast(data.table(df1),
ID + date ~ event_name,value.var = 'Time_duration',
fun.aggregate = sum)
Key: <ID, date>
ID date a b c
<num> <char> <num> <num> <num>
1: 1 2021-11-01 4 0 0
2: 1 2021-11-02 0 0 5
3: 2 2021-11-01 9 2 0
4: 2 2021-11-02 0 4 0
5: 3 2021-11-01 1 6 0
6: 3 2021-11-02 0 0 8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70057192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: exit() doesn't work anymore (Python 3.10? New Pycharm version? Windows 11?) I used to close the console automatically when there was an error with:
exit()
However, I reinstalled everything on my new laptop (worth noting it's windows 11 maybe ?), exit() doesn't work anymore and returns :
To exit the PyDev Console, terminate the console within IDE.
Is it because I have a newer version of PyCharm (currently using 2021.3.1 community edition on my new laptop), Python 3.10.1 instead of Python 3.9, or Windows 11 instead of Windows 10 ?
I can use:
import sys
sys.exit()
in the meantime.
But it's longer and makes me import sys when I used to not have to.
Anyone knows what's happening?
Thank you very much!
EDIT : ON ANOTHER IDE (same laptop) exit() WORKS. I therefore assume it's a PyCharm related problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70745571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: oracle sql - missing dates from range I've created the following script ...
SELECT
gr.RESERVATION_NO,
gr.TITLE,
gr.CATNR,
gl.DUEDATE,
gr.CRE_USR,
gl.QTY,
gl.WORK_CENTER_NO,
gl.TEC_CRITERIA,
gr.RESERVE_QTY,
gl.PLANT,
studate.dt
FROM GPS_RESERVATION gr,
(Select first_date + Level-1 dt
From
(
Select trunc(sysdate) first_date,
trunc(sysdate)+60 last_date
from dual
)
Connect By Level <= (last_date - first_date) +1 ) studate
INNER JOIN GPS_RESERVATION_LOAD gl
ON gl.work_center_no = 'ALIN'
AND gl.duedate = studate.dt
AND gl.plant = 'W'
WHERE gr.RESERVATION_NO = gl.RESERVATION_NO
AND gr.ACTIVE_FLAG = 'Y'
AND gr.reservation_no = '176601'
ORDER BY
gl.DUEDATE
I expected to see ALL DATES from sysdate to sysdate+60 but, I only get dates where duedate exists.
i.e.
I get...
I expected...
What am I doing wrong please ?
Thanks for your help.
A: You're mixing older Oracle join syntax with newer ANSI join syntax which is a bit confusing, and might trip up the optimiser; but the main problem is that you have an inner join between your generated date list and your gl table; and you then also have a join condition in the where clause which keeps it as an inner join even if you change the join type.
Without the table structures or any data, I think you want:
...
FROM (
Select first_date + Level-1 dt
From
(
Select trunc(sysdate) first_date,
trunc(sysdate)+60 last_date
from dual
)
Connect By Level <= (last_date - first_date) +1
) studate
CROSS JOIN GPS_RESERVATION gr
LEFT OUTER JOIN GPS_RESERVATION_LOAD gl
ON gl.work_center_no = 'ALIN'
AND gl.duedate = studate.dt
AND gl.plant = 'W'
AND gl.RESERVATION_NO = gr.RESERVATION_NO
WHERE gr.ACTIVE_FLAG = 'Y'
AND gr.reservation_no = '176601'
ORDER BY
gl.DUEDATE
The cross-join gives you the cartesian product of the generated dates and the matching records in gr; so if your gr filter finds 5 rows, you'll have 300 results from that join. The left outer join then looks for any matching rows in gl, with all the filter/join conditions related to gl within that on clause.
You should look at the execution plans for your query and this one, firstly to see the difference, but more importantly to check it is joining and filtering as you expect and in a sensible and cost-effective way. And check the results are correct, of course... You might also want to look at a version that uses a left outer join but keeps your original where clause, and see that that makes it go back to an inner join.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26614897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I build my gradle project using the Dockerfile I'm reading about dockerization of Spring Boot applications and all (or almost all) tutorials are based on some simple Dockerfile like
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
It usually work (however you may need to change some build target paths) but as far as I understand it requires us to build the application jar before the docker build command will be run.
I'm actually working with Gradle but for the Maven, I guess, it looks the same.
My question is: is it good convention?
If I'll download some repostitory and run docker build, regardless having proper Dockerfile, it will fail because there is no target/*.jar file (at least if someone did not commit the /build directory :P).
Should we then include some ./gradlew build commands in the Dockerfile?
A: https://github.com/palantir/gradle-docker
you should use this project
or
jar_path=$(find . |grep $APP_NAME|grep jar|grep -v original|grep -v repository|grep -v templates)
mv $jar_path ./app.jar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73484983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PluginManager::get was unable to fetch or create an instance for getObjectManager So my problem is to use Doctrine 2 with Zend Framework 2. I installed Doctrine correctly and when I tried to use it in the controller I get this error :
C:\wamp2\www\zf2\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:518
and this :
Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for getObjectManager
This is my controller :
class BlogController extends AbstractActionController
{
public function blogAction()
{
$article = $this->getObjectManager()->getRepository('\Application\Entity\Article')->findAll();
return new ViewModel(array('article' => $article));
}
}
This is my view:
<?php if (isset($article)) : ?>
<?php foreach($article as $articles): ?>
<div class="col-lg-12 text-center">
<img class="img-responsive img-border img-full" src="" alt="">
<h2><?php echo $articles->getTitle(); ?>
<br>
<small><?php echo $articles->getDate(); ?></small>
</h2>
<p><?php echo $articles->getContent(); ?></p>
<a href="<?php echo $this->url('article') ?>" class="btn btn-default btn-lg">Read More</a>
<hr>
</div>
<?php endforeach; ?>
<?php endif; ?>
For the configuration I followed this tutorial
A: Sadly you didn't follow the tutorial, otherwise you'd have noticed that inside the tutorial they define a function getObjectManager() inside the Controller. You don't define this function and therefore the Controller assumes this to be a ControllerPlugin and therefore asks the ControllerPluginManager to create an instance for this plugin. But no such Plugin was ever registered and that's why you see this error.
TL/DR -> do the tutorial step by step. Understand what you're doing, don't blindly copy paste the lines you think are important.
A: You forgot to implement the getObjectManager for your controller :
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
this method is included at the end of the IndexController in the tutorial you mentionned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21833231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pig Changing Schema to required type I'm a new Pig user.
I have an existing schema which I want to modify. My source data is as follows with 6 columns:
Name Type Date Region Op Value
-----------------------------------------------------
john ab 20130106 D X 20
john ab 20130106 D C 19
jphn ab 20130106 D T 8
jphn ab 20130106 E C 854
jphn ab 20130106 E T 67
jphn ab 20130106 E X 98
and so on. Each Op value is always C, T or X.
I basically want to split my data in the following way into 7 columns:
Name Type Date Region OpX OpC OpT
----------------------------------------------------------
john ab 20130106 D 20 19 8
john ab 20130106 E 98 854 67
Basically split the Op column into 3 columns: each for one Op value. Each of these columns should contain appropriate value from column Value.
How can I do this in Pig?
A: One way to achieve the desired result:
IN = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray,
date:int, region:chararray, op:chararray, value:int);
A = order IN by op asc;
B = group A by (name, type, date, region);
C = foreach B {
bs = STRSPLIT(BagToString(A.value, ','),',',3);
generate flatten(group) as (name, type, date, region),
bs.$2 as OpX:chararray, bs.$0 as OpC:chararray, bs.$1 as OpT:chararray;
}
describe C;
C: {name: chararray,type: chararray,date: int,region: chararray,OpX:
chararray,OpC: chararray,OpT: chararray}
dump C;
(john,ab,20130106,D,20,19,8)
(john,ab,20130106,E,98,854,67)
Update:
If you want to skip order by which adds an additional reduce phase to the computation, you can prefix each value with its corresponding op in tuple v. Then sort the tuple fields by using a custom UDF to have the desired OpX, OpC, OpT order:
register 'myjar.jar';
A = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray,
date:int, region:chararray, op:chararray, value:int);
B = group A by (name, type, date, region);
C = foreach B {
v = foreach A generate CONCAT(op, (chararray)value);
bs = STRSPLIT(BagToString(v, ','),',',3);
generate flatten(group) as (name, type, date, region),
flatten(TupleArrange(bs)) as (OpX:chararray, OpC:chararray, OpT:chararray);
}
where TupleArrange in mjar.jar is something like this:
..
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;
public class TupleArrange extends EvalFunc<Tuple> {
private static final TupleFactory tupleFactory = TupleFactory.getInstance();
@Override
public Tuple exec(Tuple input) throws IOException {
try {
Tuple result = tupleFactory.newTuple(3);
Tuple inputTuple = (Tuple) input.get(0);
String[] tupleArr = new String[] {
(String) inputTuple.get(0),
(String) inputTuple.get(1),
(String) inputTuple.get(2)
};
Arrays.sort(tupleArr); //ascending
result.set(0, tupleArr[2].substring(1));
result.set(1, tupleArr[0].substring(1));
result.set(2, tupleArr[1].substring(1));
return result;
}
catch (Exception e) {
throw new RuntimeException("TupleArrange error", e);
}
}
@Override
public Schema outputSchema(Schema input) {
return input;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15324747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: From Cider, in Emacs, is there a way to restart Figwheel to detect new dependencies? I added a new dependency to my Clojurescript app, and I want to know if I can run a function, maybe something like (restart-figwheel) to restart Figwheel. I read you have to restart Figwheel to detect new dependencies.
A: At this time, I don't think you can do this. You need to quit your current figwheel session and restart in order to pick up new dependencies added to your :dependencies in your project.clj file. In fact, the figwheel docs also recommend running lein clean before you restart figwheel to be sure you don't end up with some old code.
I think this functionality is on the roadmap, but is not a high priority. There is considerable complexity in being able to have this functionality work reliably - especially if you add in the complexity of different repl environments (such as using piggyback, and cider with figwheel).
Note that this limitaiton is just with :dependency items in the project.clj. You can add :require lines in your cljs files dynamically and have them picked up (asusming the library is already in the dependencies list of course).
I suspect part of the compicaiton is ensuring the classpath is updated and that all processes already running which use the classpath are somehow updated and making sure all loaded classes are reloaded in case the dependency changes the dependencies of those loaded classes to keep things consistent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42849591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get destination point? I am trying to navigation application on Mapbox with Unity. I want to get destination point from the user. I mean that user will write to where it wants to go and i will plot the road on the map according to destination point.
I tried reload map scrip, but it is just geolocate the map.
namespace Mapbox.Examples
{
using Mapbox.Geocoding;
using UnityEngine.UI;
using Mapbox.Unity.Map;
using UnityEngine;
using System;
using System.Collections;
public class ReloadMap : MonoBehaviour
{
Camera _camera;
Vector3 _cameraStartPos;
AbstractMap _map;
[SerializeField]
ForwardGeocodeUserInput _forwardGeocoder;
[SerializeField]
Slider _zoomSlider;
private HeroBuildingSelectionUserInput[] _heroBuildingSelectionUserInput;
Coroutine _reloadRoutine;
WaitForSeconds _wait;
void Awake()
{
_camera = Camera.main;
_cameraStartPos = _camera.transform.position;
_map = FindObjectOfType<AbstractMap>();
if(_map == null)
{
Debug.LogError("Error: No Abstract Map component found in scene.");
return;
}
if (_zoomSlider != null)
{
_map.OnUpdated += () => { _zoomSlider.value = _map.Zoom; };
_zoomSlider.onValueChanged.AddListener(Reload);
}
if(_forwardGeocoder != null)
{
_forwardGeocoder.OnGeocoderResponse += ForwardGeocoder_OnGeocoderResponse;
}
_heroBuildingSelectionUserInput = GetComponentsInChildren<HeroBuildingSelectionUserInput>();
if(_heroBuildingSelectionUserInput != null)
{
for (int i = 0; i < _heroBuildingSelectionUserInput.Length; i++)
{
_heroBuildingSelectionUserInput[i].OnGeocoderResponse += ForwardGeocoder_OnGeocoderResponse;
}
}
_wait = new WaitForSeconds(.3f);
}
void ForwardGeocoder_OnGeocoderResponse(ForwardGeocodeResponse response)
{
if (null != response.Features && response.Features.Count > 0)
{
int zoom = _map.AbsoluteZoom;
_map.UpdateMap(response.Features[0].Center, zoom);
}
}
void ForwardGeocoder_OnGeocoderResponse(ForwardGeocodeResponse response, bool resetCamera)
{
if (response == null)
{
return;
}
if (resetCamera)
{
_camera.transform.position = _cameraStartPos;
}
ForwardGeocoder_OnGeocoderResponse(response);
}
void Reload(float value)
{
if (_reloadRoutine != null)
{
StopCoroutine(_reloadRoutine);
_reloadRoutine = null;
}
_reloadRoutine = StartCoroutine(ReloadAfterDelay((int)value));
}
IEnumerator ReloadAfterDelay(int zoom)
{
yield return _wait;
_camera.transform.position = _cameraStartPos;
_map.UpdateMap(_map.CenterLatitudeLongitude, zoom);
_reloadRoutine = null;
}
}
}
In the direction example, it is just return geojson file. I could not able to plot the route on the map according to writing location. How can i define the destination point on the map by text.
A: For this you can use the directions API inside of the Unity SDK. Check out the traffic and directions example. You'll see how the response is being drawn as a line and rendered on a map. The DirectionsFactory.cs script draws a line along the route with the assigned material.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55004248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "File not found" error when I click a button This is an application for my website and I don't quite understand what is wrong with it. I have had colleagues looking at it and we can't quite figure out where the error is.
This is supposed to be a game of guess the number, where a random number is generated and the user is supposed to guess it; depending on how close you are to the answer, the colour should change. But instead it pops up a file not found error when the button is clicked.
const int = document.getElementById("Guess");
const LowOrHigh = document.querySelector("LowOrHigh");
const TimesGuessed = document.querySelector("TimesGuessed");
const WinOrLose = document.querySelector("WinOrLose");
let numberOfGuesses = 0;
const Color = document.querySelector("#Guess");
const RandomNumber = Math.random() * (100 - 1) + 1;
const win = "false";
const THEGODDAMBUTTON = document.getElementById("TreasureSubmitButton").addEventListener("click", Hey);
function Hey(int) {
let Guess = parseInt(int.valueOf);
if (RandomNumber === Guess) {
Color.style.backgroundColor = "#007F00";
Color.style.color = "#ffffff";
TimesGuessed.innerHTML('You have guessed ${numberOfGuesses} times');
win = "correct";
} else if (Guess > RandomNumber - 10 && Guess < RandomNumber || Guess < RandomNumber + 10 && Guess > RandomNumber) {
Color.style.backgroundColor = "#990000";
Color.style.color = "#ffffff";
numberOfGuesses++;
if (Guess > RandomNumber) {
LowOrHigh.innerHTML("Too high!");
} else if (Guess < RandomNumber) {
LowOrHigh.innerHTML("Too small!");
}
TimesGuessed.innerHTML('You have guessed ${numberOfGuesses} times');
WinOrLose.innerHTML("Good guess, try again!");
} else if (Guess > RandomNumber - 30 && Guess < RandomNumber || Guess < RandomNumber + 30 && Guess > RandomNumber) {
Color.style.backgroundColor = "#000099";
Color.style.color = "#ffffff";
numberOfGuesses++;
if (Guess > RandomNumber) {
LowOrHigh.innerHTML("Too high!");
} else if (Guess < RandomNumber) {
LowOrHigh.innerHTML("Too small!");
}
TimesGuessed.innerHTML('You have guessed ${numberOfGuesses} times');
WinOrLose.innerHTML("Good guess, try again!");
} else {
Color.style.backgroundColor = "#ffffff";
Color.style.color = "#000000";
numberOfGuesses++;
if (Guess > RandomNumber) {
LowOrHigh.innerHTML("Too high!");
} else if (Guess < RandomNumber) {
LowOrHigh.innerHTML("Too small!");
}
TimesGuessed.innerHTML('You have guessed ${numberOfGuesses} times');
WinOrLose.innerHTML("Good guess, try again!");
}
}
console.log(RandomNumber);
<div id="TreasureHunt">
<form action=submit method="post">
<fieldset id="guessFieldset">
<legend><strong>Please enter a number between 1 and 100</strong></legend>
<p>
<label for="Number:">Number:</label>
<input type="number" min="1" max="100" id="Guess" name="Guess">
</p>
<button type="submit" id="TreasureSubmitButton">Guess!</button>
<button type="submit" id="TreasureRestartButton">New game</button>
</fieldset>
<fieldset id="hintFieldset">
<legend><strong>Hint</strong></legend>
<p id="LowOrHigh"></p>
<p id="TimesGuessed"></p>
<p id="WinOrLose"></p>
</fieldset>
</form>
<p>In this game, your job is to guess the a number between 1 and 100! During the game, in the hint area, there will be displayed a color, if you are too high or too low and how many guesses you've had. Once you get the right number the hint area will shine
in green and you can restart the game by clickin new game. Try to guess wi the least guesses possible!</p>
</div>
A: Couple of things going on here. First, the file not found is happening because it is looking for a file called "submit" since you have:
<form action=submit method="post">. You don't need this property, nor do you need the method="post" because you're not sending your form data anywhere.
The second thing happening is that you're not passing your Hey() function an int. Since you're not using post, the form data isn't going anywhere. When you call Hey() you need to pass in document.getElementById('Guess').value since that's where you have it OR do something like this:
// no args
function Hey() {
let Guess = document.getElementById('Guess').value;
Hope that helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55660162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: NetworkAvailability check returns false yet the phone is online I have am having some issues with getting consistent results when checking if the network is available or not.
I use this code snippet inside a class AppPreferences to check the availability of a network.
/**
* @return the networkAvailable
*/
public boolean isNetworkAvailable() {
connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkAvailable = connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isConnected();
return networkAvailable;
}
Before each run I set the context as below:
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
appPreferences.setContext(getBaseContext());
if (appPreferences.isNetworkAvailable()){
// perform task
}
}
},
0,
UPDATE_INTERVAL);
I do know it is not tied to the background thread as I have a onReceive call doing the same logic and still this check fails.
It seems to predominantly happen when it moves between a cellular data connection and to wifi, or vice versa. The Context in which it was started seems to stay even though I update it.
Does anyone have any idea what could be the issue here?
A: It seems as if the active network info will stay on the state of when the Context of the Service/Activity/Receiver is started. Hence if you start it on a network, and then later disconnect from that (i.e. moves from 3G to Wifi and disconnect the 3G connection) it will stay on the first active connection making the app believe the phone is offline even though it is not.
It seems to me that the best solution is to user getApplicationContext instead as that will not be tied to when you started the particular "task".
Update: Related is that if you run applications on Androids (in particular Nexus One) for a long period of time when connected to Wifi do check that you make sure you do not let the Wifi sleep when the screen sleeps. You will be able to set that at the Advanced option under Wireless Networks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3283828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Yii2: can't create sql command using innerJoin I am not that good at SQL but i do as much as i can for the little knowledge i have..
I have made a single a flat SQL string with the help from a friend that gathers data from a table using a relative table from an initial data from the first table, the SQL was made like this:
SELECT id, username, auth_assignment.created_at
FROM `user` JOIN `auth_assignment`
ON (user.id = auth_assignment.user_id)
JOIN `auth_item`
ON (auth_item.name = auth_assignment.item_name)
WHERE auth_item.name = 'Admin'
the initial data to look is Admin so everything works in that side, but i tried to simulate this SQL using Yii2 functions.. so far i have made this code
$query = new Query;
$command = $query->select('id, username')
->innerJoin('auth_assignment', ['user.id'=>'auth_assignment.user_id'])
->innerJoin('auth_item', ['auth_item.name'=>'auth_assignment.item_name'])
->where('auth_item.name = :name', [':name'=>$name])->createCommand();
var_dump($command->query());
this returns an SQLSTATE error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN `auth_assignment` ON `user`.`id`='auth_assignment.user_id' INNER JOIN' at line 1
The SQL being executed was: SELECT `id`, `username` INNER JOIN `auth_assignment` ON `user`.`id`='auth_assignment.user_id' INNER JOIN `auth_item` ON `auth_item`.`name`='auth_assignment.item_name' WHERE auth_item.name = 'Admin'
i checked the method $command->sql; to know how the SQL was being generated.. but i really don't know how to fix it due to my lack of my knowledge to SQL and lack of understanding to yii2 api documentation
SQL is generated like this:
SELECT `id`, `username` INNER JOIN `auth_assignment` ON `user`.`id`=:qp1 INNER JOIN `auth_item` ON `auth_item`.`name`=:qp2 WHERE auth_item.name = :name
i appreciate any help
A: Try This Query
$query = (new yii\db\Query())
->select('id, username, auth_assignment.created_at')
->from('user')
->innerJoin('auth_assignment','user.id=auth_assignment.user_id')
->innerJoin('auth_item','auth_item.name = auth_assignment.item_name')
->where([
'auth_item.name' => 'Admin'
])->all();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33513417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Automatic OpenAPI generation in Spring with multipart requests I have a problem with the OpenAPI generator in a spring boot application generating the definition of a REST endpoint that accepts a multipart request.
When I am explicitly defining the parts like shown below. It generates an OpenAPI definition that is working/valid when used in for example in Azure API Management.
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public List<String> upload(@RequestPart MultipartFile file, @RequestPart UploadMetaData data) {
. . .
}
paths:
/api/v1/upload:
post:
operationId: upload
requestBody:
content:
multipart/form-data:
schema:
required:
- data
- file
type: object
properties:
gatewayId:
type: string
file:
type: string
format: binary
data:
$ref: '#/components/schemas/UploadMetaData'
responses:
"200":
description: OK
content:
'*/*':
schema:
type: array
items:
type: string
But when I am trying to use MultipartRequest instead of the annotated -File, the controller itself is still working as expected accepting an arbitrary list of multipart segments when I call it directly, but the OpenAPI definition that is generated is not reflecting the actual interface because it is trying to use the request parameter as an URL path parameter, so when I import this spec into Azure API Management it is not working.
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public List<String> upload(MultipartRequest request) {
. . .
}
paths:
/api/v1/upload:
post:
operationId: upload
parameters:
- name: request
in: query
required: true
schema:
$ref: '#/components/schemas/MultipartRequest'
requestBody:
content:
multipart/form-data:
schema:
type: string
responses:
"200":
description: OK
content:
'*/*':
schema:
type: array
items:
type: string
Other than giving my API a name, I didn't configure anything special for the generator:
@OpenAPIDefinition(info = @Info(title = "My REST API", version = "1.0"))
public class MySpringApplication {
. . .
}
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.12</version>
</dependency>
Is this a bug or am I missing some annotation or other configuration here?
A: The MultipartRequest, is not supported out of the box.
You can use the following code to enable the support.
static{
SpringDocUtils.getConfig().addFileType(MultipartRequest.class);
}
This support will be added for the future release.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70439574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible/sensible to split ASP.Net Core 2 (.NET Framework) Web Api into Class Library and Hosting projects? I'm trying to port an existing WCF Web API (targeting .NET Framework 4.6.1) to ASP.Net Core 2 using Visual Studio 2017 (v15.4.5) and am having trouble figuring out good/common/supported ways to organize projects, and what types of project they should be.
For example:
*
*Single project for Server and Hosting, or Class Library for Server and Console application for Hosting
*Windows Classic Desktop project for Console application and (new style csproj) Web Application for Server library, or both Web Applications (one outputting a Class Library, the other a Console Application)
I have the sneaking suspicion that there is something fundamental that I'm missing which means that one approach should be favoured over the others, or is even mandatory, but have found it hard to discover this from the ASP.Net Core 2 documentation.
Specific Requirements
*
*Should target .NET Framework 4.6.1
Since I need to access the Windows Registry from the internals of the Web API, I am targeting .NET Framework 4.6.1 rather than .NET Core.
*Host using HTTP.sys
I intend to use Windows Authentication in future and believe that Kestrel will not support that (Based upon HTTP.sys features).
*Host should run as a Windows Service
Ultimately, the Web API should be installed by Windows Installer and run as a service.
For the moment, I'm just trying to get the API to build/work correctly stand-alone, but would also appreciate any insight into how the choice of projects might affect publishing/deployment.
Preferred Solution
Whilst, by default, a new ASP.NET Core 2 Web Application is a single project outputting a Console Application, I would prefer to split the solution into 2 main projects:
*
*"Server" - An ASP.NET Core 2 (.NET Framework) Class Library containing the business logic of the Web API, controllers and Startup class
*"Host" - Console application which references "Server" and is responsible for hosting the Web API
This arrangement seems appropriate to me since any unit/integration test projects can reference the "Server" class library, not an executable (according to advice in Is it a bad practice to reference an exe file in C# project).
Furthermore, I'm led to believe this is reasonable because I can change the Output Type to "Class Library" in the project properties.
I'm assuming that since I'm targeting the .Net Framework, so long as I install the same NuGet packages as the "Server" project, there is no reason why the "Host" project cannot be a Windows Classic Desktop Console application.
Are there any hidden issues, perhaps relating to publishing/deployment, that make this arrangement a bad idea?
Would there be any advantage to making the Hosting project a Web Application (which would still reference the Server project)?
Attempt
Here are the steps I used to try to achieve my preferred project organization. Whilst it works, I get warnings generated during the build - see below.
Server
*
*Add New Project "Server"
*
*Choose Visual C#, Web, ASP.NET Core Web Application
In the following dialog, target .NET Framework, ASP.NET Core 2.0, and choose Web API
*Change Output Type in Project properties to "Class Library"
*Delete Program.cs
Host
*
*Add New Project "Host"
*
*Choose Visual C#, Windows Classic Desktop, Console App (.NET Framework)
*Replace contents of Program.cs with:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Server;
namespace Host
{
internal class Program
{
private static void Main(string[] args)
{
BuildWebHost(args).Run();
}
private static IWebHost BuildWebHost(string[] args) =>
new WebHostBuilder()
.UseStartup<Startup>()
.UseHttpSys(options =>
{
options.UrlPrefixes.Add("http://localhost:8080/");
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
logging.AddDebug();
})
.Build();
}
}
*Add a reference to the Server project
*Install these NuGet packages
*
*Microsoft.AspNetCore (2.0.1)
*Microsoft.AspNetCore.Mvc (2.0.1)
*Microsoft.AspNetCore.Server.HttpSys (2.0.2)
*Set as Startup Project
Problem: Build generates warnings
This solution runs under debugging, and responds correctly to http://localhost:8080/api/values and http://localhost:8080/api/values/1, but the following warnings are shown after building the solution:
Warning The referenced component 'System.Security.Cryptography.Encoding' could not be found. Host
Warning The referenced component 'System.Xml.XPath' could not be found. Host
Warning The referenced component 'System.IO.FileSystem.Primitives' could not be found. Host
Warning The referenced component 'System.IO.FileSystem' could not be found. Host
Warning The referenced component 'System.Diagnostics.StackTrace' could not be found. Host
Warning The referenced component 'System.Xml.XmlDocument' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.X509Certificates' could not be found. Host
Warning The referenced component 'System.Diagnostics.FileVersionInfo' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.Algorithms' could not be found. Host
Warning The referenced component 'System.Xml.ReaderWriter' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.Primitives' could not be found. Host
Warning The referenced component 'System.ValueTuple' could not be found. Host
Warning The referenced component 'System.Xml.XPath.XDocument' could not be found. Host
Warning The referenced component 'System.IO.Compression' could not be found. Host
Warning The referenced component 'System.AppContext' could not be found. Host
Warning The referenced component 'System.Threading.Thread' could not be found. Host
Warning The referenced component 'System.Console' could not be found. Host
If this is a reasonable arrangement of projects, why am I getting these warnings?
A: We are doing something similar. Our host is a .NET Framework 4.7.1 project:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net471</TargetFramework>
<IsPackable>true</IsPackable>
<PlatformTarget>x86</PlatformTarget>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.6" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business.csproj" />
<ProjectReference Include="..\Apis.Shared.csproj" />
<ProjectReference Include="..\Apis.Contracts.csproj" />
</ItemGroup>
</Project>
And our library projects are NetStandard2.0:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
</Project>
Program.cs looks like this:
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Startup.cs looks like this:
public class Startup
{
public Startup(IHostingEnvironment hostingEnvironment)
{
Settings = new AppSettings(hostingEnvironment);
}
public AppSettings Settings { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
// any other services registrations...
var builder = new ContainerBuilder();
// all autofac registrations...
builder.Populate(services);
return new AutofacServiceProvider(builder.Build(););
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47595244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Generating a new PDF using an existing PDF Document I'm trying to generate a new PDF document using an existing document as a base on a UWP application. I want to import the pages from the existing document, create annotations with information received from the application level and create a new PDF document combining both.
But it just creates a PDF document with the same number of pages but they are empty. When I analyze the created document the content is not available even though I imported it. But the created annotations are available in the document.
This is the file creation logic.
public async Task EmbedCurrentAnnotationsInStore(PdfDocument document)
{
if (document is null || document.IsDisposed)
return;
try
{
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("embedded_doc.pdf", CreationCollisionOption.ReplaceExisting);
PdfDocument newDocument = new PdfDocument();
PDFium.FPDF_ImportPages(newDocument.Handle, document.Handle, 0);
foreach (var page in newDocument.Pages)
await annotationConvertor.ConvertToFPDFAnnotations(page, annotationAdapter.GetAnnotations()
.Where(x =>
x.Status != AnnotationStatus.Removed &&
x.PageIndex == page.Index)
.OrderBy(x => x.AnnotationIndex));
using (var stream = await file.OpenStreamForWriteAsync())
{
newDocument.Save(stream, SaveFlags.None, document.FileVersion);
await stream.FlushAsync();
newDocument.Close();
}
}
catch (Exception ex)
{
var err = PDFium.FPDF_GetLastError();
throw ex;
}
}
ConvertToFPDFAnnotations()
public async Task ConvertToFPDFAnnotations(PdfPage page, IEnumerable<BaseAnnotation> annotations)
{
foreach (var annotation in annotations)
{
switch (annotation.AnnotationType)
{
case FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT:
await EmbedFPDFAnnotationFromHighlightAnnotation(page, annotation.AsHighlightAnnotation());
break;
default:
break;
}
}
}
EmbedFPDFAnnotationFromHighlightAnnotation()
private async Task EmbedFPDFAnnotationFromHighlightAnnotation(PdfPage page, HighlightAnnotation annotation)
{
if (page is null || page.IsDisposed)
return;
var fdfAnnotation = page.CreateAnnot(page, FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT);
fdfAnnotation.SetColor(fdfAnnotation.Handle, FPDFANNOT_COLORTYPE.FPDFANNOT_COLORTYPE_Color,
(uint)annotation.Color.R,
(uint)annotation.Color.G,
(uint)annotation.Color.B,
(uint)annotation.Color.A);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CA", annotation.Color.A.ToString());
foreach (var quadpoint in annotation.Quadpoints)
{
var refQuadpoint = quadpoint;
fdfAnnotation.AppendAttachmentPoints(fdfAnnotation.Handle, ref refQuadpoint);
}
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Index", annotation.StartIndex.ToString());
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Count", annotation.CharCount.ToString());
var rect = new FS_RECTF();
rect = annotation.Rect;
fdfAnnotation.SetRect(fdfAnnotation.Handle, ref rect);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CreationDate", annotation.CreationDate);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "M", annotation.ModifiedDate);
if (string.IsNullOrEmpty(annotation.Contents))
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Contents", annotation.Contents);
fdfAnnotation.CloseAnnot(fdfAnnotation.Handle);
}
I used this (FPDF_ImportPages) method to import the pages from the existing document.
Could someone help me with the issue I'm facing? Maybe I'm missing something here.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72113385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically selecting imageViews from ArrayList or HashMap I have a Farkle game that I am trying to create a "Computer" player for and I am having a tough time trying to get this to work.
Game Play: 1's & 5's are always scorable, Straight 1-6, 3-of-a-kind, 4-of-a-kind, 5-of-a-kind & 6-of-a-kind are scorable. Pairs are only scorable if using all 6 dice. example: 2,2,5,5,4,4.
So here is my issue. I have it selecting all dice just to make it work, but I want to find the Value of the dice that are showing on the board and these scorable combinations and select them programmatically 1-by-1. The screen shot shows the human player has selected the 5. I know the code is a mess (I have been told several times). FYI, I had to remove a lot of code to stay in the 30000 limit. Complete Code is here
Here are the files I think are needed. You will see some Toasts, this was me trying to figure out the logic of what I need to do
AiOhFarkActivity - Main Class
public class AiOhFarkActivity extends Activity implements AnimationEndListener {
private AiGameController controller;
private DieManager dm;
private ArrayList<MyImageView> imageViews = new ArrayList<MyImageView>();
// Added for AI to set the starting
// number of dice selected to 0
private int selectedDie = -1;
//public boolean performItemClick (View v, int position, long id);
private int[] letters = new int[6];
private boolean toFarkle = false;
private int animationCount = 0;
public Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Create, Initialize and then load the Sound manager and Volume Control
setVolumeControlStream(AudioManager.STREAM_MUSIC);
SoundManager. ....
r = getResources();
initializeArrays();
scoreBox = (TextView) ....
numFarkles = (TextView) ....
dieScore = (TextView) ....
scoreButton = (Button) ....
rollButton = (Button) ....
finalButton = (Button) ....
finalRoundLayout = (LinearLayout) ....
winnerButton = (Button) ....
winnerLayout = (LinearLayout) ....
winnerTextView = (TextView) ....
handler = new Handler();
// Restore GameController
if (getLastNonConfigurationInstance() != null) {
controller = (AiGameController) getLastNonConfigurationInstance();
controller.newUI(this);
updateImages(false, false);
} else {
controller = new AiGameController(this);
}
// Restore UI elements
if (savedInstanceState != null && savedInstanceState.getBoolean("hasState")) {
scoreBox.setText ....
numFarkles.setText ....
dieScore.setText ....
scoreButton.setText ....
scoreButton.setEnabled ....
rollButton.setEnabled ....
finalButton.setEnabled ....
finalRoundLayout.setEnabled ....
winnerButton.setEnabled ....
winnerButton.setText ....
winnerLayout.setEnabled ....
}
}
// These arrays allows the use of a for loop in updateImages()
private void initializeArrays() {
imageViews.add((MyImageView) findViewById(R.id.img_1));
imageViews.add((MyImageView) findViewById(R.id.img_2));
imageViews.add((MyImageView) findViewById(R.id.img_3));
imageViews.add((MyImageView) findViewById(R.id.img_4));
imageViews.add((MyImageView) findViewById(R.id.img_5));
imageViews.add((MyImageView) findViewById(R.id.img_6));
letters[0] = R.drawable.dief;
letters[1] = R.drawable.diea;
letters[2] = R.drawable.dier;
letters[3] = R.drawable.diek;
letters[4] = R.drawable.diel;
letters[5] = R.drawable.diee;
}
public void onRoll(View v) {
controller.onRoll();
}
// TODO AI
public void disableButtons(){
}
// TODO AI
public void enableButtons(){
rollButton.setClickable(true);
scoreButton.setClickable(true);
}
// TODO AI
public void disableDice(){
}
// TODO AI
public void enableDice(){
}
public void onScore(View v) {
// Calculate Score
controller.onScore();
//Play Sound
if (myPrefs.getBoolean("soundPrefCheck", true)) {
SoundManager. ....
}
// After Player Scores
// Check to see if the Current Player is now the Machine
// If machine player, roll the dice and lock
// the buttons so the human cannot cheat
// TODO AI
if (controller.isMachinePlayer() == true) {
controller.machineRoll();
disableButtons();
disableDice();
}else {
enableButtons();
enableDice();
}
}
public void updateImages(boolean toAnimate, boolean isFarkle) {
// This is used in onAnimationEnd() to determine when all animations
// have ended. Since all the animations are starting when this method is
// called the count is 0
animationCount = 0;
MyImageView i = null;
for (int j = 0; j < imageViews.size(); j++) {
Animation a = AnimationUtils.loadAnimation(this, R.anim.dice_animation);
i = imageViews.get(j);
// If were gonna animate we need to know when the animation ends.
// Hence were gonna attach this instance as a listener so
// onAnimationEnd() gets called when animations finish.
if (toAnimate) {
i.setAnimationEndListerner(this);
}
// Get the right image from the Resources. *See in DiceManager
// getImage()
i.setImageDrawable(r.getDrawable(controller.getImage(j)));
if (toAnimate && controller.shouldAnimate(j)) {
i.clearAnimation();
i.startAnimation(a);
}
}
// Used in onAnimatonEnds()
if (isFarkle)
toFarkle = true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
}
@Override
public Object onRetainNonConfigurationInstance() {
return controller;
}
public void showFarkle() {
}
private void farkleAnimation() {
}
@Override
public void onAnimationEnd(View v) {
}
}
AiGameController
public class AiGameController extends PreferenceActivity {
private ArrayList<Player> players = new ArrayList<Player>();
public AiGameController(AiOhFarkActivity ui) {
setupPlayers(ui);
dM = new DieManager();
UI = ui;
updateUIScore();
currPlayer = players.get(round % players.size());
lastPlayer = null;
machinePlayer = players.get(round % players.size());
}
public void setupPlayers(Context c) {
int numOfPlayers = 1;
for (int i = 1; i <= numOfPlayers; i++) {
// TODO AI
String player = "Human ";
String machine = "Machine";
players.add(new Player(player));
players.add(new Player(machine));
}
}
// If the currPlayer is the Machine
// TODO AI
public void machineRoll() {
// Check for Machine Player, if found Roll the dice
// Check for Machine Player, if found Roll the dice
if (currPlayer.getName() == "Machine"){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
onRoll();
handler.postDelayed(new Runnable() {
public void run() {
onClickDice(0, false);
onClickDice(1, false);
onClickDice(2, false);
onClickDice(3, false);
onClickDice(4, false);
onClickDice(5, false);
android.os.SystemClock.sleep(350);
if (ppossibleScore >= GOB_SCORE){
handler.postDelayed(new Runnable() {
public void run() {
//Play Sound
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(UI);
if (prefs.getBoolean("soundPrefCheck", true)) {
SoundManager.playSound(11, 1); // Flip Sound
}
onScore();
}
}, 750);
}else {
handler.postDelayed(new Runnable() {
public void run() {
// If the highest score possible on the table is 0 then its a farkle
if (Scorer.calculate(dM.diceOnTable(DieManager.ABS_VALUE_FLAG), true,
UI) == 0) {
currPlayer.setInRoundScore(0);
currPlayer.incrementNumOfFarkles();
// True because its a Farkle
endRound(true);
// Else just show what the player rolled
} else
repaetMachineRoll();
}
}, 750);
}
}
}, 1750);
// If all dice are selected (Hot Dice) onRoll again
// Not sure if this belongs here ..... But,
// If the numDiceRemaining <= 2 and the CurrScoreOnTable >= 300
// bank the points - call onScore
// if numDiceRemaining > 2 and CurrScoreOnTable <= 250 - call onRoll
}
}, 1750);
}
// If the currPlayer is the Machine
public boolean isMachinePlayer() {
// TODO Alert AI
// Check for Machine Player, if found Roll the dice
if (currPlayer.getName() == "Machine"){
return true;
}
return false;
}
// Always called from onRoll method
public void startRound() {
isRoundEnded = false;
currPlayer = players.get(round % players.size());
currPlayer.resetInRoundScore();
machinePlayer = players.get(round % players.size());
machinePlayer.resetInRoundScore();
updateUIScore();
// Show the Current Players Number of Farkles
String fmessage = "";
fmessage += UI.getString(R.string.stYouHave) + " " + currPlayer.getNumOfFarkles() + " " + UI.getString(R.string.stFarkles);
UI.updatenumOfFarkles(UTILS.setSpanBetweenTokens(fmessage, "$$", new StyleSpan(Typeface.NORMAL)));
}
// Can be called from onRoll or onScore
public void endRound(boolean isFarkle) {
if (!isFarkle)
UI.rollButtonState(true);
UI.scoreButtonState(false);
String pscore = UI.getString(R.string.stScore);
UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));
// show penalty
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(UI);
int farklePenaltyScore = Integer.valueOf(pref.getString("farklePenaltyPref", "-1000"));
// Checks to see if Farkle Penalty is on
if (pref.getBoolean("farklePenalty", true)) {
if (isFarkle && currPlayer.getNumOfFarkles() == 3) {
currPlayer.setInRoundScore(farklePenaltyScore);
// Show a -1000 next to his name
updateUIScore();
// There is a penalty *See animationsEnded()
negateFarklePenalty = true;
}
}
// Alert the UI a farkle is rolled
UI.updateImages(false, isFarkle);
// If its not a farkle then just clear the table and Update the images
if (!isFarkle) {
dM.clearTable();
UI.updateImages(false, false);
}
isRoundEnded = true;
round++;
lastPlayer = currPlayer;
currPlayer = players.get(round % players.size());
// Usually updateUIScore() is called to erase the "+Score" but it
// shouldn't be called if the last player farkled three times because it
// erases the -1000
if (lastPlayer.getNumOfFarkles() != 3)
updateUIScore();
if (!isFarkle && currPlayer.hasHighestScore()) {
alertOfWinner();
}
}
private void alertOfWinner() {
showGameOver();
}
// Finds the player with the Highest score
private int findHighestScore() {
for (Player p : players) {
if (p.hasHighestScore())
return players.indexOf(p);
}
return -1;
}
// Updates the ScoreBox
private void updateUIScore() {
String message = "";
for (Player p : players) {
if (p.equals(currPlayer)) {
int currInRoundScore = p.getInRoundScore();
String temp = "$$ ";
String sign = (currInRoundScore > 0) ? "+" : "";
if (currInRoundScore != 0 && !isRoundEnded)
temp = "$$ " + sign + currInRoundScore + " ";
message += "$$" + p.getName() + temp + p.getScore() + "\n";
} else {
message += p.getName() + " " + p.getScore() + "\n";
}
}
// The $$ tell setSpanBetweenTokens() what to make bold
UI.updateScoreBox(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));
}
// Number of Current Die remaining on the table
public int numOnTable() {
return dM.numOnTable();
}
// Called when the roll button is clicked or can be called from the AI
public void onRoll() {
UI.finalRoundLayout.setVisibility(View.GONE);
// Sounds
SharedPreferences mySoundPref=PreferenceManager.getDefaultSharedPreferences(UI);
if (mySoundPref.getBoolean("soundPrefCheck", true)) {
}
// Reset Score Button
String message = "";
//message += "Dice Score: 0";
// onRoll
if (isRoundEnded)
startRound();
UI.rollButtonState(false);
UI.scoreButtonState(false);
if (dM.getHighlighted(DieManager.INDEX_FLAG).length > 0) {
int scoreOnTable = Scorer.calculate(
dM.getHighlighted(DieManager.ABS_VALUE_FLAG), true, UI);
currPlayer.incrementInRoundScore(scoreOnTable);
// Show how much was picked up
updateUIScore();
dM.pickUp(dM.getHighlighted(DieManager.INDEX_FLAG));
}
dM.rollDice();
UI.updateImages(true, false);
// If the highest score possible on the table is 0 then its a farkle
if (Scorer.calculate(dM.diceOnTable(DieManager.ABS_VALUE_FLAG), true,
UI) == 0) {
currPlayer.setInRoundScore(0);
currPlayer.incrementNumOfFarkles();
// True because its a Farkle
endRound(true);
// Else just show what the player rolled
} else
UI.updateImages(true, false);
// Check for isMachinePlayer
}
// When a dice is clicked the GameController determines which dice to
// highlight and whether to enable the buttons
public void onClickDice(int index, boolean isFarkle) {
// Play Select Sound
SharedPreferences mySoundPref=PreferenceManager.getDefaultSharedPreferences(UI);
if (mySoundPref.getBoolean("soundPrefCheck", true)) {
SoundManager.playSound(10, 1); // Select Sound
}
String message = "";
String pscore = "";
if (isRoundEnded)
return;
int value = dM.getValue(index, DieManager.ABS_VALUE_FLAG);
// A letter was clicked
if (value == 0)
return;
// Always highlight 5's and 1's
if (value == 5 || value == 1) {
dM.toggleHighlight(index);
} else {
// This method determines if the dice should be highlighted
if (shouldHighlight(index)) {
// if true then get the pairs of this dice
int[] pairs = dM.findPairs(index, DieManager.INDEX_FLAG);
// Highlight them
for (int i : pairs)
dM.toggleHighlight(i);
// And highlight the original dice
dM.toggleHighlight(index);
}
}
// The score of the highlighted dice
int highlightedScore = Scorer.calculate(dM.getHighlighted(DieManager.ABS_VALUE_FLAG), false, UI);
// Second parameter is false to not ignore any extra dice
// The score the player picked up
int possibleScore = currPlayer.getInRoundScore() + highlightedScore + currPlayer.getScore();
// Display the Current Score of the selected Dice
//message += "Dice Score: " + highlightedScore;
message += (UI.getString(R.string.stDiceScore)) + ": " + highlightedScore;
UI.updateCurrentScore(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));
// Display the Potential Points in the Score Button
int ppossibleScore = currPlayer.getInRoundScore() + highlightedScore;
pscore = "+ " + ppossibleScore;
UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));
if (highlightedScore != 0) {
UI.rollButtonState(true);
// Play Hot Dice sound
if (mySoundPref.getBoolean("soundPrefCheck", true)) {
if (dM.numDiceRemain() == 0){
SoundManager.playSound(8, 1); // HotDice Sound
}
}
// Tells it when to enable the Score Button
// based on the Get-On-Board Value
if (possibleScore >= GOB_SCORE) {
UI.scoreButtonState(true);
showToast("GOB Score met");
}
// If a player is past the winning score
if (isPlayerPastWinScore) {
// Disable the score button
UI.scoreButtonState(false);
// The highest score so far
int scoreOfWinnerToBe = players.get(findHighestScore())
.getScore();
// If the player can get a higher score then enable the score
// button
if (possibleScore > scoreOfWinnerToBe) {
UI.scoreButtonState(true);
}
}
} else {
UI.rollButtonState(false);
UI.scoreButtonState(false);
}
UI.updateImages(false, false);
}
// Calculate the current Score that is possible if banked.
public int CurrScoreOnTable() {
int highlightedScore = Scorer.calculate(dM.getHighlighted(DieManager.ABS_VALUE_FLAG), false, UI);
int possibleScore = lastPlayer.getInRoundScore() + highlightedScore;
return possibleScore;
}
// Determines whether to highlight the dice clicked
private boolean shouldHighlight(int index) {
// Gets the pairs (if any)
int[] pairs = dM.findPairs(index, DieManager.INDEX_FLAG);
int[] valuesOfPairs = new int[pairs.length + 1];
// Takes the value of the pairs and puts them into the valueOfPairs
// array
System.arraycopy(dM.findPairs(index, DieManager.ABS_VALUE_FLAG), 0, valuesOfPairs, 0, pairs.length);
// Adds the dice that was clicked to the array
valuesOfPairs[pairs.length] = dM.getValue(index, DieManager.ABS_VALUE_FLAG);
// True if the value of the pairs and the dice clicked is 0
boolean isZero = Scorer.calculate(valuesOfPairs, false, UI) == 0;
int[] diceOnTable = dM.diceOnTable(DieManager.ABS_VALUE_FLAG);
// True is there are three pairs on the table
boolean isThreePair = Scorer.isThreePair(diceOnTable, UI, true) != 0;
// True if there is a straight on the table
boolean isStraight = Scorer.isStraight(diceOnTable, UI, true) != 0;
return (!isZero || isThreePair || isStraight);
}
// Score button is clicked.
public void onScore() {
// Reset the Current Dice Score and Make Roll Button Active
String message = "";
// message += "Dice Score: 0";
message += (UI.getString(R.string.stDiceScore)) + ": 0";
UI.updateCurrentScore(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));
String pscore = UI.getString(R.string.stScore);
UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));
// Values of highlighted dice on table
int[] highlighted = dM.getHighlighted(DieManager.ABS_VALUE_FLAG);
// Score of the highlighted dice
int onTable = Scorer.calculate(highlighted, false, UI);
// The players new Score
int newScore = currPlayer.getScore() + onTable + currPlayer.getInRoundScore();
currPlayer.setScore(newScore);
if (newScore >= WINNING_SCORE) {
//SharedPreferences myPrefs=PreferenceManager.getDefaultSharedPreferences(this);
isPlayerPastWinScore = true;
// If no one is over the WINNING_SCORE findWinnerToBe() returns -1
if (findHighestScore() == -1) {
// Player is the first one to pass the score
currPlayer.setOriginalWinner(true);
currPlayer.setHasHighestScore(true);
} else {
currPlayer.setHasHighestScore(true);
}
}
currPlayer.resetInRoundScore();
// False because its not a Farkle
endRound(false);
// Show the Current PLayers Number of Farkles
}
public int getImage(int index) {
return dM.getImage(index);
}
public void newUI(AiOhFarkActivity newUI) {
UI = newUI;
}
// Should not animate if value of dice is 0 ie its a letter
public boolean shouldAnimate(int index) {
return (dM.getValue(index, DieManager.VALUE_FLAG) > 0);
}
public void clearTable() {
dM.clearTable();
}
public void animationsEnded(boolean isFarkle) {
}
}
DieManager
public class DieManager {
// Will return the Indexes of the dice when this is used
public static final int INDEX_FLAG = 1;
// Will return the values of the dice when this is used
public static final int VALUE_FLAG = 2;
// Will return the absolute values of the dice when this is used
public static final int ABS_VALUE_FLAG = 3;
// The array that holds the dice
private int[] diceValues = { 0, 0, 0, 0, 0, 0 };
private HashMap<Integer, Integer> diceImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> deadImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> letterImages = new HashMap<Integer, Integer>();
// Sets @newValue to dieValues[@index]
public void setValue(int index, int newValue) {
Log.w(getClass().getName(), "Index = " + index + " Value = " + newValue);
diceValues[index] = newValue;
}
public DieManager() {
super();
initializeMaps();
}
private void initializeMaps() {
// Shows Selected
diceImages.put(-6, R.drawable.die6_select);
diceImages.put(-5, R.drawable.die5_select);
diceImages.put(-4, R.drawable.die4_select);
diceImages.put(-3, R.drawable.die3_select);
diceImages.put(-2, R.drawable.die2_select);
diceImages.put(-1, R.drawable.die1_select);
// Shows Rolled
diceImages.put(1, R.drawable.die1_roll);
diceImages.put(2, R.drawable.die2_roll);
diceImages.put(3, R.drawable.die3_roll);
diceImages.put(4, R.drawable.die4_roll);
diceImages.put(5, R.drawable.die5_roll);
diceImages.put(6, R.drawable.die6_roll);
// dice are dead
deadImages.put(0, R.drawable.die1_dead);
deadImages.put(1, R.drawable.die2_dead);
deadImages.put(2, R.drawable.die3_dead);
deadImages.put(3, R.drawable.die4_dead);
deadImages.put(4, R.drawable.die5_dead);
deadImages.put(5, R.drawable.die6_dead);
// Shows blank
letterImages.put(0, R.drawable.die_no);
letterImages.put(1, R.drawable.die_no);
letterImages.put(2, R.drawable.die_no);
letterImages.put(3, R.drawable.die_no);
letterImages.put(4, R.drawable.die_no);
letterImages.put(5, R.drawable.die_no);
}
public void rollDice() {
showToast("Rolling Dice");
boolean isNewRound = (numOnTable() == 0);
for (int j = 0; j < 6; j++) {
if (isNewRound || diceValues[j] != 0)
diceValues[j] = (int) ((Math.random() * 6) + 1);
}
}
// Returns the value or absolute value
public int getValue(int index, int flag) {
if (flag == ABS_VALUE_FLAG)
return Math.abs(diceValues[index]);
return diceValues[index];
}
// If a dice value is 0 then its a letter
public int numOnTable() {
int count = 6;
for (int i : diceValues) {
if (i == 0)
count--;
}
return count;
}
// Picking up makes the dice value 0
public void pickUp(int[] highlighted) {
for (int i = 0; i < highlighted.length; i++)
diceValues[highlighted[i]] = 0;
}
// A negative value means a die is highlighted
public void toggleHighlight(int index) {
diceValues[index] *= -1;
}
public void clearTable() {
diceValues[0] = 0;
diceValues[1] = 0;
diceValues[2] = 0;
diceValues[3] = 0;
diceValues[4] = 0;
diceValues[5] = 0;
}
// Return the dice that aren't 0
public int[] diceOnTable(int flag) {
showToast("Getting Dice Values");
if (flag == ABS_VALUE_FLAG) {
int[] array = new int[diceValues.length];
for (int i = 0; i < diceValues.length; i++)
array[i] = Math.abs(diceValues[i]);
return array;
}
return diceValues;
}
//Returns dice that are negative
public int[] getHighlighted(int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (diceValues[j] < 0) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
//Returns an array of length 0
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
// Finds in dieValues same @value and excludes @index
public int[] findPairs(int index, int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (j != index
&& Math.abs(diceValues[j]) == Math.abs(diceValues[index])) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
//Get the Dice Images
public Integer getImage(int index) {
if (diceValues[index] == 0) {
return letterImages.get(index);
} else {
return diceImages.get((diceValues[index]));
}
}
//Get the Number of dice remaining that are not 0
public int numDiceRemain() {
int counter = 0;
for (int j = 0; j < diceValues.length; j++) {
if (diceValues[j] > 0)
counter++;
}
return counter;
}
public void selectDice() {
// TODO Alert AI
}
public void selectAllDice() {
// TODO Alert AI
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30412289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel 5.2 -> 5.3 Infinite Redirect Loop after upgrade I have upgraded from Laravel 5.2 to 5.3. All URI now lead to an infinite (ERR_TOO_MANY_REDIRECTS) redirection loop at /auth/login. I tried to remove my middleware one after the other to try to find the problem. I even commented out the whole Http\Kernel and removed middleware from the RouteServiceProviders.
When I artisan route:list, I can see that now my routes have no middleware, but I still get the infinite redirection. For example, if I try to access a route without middleware my.app/foo/bar or use a random string my.app/somerandomstringthatisnotaroute I always get ERR_TOO_MANY_REDIRECTS at my.app/auth/login.
I also tried to artisan clear-compiled and artisan route:clear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41250758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to take mac address of iBeacon in Ionic Framework for the app build on android platform I am trying to build an application for android devices with ionic framework to scan the ibeacons in an environment with the help of https://www.thepolyglotdeveloper.com/2015/09/support-ibeacons-in-your-ionic-framework-mobile-app/ . I just want to know few things before stepping into this ionic framework.
1. Is it possible to scan ibeacons on android devices without giving UUID's?
2. Is it possible to fetch the mac address of ibeacons on android devices?
If the above things are not possible in Ionic Framework, which stack or framework should I use to build an application for android devices to scan both ibeacons and non ibeacons to get the mac address and RSSI?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62405678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Send Image to server using File input type I have a screen where I am capturing video from camera, taking a snap. I also have a file input and I want to set this option to the captured image from the camera, i.e..snap.
I do not want to store the snap as a cookie and later retrieve it, as it will later make the users computer heavy and will require cleaning everytime.
so the code is
<input type="file" id="visitorphoto" name="visitorPhoto" accept="image/*" capture>
which is according to this w3 document.
Any Ideas using javascript?
Thanks,
Abhijeet.
A: Use formData to upload file.
HTML:
<input type="file" id="filechooser">
Javascript Code
function uploadFile() {
var blobFile = $('#filechooser').files[0];
var formData = new FormData();
formData.append("fileToUpload", blobFile);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {
// .. do something
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
Compatibility:
http://caniuse.com/xhr2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25204621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Select specif row data (numeric) from list of 5 (dimnames) in a $ : chr row in multiple tables Hy everybody. I'm kind of stuck with simple code. In fact I have this output:
roc_value
, , MAXENT.Phillips, RUN1, PA1
Testing.data Cutoff Sensitivity Specificity
KAPPA 0.558 484.0 63.713 90.667
TSS 0.555 354.0 73.840 81.667
ROC 0.863 369.5 72.996 83.000
ACCURACY 0.788 484.0 63.713 90.667
BIAS 0.996 344.0 73.840 79.667
, , GLM, RUN1, PA1
Testing.data Cutoff Sensitivity Specificity
KAPPA 0.565 422 83.122 74.333
TSS 0.575 422 83.122 74.333
ROC 0.843 420 83.122 74.333
ACCURACY 0.782 422 83.122 74.333
BIAS 0.979 518 72.574 79.667
, , GAM, RUN1, PA1
Testing.data Cutoff Sensitivity Specificity
KAPPA 0.664 554.0 81.435 85.000
TSS 0.664 554.0 81.435 85.000
ROC 0.885 557.5 81.435 85.333
ACCURACY 0.834 595.0 76.793 88.667
BIAS 0.996 554.0 81.435 85.000
, , RF, RUN1, PA1
Testing.data Cutoff Sensitivity Specificity
KAPPA 0.768 404 83.544 92.000
TSS 0.762 404 83.544 92.000
ROC 0.950 406 83.544 92.667
ACCURACY 0.886 485 81.435 94.333
BIAS 0.987 343 84.810 89.000
, , MAXENT.Tsuruoka, RUN1, PA1
Testing.data Cutoff Sensitivity Specificity
KAPPA 0.509 368 86.498 66.000
TSS 0.527 321 90.717 61.667
ROC 0.838 372 86.498 66.333
ACCURACY 0.756 479 74.262 76.333
BIAS 0.970 488 70.464 78.667
the str(roc_value) is:
num [1:5, 1:4, 1:5, 1, 1] 0.558 0.555 0.863 0.788 0.996 ...
- attr(*, "dimnames")=List of 5
..$ : chr [1:5] "KAPPA" "TSS" "ROC" "ACCURACY" ...
..$ : chr [1:4] "Testing.data" "Cutoff" "Sensitivity" "Specificity"
..$ : chr [1:5] "MAXENT.Phillips" "GLM" "GAM" "RF" ...
..$ : chr "RUN1"
..$ : Named chr "PA1"
.. ..- attr(*, "names")= chr ""
I want to select only ROC values from Testing.data column in a single object (to continue my script), for instance:
whatidlike <- c(0.863,0.843,0.885,0.950,0.838) # only a single object with ROC values.
Tried dplyr, subset etc. and can't move on. Could someone, please, give me a hand?
A: You list object names look strange ', , RF, RUN1, PA1' but you should be able to access them using index. e.g. roc_value[[1]], roc_value[[2]]... etc
so, then further to select Testing.data would be simply as
roc_value[[1]]['Testing.data']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54651009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript link to another javascript i want create an program using javascript, but i want my file be more organize, is there some way that i can implement the concept of include or require of php. example: javascript file that only contains function let say function.js, then another javascript file main.js. is there a way that in main.js i can call a function in the function.js?
function.js
function test(){
alert("hello world");
}
main.js
$(document).ready(function(){
test();
});
A: Yes, you can always use functions out of another javascript file.
though if you executed the code immediately you need to specify the right order: First the function definition, then the function call so:
<head>
<script src="javascript.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
</head>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27605367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Google Directions API Polyline not added to map I have a problem using the Google Directions API.
I'm getting the JSON string and parsing it, getting the overview_polylines string
NSString *allPolylines = [NSString stringWithFormat:[[[routes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"]];
This thing works.
I'm having trouble adding it to the map.
I'm using this post http://iosguy.com/tag/directions-api/ which seems to be exactly what I'm after.
I've implemented the
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr
method, and it works great. I NSLogged the results and it shows up as if I'm outputting CLLocation objects.
The problem is that I can't make it show up on the map. This is the code that follows
NSMutableArray *_path = [self decodePolyLine:allPolylines];
NSInteger numberOfSteps = _path.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [_path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[_mapView addOverlay:polyLine];
[self mapView:_mapView viewForOverlay:polyLine];
I also tried adding an explicit call to
[self mapView:_mapView viewForOverlay:polyLine];
which is:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
polylineView.strokeColor = [UIColor redColor];
polylineView.lineWidth = 1.0;
return polylineView;
}
The last method gets called, I checked using NSLog, but nothing shows up on the map.
Any thoughts?
Thanks in advance!
A: The code shown looks OK except that you're not supposed to call viewForOverlay directly.
The map view will call that delegate method when it needs to show the overlay.
The simplest reason it would not be calling the delegate method is that the map view's delegate property is not set.
If the delegate property is set, then verify that the coordinates are what you're expecting and also make sure they are not flipped (latitude in longitude and vice versa).
Another thing to check:
If _mapView is an IBOutlet, make sure it is actually connected to the map view in the xib.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10809373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: autossh pid is not equal to the one in pidfile when using start-stop-daemon I am trying to create a service on my Debian Wheezy system.
When trying to use start-stop-daemon to run autossh, the pid contained into the pidfile does not match with the autossh process.
$ AUTOSSH_PIDFILE=/var/run/padstunnel.pid
$ sudo start-stop-daemon --make-pidfile --background --name mytunnel --start --pidfile /var/run/mytunnel.pid --exec /usr/lib/autossh/autossh -- -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222
$ ps -elf |grep autossh
1 S root 447 1 0 80 0 - 329 pause 19:07 ? 00:00:00 /usr/lib/autossh/autossh -M 0 -p 22 ...
$ cat /var/run/mytunnel.pid
446
This behaviour prevents from stopping autossh using start-stop-daemon or kill it using the pid from the pidfile.
Is there any reason to this behaviour ?
How to workaround it and make autossh's pid matches the pidfile ?
A: The solution I found is inspired by this answer.
Actually, the AUTOSSH_PIDFILE variable could not be used by autossh (because start-stop-daemon runs in a different environment).
So the workaround is to use :
$ sudo start-stop-daemon --background --name mytunnel --start --exec /usr/bin/env AUTOSSH_PIDFILE="/var/run/mytunnel.pid" /usr/lib/autossh/autossh -- -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222
*
*/usr/bin/env AUTOSSH_PIDFILE="/var/run/mytunnel.pid" correctly defines the necessary environment variable
*--make-pidfile and --pidfile are no longer required by start-stop-daemon
*sudo start-stop-daemon --pidfile /var/run/mytunnel.pid --stop now works to kill autossh
*--background option makes the ssh's -f optional (using -f or not does not change anything if --background is used)
The reason for the behaviour is not completely clear to me. However, it seems that autossh automatically creates several processes to handle correctly ssh instances when it does not see AUTOSSH_PIDFILE variable.
Edit:
When using it from a service init script (in /etc/init.d/servicename), the syntax has to be modified:
sudo start-stop-daemon --background --name mytunnel --start --exec /usr/bin/env -- AUTOSSH_PIDFILE="/var/run/mytunnel.pid" /usr/lib/autossh/autossh -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222
Notice the -- that must come just after the /usr/bin/env command (it was after the /usr/lib/autossh/autossh from command line).
A: Just an update for a working solution from 7 years into the future as I recently came across this exact same issue.
The AUTOSSH_PIDFILE variable for some reason will make the program fail without any output, including when using -v. What I found would work is simply foregoing -f on autossh and using --background on the start-stop-daemon. Apparently this also necessitates the -N flag on autossh, which is as best I can tell undocumented.
Could be a new development or upstream issues, but in any case the answer by OP did not work for me, but this did:
start-stop-daemon --start --background --user myuser --quiet --make-pidfile --pidfile "/var/run/myhost_autossh.pid" --exec autossh -- -M 0 -N myhost
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34094792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What data structure should I use to keep track of recently used items? I need something like a bounded queue where I can only insert say 10 elements. A new element should override the last inserted element. There should be only n distinct elements
I am looking for suggestions in Java by the way.
A: ITYM an implementation of a LRU algorithm.
*
*How to set up a simple LRU cache using LinkedHashMap
*Simple LRU Caching with Expiration
A: This is a classic application for a queue data structure. A stack of size 10 would keep track of the first 10 elements you added to it, whereas a queue of size 10 would keep track of the 10 most recent elements. If you are looking for a "recent items" list, as suggested by the title of your question, then a queue is the way to go.
edit: Here is an example, for visualization purposes:
Let's say you want to keep track of the most recent 4 items, and you access eight items in the following order:
F, O, R, T, Y, T, W, O
Here is what your data structures would look like over time:
access item queue stack
1 F [ F . . . ] [ . . . F ]
2 O [ O F . . ] [ . . O F ]
3 R [ R O F . ] [ . R O F ]
4 T [ T R O F ] [ T R O F ]
5 Y [ Y T R O ] [ Y R O F ]
6 T [ T Y T R ] [ T R O F ]
7 W [ W T Y T ] [ W R O F ]
8 O [ O W T Y ] [ O R O F ]
Removing the top element from a stack removes the item that was most recently added, not the oldest item.
Removing one element from a queue removes the oldest item, so your queue will automatically hold the most recent items.
edit: with thanks to Adam Jaskiewicz, here is some documentation on Java's Queue implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/685811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: React unit testing Leaflet I have problem with unit testing Map component.
My class component:
componentDidMount() {
const { zoom, data, center } = this.props;
const { activeButton } = this.state;
if (data[activeButton] != null) {
this.map = map('map', {
center: data[activeButton].points ? data[activeButton].points[0] : center,
zoom,
layers: [tileLayer(...SETTINGS.mapTileLayer)],
});
if (data[activeButton].points != null) {
this.addPolyline(data[activeButton].points);
}
}
}
addPolyline = (points: Points) => {
if (this.polyline != null) {
this.map.removeLayer(this.polyline);
this.map.removeLayer(this.marker.start);
this.map.removeLayer(this.marker.stop);
}
if (points != null && points[0] != null) {
this.polyline = new Polyline(points, SETTINGS.polyline);
this.marker.start = new Marker(points[0]);
this.marker.stop = new Marker(points[points.length - 1]);
this.polyline.addTo(this.map);
this.marker.start.addTo(this.map);
this.marker.stop.addTo(this.map);
this.map.panTo(points[0]);
}
};
Unit test with Jest and Enzyme
function getComponent(mockData) {
return <Map data={mockData} />;
}
const mockData = [
{ id: 0, name: '1', distance: '1', points: [[0, 0], [1, 1]] },
{ id: 1, name: '2', distance: '2', points: [[0, 0], [1, 1]] },
];
describe('LastActivity component', () => {
it('button click', () => {
const wrapper = mount(getComponent(mockData), { attachTo: document.body });
...etc...
});
With this test I get
TypeError: Cannot read property '_layerAdd' of null
this.polyline.addTo(this.map);
When I comment out line this line
this.polyline.addTo(this.map);
Everything works fine and tests pass
package.json:
"enzyme-adapter-react-16": "1.2.0",
"enzyme": "3.4.4",
"react": "16.4.2",
"react-dom": "16.4.2",
"leaflet": "1.3.4",
"jest": "23.5.0",
"jest-cli": "23.5.0",
A: I see a bunch of related issues on leaflet's github. The maintainer seems to have something against frameworks.
Check out https://react-leaflet.js.org/ that should work better with react.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52192422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Service is not running when OS is upgraded from Windows 8.1 to Windows 10 We have upgraded windows from 8.1 to 10.
Now in Windows 10 services installed by us are not running.
The same services are running properly if we install these services on Windows 8.1.
ON windows 10, we tried below things which didn't solve the problem.
*
*services-> select service -> properties -> Set [Log on] as LOCAL SERVICE
*Set full permission to "perticuler" user or "everyone" user for the folder where service files exist.
*Change owner of folder as "everyone", "system" or "perticuler" user where service files exist.
Below is a workaround which works but not feasible for us since it requires password and actually we want to know the actual reason behind this problem.
workaround :
1. services-> select service -> properties -> Set [Log on] as "This account" where user can be selected and it also requires password. Refer attached image.
Please note that the service is a dot net(c#) service and it runs internally a jar file. if it is able to run jar file then only service starts successfully.
Thanks in advance
A: I have found the cause and solution.
[Cause of problem]
Service unable to understand that, to run JAR file, which program should be run.
[Detail]
I tried to debug the code.
At the location where process is started, popup message like shown in below image is occurred.
location : processSample.Start()
*
*It means that atleast once user need to select the program.
*If we select [Java(TM) Platform SE binary] once, then after that the
service always runs successfully.
*This behavior is in Windows 10 only.
*In addition to program selection, user setting shown in image in question is also required to run the service.
*I want to say that, in default program setting already correct program is selected for .jar files as shown in below image, but still windows 10 asks user to select program once.
[Solution]
Run JAR file from windows(c#) service with settings below :
sampleProcess.StartInfo.FileName = "javaw.exe";
sampleProcess.StartInfo.Arguments = "-jar Sample.jar";
sampleProcess.StartInfo.WorkingDirectory = @"C:\SampleFolder";
sampleProcess.StartInfo.UseShellExecute = false;
sampleProcess.EnableRaisingEvents = true;
sampleProcess.StartInfo.CreateNoWindow = false;
Here working directory is the location where the [Sample.jar] does exist.
additinally a Path environment variable must be set in order to execure "javaw.exe".
Before fix I had implementation as below which is not proper for every system environment :
sampleProcess.StartInfo.FileName = "Sample.jar";
sampleProcess.StartInfo.WorkingDirectory = @"C:\SampleFolder";
sampleProcess.EnableRaisingEvents = true;
sampleProcess.StartInfo.CreateNoWindow = false;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36035082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: "CORS: No 'Access-Control-Allow-Origin' header is present ", but it is present I'm trying to log in or register in my Angular app, but whenever I access to the php file which does the HTTP calls to the DB regarding users (authentication.php), I get three errors:
*
*Access to XMLHttpRequest at 'http://localhost/authentication.php?command=login' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
*ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost/authentication.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost/authentication.php: 0 Unknown Error","error":{"isTrusted":true}}
*GET http://localhost/authentication.php?command=login net::ERR_FAILED
(The last one says GET for login, POST for register)
In authentication.php I have the following code regarding headers:
require "openDB.php";
include "validators/usuarioValidator.php";
In openDB.php:
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');
In validators/usuarioValidator.php:
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');
I've tried writing those headers in authentication.php, adding OPTIONS to Allow-Methods and allow all origins with *, but I still get the same three errors.
My user.service.ts has the following code regarding these operations:
register(user : any, key : string) : Promise<any>{
let parametros = new HttpParams().set("command", "register");
user.verif = key;
return this.http.post(this.url, user, {params: parametros}).toPromise();
}
(I'm just pasting register because login is a bit weirdly done and the problem here seems to be with authentication.php, no matter what operation it makes)
I've also tried adding withCredentials: true and responseType: "blob" to params since I'm not receiving a json in the TS, but still nothing.
A: It seems like you are not setting Headers properly in your HTTP Request body, try the following code,
register(user : any, key : string) : Promise<any>{
let parametros = new HttpParams().set("command", "register");
user.verif = key;
return this.http.post(this.url, user, {Headers: parametros}).toPromise();
}
Also, if you use the HTTPClient package to make requests then it's a bit hard to set custom headers.
If you can prevent some issues (like CORS Access-Control Errors) by using axios or a similar package
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66291989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VHDL - Error comparing std_logic_vector with declared constant unsigned? The unsigned has been cast to std_logic_vector I am trying to create a Seven Segment Display controller in Vivado 2020.2 using VHDL 2008. The entity needs to be parametrizable by system clock rate and time to display each digit in the display (there are 8 digits). Here is the code I have so far:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.numeric_std_unsigned.all;
entity SevenSeg is
generic (
-- Rate in HZ
CLK_RT : integer := 100000000;
-- Time in ms
DISPLAY_TIME : integer := 20
);
port (
clk : in std_logic;
rst : in std_logic;
dataIn : in std_logic_vector(31 downto 0);
digitDisplay : in std_logic_vector(7 downto 0);
digitPoint : in std_logic_vector(7 downto 0);
anode : out std_logic_vector(7 downto 0);
segment : out std_logic_vector(7 downto 0)
);
end SevenSeg;
architecture rtl of SevenSeg is
constant ROLL_OVER : unsigned := to_unsigned(20 * 1000000 / (1000000000 / CLK_RT), 32);
signal cnt : std_logic_vector(31 downto 0);
signal anode_sel : std_logic_vector(2 downto 0);
begin
process (clk)
begin
if (clk'EVENT AND clk = '1') then
if rst = '1' then
anode_sel <= (others => '0');
else if cnt = std_logic_vector(ROLL_OVER) then
anode_sel <= anode_sel + 1;
end if;
end if;
end process;
end rtl;
With the current state of the code, Vivado is flagging a syntax error "near end process." I am pretty sure something is wrong with cnt = std_logic_vector(ROLL_OVER) because when I comment that part of the if clause out, there is no longer any syntax errors. I have been researching comparisons in vhdl as well as the constant unsigned/vector types and nothing seems to be working. I would appreciate any insight into what is causing this error.
A: There are two alternatives, either with elsif:
if rst = '1' then
anode_sel <= (others => '0');
elsif cnt = std_logic_vector(ROLL_OVER) then
anode_sel <= anode_sel + 1;
end if;
or: else if
if rst = '1' then
anode_sel <= (others => '0');
else
if cnt = std_logic_vector(ROLL_OVER) then
anode_sel <= anode_sel + 1;
end if;
end if;
A: You are not following standard VHDL. The else if is introducing a new if condition which requires an additional end if to be correct syntax. You could use elsif instead and your code would not generate errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69807166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which is better to use for Google Assistant? Actions SDK or JSON request response I have built multiple actions on Google Assistant using the JSON request and response V2 but I have heard that using Actions SDK for building actions specifically for Google Assistant should be preferred. I am confused whether to use Actions SDK or JSON request response?
For example - On this link, for every sample code there are two tabs, Node.js using Actions SDK and JSON using the JSON request response.
Which one should be preferred and in which scenarios?
Thanks!
A: Let's first look at what those tabs mean, and then discuss what your best approach should be.
node.js vs JSON tabs
The "node.js" tab shows what the code looks like using the actions-on-google library. For the most part, this library uses the same code if you're using either the Action SDK or using Dialogflow to implement. Where there are differences, the documentation does note how you have to handle them - this is particularly true when it comes to how you have to handle responses.
The "JSON" tab shows what the JSON would look like if you are not using the actions-on-google library and need to send JSON yourself. You might do this because you're using a language besides node.js, or you just want to know what the underlying protocol looks like.
The catch is that the JSON illustrated here is what would be used by the Action on Google JSON protocol. If you're using Dialogflow, then this JSON would be wrapped inside the payload.google field and there are a couple of other differences documented. So when generating JSON for a Dialogflow response, you should use this as a guide, but need to be aware of how it might differ.
What should you use?
What you use depends on what your needs are and what your goals are for developing.
If you are trying to develop something you intend to release, or might do so someday, and you are new to voice or bot interfaces, then you'll probably want to use Dialogflow - no matter what other choices you may make.
If you have your own Natural Language Processing (NLP) system, then you will want to use the Action SDK instead of Dialogflow. How you handle it (using the actions-on-google library or using JSON) will depend on how you need to integrate with that NLP.
If you're familiar with node.js, or want to learn it, then using the actions-on-google library is a good choice and that first tab will help you. (There are other choices. Dialogflow also has a dialogflow-fulfillment library, which is good if you want to be able to support the bot platforms it supports as well. The multivocal library has a more configuration-driven template approach to building a conversational backend that was designed to work with the Assistant and Dialogflow. Both of these illustrate how to do the same things that Google's documentation does.)
If you would rather use another language, you'll need to reference the JSON documentation because there are few complete libraries for these platforms. Your best bet would be to use Dialogflow with JSON. Dialogflow has some example JSON for how to apply the Google documentation you cite to their fulfillment protocol.
Summary
*
*You should probably use Dialogflow.
*If you can, use actions-on-google or another library.
*If you have a need to use another language or want to use the JSON, be aware of the possible differences.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51745709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Retain color of Switch when disabeld I am using a Switch in xamarin forms. When I toggle, the color is Pink when true and grey when false.
When I disable the switch as I do not want the user to toggle. then the color change to Grey.
How can i retain the color of the Switch. When it is disable and it is true it should be in default color but not grey,
Could you please suggest how can i achieve this.
<Switch IsToggled="True" IsEnabled="False"/>
Thanks
Rao
A: I have investigated a bit this problem and I can see two solutions:
Easy way
Use a private boolean variable instead of using the IsEnabled property. Then when the clicked event is handled, check the switch's status with the variable.
Hard way
Overwrite the Switch control to get this behaviour. You can follow this guide.
A: As seen from the Switch for Xamarin.Forms, there is currently no option of specifying the color. Conclusively, you will have to create your own renderer for both iOS and Android.
Android
Essentially, what you need to do is to override the OnElementChanged and OnCheckChanged events and check for the Checked Property of the Control. Afterwards, you can set the ThumbDrawable of the Control and execute SetColorFilter with the color you want to apply. Doing so although requires Android 5.1+. An example is given here.
You could also create utilise the StateListDrawable and add new ColorDrawables for the StateChecked, StateEnabled and lastly, a default value as well. This is supported for Android 4.1+. An example of using the StateListDrawable is provided in detail here.
iOS
iOS is somewhat more simple. Simply create your own SwitchRenderer, override the OnElementChanged event and set the OnTintColor and ThumbTintColor.
I hope this helps.
A: You need to make custom renderer for your control in this case switch like that and set color when it changes:
class CustomSwitchRenderer : SwitchRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)
{
base.OnElementChanged(e);
this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);
this.Control.CheckedChange += this.OnCheckedChange;
}
private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44738802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parsing error: Unexpected token, expected "," in react.js I write This code in react.js
function Sidebar() {
const [rooms, setRooms] = useState( [] );
useEffect(() => {
db.collection("rooms").onSnapshot((snapshot)
=>
setRooms(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
})
))
);
}, []);
And it shows error:
./src/Sidebar.js
Line 17:9: Parsing error: Unexpected token, expected ","
15 | useEffect(() => {
16 | db.collection("rooms").onSnapshot((snapshot)
> 17 | =>
| ^
18 | setRooms(
19 | snapshot.docs.map((doc) => ({
20 | id: doc.id,
A: As Luis pointed out in comment moving => right after (snapshot) will solve the issue. Just to add use some kind of IDE. VSCode is recommended IDE for React development) but you can use any other IDE and setup eslint, prettier and autoformatonsave options so that you don't have to spend too much time in fixing these type of issues. Here is great tutorial to setup VSCode with all extensions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63661383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL How to select distinct value from multiple fields In the database(of tutor profiles), each tutor can teach up to 3 subjects, hence I've created 3 fields--Subject1,Subject2 & Subject3-- for each tutor. In my case, I would like to retrieve each specific subject within the 3 fields and add them to my combo box in my program for a criteria searching function.
Initially, I used the following code for 3 different fields :
Dim sqlSubjectComboBox As String = "SELECT DISTINCT [TutorSubject1] FROM tblTutor"
Dim cmdSubjectComboBox As New OleDbCommand(sqlSubjectComboBox, myConnection)
dr = cmdSubjectComboBox.ExecuteReader
While dr.Read()
cbSubject.Items.Add(dr("TutorSubject1").ToString)
End While
However, I realised that this sql statement will create a logic error if a same subject is placed in different field for different tutor.
Ex : Tutor A has the subject 'Chemistry' on his field Subject1. While for Tutor B, he has the same subject 'Chemistry' on field Subject2. In the end, the combo box has two 'Chemistry'.
I had spent almost a day to figure this out but to avail, partly due to my subpar programming skill and lack of experience. Hopefully someone can help me out, thanks in advance!
A: You can use the UNION operator to get the distinct list of subjects.
select TutorSubject1 FROM tblTutor where TutorSubject1 is not null
union
select TutorSubject2 FROM tblTutor where TutorSubject2 is not null
union
select TutorSubject3 FROM tblTutor where TutorSubject3 is not null
The important point here is that the UNION operator removes duplicates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29031891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to “flatten” or “collapse” a 1D mysql table into 2D? I have a table like this:
id - name - value
1 - shoes - 21
1 - gloves - 5
2 - shoes - 23
2 - gloves - 3
I want it to be converted to a table like this:
id - shoes - gloves
1 - 21 - 5
2 - 23 - 3
Is it possible to do it with one query in Mysql?
I also want the name of columns to be generated from the name column in the 1st table.
A: You may try to use join like this:
SELECT main.id, s.name AS shoes, g.name AS gloves
FROM tbl AS main
LEFT JOIN tbl s ON main.id = s.id
LEFT JOIN tbl g ON main.id = g.id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52721209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C function with pointer of points wrapping I have a method define in C/C++ DLL that takes 2 args
void SetLines(char** args,int argCount);
I need to call it from Python, what is the proper way to do so.
from ctypes import *
path="test.dll"
lib = cdll.LoadLibrary(path)
Lines=["line 2","line 2"]
lib.SetLines(Lines,len(lines))
print(code)
Excuting the Python code gives the following error:
Traceback (most recent call last):
File "<test.py>", line 6, in <module>
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1
A: After some code digging I figure it out:
any C/C++ parameter that accepts a pointer to a list of values should be wrapped in python with
MyType=ctypes.ARRAY(/*any ctype*/,len)
MyList=MyType()
and filled with
MyList[index]=/*that ctype*/
in mycase the solution was:
from ctypes import *
path="test.dll"
lib = cdll.LoadLibrary(path)
Lines=["line 1","line 2"]
string_pointer= ARRAY(c_char_p,len(Lines))
c_Lines=string_pointer()
for i in range(len(Lines)):
c_Lines[i]=c_char_p(Lines[i].encode("utf-8"))
lib.SetLines(c_Lines,len(lines))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30365831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I properly ask (or search google) for help aggregating objects from different db models? I'm trying to list objects from two different mongoDB database models on the same index page. Right now I have them split on two different index pages because I didn't think this through ahead of time.
The problem is I don't even know how to search the request above on google or within the bootstrap docs (I'm using bootstrap on the front end). I keep getting different "modals" instead of models and I'm at the end of my programming vocabulary (it's very limited).
Can you help me reword my question in the correct terminology, please?
A: I assume you are asking about the MongoDB aggregation pipeline. This is a server feature and if you haven't already, you should at least read this page to get a basic understanding of what it is from the server's standpoint.
Next, if you haven't done this already, you should install mongo shell and get it working on your machine, and try executing some simple operations (such as an insert and a find), after which you should run the various aggregation examples in the mongo shell to familiarize yourself with the feature.
After this, review your MongoDB driver documentation for how to work with the aggregation pipeline. For Ruby driver for example, this is documented here. You'll note that the syntax is different from the mongo shell examples. If you are using node.js, the syntax will also be different from mongo shell examples even though both your driver and mongo shell use javascript.
If you aren't using a driver directly but are using a higher level library such as an ODM (e.g. Mongoose), there may be yet another way of executing aggregation with its own syntax provided by that library. You may not need to know how driver aggregation works if you are using an ODM, but you may find that the ODM doesn't implement some feature that the driver implements (and MongoDB documentation references).
The reason why I suggest doing all of this is that when you are constructing aggregation pipelines, you almost always need to do so as the aggregation pipeline stages, operators and expressions are documented for the server, even if you are using a much higher level library to execute the aggregation or generally interact with your database.
Once you understand how the aggregation pipelines are executed and how to construct them, use your application schema to construct the appropriate queries. There generally isn't comprehensive documentation for aggregation pipeline beyond the official MongoDB docs, due to the size of the aggregation pipeline as a feature. You are generally on your own as far as actually constructing the pipelines for your application in the language/framework that you are using.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68293719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overriding the Copy-Paste capability under Windows OS? I'm pretty sure that's a very difficult task. Did anyone out there know how we can overrides the copy-paste capability under Windows OS?
(Overriding for the complete environment... patching the Windows OS itself.)
Ex : Trim the copied text after copying it.
Thank you.
A: It is highly unlikely that you actually need to patch the OS itself, considering that Windows always provides the ability to hook on the clipboard events directly and override them however you wish. See How to get a clipboard paste notification and provide my own data? .
A: Yes, but you haven't specified the language. Here's how you might in VB.NET (put this in a Timer's Tick handler):
If Clipboard.ContainsText() Then
Dim s As String = Clipboard.GetText()
Dim t As String = s.Trim()
If s <> t Then Clipboard.SetText(t) 'Trim all text, for example
End If
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5735626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any solution to know when specific application was maximized and viewed? (windows 11) I need track some historical logs of events when specific software as maximized and closed.
On this case I need the informations about when and how long a .doc file was viewed.
example:
2022-12-12 08:35:59 - Maximized for 35 seconds
2022-12-12 08:47:35- Maximized for 567 seconds
Do we have any solution for that? I already check in windows event viewer. But there's a bunch of log information there. I don't know how to filter... Do we have a ready to use software? or any straightforward procedure?
Thanks in advance!
I went to some options, but it's very complicated to get a linear procedure.
*Event Viewer
*Local Group Editor>Audit object access
*Software advanced security options>auditing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75048564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Defender flag some JSON output file from Trivy as Backdoor:PHP/Remoteshell.V I'm working on a project where I parse some YAML configuration files in Java, then forge a command to send to a processbuilder which calls Trivy, performs the required scans and then print out two files, one in JSON and one in HTML.
With most of the config files it works great, but with one of them, multiple JSON output files are flagged as Backdoor:PHP/Remoteshell.V by Windows Defender, so it puts them in quarantine and it stops the execution of the rest of my program because the paths don't exist anymore.
Sadly, I can't share the exact Trivy call because it is done on private Docker images that require access, but I can share some of the flagged JSON files if needed.
I tried scanning it with other malware detection software such as Gridinsoft and Zemana, but they don't detect anything.
I'm using IntelliJ IDE for this project and running it with Quarkus on a Windows computer, but I execute the Java program on WSL on a 20.04 Ubuntu because Trivy can't run on Windows.
I hope someone can help me on this issue as it is blocking me on my project, obviously I could just manually exclude the project file from the scan, but this is not a viable long term solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71996655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I convert a 12-bit integer to a hexadecimal string in C#? I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.
Example:
2748 to "ABC"
A: try
2748.ToString("X")
A: If you want exactly 3 characters and are sure the number is in range, use:
i.ToString("X3")
If you aren't sure if the number is in range, this will give you more than 3 digits. You could do something like:
(i % 0x1000).ToString("X3")
Use a lower case "x3" if you want lower-case letters.
A: Note: This assumes that you're using a custom, 12-bit representation. If you're just using an int/uint, then Muxa's solution is the best.
Every four bits corresponds to a hexadecimal digit.
Therefore, just match the first four digits to a letter, then >> 4 the input, and repeat.
A: The easy C solution may be adaptable:
char hexCharacters[17] = "0123456789ABCDEF";
void toHex(char * outputString, long input)
{
outputString[0] = hexCharacters[(input >> 8) & 0x0F];
outputString[1] = hexCharacters[(input >> 4) & 0x0F];
outputString[2] = hexCharacters[input & 0x0F];
}
You could also do it in a loop, but this is pretty straightforward, and loop has pretty high overhead for only three conversions.
I expect C# has a library function of some sort for this sort of thing, though. You could even use sprintf in C, and I'm sure C# has an analog to this functionality.
-Adam
| {
"language": "en",
"url": "https://stackoverflow.com/questions/142813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why Toast.makeText and not new Toast This is may be a noob question, but I was wondering why do we have to use a static method (makeText) to create a Toast and not a constructor.
Why do we have to use this:
makeText(Context context, CharSequence text, int duration)
instead of this:
new Toast(Context context, CharSequence text, int duration)
This is the makeText method:
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
Why don't we have the following:
public Toast (Context context, CharSequence text, int duration) {
this(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
this.mNextView = v;
this.mDuration = duration;
}
I searched the web and source code for any reason but I didn't find.
Please if you have an idea, don't hesitate.
A: The question basically drill downs to when should I make a method static. The answer is simple- when your method has a very specific task and does not change the state of the object.
Something like a utility method, say add(int a, int b) which simply returns a+b. If I need to store the value a+b for later use for the object, static method is strictly no-no (you will not be able to store a non static variable in a static method). But if we are dealing with some action which is independent of state of the object, static is the answer.
Why are we giving preference to static if it is independent of state of object?
*
*Memory- static method will only have one copy, irrespective of the actual number of object.
*Availability- Method is available even if you don't have single object
Ofcourse the downside is that we are keeping a copy of method even if we do not use it at all (if it was non-static and no object was created, we would have saved this space). But this is of lower weight than the advantages mentioned above.
As the method we are discussing here (makeText), does not need to maintain a state for later use, the best way to go is static method.
--Edit--
The answer mentioned above is more generic as to when we should use static and when non-static, let me get specific to Toast class.
Toast class gives us 2 ways to create a Toast object (Refer http://developer.android.com/reference/android/widget/Toast.html)
*
*makeText(Context context, CharSequence text, int duration) which returns a Toast object which the values assigned.
*Normal way, use new Toast(context) to create an object, then set values as required.
If you use method 1, you are saying something like Toast.makeText(context, text, duration).show(); and we are done. I use this method all the time.
Method 2 is used only for a specific case, from http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Do not use the public constructor for a Toast unless you are going to
define the layout with setView(View). If you do not have a custom
layout to use, you must use makeText(Context, int, int) to create the
Toast.
@CFlex, If I got your question properly, I guess you just want to know why we have Toast.makeText(context, text, duration) returning a Toast object, when the same thing could have been done by a constructor.
Whenever I look at something like ClassName.getObject returning object of class, I think about singleton pattern. Well, in this case we are not exactly talking about singleton, I would like to assume that makeText returns same object always (to save creation of N objects), otherwise it is just a fancy thing developed by Android team.
A: One rule: Ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
Remember that objects live in memory and they are created for certain jobs. Static methods are available for all the objects in a class and it is not necessary to create an object to use them.
So there is no reason to create an object Toast to be able to access the method makeText, when you can access it as a static method (more elegant and compact)
A: As far as I know:
That's because we don't wish to hold an instance of the object toast, which would require an amount of memory persistently used until cleaned by the GarbageCollector.
And that it always have access to being displayed, so it is not required by your application to have any set of permissions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11718171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Elasticsearch get documents where a property is not empty If I want to return all the documents which have an empty property (IMG) I can do something like that:
GET something/_search/?
{
"query": {
"term": {"IMG": ""}
}
}
It works because IMG is a keyword. If I want the exact inverse, which means get all the documents where IMG is not null, what should I type? Is there an "inverse" of term query?
In other words, is there a way with Elasticsearch to get documents where a property is not empty?
A: Your solution above would also return documents where the field is null, which you don't want I guess. So the correct solution would be this one:
GET memoire/_search/?
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "test"
}
},
"must_not": {
"term": {
"test.keyword": ""
}
}
}
}
}
A: Here is a solution. Use must_not with term query. This should work:
GET memoire/_search/?
{
"query": {
"bool": {
"must_not": {
"term": {"IMG.keyword": ""}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52333658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to check date of birth is keyed in i would like to know how to check if user has entered their date of birth in the registration form. The day and month are in a drop down list and the year is in text box form.
<b>Date of birth</b>
<select name="day" id="dobday">
<option value="na">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="dobmonth" id="dobmonth">
<option value="na">Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>`
<input type="text" name="dobyear" title="dobyear" style="color:#888;"
value="year" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
I would also like to input the function when user click on certain month, the date checks accordingly . Like the 30 , 31 and ,28 on certain months (:
Only using html or php.
A: Use Jquery to change the date according dropdowns on change of month.
myjsonarray is array as following,
{ "january":{"1","2","3" .... "31"}, "February":{"1","2"..."29"}, ... }
According to the months ...
jQuery(document).ready(function(){
prevhtml = jQuery("#dobday").html();
});
function changedays(){
var selected = jQuery("#dobmonth option:selected").text();
if(myjsonarray[selected]){
jQuery.each(myjsonarray[selected], function( index, value ) {
html +="<option value=\""+index+"\">"+value+"</option>";
});
}
if(!myjsonarray[selected]) html=prevhtml;
jQuery("#dobday").html(html);
}
Also change your select statement as
<select name="dobmonth" id="dobmonth" on-change="changedays()">
A: you can use HTML5's required attribute:
<input type=text required/>
<select required></select>
Although it's not fully supported by some older browsers
FIDDLE
UPDATE
You need to add required and for selects you need to set the first option to a blank value like so:
<option value="">Month</option>
NEW FIDDLE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27716072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How can I smoothly scale the layer in IOS to keep an object on screen? I'm working on a game where a ball is hit, and can leave the visible area of the layer. I'm setting the position of the ball each frame, as I get feedback from Box2D about its location. When the ball nears the edge of the screen, I want to zoom out just the right amount to keep the ball visible. Can someone give me a hand with the logic to do this? Thanks.
A: Let's have the size of the screen size of 480 (pixels), with the original diameter of the ball being 10 pixels.
Original size of ball = bOriginal = 10
Distance represented by screen = s = 480
Distance ball has travelled = x
Diameter of the ball = b = bOriginal
You would have a flag for when the ball reaches a certain distance from the edge of the screen. After which you have your velocity, which you already know; this can also be thought of as the rate the ball is moving towards the edge of the screen, therefore the rate at which the screen must expand with respect to the size of the ball to ensure the total distance the ball has travelled is included within the size of the screen.
If x >= 475
ratio of screen size to distance = r = 480 / (x+5)
b = bOriginal * r
end
This will demonstrate a "zoom-out" in that the ball will get continually smaller to ensure that the total distance travelled fits into the size of the screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7181109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PostgreSQL 9 JDBC driver returns incorrect metadata for stored procedures I am on a team that develops a business intelligence (reporting) tool.
We report off many sources include Stored Procedures.
We use the meta-data provided by the JDBC driver to determine the input and output paramters of a Stored Procedure.
It appears that PostgreSQL 9 JDBC drivers are incorrectly returning meta-data for the parameters of a procedure.
For instance my stored procedure looks like this:
CREATE FUNCTION person(personid int)
RETURNS TABLE(person int, name varchar(200)) AS $$
BEGIN
RETURN QUERY SELECT ipperson, firstname FROM person
WHERE ipperson = personid;
END;
$$ LANGUAGE plpgsql;
So it has one paramter in, two columns returned in a resultset.
The PostgreSQL driver is reporting that there are 3 IN parameters.
*
*personid (the parameter)
*person (first column returned)
*name (second column returned)
with no meta-data to distinguish between types.
I execute this with:
SELECT * FROM person(?);
(As a prepared statement, setting values for each ? token)
I know that I can filter using the columns returned like this:
SELECT * FROM person(5) where person = 5;
But I am more interested in getting only the parameters returned by the meta-data, so I can programmatically build the query string (I need to know how many ?'s to put in the query).
Not sure if this is a bug, or whether I am doing something wrong.
If I use a PostgreSQL 8 driver, it seems to return the correct number of parameters:
*
*personid (the parameter)
Thanks.
Specific Driver/Server versions are:
*
*PostgreSQL Server 9.11 (Mint 16)
*PostgreSQL "8" 8.0 JDBC3 with SSL(build 313)
*PostgreSQL "9" 9.3 JDBC4 (build 1100)
Additional Information to replicate what I am seeing:
DB Scripts:
CREATE TABLE testtable (
id integer,
name varchar
);
INSERT INTO testtable VALUES (1, 'Bob');
CREATE FUNCTION testproc(itemid int)
RETURNS TABLE(id int, name varchar(200)) AS $$
BEGIN
RETURN QUERY SELECT ipperson, firstname FROM testtable
WHERE id = itemid;
END;
$$ LANGUAGE plpgsql;
Java Code:
package com.hof.unittest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class TestPostgres {
public static void main(String args[]) {
try {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb", "admin", "admin");
ResultSet rs = conn.getMetaData().getProcedureColumns(null, null, "testproc", null);
System.out.println("Driver: " + conn.getMetaData().getDriverVersion());
while (rs.next()) {
System.out.println("Parameter Name: " + rs.getString(4) + " Paramter Type: " + rs.getShort(5) + " Data Type: " + rs.getInt(6));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output with different drivers (all against PostgreSQL 9.1.11 server):
Driver: PostgreSQL 8.0 JDBC3 with SSL (build 313)
Parameter Name: returnValue Paramter Type: 5 Data Type: 1111
Parameter Name: $1 Paramter Type: 1 Data Type: 4
Driver: PostgreSQL 9.0 JDBC4 (build 801)
Parameter Name: itemid Paramter Type: 1 Data Type: 4
Parameter Name: id Paramter Type: 1 Data Type: 4
Parameter Name: name Paramter Type: 1 Data Type: 12
Driver: PostgreSQL 9.3 JDBC4 (build 1100)
Parameter Name: itemid Paramter Type: 1 Data Type: 4
Parameter Name: id Paramter Type: 1 Data Type: 4
Parameter Name: name Paramter Type: 1 Data Type: 12
Note that the 8.0 Driver flags the return value as Type 5 .. all other drivers flag the 2nd and 3rd paramters as Type 1.
Obviously the PostgreSQL 8 driver is JDBC3 and the others JDBC4. If this is the reason that the results are different then that's great.. but I still want to distinguish between an actual input paramter and output parameter.
A: There was a issue in the PostgreSQL JDBC driver. Building the driver from the lastest PostgreSQL JDBC driver source code returned the correct meta-data for the Stored Procedure.
Driver: PostgreSQL 9.4 JDBC4.1 (build 1200)
Parameter Name: itemid Paramter Type: 1 Data Type: 4
Parameter Name: id Paramter Type: 5 Data Type: 4
Parameter Name: name Paramter Type: 5 Data Type: 12
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21541745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: python: how to to make iter_loadtxt ignore lines with errors I am using iter_loadtxt as seen on stack overflow to load > 600MB text files. Occasionally the program generating the files make a bad write to the text file and iter_loadtxt barfs:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "jpk_outfile_to_LOG_timeV4.py", line 296, in makeLOGtimefile
a=readjpk(filename,lateral,vertical,xpos)
File "jpk_outfile_to_LOG_timeV4.py", line 107, in readjpk
a=iter_loadtxt2( filename,delimiter=" ",skiprows=7)
File "jpk_outfile_to_LOG_timeV4.py", line 58, in iter_loadtxt2
data = np.fromiter(iter_func(), dtype=dtype)
File "jpk_outfile_to_LOG_timeV4.py", line 55, in iter_func
yield dtype(item)
*605.6998r: invalid literal for float(): -1.5005492E-5
My solution is to try and add an exception that replaces the dtype, but this doesn't work. any suggestions?
#==============================================================================
# credit to joe kington on stackoverflow:
# https://stackoverflow.com/questions/8956832
#==============================================================================
def iter_loadtxt2(filename, delimiter=' ', skiprows=6, dtype=float):
def iter_func():
with open(filename, 'r') as infile:
for _ in range(skiprows):
next(infile)
for line in infile:
line = line.rstrip().split(delimiter)
for item in line:
# added try/except/else to this loop, originally only had yiled dtype(item)
try:
yield dtype(item)
a=dtype(item)
except:
print "fail"
else:
yield a
iter_loadtxt.rowlength = len(line)
data = np.fromiter(iter_func(), dtype=dtype)
data = data.reshape((-1, iter_loadtxt.rowlength))
return data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19060820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MongoDB Stitch throwing anon-user error I am using mongodb's stitch backend to run an application, and when I try to login as an anonymous user, it throws this error:
failed to log in anonymously: { StitchError: authentication via 'anon-user' is unsupported
at /*****/*****/*****/****/node_modules/mongodb-stitch/dist/node/common.js:29:19
at
at process._tickCallback (internal/process/next_tick.js:160:7)
name: 'StitchError',
response:
Body {
url: '*****',
status: 401,
statusText: 'Unauthorized',
headers: Headers { _headers: [Object] },
ok: false,
body:
Gunzip {
_readableState: [ReadableState],
readable: false,
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object],
bytesRead: 81,
_handle: null,
_hadError: false,
_writeState: [Uint32Array],
_outBuffer: ,
_outOffset: 57,
_level: -1,
_strategy: 0,
_chunkSize: 16384,
_flushFlag: 0,
_scheduledFlushFlag: 0,
_origFlushFlag: 0,
_finishFlushFlag: 4,
_info: undefined },
bodyUsed: true,
size: 0,
timeout: 0,
_raw:
[ ],
_abort: false,
_bytes: 57 },
json: { error: 'authentication via \'anon-user\' is unsupported' } }
Items marked with ***** were removed for privacy.
I have anonymous authentication enabled in Stitch Admin Console, but it still throws this error. My app is not even able to perform any operations on the database before this happens, so I know it does not have to do with my app's Rules.
Is there something I don't know about anonymous auth?
If you know where the mongodb error reference is, that would help as well.
Thanks
A: FROM
https://github.com/Spaceface16518/Converse/issues/22
"I think you have to deploy it in the deploy session"
A: First you must allow anonymous login
Allow Users to login anonymously
Click on the review and deploy changes at the top of the stitch UI
Review and deploy changes
A: You need to go Stitch Apps > Users > Providers > Allow users to login anonymously and enable that option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49143526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to convert a string to date format when downloading an excel file using python My aim and the difficulty found on that is to convert my Date column data in excel from Number format to Date format.
In my python snippet the variable holding the date is type of string.
current_date=datetime.today().strftime('%-d/%-m/%Y')
So far so good, but when I download my excel file and access the cell with the date data the Format Cells recognize the format as Number(I am not sure if this statement worths mentioning).
Anyway, I want the date data to be of format Date and not the format of Number
How can i do it?
Here is my code:
# content-type of response
response = HttpResponse(content_type='application/ms-excel')
#decide file name
response['Content-Disposition'] = 'attachment; filename="export.xls"'
#creating workbook
wb = xlwt.Workbook(encoding='utf-8')
#adding sheet
ws = wb.add_sheet("export")
# Sheet header, first row
row_num = 0
#style
font_style = xlwt.XFStyle()
font_style.font.bold = True
#date(string)
current_date=datetime.today().strftime('%-d/%-m/%Y')
...
ws.write(row_num,1,current_date)
I read that xlrd library could help on that but I didn't manage to use it properly.
A: The answer is based on the usage of xlsxwriter library.
With the below snippet of code I finally tried to download the xlsx file and to present my date values in excel as Date format values instead of Number format values used to be by default.
snippet:
from xlsxwriter.workbook import Workbook
from io import BytesIO
# create a workbook in memory
output = BytesIO()
wb = Workbook(output)
ws = wb.add_worksheet('export')
...
current_date = datetime.now()
format2 = wb.add_format({'num_format': 'dd/mm/yy'})
...
ws.write(row_num,1,current_date,format2)
wb.close()
# construct response
output.seek(0)
response = HttpResponse(output.read(), content_type='application/ms-excel')
response['Content-Disposition'] = "attachment; filename=export.xlsx"
return response
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61657472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Not able to get all the data in JSON response from Server I am trying to retrive json data from server. I am using HttpURLConnection for connecting to server.
I am getting response code as 200 and i am also getting some data. But after some data i get garbage value.
Here's my code:
private List<Member> downloadUrl(String myUrl) throws IOException, JSONException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 50537;
try {
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("RESPONSE CODE", "The response is: " + response);
is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
Log.d("baos", "BAOS" + baos);
String JSONResp = new String(baos.toByteArray());
Log.d("JSONR", "JSONR" + JSONResp);
Log.d("JSONR", "JSONR LENGTH" + JSONResp.length());
JSONArray arr = new JSONArray(JSONResp); // <---- EXCEPTION
for (int i=0; i < 5; i++) {
Members.addMember(arr.getJSONObject(i));
Log.d("MEMBER", "MEMBER" + arr.getJSONObject(i));
}
Log.d("MEMBERS", "members error");
return Members.getMembers();
} finally {
if (is != null) {
is.close();
}
}
}
A: InputStream is = null;
try {
is = conn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33318816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get dbeaver to show the caret and table size I am using dbbeaver Version 21.1.2.202107041908 on a mac. Yes.
Once upon a time there would be a ">" next to the word Tables and when I clicked it, all the tables would show with their size in mb next to them. This is no longer the case, instead the caret disappears when I click on it. When I double click public I get all the tables in another window and they're fine. I think I might have accidentally turned this feature off somehow. I've tried searching everything like "autoupdate" or "expand branches" or some such. It would be best to fix this, but short of that, what's the right vocabulary to investigate this issue?
A:
If you have letters above the elephant and it doesn't relate to the name of any object in the folder, the carets will disappear. Can I just also say this was not a feature on pgadmin3 so it's not a solid picnic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68686275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to make table columns with the same width in GitHub markdown? I'm trying to make table with two identical screenshots, but the right column is wider then left one. Moreover, it depends on text in the row below, but I don't clearly understand, how it depends exactly.
Two simple examples:
 | 
:---:|:---:
Usage on GNOME 3 | Drag-and-drop on GNOME 3
 | 
:---:|:---:
Usage on GNOME 3 | Drag and drop on GNOME 3
The same text length, the same words... What's wrong with hyphens and how can I fix it?
A: If the only difference is truly the hyphen, try a different type of hyphen (e.g. an 'actual' hyphen, instead of the minus sign: http://unicode-table.com/en/2010/).
I should say I cannot reproduce this exactly.
The images in my example (left vs. right) are about a pixel or so different, not as much as yours:
A: I had this same issue and was only able to solve it with html. You can add html code directly into the markdown file:
<table width="100%">
<thead>
<tr>
<th width="50%">First header</th>
<th width="50%">Second header long</th>
</tr>
</thead>
<tbody>
<tr>
<td width="50%"><img src="https://docs.github.com/assets/cb-194149/images/help/images/view.png"/></td>
<td width="50%"><img src="https://docs.github.com/assets/cb-194149/images/help/images/view.png"/></td>
</tr>
</tbody>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38787198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Youtube analytics api issue Trying to get the youtube anaytics channel report from this scope:
https://www.googleapis.com/auth/yt-analytics.readonly
and two channel IDs
*
*UC2QjLUbr7XeJpiYgflSuZ-w
*UCH8FFDRgoEtYGm00oqIADUQ
First channel id worked perfectly.
Second id shows me this error (below image), any ideas?
Many Thanks
Forbidden [403] Errors [ Message[Forbidden] Location[ - ]
Reason[forbidden] Domain[global] ]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34647426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Turning a string of a bunch of words into a list with all the words separated So I have a huge string of words separated by spaces and tabs and was wondering what I could do to quickly append each individual word to a list.
EX.
x = "hello Why You it from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']
The string has tabs and multiple spaces varying between words and I just need a quick solution instead of manually fixing the problem
A: You can use str.split:
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>>
Without any arguments, the method defaults to splitting on whitespace characters.
I just noticed that all of the strings in your example list are lowercase. If this is needed, you can call str.lower before str.split:
>>> x = "hello Why You it from the"
>>> x.lower().split()
['hello', 'why', 'you', 'it', 'from', 'the']
>>>
A: str.split() should do it:
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
If you want all lowercase (as @iCodez also points out):
>>> x.lower().split()
['hello', 'why', 'you', 'it', 'from', 'the']
From the link above:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
sep is the first argument of split().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23936000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Error : The support for this usage was removed in Celery 5.0. Instead you should use `--app` as a global option I am having a fastapi when i build container image i was unable to run the celery worker
dockercompose file
version: "3.8"
services:
web:
build: .
ports:
- "8080:8000"
command: uvicorn app.main:app --host 0.0.0.0 --reload
environment:
- CELERY_BROKER_URL=redis://redis:6379/0
- CELERY_RESULT_BACKEND=redis://redis:6379/0
depends_on:
- redis
worker:
build: .
command: celery worker --app=worker.celery --loglevel=info
environment:
- CELERY_BROKER_URL=redis://redis:6379/0
- CELERY_RESULT_BACKEND=redis://redis:6379/0
depends_on:
- web
- redis
redis:
image: redis:6-alpine
dashboard:
build: .
command: flower --app=worker.celery --port=5555 --broker=redis://redis:6379/0
ports:
- 5556:5555
environment:
- CELERY_BROKER_URL=redis://redis:6379/0
- CELERY_RESULT_BACKEND=redis://redis:6379/0
depends_on:
- web
- redis
- worker
I am getting this error You are using --app as an option of the worker sub-command
celery worker --app celeryapp <...>
The support for this usage was removed in Celery 5.0. Instead you should use --app as a global option:
celery --app celeryapp worker <...>
Error: no such option: --app. I am not sure where i am doing wrong
A: The error message tells you what you need to change - the --app parameter has moved from being a parameter to celery worker to being a parameter to celery instead.
Your old command:
celery worker --app=worker.celery --loglevel=info
needs to be changed by moving --app to the left (so that it is a parameter to celery instead):
celery --app=worker.celery worker --loglevel=info
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71908797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Decoding a file with bit-manipulation Constantly getting segmentation fault, and i'm not able to solve this. If the program runs the "encodeFile" - function, the program should be able to read the input file character by character and compress the character of a 2 bit value. The values will then be printed in the output file. I'm very new to this language. How do i solve this task?
//The function
void encodeFile(char *fpInputfile,char *fpOutputfile)
{
FILE *fileInput = fopen(fpInputfile, "r");
FILE *fileOutput = fopen(fpOutputfile, "w");
if (!fileInput || !fileOutput){
printf("ERROR MESSAGE: can not open the selected file \n");
exit(1);
}
char symbols[4];
char encodeB[4] = {0x00, 0x01, 0x02, 0x03};
size_t c = fread(symbols, sizeof(char), 4, fileInput);
while (c != 0){
int i = 0;
int j = 0;
char temp = 0;
while (c > 0){
if (symbols[j] == ' '){
temp = encodeB[0];
}
else if (symbols[j] == ':'){
temp = encodeB[1];
}
else if (symbols[j] == '@'){
temp = encodeB[2];
}
else if (symbols[j] == '\n'){
temp = encodeB[3];
}
else{
}
j++;
i |= temp << (c *2);
c++;
}
//c = fread(symbols, sizeof(char), 4, fileInput);
//fwrite(&temp, 1, 1, fileOutput);
}
fclose(fileInput);
fclose(fileOutput);
}
A: while (c > 0){
...
c++;
}
This is going to cause an infinite loop. The segmentation fault is from reading symbols[4], which is an access violation.
I strongly recommend learning how to step through code in a debugger if you want to use this language. Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26130156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add an object that is added with Ext.create to my Viewport? I'm new using Ext JS and I need to add a button in my Viewport.
I have tried adding it as an item but it doesn't work when I click on it:
items: [ {
xtype: 'datepicker',
width: 211
},
{
xtype: 'datepicker',
width: 211
},
{
xtype: 'button',
text: 'Search',
width: 211
},
],
So then, in the official documentation I have found another way to add it:
Ext.create('Ext.Button', {
text : 'Button',
renderTo : Ext.getBody(),
listeners: {
click: function() {
// this == the button, as we are in the local scope
this.setText('I was clicked!');
},
mouseover: function() {
// set a new config which says we moused over, if not already set
if (!this.mousedOver) {
this.mousedOver = true;
alert('You moused over a button!\n\nI wont do this again.');
}
}
}
});
But I want it in the west region I defined in my Viewport and I have no idea about how to achieve this since I'm completely new at Ext JS.
My code:
function init() {
Ext.application({
name: 'MyApp',
launch: function() {
Ext.create('Ext.data.Store', {
storeId:'prices',
fields:['name', 'priceNight', 'totalPrice', 'Check-in', 'Check-out'],
data:{'items':[
]},
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
}
});
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: [{
title: 'West',
region: 'west',
margins: '0 5 0 5',
flex: .3,
collapsible: true,
split: true,
titleCollapse: true,
items: [
{
xtype: 'datepicker',
width: 211
},
{
xtype: 'datepicker',
width: 211
},
{
//I want the button here.
},
],
}, {
title: 'Center',
region: 'center',
collapsible: false,
items: {
// I want to add it just there
xtype: 'grid',
store: Ext.data.StoreManager.lookup('prices'),
columns: [
],
}
}]
});
}
});
}
I would like the button here:
Any ideas?
Thank you in advance!
A: I have just figured out how to do it! I'm going to post here what I did so maybe it will result helpful for some people:
It's just simple as invocating it using a variable.
Button code:
var button = Ext.create('Ext.Button', {
text : 'Button',
renderTo : Ext.getBody(),
listeners: {
click: function() {
// this == the button, as we are in the local scope
this.setText('I was clicked!');
},
mouseover: function() {
// set a new config which says we moused over, if not already set
if (!this.mousedOver) {
this.mousedOver = true;
alert('You moused over a button!\n\nI wont do this again.');
}
}
}
});
In your viewport you just have to add it as an item:
...
items: [
{
items: button //button is the variable that we defined when we created the button
}
]
...
Final result:
I hope this will help someone who is having the same question as me :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55394679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do find out MSOLAP.2 provider installed in my machine? How do find out MSOLAP.2 provider installed in my machine. Also, How can i test the same through C# code?
Any help or guidelines are greatly appreciated !!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15969430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: simple questions of callbacks with and without an array function i have a simple question that has border me for a very long time. so can anyone tell me what is the difference between onClick{()=> function()}} and onClick{function()}? what is the difference between having a arrow function and without an arrow function? and are these two function both callback functions?
A: I believe you meant more what is the difference between onClick={() => callback()} and onClick={callback} (notice sans ()). If you did onClick={callback()} then the callback would be invoked immediately and not when the click occurs.
*
*onClick={() => callback()}: An anonymous function is created each time the component is rendered
*onClick={callback}: A "reference" to the callback function is passed each render cycle instead
There isn't much of a difference between the two other than if using the direct reference version it will also be passed the onClick event, but if the callback doesn't take any arguments anyway this isn't an issue. With the anonymous function there may be higher memory usage (since each component receives a copy of the callback) and some marginal performance hit in constructing the copies.
Using an anonymous callback function allows for other arguments to be passed
onClick={() => callback(customArg)}
Or you can proxy the event object and pass other args
onClick={event => callback(event, customArg)}
You can achieve a similar effect with a direct reference by creating a curried callback function. This allows you to still pass additional arguments and the onClick event
const callback = customArg => event => {...}
...
onClick={callback(customArg)}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63857398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Groovy/Grails validations and hasFieldErrors issue I have created a custom tag that looks like this:
def textField = { attrs ->
def field = attrs.name.split('\\.')[-1]
log.error("--------- Field is ${field}")
if (attrs.bean && attrs.bean.errors.hasFieldErrors(field)) {
def className = attrs.remove('class')
def classStr = 'errors '
if (className) {
classStr += className
}
attrs.put('class', classStr)
attrs.put('value', attrs.bean[field])
attrs.remove('bean')
}
out << g.textField(attrs)
}
I'm calling it in my GSP like this:
<my:textField bean="${client}" name="client.firstName"/>
<my:textField bean="${client}" name="client.lastName"/>
...
<my:textField bean="${client}" name="client.workPhone"/>
And here is my domain-class
class Client {
String email
String address
String city
String state
String zip
String firstName
String lastName
String phone
String workPhone
String mobilePhone
String birthCountry
String citizenshipCountry
String emergencyContactName
String emergencyPhone
String disabilities
String experience
static constraints = {
email(email:true, unique:true, blank:false)
address(blank:false)
city(blank:false)
state(blank:false)
zip(blank:false)
firstName(blank:false)
lastName(blank:false)
phone(blank:false)
emergencyContactName(blank:false)
emergencyPhone(blank:false)
workPhone(blank:true, nullable:true)
mobilePhone(blank:true, nullable:true)
birthCountry(blank:true, nullable:true)
citizenshipCountry(blank:true, nullable:true)
disabilities(blank:true, nullable:true)
experience(blank:true, nullable:true)
}
static mapping = {
disabilities type: 'text'
experience type: 'text'
}
static hasMany = [courses:ClientCourseMap]
}
The page loads fine except when I actually have a "client" bean. It loads all the way up to the last tag "client.workPhone". Then I get the following exception:
2010-03-06 18:32:35,329 [http-8080-2] ERROR view.GroovyPageView - Error processing GroovyPageView: Error executing tag : org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag : groovy.lang.MissingPropertyException: No such property: client for class: com.personal.Client at /Users/dean/Projects/PersonalGrails/grails-app/views/registration/index.gsp:98 at /Users/dean/Projects/PersonalGrails/grails-app/views/registration/index.gsp:145
The problem is when hasFieldErrors is called on the bean. It passes in "field" which should be "workPhone". Stepping through a debugger shows that field is exactly "workPhone". However, with further inspection into the field variable, it shows that the internal value of field is "client.workPhone" and offset = 7, count = 9, hash = 0. However, if you call toString(), you get back "workPhone" as you'd expect.
I'm wondering of Grails or maybe even Spring is not using this string correctly? It looks like it's trying to use the real value of that string instead of paying attention to the offset/count of that string and getting back what is intended.
Does anyone see something I'm doing wrong? Or do you know of a workaround? I can give whatever info is needed, just ask... This is driving me nuts!
A: It looks like the intention of your tag is to reduce the amount of boilerplate GSP code needed when rendering a form. Have you considered using the bean-fields plugin instead?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2394530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python- How to change the file name of a variable within a function So basically I want to change the file name of the variable within the function after I've called it, however I'm unsure of exactly how to do this. I'm pretty sure it'll be something fairly simple, however I'm probably looking at it the wrong way. Below is a more detailed explanation of what I want to achieve:
Say I have two files, uncooked_fish and uncooked_cake:
def cook(food):
food.save(food + "_XYZ.png") #the current saving method I'm using, which is not sufficient
After calling them within the function, I want to change their names to cooked_fish.png and finished_cake.png, however with my current saving method, I'm unable to do so. Any help would be very much appreciated!
A: As suggested by @hcwhsa, you should rewrite your cook method as follows:
import os
def cook(food):
// make something with food...
os.rename(food, food + '.png') // e.g.: rename 'finished_cake' to 'finished_cake.png'
A: I ended up using string slicing to remove the file extensions, which allowed me to insert additional information before then replacing the file extension, code is as follows:
food.save (food[0:-4]+ '_X.png')
Essentially, using slicing you'd be able to completely rewrite the file name, so having a similar effect to os.rename.
Thanks for all of your help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19335836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Table of contents does not appear in the left sidebar in Jupyterlab 3.4.2 The table of contents extension is built-in JupyterLab since version 3.0. Howerver, there is no TOC in the left sidebar of my jupyterlab. How can I make my TOC appear properly? Thanks.
left sidebar:
settings:
A: For me, the following screenshot resolved the issue,
that is to untick the "include cell output in headings" from the theme tab - Table of Contents, in the settings.
Settings → Table of Contents:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72238542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get length of integers in PHP ? I want to get the length of integer values for validation in PHP.
Example:
Mobile numbers should be only 10 integer values. It should not be more than 10 or less than 10 and also it should not be included of alphabetic characters.
How can I validate this?
A: In my opinion, the best way is:
$length = ceil(log10($number))
A decimal logarithm rounded up is equal to length of a number.
A: If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don't want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.)
A: if (preg_match('/^\d{10}$/', $string)) {
// pass
} else {
// fail
}
A: $num_length = strlen((string)$num);
if($num_length == 10) {
// Pass
} else {
// Fail
}
A: This will work for almost all cases (except zero) and easily coded in other languages:
$length = ceil(log10(abs($number) + 1));
A: Use intval function in loop,
See this example
<?php
$value = 16432;
$length=0;
while($value!=0) {
$value = intval($value/10);
$length++
}
echo "Length of Integer:- ".$length;
?>
A: $input = "03432 123-456"; // A mobile number (this would fail)
$number = preg_replace("/^\d/", "", $number);
$length = strlen((string) $number);
if ($number == $input && $length == 10) {
// Pass
} else {
// Fail
}
A: If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don't.
A: From your question, "You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:"
<?php
$int = 1234567890; //The integer variable
//Check if the variable $int is an integer:
if (!filter_var($int, FILTER_VALIDATE_INT)) {
echo "Only integer values are required!";
exit();
} else {
// Convert the integer to array
$int_array = array_map('intval', str_split($int));
//get the lenght of the array
$int_lenght = count($int_array);
}
//Check to make sure the lenght of the int does not exceed or less than10
if ($int_lenght != 10) {
echo "Only 10 digit numbers are allow!";
exit();
} else {
echo $int. " is an integer and its lenght is exactly " . $int_lenght;
//Then proceed with your code
}
//This will result to: 1234556789 is an integer and its lenght is exactly 10
?>
A: By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input.
*
*Use integerish() to validate that a value casts to an integer
*Use length() to validate that a string has a certain number of characters
Example
Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string
As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user.
Example
try {
Assert::integerish($input);
Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
As an extra, it's even possible to check if the value is not a non-negative integer.
Example
try {
Assert::natural($input);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
I hope it helps
A: A bit optimazed answer in 2 or 3 steps depends if we allow negative value
if(is_int($number)
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900
//Code
}
Note that will allow negative up to 9 numbers like -999999999
So if we need skip negatives we need 3rd comparision
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
Last case when we want from -1 000 000 000 to 1 000 000 000
if(is_int($number)
&& $number >= 0
&& strlen(str_replace('-', '', (string)$number)) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
For compare
First naswer with regex
if (preg_match('/^\d{10}$/', $number)) {
// Fastest test with 00:00:00.246200
}
** Tested at PHP 8.0.12
** XAMPP 3.3.0
** Ryzen 7 2700
** MSI Radeon RX 5700 8G
Tested like
$function = function($number)
{
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
return true;
}
}
$number = 1000000000;
$startTime = DateTime::createFromFormat('U.u', microtime(true);
for($i = 0; $i < 1000000000; $i++)
{
call_user_func_array($function, $args);
}
$endTime = DateTime::createFromFormat('U.u', microtime(true);
echo $endTime->diff($startTime)->format('%H:%I:%S.%F');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3998482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How can I make the default scrolling logo section move faster so that I can change logos in less than two seconds? as I'm trying to customize a Hugo template, I'm trying to make the scrolling logos move faster (see the picture below), meaning they can change every 2 seconds or so.
Here is the picture of the template that I'm trying to make changes to.
Also, you can refer to the full template here: https://docs.gethugothemes.com/copper/
I'm new to Hugo so I'm not sure how can I make changes to the default state.
If I go into the Hugo code, here is the carousel that belongs to the logo images. So basically I have to make changes to it. Does anyone know how to make the logos move faster?
clients_logo_slider:
enable: false
logos:
- images/brands/01-colored.png
- images/brands/02-colored.png
- images/brands/03-colored.png
- images/brands/04-colored.png
- images/brands/05-colored.png
- images/brands/06-colored.png
- images/brands/01-colored.png
- images/brands/02-colored.png
- images/brands/03-colored.png
- images/brands/04-colored.png
- images/brands/05-colored.png
- images/brands/06-colored.png
A: You need to add your changes into theme. I found carousel by the path themes/copper/layouts/partials/testimonial.html:
<!-- start of brand-carousel -->
{{ if $data.homepage.clients_logo_slider.enable }}
{{ with $data.homepage.clients_logo_slider }}
<section class="section-padding bg-white overflow-hidden">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6 col-md-9 text-center mb-30">
<span class="section-title fw-extra-bold fs-36">{{ .title | markdownify }}</span>
</div>
</div>
<div class="row">
<div class="col-md-12" data-aos="fade-left">
<div class="brand-carousel">
{{ range .logos }}
<div class="brand-item d-flex align-items-center justify-content-center">
<img class="img-fluid" src="{{ . |absURL}}" alt=""></div>
{{ end }}
</div>
</div>
</div>
</div>
</section>
{{ end }}
{{ end }}
<!-- end of brand-carousel -->
Here I see css class <div class="brand-carousel">
And logic I found by the path themes/copper/assets/js/script.js:
// brandCarousel fix
function brandCarousel() {
$('.brand-carousel').slick({
dots: false,
arrows: false,
infinite: true,
speed: 500,
autoplay: true,
autoplaySpeed: 3000,
mobileFirst: true,
slidesToScroll: 1,
responsive: [{ ...
So, function brandCarousel() take div with class .brand-carousel and make it slick. I didn't check it, but I recommend you try to change some of this option, and start with autoplaySpeed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75053750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get text content of 3rd element inside of . With several div containers with the same name I have the following code.
var bTags = document.getElementsByClassName("Wrapper");
var kind = bTags[0];
console.log(kind);
console.log(kind.childNodes[4].text);
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}}</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
In my example the "console.log(kind);" successfully logs the HTML object. Here its not working of course because its not defined. But somehow the childNodes[4].text is undefined. I just want to access the text of the p element with the class "placeDescription" of this specific parentNode. A static try like the following is not possible because I have several HTML ".Wrapper" objects who just differ by content.
I think I can access them by just writing the p elements into divs and then with ChildNodes but thats not very clean imo. Why is kind.childNodes[4].text undefined when kind is not ?
const el = document.querySelector('.Wrapper p:nth-of-type(3)');
if (el) {
console.log(el.textContent)
}
Thanks for reading this.
A: Your code would work if you changed text to textContent (or innerText on old IE, but it's not quite the same thing) and 4 to 3. But, it's fragile. You can be more precise with querySelector:
var div = document.querySelector(".Wrapper div");
console.log(div.textContent);
Live Example:
var div = document.querySelector(".Wrapper div");
console.log(div.textContent);
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}}</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
Live your version, that only looks at the first such match. If you want all of them, you'll need a loop:
var wrappers = document.querySelectorAll(".Wrapper"); // Or .getElementsByClassName("Wrapper");
for (var i = 0; i < wrappers.length; ++i) {
var div = wrappers[i].querySelector("div");
console.log(div.textContent);
}
Live Example:
var wrappers = document.querySelectorAll(".Wrapper"); // Or .getElementsByClassName("Wrapper");
for (var i = 0; i < wrappers.length; ++i) {
var div = wrappers[i].querySelector("div");
console.log(div.textContent);
}
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} first</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} second</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} third</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
In a modern browser (or with the polyfill approach I describe in this other answer), you can use forEach instead of the for loop (or even for-of in ES2015+), which makes it a bit more concise:
document.querySelectorAll(".Wrapper").forEach(function(wrapper) {
var div = wrapper.querySelector("div");
console.log(div.textContent);
});
Live Example:
document.querySelectorAll(".Wrapper").forEach(function(wrapper) {
var div = wrapper.querySelector("div");
console.log(div.textContent);
});
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} first</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} second</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} third</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
Or with ES2015+ (again, you may need to do some polyfilling per above):
for (const wrapper of document.querySelectorAll(".Wrapper")) {
const div = wrapper.querySelector("div");
console.log(div.textContent);
}
Live Example:
for (const wrapper of document.querySelectorAll(".Wrapper")) {
const div = wrapper.querySelector("div");
console.log(div.textContent);
}
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} first</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} second</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
<div class="Wrapper">
<h3 class="date" id="date">{{date}}</h3>
<div class="descriptionWrapper">
<p class="jobDescription">{{job}} third</p>
<p class="jobAreaDescription">{{jobArea}}</p>
<p class="placeDescription">{{ort}}</p>
<p class="kindDescription">{{anstellung}}</p>
</div>
<div class="jobLink">
{{#custom_link jobLink}}
{{linkText}}
{{/custom_link}}
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60335875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Laravel htaccess, redirect url if find /en My old url
www.example.com/cn/news
www.example.com/cn/event
I want to if user enter /cn url Laravel will redirect into this url
www.example.com/en/news
www.example.com/en/event
here is my laravel .htaccess in root folder
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
I try this one but it doest work
RewriteCond %{THE_REQUEST} /cn [NC]
RewriteRule ^ /%1/en/%2/? [L,R=301]
UPDATE
now .htaccess look like this but still didnt work
RewriteEngine On
RewriteRule ^(.)$ public/$1 [L]
RewriteRule ^cn/(.)$ en/$1 [L,R=301]
A: RewriteRule ^cn/?(.*)$ en/$1 [L,R=301]
This rule alone should work.
Match a cn prefix with an optional / and capture all characters after the /.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52276393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding an Individual JSON Object to an Array to Parse and Process I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
A: *
*Read the file line by line (each line is a separate json)
*Parse the line json text to JavaScript object
*Put/push/append JavaScript object into a JavaScript array
A: This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
A: Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as @Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up @torazaburo - have updated my answer which I should've done much earlier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36977910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Rails3: linking to offsite mp3 files and have them save to user's hard-drive rather than stream in the browser I have some very large mp3's stored at a remote location and I presently link to them like so:
= link_to "mp3", "http://website-where-file-is-stored.com/file-123456.mp3"
When a user clicks the link, the file starts to play in the browser. I would like the file to download to the users hard-drive after they click the link.
I've read a number of articles like this one and this one which promote methods that work in different situations to my own.
I have multiple files. Each file is stored on a remote server which does not have a rails app running.
I don't require users to be authorized prior to downloading anything so I don't want my rails app to be called into action in any way as I need to be conservative with my rails processes.
Is this something I need to do in config.ru? Is there a guide or tutorial detailing the best way to do this?
I know that I need to set the Content-Disposition header but as I said, I can't figure out how to do that I do not have a rails app running on the remote server, it's just a bunch of server space.
A: You can make a controller action somewhere that is dedicated to file downloads.
So, the link_to goes to that action, which somehow knows which file the user wants (either by dropping the entire url into a query variable or some other method appropriate to your application).
That action does a redirect_to http://website-where-file-is-stored.com/file-123456.mp3
When most modern browsers encounter such a situation, they won't render a blank page and start a download -- they will start the download, but then keep the user on the original page with the link_to. Perfect!
To have the file download as an attachment and not render in the browser (if it's a movie or pdf for example), website-where-file-is-stored.com has to serve the file with the header Content-disposition: attachment. See more info here: http://www.boutell.com/newfaq/creating/forcedownload.html
A: OK, I fixed this by adding the following cgi script to the cgi-bin on my remote server. the script sets the Content-Disposition header. In my case, the script is named "download.cgi".
#!/usr/local/bin/perl -wT
use CGI ':standard';
use CGI::Carp qw(fatalsToBrowser);
my $files_location;
my $ID;
my @fileholder;
$files_location = "../";
$ID = param('ID');
open(DLFILE, "<$files_location/$ID") || Error('open', 'file');
@fileholder = <DLFILE>;
close (DLFILE) || Error ('close', 'file');
print "Content-Type:application/x-download\n";
print "Content-Disposition:attachment;filename=$ID\n\n";
print @fileholder
And instead of doing link_to 'Download', "http://path/to/filename.mp3" I do this:
link_to 'Download' "http://path/to/cgi-bin/download.cgi?ID=filename.mp3"
If you want to use the same script, just bear in mind that the line: $files_location = "../" is a relative path.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3261809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What are the differences between ways of writing OpenMP sections? What (if any) differences are there between using:
#pragma omp parallel
{
#pragma omp for simd
for (int i = 0; i < 100; ++i)
{
c[i] = a[i] ^ b[i];
}
}
and:
#pragma omp parallel for simd
for (int i = 0; i < 100; ++i)
{
c[i] = a[i] ^ b[i];
}
Or does the compiler(ICC) care?
I know that the first one defines a parallel section and than a for loop to be divided up and you can multiple things after the loop. Please do correct me if I'm wrong, still learning the ways of openmp..
But when would you use one way or the other?
A: Simply put, if you only have 1 for-loop that you want to parallelise use #pragma omp parallel for simd.
If you want to parallelise multiple for-loops or add any other parallel routines before or after the current for-loop, use:
#pragma omp parallel
{
// Other parallel code
#pragma omp for simd
for (int i = 0; i < 100; ++i)
{
c[i] = a[i] ^ b[i];
}
// Other parallel code
}
This way you don't have to reopen the parallel section when adding more parallel routines, reducing overhead time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53218701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java paste to current cursor position I want to make simple java program that will insert some text into current cursor position. That cursor position can be in any text editor, for example notepad. Is this possible?
A: Using this article as a base about copy/paste, you may see that you can only put something to the clipboard but not directly changing the content of a foreign's process Textbox.
You might want to get the window handle of the box and send a message to it using the Windows API. This works on windows only, I don't know whether there's an equivalent way on Mac OS / Linux. Maybe this doesn't even work directly from java. You would need to type some C/C++-code and use the Java Native Interface (JNI)
regards
A: It's a hack, but look into java.awt.Robot. It lets you programmatically make mouse clicks and key presses, among lots of other useful things. So one way to do it would be:
*
*Use Atmocreations' article to put text in the clipboard
*When you want to paste it, use Robot to click at the current position (if you need to give that field focus)
*Use Robot to press Ctrl-V (or whatever your system expects for a paste)
Like I said, it's not at all a clean solution, but it will work in a pinch.
A: If u are asking for the current cursor location, i think u should use this :
Display.getCurrent().getCursorLocation()
Having the cursor location, what to do next requires further details. If u want to automatically write some text into foreign applications like Word or Notepad, this sounds more like a virus to me..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1549333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reference parent DataContext in user control [C++/winrt] Edit: Solved via blank user control, not custom control (See below solution)
I'm basically trying to modularize complex XAML stuff away from MainPage into a user control, hence I need to figure out how to inject the local DataContext within MainPage.Xaml into my user control.
Following the MSDN Doc's tutorial for custom user controls, I have a custom control in my MainPage.xaml file, called NutriDetailsControl.
// MainPage.xaml
...<ListBox x:Name="ItemList" ItemsSource="{x:Bind Basket}" RelativePanel.Below="AddDelCol"
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="local:BasketItem">
<StackPanel GotFocus="ItemGotFocus" Orientation="Horizontal">
<Button Content="Delete" Click="DeleteItemClickHandler"/>
<TextBlock VerticalAlignment="Center" Text="{x:Bind Name, Mode=OneWay}"/>
HERE-------> <local:NutriDetailsControl Background="Red" MyItem="Hello, World!" MyBasketItem="x:Bind ???"/>
...
...
...
...
...</ListBox>
MyItem is a string, and I am able to access it within the custom user control, but I can't access MyBasketItem, which is a DependencyProperty of type BasketItem (ViewModel variable within the local DataContext). In Generic.Xaml, I've tried to access BasketItem's data via binding locally, and through the DependencyProperty I passed in (MyBasketItem),
<!-- \Themes\Generic.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:NutritionBasket">
<Style TargetType="local:NutriDetailsControl" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:NutriDetailsControl">
<Grid Width="30" Height="30" Background="{TemplateBinding Background}">
(THIS WORKS)------> <!--<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{TemplateBinding MyItem}"/>-->
<Button HorizontalAlignment="Right" VerticalAlignment="Center" Content=">">
<Button.Flyout>
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabNavigation" Value="Cycle"/>
</Style>
</Flyout.FlyoutPresenterStyle>
<StackPanel>
LOOK HERE ----------------> <TextBlock Text="{x:Bind Name}"/>
AND HERE ----------------> <TextBlock Text="{TemplateBinding MyBasketItem.Name}"/>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
For the first line, I am trying to access BasketItem->Name() via the local DataContext. I am getting an error "This Xaml file must have a code-behind to use {x:Bind}".
For the second line, when I am passing in BasketItem as a DependencyProperty within NutriDetailsControl.h, I am getting "MyBasketItem is not supported in a Windows Universal project"
I know that for Name(), I can simply pass it in as a DependencyProperty; my GOAL is to reference another variable, BasketItemNutri() which is a sub-ViewModel variable of BasketItem. So I need to figure out a way to either pass in BasketItem, or BasketItemNutri, from the MainPage into custom user control.
Any help would be appreciated. What should I do?
A: Solved
I wasn't able to get the Nico's solution to work for me, since I still needed to somehow bind within NutriDetailsControl.xaml to MyBasketItem, and no permutation I tried seemed to work.
After reading the Data Binding in Depth, I thought maybe I should forget about this whole custom control thing situation, and just go with a blank user control, called NutriControl.
I created a DependencyProperty in NutriControl.idl (blank user control) by adding
static Windows.UI.Xaml.DependencyProperty MyBasketItemProperty{ get; };
BasketItem MyBasketItem;
(Note that MyBasketItemProperty and MyBasketItem; must be the same). A DependencyProperty of a user control, "exposed" through the NutriControl.idl file, is basically like a box that you can put data into from other Xaml files (like MainPage.xaml). The data can be text, class objects (including your viewmodels), etc.
// Mainpage.Xaml
<local:NutriControl MyBasketItem="{x:Bind}"/>
"x:Bind" binds to the local DataContext (DataType??), which was a BasketItem here, so I didn't need to specify anything else.
// NutriControl.h
...other stuff...
struct NutriControl : NutriControlT<NutriControl>
{
NutriControl();
NutritionBasket::BasketItem MyBasketItem()
{
return winrt::unbox_value<NutritionBasket::MyBasketItem>(GetValue(m_myBasketItemProperty));
}
void MyBasketItem(NutritionBasket::MyBasketItem const& value)
{
SetValue(m_myBasketItemProperty, winrt::box_value(value));
}
static Windows::UI::Xaml::DependencyProperty MyBasketItemProperty() { return m_myBasketItemProperty; }
static void OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const&, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const&);
private:
static Windows::UI::Xaml::DependencyProperty m_myBasketItemProperty;
};
}
...other stuff...
// NutriControl.c
NutriControl::NutriControl() {
InitializeComponent();
}
Windows::UI::Xaml::DependencyProperty NutriControl::m_myBasketItemProperty =
Windows::UI::Xaml::DependencyProperty::Register(
L"MyBasketItem",
winrt::xaml_typename<NutritionBasket::BasketItem>(),
winrt::xaml_typename<NutritionBasket::NutriControl>(),
Windows::UI::Xaml::PropertyMetadata{ winrt::box_value(L"default label"), Windows::UI::Xaml::PropertyChangedCallback{ &NutriControl::OnMyBasketItemChanged } }
);
void NutriControl::OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& /* e */)
{
// still unimplemented
}
// NutriControl.Xaml
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button HorizontalAlignment="Right" VerticalAlignment="Center" Content=">">
<Button.Flyout>
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabNavigation" Value="Cycle"/>
</Style>
</Flyout.FlyoutPresenterStyle>
<StackPanel>
see here--------> <TextBlock Text="{x:Bind MyBasketItem.Nutrition.Amount, Mode=OneWay}"></TextBlock>
and here--------> <ListBox ItemsSource="{x:Bind MyBasketItem.Nutrition.Elems}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="local:BasketItemNutriElem">
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="{x:Bind Nutrient, Mode=OneWay}"/>
<TextBlock VerticalAlignment="Center" Text="{x:Bind Amount, Mode=OneWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
</StackPanel>
This worked. MyBasketItem (-> Nutrition) and (->Elems->BasketItemNutriElem) are both sub-viewmodels of type BasketItem, so I've successfully passed local instances of viewmodels from MainPage.Xaml to a user control.
A:
So I need to figure out a way to either pass in BasketItem, or BasketItemNutri, from the MainPage into custom user control.
You has placed NutriDetailsControl in the DataTemplate, so you can't use x:Bind to bind property in the code behind directly. For this scenario, the better way is that use bind element name then find it's DataContext
MyBasketItem="{Binding ElementName=ItemList,Path=DataContext.MyBasketItem}"
Please note, you need specific current page as page's DataContext.
public MainPage()
{
this.InitializeComponent();
DataContext = this;
}
For more detail please refer this case reply .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68157433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to take backup and Restore huge Cassandra Database tables? Need to Migrate Cassandra 2.0 to 3.11 to new server
Old Server : Cenos5/6
Old Cassandra Version : 2.0
New Server : Centos8
New Cassandra Version - 3.11
There are few tables with 20 Million records tried Snapshot and Copy method but the Backup is not being restored.
Any Better approach?
Any other tool?
Tried Snapshot Method - which is not working may be coz of version difference
Tried COPY method but that is only working for small tables, I used it for other tables which were small in size.
I have 4 tables which have 5 million to 20 millions records.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75498291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a parameterized stored procedure on an AS400 and cannot get results in SSRS I have a working stored procedure that returns results in Microsoft query and iSeries Navigator. When I call the same stored procedure using Microsoft Report Builder 3.0, I either get no results or an error saying one of the temporary files used in the procedure is in use.
Is there something special that needs to be done using Report Builder?
I am using an ODBC connection to the AS400, if that's relevant.
Thanks.
A: Recommended ... different approach. Locate your stored procedure on your SSRS Reports SQL Server. Debug this stored procedure with SSMS. Once that is working, you will have no issue getting the data into SSRS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36991913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: injecting mocks with mockito and powermocks I was wondering how should I go about injecting a mocks - we have bunch of classes that do server calls, however our CI system can not access external resources and thus will not make a call to a server. Thus, the call has to be simulated and hardcoded values (such as response codes) needed to be return.
So, here is a snippet of a code:
HttpPost httpRequest = new HttPost(uri);
//some code here
try{
httpRequest.setEntity(entity);
HttpResponse response = httpClient.execute(httpRequest);
...
//other, irrelevant, code is here
So, is it possible to inject a mock into httpClient.execute(httpRequest) and return hardcoded response entity from a test unit?
Thank you
A: Usually mocking some object looks like this:
public class TestClass {
private HttpServer server;
public HttpServer getServer() {
return server;
}
public void setServer(HttpServer server) {
this.server = server;
}
public void method(){
//some action with server
}
}
And test class:
public class TestClassTest {
//class under test
TestClass test = new TestClass();
@org.junit.Test
public void testMethod() throws Exception {
HttpServer mockServer = Mockito.mock(HttpServer.class);
test.setServer(mockServer);
//set up mock, test and verify
}
}
Here you some useful links:
*
*Code example
*Official documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17956840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Nativescript JS send URLSearchParams into POST request I want to send data to an API not with JSON but with x-www-form-urlencoded (URLSearchParams).
I tried with this code but the data is not received correctly by the API.
return fetchModule.fetch(config.apiUrl + "auth/register",
{
body: JSON.stringify({
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
}),
method: "POST",
headers:{
"content-type" : "application/x-www-form-urlencoded"
}
}).then(handleErrors);
A: Simply change the JSON.stringify for a URLSearchParams and remove the content-type header, fetch will automatically add the correct content-type when it detects URLSearchParams as a body
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: new URLSearchParams({
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
}),
method: "POST"
}).then(handleErrors);
A: I don't think the {N} runtime has access to URLSearchParams class, it's browser specific.
You could achieve the same with a simple loop through keys in object,
var data = {
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
};
var endocedStr = "";
for (var prop in data) {
if(endocedStr) {
endocedStr += "&";
}
endocedStr += prop + "=" + data[prop];
}
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: endocedStr
method: "POST"
}).then(handleErrors);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54531563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript - how to pass an undefined argument to child anonymous function Ok, after a couple of hours of googling I haven't found a solution that (works) and doesn't use eval(). I have an array which i would like to run the same function to nest and do roll-up sums.
dsAhsBes = createAhsBesok(dsFilterBes, dsAhsBes, "d.Ar")
function createAhsBesok(ds, output, groupVar) {
output = d3.nest()
.key(function(d) {
return eval(groupVar);
})
.rollup(function(d) {
return {
"Count": d3.sum(d, function(g) {
return g.Count;
})
};
}).entries(ds);
output.forEach(function(d) {
d.Count = +d.values.Count;
d.Dep = "Main";
});
return (output);
}
The snippet above works, but I rather use something else than eval(), if possible. How do i get the child function to parse groupVar the right way without using eval?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31450313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Upgraded to Az modules from AzureRM now cannot login with Runbook I have just started looking at Azure Automation and created my first Runbook today and everything was working fine. I then read that AzureRM was replaced with the Az module so thought I had better migrate my Runbook and get straight onto the new stuff!
My original code was working absolutely fine using the AzureRM modules, but since upgrading to the latest Az modules I just can't authenticate. My automation account is exactly the same from a configuration perspective other than I have added in all of the matching Az modules to allow me to use them in my run books.
{
$servicePrincipalConnection=Get-AutomationConnection -Name 'AzureRunAsConnection'
$servicePrincipalConnection.TenantID
$servicePrincipalConnection.ApplicationID
$servicePrincipalConnection.CertificateThumbprint
Connect-AzAccount -ServicePrincipal `
-Tenant $servicePrincipalConnection.TenantID `
-ApplicationId $servicePrincipalConnection.ApplicationID `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
Write-Verbose "Connected to Azure using Automation Connection" -verbose
}
I currently get the following error and am at a complete loss as to the reason, documentation is very thin on the ground and the bits I have found simply show what I already have!
should be present. If you are accessing as application please make sure service principal is properly created in the
tenant.
At Do-Authentication:9 char:9
+
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
A: Oh lord how many times do I answer my own question right after posting it!!!
I did attempt to delete some modules from the list that is the AzureRM ones, I didn't think it let me do it so I ended up just leaving them, I have no idea whether that is relevant or not but thought I'd mention it.
On the Automation Account blad within the Azure portal I clicked on the "Run as accounts" option and it said it was incomplete, I deleted and recreated it and now everything works OK.
Might help someone else so thought I'd post the answer.
A: There are quite a few things to consider while the Az module in Azure Automation. This doc talks about these in greater detail. There is also a note that is worth quoting, from the same doc:
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57529029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: correct syntax for merge This question might appear to be very stupid but I don't understand how to merge two sorted vectors with std::merge.
I tried some code using cplusplus reference.
struct t
{
t(int x):a(x){}
int a;
};
bool operator<(const t& p,const t&b)
{
return p.a<b.a;
}
int main()
{
vector<t> a,b,c;
a.push_back(t(10));
a.push_back(t(20));
a.push_back(t(30));
b.push_back(t(1));
b.push_back(t(50));
merge(a.begin(),a.end(),b.begin(),b.end(),c.begin());
return 0;
}
There is a segmentation fault with this code.
A: You will want to make sure c is big enough, or grows:
std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(c));
Alternatively:
c.resize(a.size() + b.size());
std::merge(a.begin(),a.end(),b.begin(),b.end(),c.begin());
See it Live On Coliru
#include <algorithm>
#include <vector>
#include <iterator>
struct t
{
t(int x):a(x){}
int a;
};
bool operator<(const t& p,const t&b)
{
return p.a<b.a;
}
int main()
{
std::vector<t> a,b,c;
a.push_back(t(10));
a.push_back(t(20));
a.push_back(t(30));
b.push_back(t(1));
b.push_back(t(50));
std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(c));
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23304400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to stop Translate when I need? I have a cupboard with boxes. When I look on the box and press mouse button, I want to open/close it with Translate. I want to move box, till it's X coordinate will be 1.0 (and start point is 1.345). But it moves longer than that point.
I tried to use FixedUpdate, but it doesn't helped..
public LayerMask mask;
private bool shouldClose;
private bool changeXCoordinate;
private Transform objectToMove;
void Update ()
{
if (changeXCoordinate)
OpenCloseBox();
else if(DoPlayerLookAtCupboardBox() && Input.GetMouseButtonDown(0))
changeXCoordinate = true;
}
bool DoPlayerLookAtCupboardBox()
{
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 1.5f, mask.value);
if (isHit && !changeXCoordinate)
{
objectToMove = _hit.transform;
return true;
}
else
return false;
}
void OpenCloseBox()
{
if (shouldClose)
{
if(objectToMove.position.x != 1.345f) // It must stop at this point, but it don't
{
changeXCoordinate = false;
shouldClose = !shouldClose;
}
else
objectToMove.Translate(Vector3.right * Time.deltaTime);
}
else
{
if (objectToMove.position.x >= 0.1f) // The same problem here..
{
changeXCoordinate = false;
shouldClose = !shouldClose;
}
else
objectToMove.Translate(Vector3.left * Time.deltaTime);
}
}
A: Its better to use a tween engine , like http://dotween.demigiant.com/.
If you install Dotween the you can simply use
transform.DOMove(new vector3(1 ,0 , 1) , duration);
You can also set Ease for tweens. or use Oncomplete fucntions;
transform.DOMove(new vector3(1 ,0 , 1) , duration).SetEase(Ease.OutCubic).OnCompelete(() => { shouldClose = true; });
But the answer for your question is that positions are not exact numbers so you shouldn't use something like this != , you must use < or > .
to fix you problem i would recommend you to do something like this ;
if(x > 1.345f)
{
x = 1.345f
}
This will fix your problem.
A: In this kind of situation, you should use an animation, this allows full control on any aspect of the movement.
If you really want to use code, you could use Vector3.MoveTowards which creates a linear translation from position A to position B by a certain step amount per frame:
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step * Time.deltaTime);
As for your issue, you are checking if the position is a certain float. But comparing float is not accurate in computer due to inaccuracy of value.
1.345 is most likely 1.345xxxxxx and that is not the same as 1.34500000. So it never equal.
EDIT: Using equality also results in the fact that you are checking if the value is greater or equal. But consider this:
start : 10 movement : 3
if(current >= 0){ move(movement);}
frame1 : 10
frame2 : 7
frame3 : 4
frame4 : 1
frame5 : -2 we stop here
This is why you should use animation or MoveTowards when wishing to move to exact point. Or add extra:
if(current >= 0){ move(movement);}
else { position = 0; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34824893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Turn warnings into error only within supplied diff At a company I used to work at, the build system was set up to turn warnings into errors only within changed code. It worked by supplying generating a diff (typically between the branch you were trying to merge and master and then supplying that diff to some compilation tool, and the tool would produce warnings only within the supplied diff.
This was great as it allowed you to e.g. deprecate some function, and have the build system prevent people from introducing new uses of that function, and then remove old usages of that function later.
Unfortunately, I didn't look at the setup closely enough before I left the company, and don't know how to replicate it. My question: How can I replicate this setup?
Question is tagged Clang but I would also be interested in answers that use tooling from other compilers.
A: If I had to implement that, my first idea would be:
*
*Get merged file.
*Analyze diff to figure out which regions were changed.
*Generate a new file and inject #pragma directives1 that locally enable/disable warnings around the changed regions.
*Also inject #line directives to make it look like warnings/errors are coming from the original file.
*Compile modified file and save compiler warnings/errors.
*Delete modified file.
*Present compiler diagnostics to the user.
1 E.g. https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas for GCC.
A: Clang supports GCC's #pragma diagnostic.
For example:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
// ... changed code here ...
#pragma GCC diagnostic pop
MSVC also has something similar:
#pragma warning(push, 3)
// ... changed code here ...
#pragma warning(pop)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53749946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to clear boost function? Having a non-empty boost::function, how to make it empty (so when you call .empty() on it you'll get true)?
A: Simply assign it NULL or a default constructed boost::function (which are empty by default):
#include <boost/function.hpp>
#include <iostream>
int foo(int) { return 42; }
int main()
{
boost::function<int(int)> f = foo;
std::cout << f.empty();
f = NULL;
std::cout << f.empty();
f = boost::function<int(int)>();
std::cout << f.empty();
}
Output: 011
A: f.clear() will do the trick. Using the example above
#include <boost/function.hpp>
#include <iostream>
int foo(int) { return 42; }
int main()
{
boost::function<int(int)> f = foo;
std::cout << f.empty();
f.clear();
std::cout << f.empty();
f = boost::function<int(int)>();
std::cout << f.empty();
}
will yield the same result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15760929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: No 'Access-Control-Allow-Origin' error in http get I am getting the following error message in ionic project, when i execute http get function.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://creator.ionic.io' is therefore not allowed
access.
My code is, how do i add the headers to remove such error
var ret = {
all:function(){
var deferred = $q.defer();
$http.get(zones_url).then(function(resp){
console.log(resp);
});
return deferred.promise;
}
}
return ret;
Can anyone advice me please.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47105078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Figuring out C Declarations like: double (*b)[n] I'm trying to figure out some C declarations. What is the meaning of these C declarations?
double (*b)[n];
double (*c[n])();
double (*d())[n];
A: The basic rule to parse C declarations is "read from right to left and the inside out jumping toward the right when leaving a pair of parenthesis", i.e. start the the most deeply nested pair of parenthesis and then work yourself out looking toward the right. Technically you must know operator associativity, but it works well enough in most situations.
Now lets apply this (simplified) rule to your question:
double (*b)[n];
^
b is a
double (*b)[n];
^
pointer to
double (*b)[n];
^^^
and array
double (*b)[n];
^^^^^^
of doubles.
double (*c[n])();
^^^^
c is an array of
double (*c[n])();
^
pointers to
double (*c[n])();
^^
functions
double (*c[n])();
^^^^^^
returning double.
double (*d())[n];
^^^
d is a function
double (*d())[n];
^
returning a pointer to
double (*d())[n];
^^^
an array of
double (*d())[n];
^^^^^^
doubles
There's a neat utility found on most *nixes, called cdecl, which takes a C declaration string and turns it into a natural language sentence.
A: Let try this way.
first, you should be familiar with these three symbols:
1. * -- a pointer.
2. [] -- an array.
3. () -- a function.(notice: not parentheses)
we take "double (*d())[n]" as an example.
the first step is to find out the identifier in the declaration, an identifier is the name of variable, here it is "d".
(i)
-- what is "d"?
------------------------------------------------------------------------
look to the right side of the identifier, to see if there is a "[]" or a "()" :
...d[]...: d is an array.
...d()...: d is a function.
if neither, look to the left side, to see if there is a "*" :
...*d...: d is a pointer.
------------------------------------------------------------------------
now we've found that d is a function.
use x to replace d(), then the declaration becomes "double (*x)[n]"
(ii)
-- what is "x"?
------------------------------------------------------------------------
repeat (i), we find that x is a pointer.
that means, d is a function returning a pointer.
------------------------------------------------------------------------
use y to replace *x, then the declaration becomes "double y[n]"
(iii)
-- what is "y"?
------------------------------------------------------------------------
repeat (i), we find that y is an array of n elements.
that means, d is a function returning a pointer to an array of n elements.
------------------------------------------------------------------------
use z to replace y[n], then the declaration becomes "double z"
(iv)
-- what is "z"?
------------------------------------------------------------------------
repeat (i), we find that z is a double.
that means, d is a function returning a pointer to an array of n double elements.
------------------------------------------------------------------------
let's see another expression:
void (*(*f)(int)[n])(char)
1.
we find f.
2.
f is a pointer. *f -> a
void (*a(int)[n])(char)
3.
a is a function. a() -> b
void (*b[n])(char)
--f is a pointer to a function (with an int parameter)--
4.
b is an array. b[] -> c
void (*c)(char)
--f is a pointer to a function returning an array (of n elements)--
5.
c is a pointer. *c -> d
void d(char)
--f is a pointer to a function returning an array of n pointers--
6.
d is a function returning void.
--f is a pointer to a function returning an array of n pointers to functions (with a char parameter) returning void--
A: double (*b)[n];
b is a pointer to an array of n doubles
double (*c[n])();
c is an array of n pointers to functions taking unspecified number of arguments and returning double
double (*d())[n];
d is a function taking unspecified number of arguments and returning a pointer to an array of n doubles
In general, in order to parse these kind of declarations in your head, take the following approach. Let's see the last declaration, for example
double (*d())[n];
what is the first thing that is done to d? It is called with (), therefore it's a function taking unspecified number of arguments and returnig... what's the thing done with the result? It is dereferenced (*), therefore it's a pointer to. The result is then indexed, therefore it's an array of n... what's left? a double, therefore of doubles. Reading the parts in bold, you'll get your answer.
Let's see another example
void (*(*f)(int)[n])(char)
Here, f is first dereferenced, therefore it's a pointer to... it's then called with (int), therefore a function taking int and returning , the result is then indexed with [n], so an array of n. The result is dereferenced again, so pointers to. Then the result is called by (char), so functions taking char and returning (all is left is void) void. So f is a pointer to a function taking int and returning an array of n pointers to functions taking char and returning void.
HTH
A: There are two great resources to understand "C gibberish":
*
*http://cdecl.org/ - Online service that translates "C gibberish ↔ English"
*The "Clockwise/Spiral Rule" by David Anderson if you want to understand what better what is going on
Output of cdecl.org:
*
*double (*c[n])(): Syntax error (n is not valid here)
*double (*c[])(): declare c as array of pointer to function returning double
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13247473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: calculate mean value for the missing values I need to calculate the mean of neighbor values to replace it with NaN value, but the problem is, I don't want to make my code more complicated.
For example,
I have there 20 countries and 4 car types from 2010 to 2020, but there are some missing values in the beginning or middle or end sometimes next two each other.
The solution came in my mind is that I slice the data and then replace the NaN with 3 neighbors before and after the missed valueS, but it is not always in the middle so there would be in beginning 3 missed values.
What is the best solution for the missing values?
A: Try this
import numpy as np
import pandas as pd
sample_date = { 'countries': ['USA','Canada','USA','UK','USA','UK','DE'],
'car_type': ['sedan','sedan','Hatchback','coupe','sedan','coupe','coupe'],
'years': [2010,2010,2011,2011,2017,2017,2010],
'price': [4000,np.NaN,4000,4000,np.NaN,np.NaN,4000]}
data = pd.DataFrame(sample_date)
fillValue = 4000
data['price'].fillna(value=fillValue, inplace=True)
print('update Dataframe:')
print(data)
mean_value=data['price'].mean()
print(mean_value)
answer will be 4000 as I'm replacing NaN with neighbors as '4000'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70915585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Netbeans (Java): 3rd library works but how could I compile it into jar? I'm using 3rd libraries (substance, trident) and I added them as libraries (I added the .jar's) to my project in Netbeans. This works also but if I use the builded jar outside the project directory it doesn't work like it should (the choosen UI don't show), I get the error:
java.lang.ClassNotFoundException:
org.pushingpixels.substance.api.skin.SubstanceOfficeBlue2007LookAndFeel
I set that UI/LookAndFeel like that in my code:
UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceOfficeBlue2007LookAndFeel");
How could I make this work/run?
A: You've got 2 choices:
*
*Put the library jar on the
classpath.
*Assemble\Build the library jar with
the regular jar.
For option 1, you most likely need the jar located "near" the main jar on the file system; though, this is not necessarily a requirement. When you run the jar you then include the library jar on the classpath.
For option 2, you use some type of tool like maven's assembly plugin or the fatjar plugin in Eclipse (sorry, I don't know what the analog is in NB).
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4473066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Next.js Add slug/params to clean URL I have a structure with a clean URL in the "pages" folder like this ...
/pages/items/[pageNumber]/index.tsx
And if I use router.push I use it like this to get to that page ...
router.replace("/items/[pageNumber]", "/items/1")
That works great, but now I want to add a query params (for filter) to that URL, how can I do that?
I tried this ...
router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });
But that doesn't work, and I'm wondering how to do that.
A: When you use it like this
router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });
you are not passing query params to the page, you are only showing them in the address bar, I guess.
How about something like this:
router.push({
pathname '/items/[pageNumber]/',
query: {
param1: 'yes',
},
}, {
pathname: '/items/1/',
query: {
param1: 'yes',
},
});
Don't forget to update query part for your case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63360586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get list item count from all lists on all webs of site I found the following post that returns lists items from all lists on all webs within a site. I am trying to figure out how to return the list item count instead of the list items. Any assistance would be appreciated.
JSOM dynamicly get two announcements from all lists in all webs
UPDATE:
I am able to return details of all document libraries on a site using this:
function retrieveAllListProperties() {
var clientContext = new SP.ClientContext.get_current();
var oWebsite = clientContext.get_web();
this.collList = oWebsite.get_lists();
clientContext.load(collList);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
var tCount = 0;
var listInfo = 'Lists on the current site:' + '\n\n';
var listEnumerator = collList.getEnumerator();
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
if (oList.get_baseTemplate() === 101) {
listInfo += 'URL: ' + oList.get_parentWebUrl() + ' | Title: ' + oList.get_title() + ' | BaseType: ' + oList.get_baseTemplate() + ' | Count: ' + oList.get_itemCount() + '\n';
tCount += + oList.get_itemCount();
}
}
listInfo += '\nTotal Documents: ' + tCount;
console.log(listInfo);
}
function onQueryFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
I am able to return all sites and sub sites of a site collection using this:
function getAllWebs(success,error)
{
var siteUrl = '/sites/usaraf/g357';
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
var getAllWebsInner = function(web,result,success,error)
{
level++;
var ctx = web.get_context();
var webs = web.get_webs();
ctx.load(webs,'Include(Title,ServerRelativeUrl,Webs)');
ctx.executeQueryAsync(
function(){
for(var i = 0; i < webs.get_count();i++){
var web = webs.getItemAtIndex(i);
result.push(web);
if(web.get_webs().get_count() > 0) {
getAllWebsInner(web,result,success,error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web,result,success,error);
}
getAllWebs(
function(allwebs){
for(var i = 0; i < allwebs.length;i++){
console.log(allwebs[i].get_title() + "-" + allwebs[i].get_serverRelativeUrl());
}
},
function(sender,args){
console.log(args.get_message());
});
I am trying to figure out how to tie the two together so I return the following for all specified lists on all sites and sub sites.
Lists on the current site:
URL: /sites/usaraf-ea/visa | Title: Applications | BaseType: 101 | Count: 24
URL: /sites/usaraf-ea/visa | Title: docDropOff | BaseType: 101 | Count: 28
URL: /sites/usaraf-ea/visa | Title: docResources | BaseType: 101 | Count: 5
URL: /sites/usaraf-ea/visa | Title: Documents | BaseType: 101 | Count: 2
URL: /sites/usaraf-ea/visa | Title: Site Assets | BaseType: 101 | Count: 23
Total Documents: 82
A: When you got listitem collection, you could call listItems.get_count() to return items count.
Sample code:
<script type="text/javascript">
var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(getListItemsCount, "sp.js");
function getListItemsCount() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("Child");
var camlQuery = new SP.CamlQuery();
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(Id)');
clientContext.executeQueryAsync(function () {
alert(listItems.get_count());
},
function () {
alert('error');
});
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49501411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Controlling Multiple Switch button in Android I'm Building a simple profile manager android application Using Switch Button in Android.
There are 3 switches named General,Silent and Vibrate.
Problem is all 3 switches are working together
I want the General Switch to be disabled when the silent switch is activated and silent to be disable when the general Switch is activated.
Where is my Code and what should be added ?
general = (Switch) findViewById(R.id.generalSwitch);
silent = (Switch) findViewById(R.id.silentSwitch);
vibrate = (Switch) findViewById(R.id.vibrateSwitch);
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
general.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(MainActivity.this,"General Mode Activated",Toast.LENGTH_LONG).show();
}
});
silent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(MainActivity.this,"Silent Mode Activated",Toast.LENGTH_LONG).show();
}
});
vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(MainActivity.this,"Vibrate Mode Activated", Toast.LENGTH_LONG).show();
}
});
`
A: Test with this:
general.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
silent.setChecked(false);
}
}
});
silent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
general.setChecked(false);
}
}
});
if general switch is inactive and silent switch is active, when you press general, this change your state to active and you change silent switch to inactive.
A: When you say disabled first thing I imagine is switch can not to be touchable. Like in the picture.
If you want to do something like this you should add in setOnClickListener block
something like ;
silent.setEnabled(false)
But I think you meant that;
When the silent switch is ON general switch is OFF and when the general switch is ON silent switch is OFF
Than you can use setChecked method.
Like this;
general.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(MainActivity.this,"General Mode Activated",Toast.LENGTH_LONG).show();
silent.setChecked(false);
}
});
silent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(MainActivity.this,"Silent Mode Activated",Toast.LENGTH_LONG).show();
general.setChecked(false);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35637899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to hide some models in django grappelli admin? How to hide some of the models?
I need them registred to be used by other models, while calling via FK or nested etc.
I found one solution which is rather much about view layer of (MVC)
http://blog.jholster.com/post/1534211028/hide-app-names-in-django-admin
I would like to set it in admin.py, that some of registred models are hidden.
A: If the models are in your application, just don't register them in the first place. If the model is in a third party app like the django.contrib.auth then use AdminSite unregister method. You can put this in any admin.py or urls.py important is to be discovered by the admin.autodiscover.
# admin.py
from django.contrib.auth.models import User
admin.site.unregister(User)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22842792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ImportError: DLL load failed: The file cannot be accessed by the system Traceback (most recent call last):
File "<ipython-input-9-a40793f9ded7>", line 7, in <module>
from sklearn.model_selection import train_test_split
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\__init__.py", line 76, in <module>
from .base import clone
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 16, in <module>
from .utils import _IS_32BIT
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\__init__.py", line 20, in <module>
from .validation import (as_float_array,
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 21, in <module>
from .fixes import _object_dtype_isnan
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\fixes.py", line 18, in <module>
from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\__init__.py", line 113, in <module>
from .isolve import *
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 6, in <module>
from .iterative import *
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in <module>
from . import _iterative
ImportError: DLL load failed: The file cannot be accessed by the system.
Got this error while trying to run some already used python scripts on pycharm. Has anybody had this error before and has he solved it? It started after I installed a package in python but never used it. The problem is located when I try to import train_test_split on scikit-learn and tensorflow, the sklearn package and seaborn. The other parts of the code seem unaffected.
I have already reinstalled anaconda and python as well as changing the python files. Any help would be greatly appreciated.
A: After reinstalling the python as well as updating all the packages (conda update --all) and changing the PATH file, it seems that the issue is solved in all of my IDE's except PyCharm. It seems that all that remains is an interpreter issue. I will post updates if something else comes into my attention.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60617135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits