text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to create hashMap that has a list of hashmap in kotlin?
What I am trying to achieve is is a map that has a list of maps in which the first key is ID and value obviously is a map of which the key is Session and the value is an OBJECT.
var newSession = ConcurrentHashMap<String, ConcurrentHashMap<WebSocketSession, String>>()
What if I want to save multiple session maps with the same ID? Whenever I pass an ID I want to get a map from which I should be able to search a particular session?
Sorry for not being so clear, but I am stuck here for a while and am kinda newbie in Kotlin!
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57505264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove something from one list and add it to another in python I have a nested list that has certain elements with an [x] at the beginning. I want the function to remove those elements and move them to the last list in list1 (at index 2). But it should remove the [x] from it before placing it in the last list. It should also count how many were removed from each list.
For example:
list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']
# After:
list1 = [['stretch'], ['school'], ['sleep','midterm', 'homework', 'eat', 'final']]
# Output:
# 2 removed from 1st list
# 1 removed from 2nd list
A: This is how you would do that:
list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
for x in range(0,len(list1)-1):
lst = list1[x]
count = 0
to_be_removed = []
for str in lst:
if str[0:3] == "[x]":
to_be_removed.append(str)
list1[-1].append(str[3:])
count += 1
for str in to_be_removed:
lst.remove(str)
print(f"{count} items were removed from list {x+1}" )
print(list1)
A: list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
new_list = [list() for i in range(len(list1))]
new_list[2] = list1[2]
items = 0
for i in range(len(list1)-1):
for j in list1[i]:
if "[x]" in j:
new_list[2].append(j.replace("[x]", ""))
items += 1
else:
new_list[i].append(j)
print(list1, new_list, items)
A: I think you have a data structure problem. Your code shouldn't match user input, you should get away from that as soon as possible, and separate display and storage. That being said, you can take a step towards those changes by still discarding the silliness asap:
Example of running:
$ python code.py
[['[x]homework', '[x]eat', 'stretch'], ['[x]final', 'school'], ['sleep', 'midterm']]
changed count is 0
[['stretch'], ['school'], ['sleep', 'midterm', 'homework', 'eat', 'final']]
with source code like below
def main():
list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
print(list1)
count, list2 = process(list1)
print(f'changed count is {count}')
print(list2)
def parse(silly_item):
if silly_item.startswith('[x]'):
finished = True
raw_item = silly_item[3:]
else:
finished = False
raw_item = silly_item
return finished, raw_item
def process(silly_data_format):
todos, done = silly_data_format[:-1], silly_data_format[-1]
count = 0
new_todos = []
new_done = done[:]
for todo in todos:
new_todo = []
for silly_item in todo:
finished, raw_item = parse(silly_item)
target = new_done if finished else new_todo
target.append(raw_item)
new_todos.append(new_todo)
new_silly_data_format = new_todos + [new_done]
return count, new_silly_data_format
if __name__ == '__main__':
main()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74439284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: shorter way to execute a function named as $_POST value if (isset($_POST['fn'])) {
if ($_POST['fn'] == 'giveme_lb') {giveme_lb();}
elseif ($_POST['fn'] == 'giveme_lc') {giveme_lc();}
elseif ($_POST['fn'] == 'ico_save') {ico_save();}
...
}
So I need to execute a function with the name of $_POST['fn'] value.
Any shorter way to say this?
something like $_POST['fn']();
A: call_user_func($_POST['fn']);
See http://php.net/call_user_func.
But in fact $_POST['fn']() will work in all non-ancient PHP versions as well (5.3+ if I remember correctly).
But you absolutely need to whitelist the value first, so users can't invoke arbitrary code on your system:
$allowed = ['giveme_lb', ...];
if (!in_array($_POST['fn'], $allowed)) {
throw new Exception("Not allowed to execute $_POST[fn]");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52054161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Filling form fields in Word automatically with pywin32 I have a little problem to solve, but I don´t get an acceptable solution. I try to have a script that automaticcaly fills in FormFields in Word with entries of dictionaries. So far I used pywin32 for that task and somehow I managed to find a solution that works at all. At least as long as I update the word document.
The command that I use so far in a loop is "marks(i).Result = keyValue". Here "marks" is - as far as I understand - a formfields object, which I get by "marks = doc.FormFields".
As I said, all this works to some extent, but as soon as I update the document in Word, all entries disappear again.
Would be really great if someone could help me and knows how to make it that the entry remains permanent. Unfortunately I do not understand the documentation of pywin32 at all. Attached below is the whole function.
Thanks in advance!
def wordExport(window, excDict, docPath):
wordApp = win32com.client.Dispatch('Word.Application') #Word App Object
wordApp.Visible = False
doc = wordApp.Documents.Open(docPath) #Open .docx
marks = doc.FormFields # FormFields object
cMarks = marks.Count # FormField count
cMatches = 0 #Match counter
cOverwrt = 0 #Fields overwritten
for i in range(1, cMarks + 1):
fieldName = str(marks(i).Name) #String object of FormField
#Default Cases --------------------------------------------------------------------
if fieldName in excDict:
keyValue = excDict.get(fieldName) #Get value to key(FormField)
resultIsEmpty = not marks(i).Result #No text has been entered before
# No prior entry present
if keyValue != "None"
marks(i).Result = keyValue + " "
cMatches += 1
if not resultIsEmpty:
cOverwrt += 1
doc.Close()
wordApp.Visible = False
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75086041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why when I click messagebox OK button the close code not execute? I have windows form application and I want to prevent making duplicate orders for the same patient
and I check if the patient have order today and if I try to make another order it will show message
patient have order today then when click ok button I need to close the window , but its not closing the window when click ok button ,
This is the code I used :
var patientNumber = order.GetPatientNumber(Convert.ToInt32(textPatientID.Text),Program.branch_id); // int?
bool patientExists = patientNumber.HasValue;
if (patientExists == true)
{
DialogResult dialogResult = MessageBox.Show("PATIENT HAS ORDER TODAY ", "DUPLICATE ORDER ", MessageBoxButtons.OK, MessageBoxIcon.Stop);
if (dialogResult == DialogResult.OK)
{
this.Close();
}
}
I tried also to close the form without if but also not closing :
var patientNumber = order.GetPatientNumber(Convert.ToInt32(textPatientID.Text),Program.branch_id); // int?
bool patientExists = patientNumber.HasValue;
if (patientExists == true)
{
DialogResult dialogResult = MessageBox.Show("PATIENT HAS ORDER TODAY ", "DUPLICATE ORDER ", MessageBoxButtons.OK, MessageBoxIcon.Stop);
this.Close();
}
why its not closing what's the wrong please your help ?
A: I can see no reason in
if (dialogResult == DialogResult.OK)
check, since the dialog has the only OK button:
if (order
.GetPatientNumber(int.Parse(textPatientID.Text), Program.branch_id)
.HasValue) {
MessageBox.Show(
"PATIENT HAS ORDER TODAY",
"DUPLICATE ORDER",
MessageBoxButtons.OK,
MessageBoxIcon.Stop);
Close();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70476369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fly command won't work after installing flight plan So I was working through a tutorial to deploy my node app to a server. They had me npm install flightplan -g so I can use the 'fly' command. This all worked but for the fly command to work I needed to install rsync. I finally got rsync to work after changing my PATH. But now when I use to fly command I get "'fly' is not recognized as an internal or external command,
operable program or batch file."
I've tried changing the PATH hundreds of times to different things and I can't for the life of my get the fly command to work again. I've tried reinstalling flightplan globally a bunch of times. NOTHING IS WORKING.
A: Node JS NPM modules installed but command not recognized
This was the answer I was looking for.. I had the end of my path set to npm/fly and not just npm....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36577812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Worklight 6.1 and iOS 8 I have some Apps developed with WL 6.1 and now, I updated my device to iOS 8 and none of the App is working. All of then are stucked in the Splash Screen.
I can't update WL because my server is in the "old" version.
Any suggestion?
A: Update:
Please see the following tech note for iOS 8 support: http://www-01.ibm.com/support/docview.wss?uid=swg21684538
The link includes download links for patched versions of Worklight 5.0.6, 6.0, 6.1 and 6.2 as well as a list of fixed issues and other instructions.
*
*The relevant iFix is that from September 18th at the least.
*The fix is Studio-only.
*Users of Worklight 6.1.0.x should use the iFix from September 19th containing an App Store submission bug fix.
*Users of Worklight 6.0.0.x should also delete the wlBuildResources folder from the tmp directory prior to generating the fixed version (close Eclipse > Delete > Open Eclipse).
*Due to the nature of the defect (in native code, before the Worklight framework initializes), there are no alternatives other than the below...
Scenarios:
*
*If a user has already upgraded to iOS8 and the application got stuck on the splash screen, AFAIK the way to handle it is to either:
*
*Uninstall/re-install the application from the App Store.
*Install a newer app version (see below) from the App Store.
*If a user did not yet upgrade to iOS8, it is best to use the fixed Worklight Studio to generate an updated app, increment its version and re-publish it. Then, Remote Disable the existing version and direct users to install the fixed version from the App Store; the fixed version should then continue to work after upgrading to iOS8.
Old:
Worklight in general does support iOS 8, but this is a specific scenario that requires further investigation. Thanks for the report, We're going to look into it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25777073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GDB: Seeing the source code lines? Does any program compiled with the -g command have its source code available for gbd to list even if the source code files are unavailable?? Also when you set the breakpoints at a line in a program with a complicated multi source file structure do you need the names of the source code files??
A: OP's 1st Question:
Does any program compiled with the -g command have its source code available for gbd to list even if the source code files are unavailable??
No. If there is no path to the sources, then you will not see the source.
OP's 2nd Question:
[...] when you set the breakpoints at a line in a program with a complicated multi source file structure do you need the names of the source code files??
Not always. There are a few ways of setting breakpoints. The only two I remember are breaking on a line or breaking on a function. If you wanted to break on the first line of a function, use
break functionname
If the function lives in a module
break __modulename_MOD_functionname
The modulename and functionname should be lowercase, no matter how you've declared them in the code. Note the two underscores before the module name. If you are not sure, use nm on the executable to find out what the symbol is.
If you have the source code available and you are using a graphical environment, try ddd. It stops me swearing and takes a lot of guesswork out of gdb. If the source is available, it will show up straight away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20726167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pymongo, Motor memory leak Background: I use tornado + motor, and found the mem_usage increase.
Then I code the test.py. The db.tasks "size" : 12192854 (10+M). After one minute, MEM USAGE / LIMIT is 1.219GiB / 8GiB
env:
*
*python 3.7.5
*motor 2.5.0 (2.1.0 before upgrade)
*multidict 4.7.5
*pymongo 3.12.0
Here are my code
import os
import gc
import time
import logging
import asyncio
import uvloop
import pdb
import pymongo
import base64
from tornado.platform.asyncio import AsyncIOMainLoop
from guppy import hpy
from motor import motor_asyncio
mongo_auth = 'xxxxx='
runtime_mongos = arch_mongos = {
"host": f"mongodb://{base64.b64decode(mongo_auth).decode()}@" + ','.join(
[
"1xxx:27024",
"2xxx:27024",
"3xxx:27024",
]),
"readPreference": "secondaryPreferred"
}
table = motor_asyncio.AsyncIOMotorClient(**runtime_mongos)["db"]["tasks"]
async def get_data():
return await table.find().sort([
("priority", pymongo.ASCENDING),
("start_uts", pymongo.ASCENDING),
]).to_list(None)
async def test():
while True:
a = await get_data()
print(len(a))
await asyncio.sleep(1)
gc.collect() # no use!
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
A: Finally, I found the python process has a lot of threads, then I get a clue about the motor 'ThreadPoolExecutor'.
code in motor 2.1:
if 'MOTOR_MAX_WORKERS' in os.environ:
max_workers = int(os.environ['MOTOR_MAX_WORKERS'])
else:
max_workers = tornado.process.cpu_count() * 5
_EXECUTOR = ThreadPoolExecutor(max_workers=max_workers)
I set MOTOR_MAX_WORKERS=1 and the mem_usage keeps in low level.
I deploy my project in docker.But, the cpu of the container is not exclusive.I guess this is the reason of 'max_workers' is irrational.
My fault...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68668858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Datatype-generic programming libraries for Scala I'm looking for a Scala library allowing for datatype-generic programming (like Scrap Your Boilerplate, for example). A list of libraries with appropriate links and short descriptions for each one would be a perfect answer.
A: Well,
*
*Adrian Moors has reimplemented Jeremy Gibbons' Origami programming : The paper. The source.
*Bruno Oliveira and Jeremy Gibbons have re-implemented Hinze's Generics for the masses, Lämmel & Peyton-Jones' Scrap your Boilerplate with Class, and Origami Programming, and written a detailed comparison about it.
Source here.
*Naturally, the Scala Collections library itself can easily be seen as an instance of generic programming, as Martin Odersky explains, if only because of its reliance on implicits, Scala's flavor of Type Classes.
A: Christian Hofer, Klaus Ostermann, Tillmann Rendel and Adriaan Moors's Polymorphic Embedding of DSLs has some accompanying code which is 'very generic'. They cite Finally Tagless, Partially Evaluated as an 'important influence', which endears this paper to me for some reason...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3031449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Fast search on encrypted data? I've got a requirement to encrypt Personally identifiable information (PII) data in an application DB. The application uses smart searches in the system that use sound like, name roots and part words searches to find name and address quickly.
If we put in encryption on those fields (the PII data encrypted at the application tier), the searches will be impacted by the volume of records because we cant rely on SQL in the normal way and the search engine (in the application) would switch to reading all values, decrypt them and do the searches.
Is there any easy way of solving this so we can always encrypt the PII data and also give our user base the fast search functionality?
We are using a PHP Web/App Tier (Zend Server and a SQL Server DB). The application does not currently use technology like Lucene etc.
Thanks
Cheers
A: Encrypting the data also makes it look a great deal like randomized bit strings. This precludes any operations the shortcut searching via an index.
For some encrypted data, e.g. Social security number, you can store a hash of the number in a separate column, then index this hash field and search for the hash. This has limited utility obviously, and is of no value in searches name like 'ROB%'
If your database is secured properly may sound nice, but it is very difficult to achieve if the bad guys can break in and steal your servers or backups. And if it is truly as requirement (not just a negotiable marketing driven item), you are forced to comply.
You may be able to negotiate storing partial data in unencrypted, e.g., first 3 character of last name or such like so that you can still have useful (if not perfect) indexing.
ADDED
I should have added that you might be allowed to hash part of a name field, and search on that hash -- assuming you are not allowed to store partial name unencrypted -- you lose usefulness again, but it may still be better than no index at all.
For this hashing to be useful, it cannot be seeded -- i.e., all records must hash based on the same seed (or no seed), or you will be stuck performing a table scan.
You could also create a covering index, still encrypted of course, but a table scan could be considerable quicker due to the reduced I/O & memory required.
A: I'll try to write about this simply because often the crypto community can be tough to understand (I resisted the urge to insert a pun here).
A specific solution I have used which works nicely for names is to create index tables for things you wish to index and search quickly like last names, and then encrypt these index column(s) only.
For example, you could create a table where the key column contains one entry for every possible combination of characters A-Z in a 3-letter string (and include spaces for all but the first character). Like this:
A__
AA_
AAA
AAB
AAC
AAD
..
..
..
ZZY
ZZZ
Then when you add a person to your database, you add their index to a second column which is just a list of person ID's.
Example: In your patients table, you would have an entry for smith like this:
231 Smith John A 1/1/2016 .... etc
and this entry would be encrypted, perhaps all columns but the ID 231. You would then add this person to the index table:
SMH [342, 2342, 562, 12]
SMI [123, 175, 11, 231]
Now you encrypt this second column (the list of ID's). So when you search for a last name, you can type in 'smi' and quickly retrieve all of the last names that start with this letter combination. If you don't have the key, you will just see a cyphertext. You can actually create two columns in such a table, one for first name and one for last name.
This method is just as quick as a plaintext index and uses some of the same underlying principles. You can do the same thing with a soundex ('sounds like') by constructing a table with all possible soundex patterns as your left column, and person (patient?) Id's as another column. By creating multiple such indices you can develop a nice way to hone in on the name you are looking for.
You can also extend to more characters if you like but obviously this lengthens your table by more than an order of magnitude for each letter. It does have the advantage of making your index more specific (not always what you want). Truthfully any type of histogram where you can bin the persons using their names will work. I have seen this done with date of birth as well. anything you need to search on.
A table like this suffers from some vulnerabilities, particularly that because the number of entries for certain buckets may be very short, it would be possible for an attacker to determine which names have no entries in the system. However, using a sort of random 'salt' in your index list can help with this. Other problems include the need to constantly update all of your indices every time values get updated.
But even so, this method creates a nicely encrypted system that goes beyond data-at-rest. Data-at-rest only protects you from attackers who cannot gain authorization to your systems, but this system provides a layer of protection against DBA's and other personnel who may need to work in the database but do not need (or want) to see the personal data contained within. They will just see ciphertext. So, an additional key is needed by the users or systems that actually need/want to access this information. Ashley Madison would have been wise to employ such a tactic.
Hope this helps.
A: Sometimes, "encrypt the data" really means "encrypt the data at rest". Which is to say that you can use Transparent Data Encryption to protect your database files, backups, and the like but the data is plainly viewable through querying. Find out if this would be sufficient to meet whatever regulations you're trying to satisfy and that will make your job a whole lot easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23529067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Connect to postgres database on local linux install I'm trying to figure out how to connect via my ruby app using PGConn in order to connect to my postgres database on the aws ec2 linux server.
db_connection = PGconn.connect("ip-172-31-90.9.us-west-2.compute.internal", 5432, '', '', "testdb", "username", "password")
I keep getting an error
app.rb:21:in `initialize': could not translate host name "ip-172-31-90-9.us-west-2.compute.internal." to address: nodename nor servname provided, or not known (PG::ConnectionBad)
I ran /sbin/ifconfig -a on the linux server to get the IP address, but it still can't connect. I also edited the files per the instructions from the site http://www.cyberciti.biz/tips/postgres-allow-remote-access-tcp-connection.html
A: IP of "ip-172-31-90-9" seems private IP address.
So what you need do:
*
*assign public IP or Elastic IP to that ec2 instance.
*set inbound rule in its security group and open the port 5432 to 0.0.0.0/0 or any IP ranges in your case
*test the port from your local
telnet NEW_Public_IP 5432
If can, then you should be fine to connect the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32833406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fql returning array.. but i need an object I'm using this code to get list of friends.
$params = array(
'method' => 'fql.query',
'query' => "SELECT uid FROM user WHERE uid = me()
OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())",
);
$result = $facebook->api($params);
now i'm displaying the picture of user as
echo "<img src='http://graph.facebook.com/".$result[0]."/picture'>";
but it is still returning the result as an array like this:
http://graph.facebook.com/array/picture
I need the uid at that place where it is showing array. Help please. its really important
print_r ($result[0]); gives the following output----
Array ( [uid] => XXXXXXXX )
A: This is 2-D array no need to convert it into object you can still access it
To access uid you have to do something like this
echo $result[0]['uid'];
Hence you code will become
echo "<img src='http://graph.facebook.com/".$result[0]['uid']."/picture'>";
If you still want object instead of array you can do type cast.
$result_obj= (object) $result[0];
echo $result_obj->uid;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5514073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get text inside tag using python and BeautifulSoup I'm trying to get text (example text) inside tags using beautiful soup
The html structure looks like this:
...
<div>
<div>Description</div>
<span>
<div><span>example text</span></div>
</span>
</div>
...
What i tried:
r = requests.get(url)
soup = bs(r.content, 'html.parser')
desc = soup.find('div.div.span.div.span')
print(str(desc))
A: You cannot use .find() with multiple tag names in it stacked like this. You need to repeatedly call .find() to get desired result. Check out docs for more information. Below code will give you desired output:
soup.find('div').find('span').get_text()
A: r = requests.get(url)
soup = bs(r.content, 'html.parser')
desc = soup.find('div').find('span')
print(desc.getText())
A: Your selector is wrong.
>>> from bs4 import BeautifulSoup
>>> data = '''\
... <div>
... <div>Description</div>
... <span>
... <div><span>example text</span></div>
... </span>
... </div>'''
>>> soup = BeautifulSoup(data, 'html.parser')
>>> desc = soup.select_one('div span div span')
>>> desc.text
'example text'
>>>
A: Check this out -
soup = BeautifulSoup('''<div>
<div>Description</div>
<span>
<div><span>example text</span></div>
</span>
</div>''',"html.parser")
text = soup.span.get_text()
print(text)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68259822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Too many internal channel errors while using Channel API We use Channel API in our Google App Engine application to send updates to our users. The code to send updates is something like this
for(String clientID: listOfClientID)
channelService.sendMessage(new ChannelMessage(clientID, stringMessage));
Over the past few weeks, we've been getting too many exceptions in this method. We get around around 150 exceptions for a 8-hour peak usage period.
com.google.appengine.api.channel.ChannelFailureException: An internal channel error occured.
The loop can have 500-3000 iterations. Is it a problem when ChannelService tries to send a message to a channel that has been closed? If I remove closed channels from the list, will it completely solve the problem? Please note that this large number of exceptions have been a trend only in the past few weeks and we've been using Channel API for several months.
A: Turns out that the problem was the server trying to send messages to channels that have expired. The error rate has gone down considerably when I made sure that doesn't happen anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26299283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to call Java method which returns String from C using JNI? Is there a way to call a java method, which returns a String in C?
For Integer it works like that:
JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) {
jclass employeeClass = (*env)->GetObjectClass(env, employeeObject);
jmethodID midGetAge = (*env)->GetMethodID(env, employeeClass, "getAge", "()I");
int age = (*env)->CallIntMethod(env, employeeObject, midGetAge);
return age;
}
I've searched for a long time but nothing works for String.
Finally, I want to get a char*
Thanks in advance!
A: Below is an example of JNI code calling a method returning a string. Hope this helps.
int EXT_REF Java_JNITest_CallJava(
JNIEnv* i_pjenv,
jobject i_jobject
)
{
jclass jcSystem;
jmethodID jmidGetProperty;
LPWSTR wszPropName = L"java.version";
jcSystem = i_pjenv->FindClass("java/lang/System");
if(NULL == jcSystem)
{
return -1;
}
jmidGetProperty = i_pjenv->GetStaticMethodID(jcSystem,
"getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
if(NULL == jmidGetProperty)
{
return -1;
}
jstring joStringPropName = i_pjenv->NewString((const jchar*)wszPropName, wcslen(wszPropName));
jstring joStringPropVal = (jstring)i_pjenv->CallStaticObjectMethod(jcSystem,
jmidGetProperty, (jstring)joStringPropName);
const jchar* jcVal = i_pjenv->GetStringChars(joStringPropVal, JNI_FALSE);
printf("%ws = %ws\n", wszPropName, jcVal);
i_pjenv->ReleaseStringChars(joStringPropVal, jcVal);
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40005820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Indexing JSON column in MySQL 8 So I'm experimenting with json column. Mysql 8.0.17 supposed to work with multi value JSON indexes, like this:
CREATE INDEX data__nbr_idx ON a1( (CAST(data->'$.nbr' AS UNSIGNED ARRAY)) )
I have column categories with JSON like this ["books", "clothes"].
I need to get all products from "books" category. I can use "json_contains" or new "member of".
SELECT * FROM products WHERE JSON_CONTAINS(categories, '\"books\"')
SELECT * FROM products WHERE "books" MEMBER OF(categories)
And it works. The problem is that of course EXPLAIN will reveal that there queries are making full table scan, and because of that it is slow.
So I need some index.
I changed index example by replacing "unsigned" type with "char(32) since my categories are strings and not numbers. I cannot find any example for this in google so I assumed that char() will be fine, but not.
This is my index query:
CREATE INDEX categories_index ON products((CAST(categories AS CHAR(32) ARRAY)))
also tried
CREATE INDEX categories_index ON products((CAST(categories->'$' AS CHAR(32) ARRAY)))
but selects are still making full table scan. What I'm doing wrong?
How to correctly index json column without using virtual columns?
A: For a multi-valued json index, the json paths have to match, so with an index
CREATE INDEX categories_index
ON products((CAST(categories->'$' AS CHAR(32) ARRAY)))
your query has to also use the path ->'$' (or the equivalent json_extract(...,'$'))
SELECT * FROM products WHERE "books" MEMBER OF(categories->'$')
Make it consistent and it should work.
It seems though that an index without an explicit path does not work as expected, so you have to specify ->'$' if you want to use the whole document. This is probably a bug, but could also be an intended behaviour of casting or autocasting to an array. If you specify the path you'll be on the safe side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61034231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Python, how to randomly add/append elements from one list to another? import random
global colours
global current
colours = ["Red","Yellow","Blue","Green","Orange","White"]
current = []
def randompicker():
for i in range(4):
current = random.choice(colours)
randompicker()
print(colours)
print(current)
Hey, so the above program is supposed to randomly add 4 of the elements from the list called colours into the other list named current. I have looked through the forums, but I cannot find help specific to this case.
In short, Is there a quick and efficient way to add 4 random elements from one list straight into another?
Thanks
A: You're describing the basic usage of random.sample.
>>> colours = ["Red","Yellow","Blue","Green","Orange","White"]
>>> random.sample(colours, 4)
['Red', 'Blue', 'Yellow', 'Orange']
If you want to allow duplicates, use random.choices instead (new in Python 3.6).
>>> random.choices(colours, k=4)
['Green', 'White', 'White', 'Red']
A: To fix your original code, do
current.append(random.choice(colours))
instead of
current = random.choice(colours)
You should also make current a local variable and return it rather than a global variable. In the same light, you should pass the array of choices as a parameter rather than working on a global variable directory. Both of these changes will give your function greater flexibility.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42283451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to have PhantomJSCloud wait for imbedded javascript in content I am passing an HTML string to PhantomJSCloud in the "content" of the page. The HTML has JS embedded in it inside script tags at the end of the string. When I return the jpeg that I am requesting from PJSC, the objects that the JS manipulates, have not been manipulated. I know the js works, because I can copy and paste the whole html string to a file, open it in chrome, and watch it happen.
It is using Chart.js, which has an animation option, but i have set it to false.
Currently my request JSON looks like this:
"pages": [
{
"content": "$$$CONTENT$$$",
"renderSettings": {
"quality": 100,
"selector": "[id='report']"
},
"requestSettings": {
"ioWait": 5000,
"waitInterval": 5000
}
}
]
}
Replacing the "$$$CONTENT$$$" with my actual HTML string. The whole request takes less than 5 seconds so the "waitInterval" doesn't seem to be what I'm looking for.
A: This turned out to not be an issue of whether it was waiting on the javascript. My javascript was manipulating text, and some of that text had a \n inside of it. It apparently needed a \\\n
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58032764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Plotting contours without transitions in matlab let's assume i have three matrices X,Y,Z.
X and Y are created using meshgrid and represent a 2-dimensional grid. Z contains values for this grid which can be either 0, 1 or 2.
Each of these colors represents one color (red, green, and blue). I would like to draw the two dimensional grid using these colors as background. At the moment i am doing this with contourf:
contourf(X, Y, Z, [0 1 2]);
colormap(bgcolors(1:3,:));
The entries 1-3 contain the color information for red, green and blue. The result looks as follows:
The problem is the small green area on the top of the figure. No value of Z is green in this area (1), but the values on the left are blue (2) and on the right red (0). The contourf command instead uses the colormap to draw the transition between the red and blue area. As the green color is between these values in the colormap, the transition is drawn in green.
Is there a better command for drawing such figures? I simply want to have a colored background where the color depends on the value of Z.
A: If your grid is regular (i.e. similar to the output of meshgrid), you could also use image, imagesc or, if the imageprocessing toolbox is available, also imshow together with a matching colorscale.
imagesc(Z)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23428788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Behaviour of LayoutTransition.CHANGING in ExpandableListView: animation is ok; but view is not clickable after the first click I'm new to Android, and decided to practise with ExpandableListView.
The application is very basic ExpandableListView: taken from here:
https://startandroid.ru/ru/uroki/vse-uroki-spiskom/86-urok-45-spisok-derevo-expandablelistview.html
I try to improve the animation of expanding and right after
elvMain.setAdapter(adapter); (the last line of code) I applied the following code:
LayoutTransition layoutTransition = elvMain.getLayoutTransition();
layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
The parent expands very nice and smooth, but after this first click, the whole view is not clickable, but... if I swipe just a bit on the buttons (in any direction), the parents and children respond to the swipe: the parents expand ok, or they become clickable after this swipe, but, again, only once.
What may hinder them from being clickable, and how this couold be worked around? Please share your experience or expertise. Thank you so much!
I have thoroughly investigated the problem, and tried a lot of things, but could not figure it out...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73931423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to insert value in mongodb using python 3.4.3 i have written the following code & i have searched on net.. but i'm not getting anything i've tried everything but still getting same error. Just unable to understand this error can anyone help me out please. I really need help.
from pymongo import MongoClient, collection
c = MongoClient("localhost" , 27017 , connect = True)
c.test_database
from datetime import datetime
db = c.name
result = db.restaurants.insert_one(
{
"address": {
"street": "2 Avenue",
"zipcode": "10075",
"building": "1480",
"coord": [-73.9557413, 40.7720266]
},
"borough": "Manhattan",
"cuisine": "Italian",
"grades": [
{
"date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
"grade": "A",
"score": 11
},
{
"date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
"grade": "B",
"score": 17
}
],
"name": "Vella",
"restaurant_id": "41704620"
})result.inserted_id
and here is my error , which i'm unable to understand
Traceback (most recent call last):
File "E:\practice\db.py", line 29, in <module>
"restaurant_id": "41704620"
File "C:\Python34\lib\site-packages\pymongo\collection.py", line 622, in insert_one
with self._socket_for_writes() as sock_info:
File "C:\Python34\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 712, in _get_socket
server = self._get_topology().select_server(selector)
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 142, in select_server
address))
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 118, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017:
[WinError 10061] No connection could be made because the target machine actively refused it
please if anyone knows about it please help me out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36010690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: text is not fully displayed in textview Textview ["text_body_story"] is not fully displaying the content. I have used the following xml code. I have used a listview, then when one of the items is selected, it displays my assigned string from string array. My string is extremely large sometimes upto 4000 words. The following xml code is inside of a relative layout.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/text_story_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:fontFamily="sans-serif-condensed"
android:text="text_story_name"
android:textSize="16sp"
android:textAllCaps="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textStyle="bold" />
<TextView
android:id="@+id/text_author_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text_author_name"
android:textAlignment="center"
android:textSize="14sp"
android:textStyle="bold|italic" />
<Space
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000000"
/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000000"
app:srcCompat="?attr/actionModeSplitBackground" />
<TextView
android:id="@+id/text_body_story"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text_body_story"
android:inputType="textMultiLine"
android:singleLine="false"
android:padding="10dp"
android:layout_marginBottom="10dp"/>
</LinearLayout>
</ScrollView>
How can I display the whole text in the textView?
A: To display multiple lines add :
android:ellipsize="none" //the text is not cut on textview width
android:scrollHorizontally="false" //the text wraps on as many lines as necessary
A: I recomend to use:
<TextView
android:singleLine="false"
/>
or
android:ellipsize="end"
android:singleLine="true"
with
android:layout_width="wrap_content"
or
android:inputType="textMultiLine"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49034650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: docker-compose complete the build but get a "Connection to localhost:5432 refused" in the terminal when the API try start I'm unable to get my Angular project working on Docker-Desktop for the last two days (it was working fine three weeks ago!)
I got a Front-end (web) & Back-end (API) with a PostgreSQL database.
Back-end Dockerfile:
FROM openjdk:17.0.1-jdk-slim
WORKDIR /app
ADD target/prj-0.0.1-SNAPSHOT.jar prj.jar
ENTRYPOINT ["java", "-jar", "prj.jar"]
Frontend Dockerfile:
FROM node:16.17.0-bullseye-slim as builder
LABEL desc="PRJ"
WORKDIR /app
COPY ["package.json","package-lock.json","/app/"]
RUN apt-get update -y && apt-get install curl -y && apt-get install nano -y
RUN npm install -g @angular/cli
COPY . /app
RUN ng build
CMD ng serve --host 0.0.0.0 --port 4200
Docker-compose file
version: "3.8"
services:
### FRONTEND ###
web:
container_name: prj-web
restart: always
build: ./frontend
ports:
- "4200:4200"
depends_on:
- "api"
networks:
customnetwork:
ipv4_address: 172.20.0.12
### BACKEND ###
api:
container_name: prj-api
restart: always
build: ./backend
ports:
- "2022:2022"
depends_on:
- "db"
networks:
customnetwork:
ipv4_address: 172.20.0.11
### DATABASE ###
db:
container_name: prj-db
restart: always
image: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=postgres
networks:
customnetwork:
ipv4_address: 172.20.0.10
networks:
customnetwork:
driver: bridge
ipam:
config:
- subnet: 172.20.0.0/16
gateway: 172.20.0.1
This was working fine when I did a docker-compose up -d. Got a stack with the 3 containers running and project was available in my browser through localhost:4200
What I did during the 3 weeks was just adding components in the Front-end. I did not change anything neither in the Back-end nor in the config files...
If I run the web and the DB in Docker-Desktop and I compile the Back-end in my IDE (Intellij) the apps is working my API interact with the DB and WEB container from Docker-Desktop.
I can connect to my PostgreSQL DB from DBeaver on Windows without problem.
It seems that the API can't access the DB inside Docker-Desktop.
Find several things about that specific issue, change the
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
to
spring.datasource.url = jdbc:postgresql://db:5432/postgres
But by doing this I can't run a
./mvnw clean package
command, got an error during the build as it can't connect to the DB.
A: Ok finally i found the solution!
To avoid any error during the ./mvnw clean package i added -DskipTests and changed the spring datasource from
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
to
spring.datasource.url = jdbc:postgresql://db:5432/postgres
and problem solved!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75514786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using AJAX to do a set of sequential tasks on PHP server I'm having an issue with the inherent asynchronous-ness of AJAX with what I'm trying to accomplish...
Using a file upload form, I'm trying to send a set of data to my LAMP server which then loops through each subset of the data and generates a PDF for each subset. This takes a good 2 minutes or so to process all of the PDFs since there are so many (like 100) being generated for each subset of data.
I am hoping to use JavaScript/jQuery to segment the data into subsets that I will post to the server one at a time, and as each PDF is generated, get a response from the server and increment a progress bar, then send the next request.
How would you accomplish this in a loop? What's below doesn't work because jQuery doesn't care about the state of the server and sends all requests asynchronously.
var i = 0;
$.each(data_stuff, function(key, value) {
$.post( window.location.href, {
stuff: key,
data: value
}).done(function( data ) {
if (data == 1) {
$('div#counter').text(i);
}
});
$i++;
});
Thanks!
A: Assuming data_stuff is an Object, you can try this:
var i = 0;
// We need an array (not object) to loop trough all the posts.
// This saves all keys that are in the object:
var keys = Object.keys(data_stuff);
function postNext() {
// For every POST request, we want to get the key and the value:
var key = keys[i];
var value = data_stuff[key];
$.post( window.location.href, {
stuff: key,
data: value
}).done(function( data ) {
if (data == 1) {
$('div#counter').text(i);
}
// Increment i for the next post
i++;
// If it's the last post, run postsDone
if(i == keys.length) {
postsDone();
}
// Else, run the function again:
else {
postNext();
}
});
});
postNext();
function postsDone() {
// All data was posted
}
This will only post the next bit of data_stuff after the previous $.post was done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43358097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is CanvasRenderingContext2D#drawImage() an async method in Chrome70 I want to render a video in a canvas with 25fps or more. So I use CanvasRenderingContext2D#drawImage() to render every frame in the canvas. It works in chrome69 and FireFox. But it does not work in chrome70.
Here is the code fragment:
if (frame >= this.inFrame && frame <= this.outFrame) {
// this.ctx.drawImage(this.video,
// this.sourceRect.x, this.sourceRect.y, this.sourceRect.width, this.sourceRect.height,
// this.rect.x, this.rect.y, this.rect.width, this.rect.height);
this.frame.init(this.canvas); // line 6, breakpoint here.
this.frame.isPlaying = this.isPlaying;
let image = this.frame;
for (let i = 0; i<this.filters.length;i++) {
image = this.filters[i].getImageWithFilter(frame, image);
}
return image;
}
I put a breakpoint at line 6. At this time, The video is loaded.
this.video.readyState=4
And I execute this command in dev tools.
document.getElementById("test_canvas").getContext('2d').drawImage(this.video, 0, 0);
Sometimes the test canvas shows the correct video frame, sometimes not, just nothing to show.
Let's keep the program going on, the canvas will show the correct video frame finally.
So I doubt that the CanvasRenderingContext2D#drawImage() is an async method in Chrome70. But I find nothing in Chrome website.
Could anyone help me with this question or help me render correctly in every frames.
A: You can check that by imply calling getImageData() or even just fillRect() right after your drawImage() call.
If the returned ImageData is empty, or if there is no rect drawn over your video frame, then, yes, it might be async, which would be a terrible bug that you should report right away.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var vid = document.createElement('video');
vid.muted = true;
vid.crossOrigin = 'anonymous';
vid.src = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm'
vid.play().then(() => {
ctx.drawImage(vid, 0, 0);
console.log(
"imageData empty",
ctx.getImageData(0, 0, canvas.width, canvas.height).data.some(d => !!d) === false
);
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 50, 50);
});
document.body.append(canvas);
So now, to give a better explanation as to what you saw, the debugger will stop the whole event loop, and Chrome might have decided to not honor the next CSS frame drawing when the debugger has been called. Hence, what is painted on your screen is still the frame from when your script got called (when no image was drawn).
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var vid = document.createElement('video');
vid.muted = true;
vid.crossOrigin = 'anonymous';
vid.src = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm'
vid.play().then(() => {
ctx.drawImage(vid, 0, 0);
const hasPixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data.some(d => !!d);
alert('That should also block the Event loop and css painting. But drawImage already happened: ' + hasPixels)
});
document.body.append(canvas);
canvas{
border:1px solid;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53187982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I package my Java Maven desktop app with Netbeans 12.6 so that it can be installed on multiple operating systems? I've been searching high and low for answers for this, but it has proved pretty hard. Maybe I'm just not searching for the right thing, but I'm not sure.
Essentially, I have an app. I want it to work on my Windows system and another MacOS system. I'd also like it to be installed as you would an application made for the average computer user. I know I can run it from the console with java -jar, but I'm more hoping to get some kind of installer, like the .exe/.msi files you get from C# and VS Studio.
I've found a lot of solutions, but very few are up to date (either broken links or depreciated) and even less mention using the Netbeans Maven projects. For example, mosto of the advice I've seen so far says:
*
*Clean and build
*Run the .jar file from the dist folder in the PROJECT_HOME parent folder
The issue is the doing the clean and build action with a Netbeans Maven project doesn't create a dist folder. And anyway, this doesn't help me make a clean, neat desktop application which is installed in the way most people are used to.
Does anyone know how to do this, or can anyone point me in the direction of some relevant documentation I can check? Thanks in advance.
A: For building your application into a jar file, run mvn clean package which should create a target folder which contains the jar. Also, consider looking into the configuration for maven-jar-plugin maven-shade-plugin and maven-assembly-plugin to customize the jar more.
For creating an installer for your application such as an .exe or .msi file, I'd recommend using Inno Setup (link) or maybe look into jpackage depending on your Java version and environment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71400804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Is it possible to set Redis key expiration time when using Spring Integration RedisMessageStore Dears, I'd like to auto-expire Redis keys when using org.springframework.integration.redis.store.RedisMessageStore class in Spring Integration. I see some methods related to "expiry callback" but I could not find any documentation or examples yet. Any advice will be much appreciated.
@Bean
public MessageStore redisMessageStore(LettuceConnectionFactory redisConnectionFactory) {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory, "TEST_");
return store;
}
Spring Boot: 2.6.3, spring integration and spring-boot-starter-data-redis.
A: The RedisMessageStore does not have any expiration features. And technically it must not. The point of this kind of store is too keep data until it is used. Look at it as persistent storage. The RedisMetadataStore is based on the RedisProperties object, so it also cannot use expiration feature for particular entry.
You probably talk about a MessageGroupStoreReaper, which really calls a MessageGroupStore.expireMessageGroups(long timeout), but that's already an artificial, cross-store implementation provided by the framework. The logic relies on the group.getTimestamp() and group.getLastModified(). So, still not that auto-expiration Redis feature.
The MessageGroupStoreReaper is a process needed to be run in your application: nothing Redis-specific.
See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#reaper
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70826832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Round Corner (css and javascript) Please go to: http://jlecologia.com/page1c.html to see the problem
The top box look fine but in IE6 there is a double top and bottom border.
can somebody point me ut what i have done wrong ?
Or can anybody tell me a javascript rounded box that accept to do that effect with the border that is unequal. I have test some and they all fail, so i have done the picture round box but i like the jQuery javascript approach better.
A: Take a look at the JQuery's round corner plugin
And here is a demo
A: The default for background images to to have them repeat.
Try: background: transparent url(../images/roundbox-top.jpg) 0 0 no-repeat;
Edited after comment to provide full solution:
IE6 sets the height of empty divs to your font-size if the height specified in the css is less than the font-size.
On #roundbox .top and #roundbox .bottom, put
font-size:0;
line-height:0;
That will collapse the div to the right height.
A: In addition to the change you've made for the bottom border, setting the font-size of the element with class "top" to 7px fixes it in my IE6.
A: Try using the web developer toolbar in Firefox to validate the CSS and HTML. I did a quick check and there are multiple errors in each. The rendering difference, I suspect, is because IE does not handle malformed content as well as FF. In particular, even small errors in CSS files tend to snowball in IE and melt down an otherwise good layout. Not sure if IE7 and IE8 have made any improvements in this regard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/928691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Routing Rails Admin Controller Create Action A dedicated admin/countries_controller is being correctly used for all actions (index, ...), except for creating records. Here the regular countries_controller from the parent controller directory is active:
Started POST "/countries" for 127.0.0.1 at 2011-06-29 23:26:38 +0200
Processing by CountriesController#create as HTML
What is missing to have the POST action being routed to admin/countries?
routes.rb:
resources :countries
namespace :admin do
resources :countries
end
rake routes:
countries GET /countries(.:format) {:action=>"index", :controller=>"countries"}
POST /countries(.:format) {:action=>"create", :controller=>"countries"}
new_country GET /countries/new(.:format) {:action=>"new", :controller=>"countries"}
admin_countries GET /admin/countries(.:format) {:action=>"index", :controller=>"admin/countries"}
POST /admin/countries(.:format) {:action=>"create", :controller=>"admin/countries"}
new_admin_country GET /admin/countries/new(.:format) {:action=>"new", :controller=>"admin/countries"}
Similar question unanswered here:
Rails help with building Admin area - Routing problem
A: Your form_for needs to be namespaced too:
<%= form_for [:admin, @country] do |f| %>
...
<% end %>
When you pass @country to form_for it's not going to know what namespace you want this form to go to and so it will default to just the standard POST /countries URL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6527639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MYSQL: how to retrieve all table rows + only the last row where column equals OK, a bit of a complicated query, for me anyway.
I'm trying to build a MYSQL query to retrieve all the rows from a DB, but I only want the last row where the column 'topic' equals 'This Week'.
So, what I mean is this:
I have a DB table with all my blog articles. Every week, I write a summary of the aviation news from the past week. I now want to show all the blog posts on the index page, but I also only want to show the last 'This Week' post.
This is the query I use now to retrieve all the rows:
SELECT * FROM articles WHERE published = '1' ORDER BY date_time DESC LIMIT 10
So I need a query that returns all the rows from my table 'articles' + only the last row where 'topic' = 'This Week'.
Anyone who can help me with this?
A: you may use Unions ( something like this
SELECT * FROM articles WHERE published = '1' ORDER BY date_time DESC LIMIT 10
UNION
SELECT * FROM articles WHERE WHERE topic="This Week" order by ID desc LIMIT 1
you may use UNION or UNION ALL whichever suits your need
you may wanna check the actual query and format it as per your needs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40726978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to delete string from a string in Python? This can look like a simple question but not in my situation.
I have a list
list0 = ['amigohello','amigobye']
And i want to delete "amigo" from it.
If I try:
for x in list0:
print x.split("amigo")
It gives me next:
['', 'hello']
['', 'bye']
I tried:
for x in list0:
x = str(x.split("amigo"))
print x.split("[''")
Also:
for x in list0:
print x.strip('amigo')
And it gives me:
hell
bye
The most strange is that in this output doesnt delete all 'o' if i change 'amigohello' to 'amigohoeollo'
And of course i tried with x.strip('amigo')[0]
What i just want to do is delete exactly on string everything that is "amigo", not a.m.i.g.o or ami.go., only if i found amigo without the [] problem or a solution to the [] problem. Thanks.
A: You should use str.replace to replace exact appearances of the word amigo:
for x in list0:
print x.replace("amigo", "")
'hello'
'bye'
A: There's a replace method in which you can replace the undesired word for an empty string.
list0 = ['amigohello','amigobye']
for x in list0:
print(x.replace("amigo", "")) # hello, bye
A: list0 = [item.replace('amigo','') for item in list0]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45643326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass Count of Group Rows fro one group to another I have one group that groups by month, and another group that groups by year beneath it. In the month group row there is a sum of a field. In the year group I want to display the monthly average, not the sum for the year.
Jan 2008 10
Feb 2008 15
Mar 2008 35
2008 20
So 2008 summary line is 60/3 = 20. I suspect it is something using CountRows but not sure how to accomplish.
A: You should be able to just do something like this...
=Sum(Fields!myAmountField.Value) / CountDistinct(Fields!myMonthField.Value)
if your report spans more than one year you may have to do something like
=Sum(Fields!myAmountField.Value, "myYearGroupName") / CountDistinct(Fields!myMonthField.Value, "myYearGroupName")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55479993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: variables' scope and place the following code inside one of the functions in scope.js so the output is a: 1, b: 8, c: 6 var a = 1, b = 2, c = 3;
(function firstFunction(){
var b = 5, c = 6;
(function secondFunction(){
var b = 8;
(function thirdFunction(){
var a = 7, c = 9;
(function fourthFunction(){
var a = 1, c = 8;
})();
})();
})();
})();
Use your knowledge of the variables' scope and place the following code
inside one of the functions in scope.js so the output is a: 1, b: 8, c: 6
console.log("a: "+a+", b: "+b+", c: "+c);
A: var a = 1, b = 2, c = 3;
(function firstFunction(){
var b = 5, c = 6;
(function secondFunction(){
var b = 8;
console.log("a: "+a+", b: "+b+", c: "+c); //a: 1, b: 8, c: 6
(function thirdFunction(){
var a = 7, c = 9;
(function fourthFunction(){
var a = 1, c = 8;
})();
})();
})();
})();
A: var a = 1, b = 2, c = 3;
(function firstFunction(){
var b = 5, c = 6;
(function secondFunction(){
var b = 8;
(function thirdFunction(){
var a = 7, c = 9;
(function fourthFunction(){
var a = 1, c = 8;
})();
})();
console.log("a: "+a+", b: "+b+", c: "+c); // it's here because of 'hoisting'. if you need more I can explain
})();
})();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45949228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: RAILS: -destroy just erasing record (not deleting) bicycle.rb
has_many :pictures, as: :imageable
accepts_nested_attributes_for :pictures, allow_destroy: true, :reject_if => proc { |obj| obj.blank? }
picture.rb
belongs_to :imageable, polymorphic: true
has_attached_file :image
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]
Edit view
<% @bicycle.pictures.each do |pic| %>
<%= bicycle_form.fields_for :pictures, pic do |frm| %>
<div class="col-lg-2">
<%= image_tag pic.image.url, class: 'edit-image-thumb'%>
Delete: <%= frm.check_box :_destroy %>
</div>
<% end %>
<% end %>
Picture attribute _destroy is whitelisted:
pictures_attributes: [:id, :image, :_destroy]
Problem:
As i understand, _destroy checkbox must delete whole record in database (picture record), but it's just erasing image_file_name image_content_type image_file_size column values, but record still exists.
Explanation:
I have bicycle which has many pirctures. So when i am creating new bicycle, i can attach many pictures. If i want to delete them, i am going to edit view and checking checkboxes for pictures i want to delete. But pictures records doesn't deleting from db, just clearing columns image_file_name image_content_type image_file_size leaving them blank but columns (in the same record) imageable_type and id still have values. So the image is showing up (it still exitst) but like missing (record exists but field with image name is nil)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37369078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: tns plugin add nativescript-floatingactionbutton Installation Failed I wanted to use the Floating button in my App.
tns plugin add nativescript-floatingactionbutton
But the Installation failed. Below is the installation error.
I tried this also
sudo npm i nativescript-floatingactionbutton
A: This looks like a permission error, since it is not able to write to your node_modules folder.
A: sometimes sudo doesn't work you just have to do su first then Enter, then type commands normally like tns plugin add nativescript-xxxxxxx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55651786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .NET 2.0 C# Treeview Drag/Drop within TreeNodes I am interested in capturing a drag/drop event that will start with the user dragging an existing TreeNode somewhere within the TreeView. While the user is dragging the TreeNode around, I am interested in capturing when the node has been dragged between two tree nodes. When the user does this, I wanted to display a hash mark in-between the tree nodes to designate if the node would be dropped within the node as a child or as a sibling. This hash mark would display either:
- underneath the destination node (to indicate the source node will be dropped as a child of the destination node
OR
- underneath the destination node to the left (to indicate the source node will be dropped as a sibling of the destination node), before or after...
I have made some headway using the DragOver event. I am calculating the mouse location and deriving what the top and bottom nodes are as I drag the mouse around..
int threshold = 8; //Joe(hack)
Point mouseLocation = mouseLocation = treeViewConditions.PointToClient(new Point(e.X, e.Y - threshold));
TreeNode topNode = treeViewConditions.GetNodeAt(mouseLocation);
mouseLocation = treeViewConditions.PointToClient(new Point(e.X + threshold, e.Y));
TreeNode bottomNode = treeViewConditions.GetNodeAt(mouseLocation);
if (topNode != null && bottomNode == null)
{
textBoxDescription.Text = "handling top node";
}
else if (topNode == null && bottomNode != null)
{
textBoxDescription.Text = "handling bottom node";
}
else if (topNode != null && bottomNode != null)
{
if (topNode != bottomNode)
{
textBoxDescription.Text = "between!";
}
else if (topNode == bottomNode)
{
}
}
However in doing this, it just feels dirty. I am wondering if anyone knew of a better way to do accomplish this.
Thanks a ton in advance!
A: Drawing the 'hash mark' is going to be the real problem. TreeView has a DrawMode property but its DrawItem event doesn't let you draw between the nodes.
You need to handle this by changing the cursor to indicate what is going to happen. Use the GiveFeedback event, set e.UseCustomCursors to false and assign Cursor.Current to a custom cursor that indicates the operation.
A: This article articulates the same issue and provides an approach somewhat similar to the one you are already following (with the exception that the thresholds are essentially percentages of the height of the tree node). Based on this, and the fact that when I was doing this before, that was the best approach I could find, I think you're basically on track.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3662585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flash Builder 4.6 | Remove Child | s:TileGroup I’m sure it’s something super simple that I’m missing, but I’m having issues removing a VBox that’s inside an s:Tilegroup. I can't get it to delete. For a test, I was able to delete the VBox when I only added to the stage (instead of the s:TileGroup). The code below shows the concept that I’m playing with as well.
*
*I have a button on stage as well as a blank s:TileGroup to start
*When you click the button, it dynamically adds a VBox (that holds some text well) to the s:TileGroup
*When that VBox is created, I’m also adding an event listener so that when you click the vbox, it can be deleted
<fx:Script>
<![CDATA[
protected function removeVBOX(event:Event):void{
var t:DisplayObject = DisplayObject(event.target);
t.parent.removeChild(t);
}
private function addVbox() : void {
var vbox :VBox = new VBox();
vbox.addEventListener(MouseEvent.CLICK,removeVBOX);
vbox.width = 400;
vbox.height = 500;
vbox.horizontalScrollPolicy = "off";
vbox.verticalScrollPolicy = "off";
vbox.setStyle("backgroundAlpha", 0.39);
vbox.setStyle("backgroundColor", 0x000000);
vbox.setStyle("paddingLeft", "15");
vbox.setStyle("paddingTop", "15");
vbox.setStyle("paddingRight", "15");
vbox.setStyle("paddingBottom", "15");
var sText :RichText = new RichText();
var sText2 :RichText = new RichText();
var sText3 :RichText = new RichText();
sText.text = "Hello 1";
sText2.text = "Hello 2";
sText3.text = "Hello 3";
//addElement(vbox);
table.addElement(vbox);
vbox.addElement(sText);
vbox.addElement(sText2);
vbox.addElement(sText3);
}
]]>
</fx:Script>
<s:Button x="743" y="767" label="Button" click="addVbox()"/>
<s:TileGroup id="table" x="152" y="81" width="627" height="650" horizontalAlign="center" horizontalGap="13"
orientation="columns" requestedColumnCount="1" verticalAlign="middle" verticalGap="13" >
</s:TileGroup>
A: Looking at your code, I see that you're adding your VBox to the TileGroup as follows:
table.addElement(vbox);
But then you're trying to remove it using removeChild():
t.parent.removeChild(t);
The proper method to add/remove items to/from Spark containers is add/removeElement():
var t:IVisualElement = IVisualElement(event.target);
t.parent.removeElement(t);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32948614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Text Only Once Through Random Method I am new to Android. I am showing Text in the TextView on Button click Randomly. On 1st Textview the Heading and on 2nd the explaination of that heading. I am able to show the Heading and Explaination Randomly and now I want if the Text is shown once should not be shown again means it will be removed. This is the point where I stuck. I am not able to remove the texts. Any help will be appreciated. I am posting my code here.
MainActivity.java
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text_heading.setText(array_heading.get(int_text)); //getting error
text_explain(array_explain.get(int_text)); //getting error
array_heading.remove(int_text); //getting error
array_explain.remove(int_text); //getting error
}
});
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer>array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
}
}
A:
I am not able to remove the texts. Any help will be appreciated. I am
posting my code here.
To clean the content of the TextView you could pass null to setText. E.g
text_heading.setText(null);
If you want to change the content every time you click on the button, you have to move
int_text = random.nextInt(array_heading.length);
your onClick callback,
You should be aware of the fact that next int returns an int between [0, n). array_heading.length -1 is necessary only if you want to exclude R.string.source_text9_explain from the possible texts you want to show. Keep also in mind that if array_heading contains more items than array_explain you could get ArrayIndexOutBoundException
A: You must use ArrayList for it.
ArrayList<Integer> heading = Arrays.asList(array_heading);
ArrayList<Integer> explain = Arrays.asList(array_explain);
Now set text from this arraylists. And when its set once remove it from the arraylist so it cannot be shown again.
Use like this
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size());
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text));
text_explain.setText(array_explainList.get(int_text));
array_headingList.remove(int_text);
array_explainList.remove(int_text);
if(array_headingList.size() == 0){
click.setEnabled(false);
Toast.makeText(getApplicationContext(),"All text finished",Toast.LENGTH_SHORT).show();
} else if(array_headingList.size() == 1){
int_text = 0;
} else {
int_text = random.nextInt(array_headingList.size());
}
}
});
A: TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text)); //getting error
text_explain.setText(array_explainList.get(int_text)); //getting error
array_headingList.remove(int_text); //getting error
array_explainList.remove(int_text); //getting error
}
});
}
}
A: I would keep the strings together in an object:
public class Item {
private final int textId;
private final int textExplanationId;
public class Item(int textId, int textExplanationId){
this.textId = textId;
this.textExplanationId = textExplanationId;
}
public int getTextId(){return textId;}
public int getTextExplanationId(){return textExplanationId;}
}
Then I would store those in an ArrayList:
List<Item> items = new ArrayList<Item>(new Item[]{
new Item(R.string.source_text1, R.string.source_text1_explain),
new Item(R.string.source_text2, R.string.source_text2_explain),
//etc
});
Then I would shuffle that array once:
Collections.shuffle(items);
And read from it in order:
Item current = items.get(currentIndex++);
text_heading.setText(current.getTextId());
text_explain.setText(current.getTextExplanationId());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34154642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to draw angstrom (Å) using AggPas? Summarization:
No luck in finding how to output the angstrom sign using AggPas library.
===============================================
The text-drawing function in the AggPas library takes a PAnsiChar parameter. I am wondering how can I can use PAnsiChar to point to text containing angstrom (Å)?
SetThreadLocale($0409); // No difference.
ShowMessage(Chr(0197)); // Correct
ShowMessage(AnsiString(Chr(0197))); // Wrong - question mark
ShowMessage(PAnsiChar(Chr(0197))); // AV
ShowMessage(UTF8String(Chr(0197))); // Correct
ShowMessage(UTF8Encode(Chr(0197))); // Correct
ShowMessage(RawByteString(Chr(0197))); // Wrong - question mark
ShowMessage(AnsiString(UTF8String(Chr(0197)))); // Wrong - question mark
ShowMessage(AnsiString(UTF8Encode(Chr(0197)))); // Correct
ShowMessage(RawByteString(UTF8String(Chr(0197)))); // Wrong - question mark
ShowMessage(RawByteString(UTF8Encode(Chr(0197)))); // Correct
ShowMessage(PAnsiChar(AnsiString(UTF8Encode(Chr(0197))))); // Wrong - strange character
ShowMessage(PAnsiChar(RawByteString(UTF8Encode(Chr(0197))))); // Wrong - strange character
For your convenience, the DrawTextCenterAligned procedure in the following code cannot output the angstrom letter.
unit u2DRenderEngine_aggpas;
interface
uses
u2DRenderEngine, uMathVector3D,
agg_2D,
Graphics, IniFiles, Types;
type
T2DRenderEngine_aggpas = class;
T2DRenderEngine_aggpas = class(T2DRenderEngine)
private
fFontBMP: TBitmap;
fVG: Agg2D;
protected
function GetActualStringBoundingBox(aText: string; aFont: TFont)
: TRect; override;
public
constructor Create;
destructor Destroy; override;
procedure AttachBMP(aBMP: TBitmap; flip_y: Boolean);
procedure Flush; override;
procedure DrawLine(aP, bP: TPoint3D; aPen: TPen); override;
procedure DrawCircle(Center: TPoint3D; Radius: Extended;
R, G, B: Integer); override;
procedure FillCircle(Center: TPoint3D; Radius: Extended;
R, G, B: Integer); override;
procedure DrawPolygon(aPts: TAPoint3D; R, G, B: Integer); override;
procedure FillPolygon(aPts: TAPoint3D; R, G, B: Integer); override;
procedure DrawTextLeftAligned(aLeft: TPoint3D; aText: string; aFont: TFont;
clearBackground: Boolean); override;
procedure DrawTextCenterAligned(aCenter: TPoint3D; aText: string;
aFont: TFont; clearBackground: Boolean); override;
end;
implementation
uses
u2DUtils_Vcl, SysUtils, Math;
{ TRenderEngine_2D_aggpas }
constructor T2DRenderEngine_aggpas.Create;
begin
inherited;
fFontBMP := TBitmap.Create;
fFontBMP.Width := 2;
fFontBMP.Height := 2;
fVG.Construct;
end;
destructor T2DRenderEngine_aggpas.Destroy;
begin
inherited;
end;
procedure T2DRenderEngine_aggpas.AttachBMP(aBMP: TBitmap; flip_y: Boolean);
var
tmpBuffer: pointer;
tmpStride: Integer;
begin
if aBMP.Empty then
raise Exception.Create('AttachBMP: aBMP is Empty!');
if aBMP.PixelFormat <> pf32bit then
raise Exception.Create('AttachBMP: aBMP should be 32bit!');
tmpStride := Integer(aBMP.ScanLine[1]) - Integer(aBMP.ScanLine[0]);
if tmpStride < 0 then
tmpBuffer := aBMP.ScanLine[aBMP.Height - 1]
else
tmpBuffer := aBMP.ScanLine[0];
if flip_y then
tmpStride := tmpStride * -1;
fVG.attach(tmpBuffer, aBMP.Width, aBMP.Height, tmpStride);
end;
procedure T2DRenderEngine_aggpas.Flush;
begin
end;
procedure T2DRenderEngine_aggpas.DrawLine(aP, bP: TPoint3D; aPen: TPen);
begin
fVG.line(aP.X, aP.Y, bP.X, bP.Y);
end;
procedure T2DRenderEngine_aggpas.DrawCircle(Center: TPoint3D; Radius: Extended;
R, G, B: Integer);
begin
fVG.lineColor(R, G, B);
fVG.noFill;
fVG.ellipse(Center.X, Center.Y, Radius, Radius);
end;
procedure T2DRenderEngine_aggpas.FillCircle(Center: TPoint3D; Radius: Extended;
R, G, B: Integer);
begin
fVG.fillColor(R, G, B);
fVG.noLine;
fVG.ellipse(Center.X, Center.Y, Radius, Radius);
end;
procedure T2DRenderEngine_aggpas.DrawPolygon(aPts: TAPoint3D; R, G, B: Integer);
var
Len, I: Integer;
poly: array of double;
begin
Len := Length(aPts);
SetLength(poly, Len * 2);
for I := 0 to Len - 1 do
begin
poly[2 * I] := aPts[I].X;
poly[2 * I + 1] := aPts[I].Y;
end;
fVG.lineColor(R, G, B);
fVG.noFill;
fVG.polygon(@poly[0], 4);
end;
procedure T2DRenderEngine_aggpas.FillPolygon(aPts: TAPoint3D; R, G, B: Integer);
var
Len, I: Integer;
poly: array of double;
begin
Len := Length(aPts);
SetLength(poly, Len * 2);
for I := 0 to Len - 1 do
begin
poly[2 * I] := aPts[I].X;
poly[2 * I + 1] := aPts[I].Y;
end;
fVG.fillColor(R, G, B);
fVG.noLine;
fVG.polygon(@poly[0], 4);
end;
procedure T2DRenderEngine_aggpas.DrawTextLeftAligned(aLeft: TPoint3D;
aText: string; aFont: TFont; clearBackground: Boolean);
var
tmpRect: TRect;
tmpRectWidth, tmpRectHeight: Integer;
tmpPt: TPoint3D;
begin
tmpRect := GetActualStringBoundingBox(aText, aFont);
tmpRectWidth := tmpRect.Right - tmpRect.Left;
tmpRectHeight := tmpRect.Bottom - tmpRect.Top;
tmpPt.X := aLeft.X;
tmpPt.Y := aLeft.Y - tmpRectHeight;
if clearBackground then
begin
fVG.fillColor(255, 255, 255);
fVG.noLine;
fVG.Rectangle(tmpPt.X, tmpPt.Y, tmpPt.X + tmpRectWidth,
tmpPt.Y + tmpRectHeight);
end;
// Font & Colors
fVG.fillColor(0, 0, 0);
fVG.noLine;
fVG.TextHints(True);
if Agg2DUsesFreeType then
fVG.Font(PAnsiChar(AnsiString(UTF8Encode(LowerCase(aFont.Name) + '.ttf'))),
Abs(aFont.Height))
else
fVG.Font('Arial', 40.0);
// Text
fVG.Text(tmpPt.X, tmpPt.Y + tmpRectHeight, PAnsiChar(AnsiString(aText)));
end;
procedure T2DRenderEngine_aggpas.DrawTextCenterAligned(aCenter: TPoint3D;
aText: string; aFont: TFont; clearBackground: Boolean);
var
tmpRect: TRect;
tmpRectWidth, tmpRectHeight: Integer;
tmpPt: TPoint3D;
begin
tmpRect := GetActualStringBoundingBox(aText, aFont);
tmpRectWidth := tmpRect.Right - tmpRect.Left;
tmpRectHeight := tmpRect.Bottom - tmpRect.Top;
tmpPt.X := aCenter.X - tmpRectWidth / 2.0;
tmpPt.Y := aCenter.Y - tmpRectHeight / 2.0;
if clearBackground then
begin
fVG.fillColor(255, 255, 255);
fVG.noLine;
fVG.Rectangle(tmpPt.X, tmpPt.Y, tmpPt.X + tmpRectWidth,
tmpPt.Y + tmpRectHeight);
end;
// Font & Colors
fVG.fillColor(0, 0, 0);
fVG.noLine;
fVG.TextHints(True);
if Agg2DUsesFreeType then
fVG.Font(PAnsiChar(AnsiString(UTF8Encode(LowerCase(aFont.Name) + '.ttf'))),
Abs(aFont.Height))
else
fVG.Font('Arial', 40.0);
// Text
fVG.Text(tmpPt.X, tmpPt.Y + tmpRectHeight, PAnsiChar(AnsiString(aText)));
end;
function T2DRenderEngine_aggpas.GetActualStringBoundingBox(aText: string;
aFont: TFont): TRect;
var
tmpRectWidth, tmpRectHeight: Integer;
begin
Self.fFontBMP.Canvas.Font.Assign(aFont);
tmpRectWidth := Self.fFontBMP.Canvas.TextWidth(aText);
tmpRectHeight := Self.fFontBMP.Canvas.TextHeight(aText);
// 2011-03-07 hard-coded
tmpRectWidth := Ceil(tmpRectWidth * 1.05);
// 2011-03-07 hard-coded
tmpRectHeight := Ceil(tmpRectHeight * 0.70);
FillChar(Result, SizeOf(Result), 0);
Result.Right := tmpRectWidth;
Result.Bottom := tmpRectHeight;
end;
end.
A: If the unit takes it's input as PAnsiChar, you're toast. Unless the default code page on your system can encode the Å character, there's simply no way of putting that information into an ANSI CHAR. And if such encoding was available, all of your routines that now show question marks would have shown the proper char.
Slightly longer info:
Unicode is encoding a vast amount of characters, including all characters in all written languages, special symbols, musical notes, the space is so vast there's encoding for Klingon characters! Ansi chars are encoded using a table lookup that maps the values that can be encoded in one byte to a selection of Unicode chars.
When using AnsiString you can only use less then 256 Unicode chars at a time. When you try to encode one Unicode char to one AnsiString you'll essentially doing a lookup in the code page table, looking for a code that points back to the original Unicode char. If no such encoding is available you get the famous question mark!
Here's a routine that converts string to UTF8 string and returns it as AnsiString (all UTF8 is actually valid - but meaningless - AnsiString):
function Utf8AsAnsiString(s:string):AnsiString;
var utf8s:UTF8String;
begin
utf8s := UTF8String(s);
SetLength(Result, Length(utf8s));
if Length(utf8s) > 0 then
Move(utf8s[1], Result[1], Length(utf8s));
end;
You can pass the result of this function and hope the unit can handle UTF8. Good luck.
A: You need an intermediary step to load the char into a string, like so:
const
ANGSTROM = Chr(0197);
procedure ShowAngstrom;
var
message: AnsiString;
begin
message := ANGSTROM;
ShowMessage(PAnsiChar(message));
end;
EDIT: Here's a guess as to what the problem might be if this doesn't work for AggPas.
I'm not familiar with AggPas, but I have used the Asphyre graphics library, and its text-drawing system, back in the pre-Unicode days, required you to generate a specialized bitmap by giving it a font file and a range of characters it could print. (Not sure if it's improved since then; I haven't used it in a while.) Any character outside that range wouldn't print properly.
If AggPas works in a similar way, it could be that the font image you have doesn't contain anything for character 197, so no matter how correct your Delphi code is, it's got nothing to map to and you're not going to get the right output. See if you can verify this.
If not... then I'm out of ideas and I hope someone else here is more familiar with the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5251317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Line break caused by long words visually breaks the centering of paragraphs with left-aligned text I am creating a centered paragraph with left-aligned text. In most cases, everything works very well. However, when there is a really long word at the end of the line which forces the text to break to the newline, it leaves a lot of white space at the end of the first line. This makes the whole paragraph look visually "uncentered" - leaning more towards the left side like shown in the code example (imagine gray background not being there).
I have tried to experiment with inline-block but unsuccessfuly so far. As I believe this could be a very nice riddle, I decided to share it here. Note: It is also not clear what text ends up inside the paragraph, so we need to think of a general solution (no hardcoded margins etc.). Words need to stay as they are, break-word is not appropriate for my scenario.
.content {
margin: auto;
width: 400px;
}
p {
background-color: #eee;
}
<div class="content">
<p>
At vero eos et accusamus et iusto odio digducimusverylongword qui
</p>
</div>
I tried to work with this discussion: Center a short text block that is align left. But it does not seem to be valid when the linebreak is automatic instead of an explicit <br> element.
A: Depending upon your i18n end goal, you could just define the word-break property:
.content {
margin: auto;
width: 400px;
}
p {
background-color: #eee;
word-break: break-all;
}
<div class="content">
<p>
At vero eos et accusamus et iusto odio digducimusverylongword qui
</p>
</div>
A: Although I realise it's probably not what you're looking for (and that @BenM's answer of using word-break: break-all is probably more appropriate)... another option is simply using text-align:justify...
.content {
margin: auto;
width: 400px;
}
p {
background-color: #eee;
text-align:justify;
}
<div class="content">
<p>
At vero eos et accusamus et iusto odio digducimusverylongword qui
</p>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58803288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boostrap carousel issues on ASP.Net Razor Page I am having a fair few issues using ASP.Net MVC 5 + Twitter Bootstrap 3.
Styling, that works, no issues - but the carousel I put in does not cycle, nor does it respond to the next/prev arrows or the navigation buttons.
I even gave in and pulled a carousel example from an article: (Bootstrap Carousel Tutorial to rule out errors in my code.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css") <!-- this is the bundle name -->
@Scripts.Render("~/Content/bundles/modernizr")
</head>
<body>
<!--------------------------- Carousel ------------------------------->
( Exact code from http://bootstrapbay.com/blog/bootstrap-3-carousel-tutorial/ )
<!-------------------------------------------------------------------->
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
But It doesn't work, as described at the start. Any clues? [I don't want to clutter up the question with my Site.less or BundleConfig code - but if you need it, ask.]
( for the record I also tried
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<script src="~/Content/Scripts/bootstrap/js/bootstrap.min.js"></script>
<script src="~/Content/Scripts/respond.js"></script>
rather than bundling - but same result...)
A: Once pointed to look in the right direction I found that I moved the the files/renamed the bundle and hadn't updated the call.
instead of
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
I should have had
@Scripts.Render("~/Content/bundles/jquery")
@Scripts.Render("~/Content/bundles/bootstrap")
to match the bundle config
var jqueryBundle = new ScriptBundle("~/Content/bundles/jquery");
...
var bootstrapBundle = new ScriptBundle("~/Content/bundles/bootstrap");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27152441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update Query not working in Android Sqlite My Java code Update Data base Table
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+code;
Log.d("Qry", qq);
myDbHelper.updatequery(qq);
updatequery method
public void updatequery(String qry)
{
Cursor c = myDataBase.rawQuery(qry, null);
Log.d("Up", ""+c.getCount());
}
When i updated Data base the count return 0 and table not updated
I am using this Also but not work
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+"'"+code+"'";
Please Help Me how i can fix this problem
Thanks In Advance
A: Use execSQL() for such SQL and not rawQuery().
rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program.
execSQL() both compiles and runs the SQL program.
There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe.
A: To update sqlite query change
Cursor c = myDataBase.rawQuery(qry, null);
to this
myDataBase.execSQL(qry);
A: try to use this:
ContentValues values = new ContentValues();
values.put("Recieve", str);
db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23989013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Issue creating Azure scheduler SchedulerClient class There is an argument called cloudServiceName when creating a new instance of SchedulerClient, but there's no documentation available on where that value comes from and the Azure portal isn't helpful either.
Here's the code I have so far:
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "[Thumbprint]", false)[0];
store.Close();
var cloudCreds = new CertificateCloudCredentials("[MySubscriptionId]", certificate);
var client = new SchedulerClient("[Where do I find this value]", "MyJobCollection", cloudCreds);
A: You must be using the old version of the Scheduler SDK. Please find the latest SDK here.
We also have a code sample for said SDK:
https://github.com/Azure-Samples/scheduler-dotnet-getting-started
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45000152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to append two files within the same script after if loop statements OR how to append directly to text file. Python I have a script that I've been working on turning four individual steps(scripts) into 1. I'm down to my last problem and I know I'm over thinking it but need a bit of help to turn the corner.
I either need to figure out how to merge two files after the last IF-LOOP Statement or find some way to write directly to one text file from the script in the order needed (listed below as final).
Currently, the script shows I'm trying to merge(append) at the bottom after the IF-LOOP statements. If a more efficient way is better please shine some light for me. Just to be more clear hopefully, I have tried to write directly to one file and both if-Statement matches show up but my second da_list header repeats because it's inside the loop or doesn't show at all if I have the text header outside the loop. That's why you see the headers appearing before the if statements. Also, just so you know what the cf.txt file look like.
cf.txt example piece. Dots (periods) are one per column (A-D). Mixchar words start in column E
ABCDE
header row
. . . . 5J1SYMC2
. . . . 2TEHUOB1
. . . . TWSIHNB2
. . . . SYHNRWE2
. . . . BFHYSJF1
cf = open(r"E:\test2\cf.txt", "r")
f = open(r"E:\test2\F.txt", "r")
da = open(r"E:\test2\DA.txt","r")
output5 = open(r"E:\test2\output5.txt", "a")
output6 = open(r"E:\test2\output6.txt", "a")
list2 = f.read().split()
list3 = da.read().split()
next(cf)
newlist = []
f_list = []
da_list = []
output5.write(" F_List \n") #text header for output5
output5.write("\n")
output6.write(" Da_List \n") #text header for output6
output6.write("\n")
for line in cf: #cycles thru cf.txt column 5 removes last 2 chars_
rc = (line.split()[4][:-2]) #and append string(rc) in (newlist).
if rc not in newlist:
newlist = []
newlist.append(rc)
check = any(item in newlist for item in list2) #check string(rc) if exist in f_list_
if check is True: #clears previous f_list line and appends new.
if rc not in f_list:
f_list = []
f_list.append(f'{rc}', ),
output5.write(f'{f_list}'[2:-2]), #writes (rc) strings that exist in f_list to
output5.write('\n') #output5.txt
check = any(item in newlist for item in list3) #check string(rc) if exist in da_list_
if check is True: #clears previous da_list line and appends new.
if rc not in da_list:
da_list = []
da_list.append(f'{rc}', ),
output6.write(f'{da_list}'[2:-2]), #writes (rc) strings that exist in f_list to
output6.write('\n') #output6.txt
fin = open(r"E:\test2\output6.txt", "r") #trying to append output6.txt to output5.txt
data2 = fin.read()
fin.close()
fout = open(r"E:\test2\output5.txt", "a")
fout.write(data2)
fout.close()
Final result wanted in output5.txt file. F_list header with random mixchar words matches from (cf.txt) string and f_list. And the same for the da_list printed(appended) below.
F_List
2TEHUO
5JESYM
BFHYSJ
SYHNRW
TWSIHN
Da_List
HKHDU7
DJSKUO
DJDH8
KSIE3
SWSYR
A: One solution could be to just append the file to the second file. You should consider using variables for the file paths instead of copy-paste. Also, the name of the files is a bit confusing.
output5.close()
output6.close()
with open(r"E:\test2\output5.txt", 'a') as output5:
with open(r"E:\test2\output6.txt", "r") as output6:
output5.write(output6.read())
Relevant question about appending files
Here is a explanation of how you can use the with statement
Also, instead of writing the content directly to the files in the if statement, why not just store it into strings? Then in the end you could write it to a file.
If you try to read from a file, before closing it, the text won't show up. You can try the snippet below.
output5 = open(r"Test", "w")
output5.write("Foo")
output6 = open(r"Test", "r")
print(output6.read())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62436813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Determine an empty array in php Hello I am developing an admin backend for an android app for a restaurant. I need to list all food items the restaurant offers based on their categories. The trouble is there can be some categories which doesn't have any item listed under it, and if such a category is encountered the php back end is supposed to return just an empty list but the category name should be there.
My current code so far
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
$row1 = $value->fetch(PDO::FETCH_OBJ);
$main = array('data'=>array($row1));
echo json_encode($main);
}
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
Gives an output like this
{"data":[{"id":"2","name":"Rice","price":"120","description":"Plain Rice","image":"6990_abstract-photo-2.jpg","time":"12 mins","catagory":"Lunch","subcat":""}]}
{"data":[{"id":"4","name":"Dal","price":"5","description":"dadadad","image":"","time":"20 mins","catagory":"Dinner","subcat":""}]}
{"data":[false]}
My problem is the last output where it shows {"data":[false]} should be like this {"data":["catagory":"Soup"]} To do that I would need to find out when the $main variable is empty and then manually add the category to it.
Any ideas or work around to this situation?
A: you want this modification..........
if ($row1 = $value->fetch(PDO::FETCH_OBJ)){
$main = array('data'=>array($row1));
echo json_encode($main);
}else{
echo '{"data":["catagory":"' . $row['category'] . '"]}';
}
A: You problem stems from the fact that you have a 'soup' category but you don't have any items belonging to the soup category. You should add a condition for empty result and change the echoing array accordingly.
if (empty($row1))
{
$main = array('data'=>array('category'=>$cat));
}
else
{
$main = array('data'=>array($row1));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26454688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Auto desk Forge Viewer PDF Snap and Zoom Issue When using forge viewer for PDF’s, is it possible to enable the Snap feature for measuring (same as when viewing models). Also, can the zoom level be changed i.e. we want to zoom in closer than the default maximum?
Both of these are possible in BIM360 so I hope it is also possible in our application, can you please advise.
Currently we are used v7 viewer. We are added the snap extension and setZoomInLimitFactor method also. But still we are unable to get snapping feature and zoom in function at PDF files.
function launchViewer(urn, viewableId) {
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken,
api: 'derivativeV2' + (atob(urn.replace('_', '/')).indexOf('emea') > -1 ? '_EU' : '') // Both BIM 360 US and EU regions
};
Autodesk.Viewing.Initializer(options, () => {
viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer'));
viewer.start();
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
function onDocumentLoadSuccess(doc) {
// if a viewableId was specified, load that view, otherwise the default view
var viewables = (viewableId ? doc.getRoot().findByGuid(viewableId) : doc.getRoot().getDefaultGeometry());
viewer.loadDocumentNode(doc, viewables).then(i => {
viewer.loadExtension('Autodesk.VisualClusters');
viewer.loadExtension('Autodesk.Snapping');
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.loadExtension("Autodesk.Viewing.MarkupsGui");
viewer.loadExtension('Autodesk.Measure');
viewer.loadExtension('Autodesk.DefaultTools.NavTools');
viewer.loadExtension('Autodesk.PDF');
viewer.loadExtension('Autodesk.DocumentBrowser');
viewer.loadExtension('Autodesk.Viewing.ZoomWindow');
// any additional added here
});
viewer.navigation.setZoomInLimitFactor(2500);
console.log(viewer.navigation.getZoomInLimitFactor());
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
}
kindly advise if we missed anything. Thanks in advance.
A: it looks you are using the old way to translate PDF then load it to viewer. In the old way, the PDF is translated to tiled images. So snapping may not be working, and zoom has max limit due to the max resolution of tiled images.
Actually, Forge Viewer has supported to load native PDF directly, without translation. Since it is native, it is vector graphics. The snapping will work, and it can be zoomed to large/much small scale.
To play it, please download the sample project,
https://github.com/Autodesk-Forge/viewer-javascript-offline.sample
and replace the line to your local pdf file
var options = {
'env' : 'Local',
'document' : './my_PDF_folder/mytest.pdf'
};
This feature is from the extension Autodesk.PDF, but it will be loaded de default, you do not need to load it explicitly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70278410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use multi-languages for iPhone application using NSBUNDLE? How to use multi languages for iPhone application?. Currently I used five languages. How to use it in iPhone development using nsbundle?
A: Their is one easiest way to develop multi language app by using string file. only you need to make different string file for each languages and then use NSLocalizedString to use current language. For Ex:
UIlabel *label;
label.text= NSLocalizedString(@"Key", nil);
and in Localizable.strings (english) string file it will be defined as
"Key"="English Name";
and in Localizable.strings (german) string file it will be defined as
"Key"="german Name";
It will automatically set the value of current language on uilabel from device.
And you can localize the xib directly , it will create different xib for each language and set the text accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23867876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Extend Richfaces components - for example customize Datatable component for specific implementation How to extend the functionality of Richfaces components for example Data table with custom header and sorting techniques. i have seen extended data table but did not get much information from it. Please point me to an example if at it is available.
Thanks
Soma
A: Well, you can extend a JSF component with the regular java extension (extends). You will have to extend a number of classes, depending on the exact component:
*
*UIComponentName/HtmlComponentName
*HtmlComponentNameRenderer
*ComponentNameTag
and you might need to register the renderer in faces-config.xml.
You can take a look at this thread, or google for "Extend JSF component" or "Create custom JSF component".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2348178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Glitch while unpacking the attribute names and coefficients This isn't actually an error that is thrown as much as a glitch I don't understand.
list(zip(X_train_select.columns, lr_mod.coef_))
I use this line to show me the coefficients of a model along with the name of the features, after training a model using sklearn, to understand which feature is of more importance and which plays a very little role in making predictions.
[('onnet_mou_8',
array([-0.66702875, -0.36908825, -0.62763428, 0.55019987, 0.42000536,
0.23324475, -0.34923 , -0.53591227, -0.51666227, -0.20964182,
0.16327186, 0.30434683, 0.17354234, -0.6427968 , 0.04148923,
-0.39615 , 0.2321794 , -0.2989932 , -0.2238154 , -0.32478291,
-0.3414018 , 0.51018786, -0.10059598, -0.38008471]))]
This is the output I'm getting. I don't understand why I'm not getting a full-fledged output.
I've tried converting the data type of feature columns to a NumPy array, tried to attack this issue by trying to plot a feature importance graph, and a few more things. I got different types of errors for all those different methods and I'm back to inspecting why this isn't working properly.
Index(['onnet_mou_8', 'offnet_mou_8', 'roam_ic_mou_8', 'roam_og_mou_8',
'loc_og_t2t_mou_8', 'std_og_t2t_mou_8', 'loc_ic_t2t_mou_8',
'loc_ic_t2m_mou_8', 'spl_ic_mou_8', 'total_rech_num_8',
'total_rech_amt_6', 'total_rech_amt_7', 'total_rech_amt_8',
'last_day_rch_amt_8', 'max_rech_data_7', 'av_rech_amt_data_8',
'vol_2g_mb_6', 'vol_2g_mb_8', 'monthly_2g_8', 'total_6', 'total_7',
'avg_of_6_7', 'arpu_8-7', 'loc_ic_8-7'],
dtype='object')
These are my features.
Any help would be much appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65073061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why must a final variable be initialized before constructor completes? Why must a final variable be initialized before constructor completes?
public class Ex
{
final int q;
}
When I compile this code I get error like this
err:variable q might not have been initialized
A: The final keyword applied to a field has one of two effects:
*
*on a primitive, it prevents the value of the primitive from being changed (an int can't change value)
*on an object, it prevents the "value of the variable", that is, the reference to the object, from being changed. That is to say that, if you have a final HashMap<String,String> a, you will only be able to set it once, and you won't be able to do this.a=new HashMap<String,String>(); again, but nothing keeps you from doing this.a.put("a","b"),s since that doesn't modify the reference, only the content of the object.
A: The official reason is that it is defined by the Java Language Specification 8.3.1.2:
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).
A: The final modifier prevents your from changeing the variables value, hence you have to initialize it where you declare it.
A: Because final prevents you from modifying variables, but it has to be initialized at some point, and the constructors is the right place to do so.
In your case, it would be called a blank final because it is not initialized when declared.
A: The value of a final variable can only be set once. The constructor is the only place in the code for a class that you can guarantee this will hold true; the constructor is only ever called once for an object but other methods can be called any number of times.
A: A final variable must be initialized at the declaration or in a constructor.
If it has not been initialized when the constructor returns, it may never be initialized, and may remain an uninitialized variable. The compiler cannot prove it will be initialized, and thus throws an error.
This Wikipedia excerpt explains it well:
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)
A: Final modifier does not allow to change your variable value. So you need to assign a value to it at some place and constructor is the place you have to do this in this case.
A: The language specification contains specific guarantees about the properties of final variables and fields, and one of them is that a properly constructed object (i.e. one whose constructor finished successfully) must have all its final instance fields initialized and visible to all threads. Thus, the compiler analyzes code paths and requires you to initialize those fields.
A: If an instance variable is declared with final keyword, it means it can not be modified later, which makes it a constant. That is why we have to initialize the variable with final keyword.Initialization must be done explicitly because JVM doesnt provide default value to final instance variable.Final instance variable must be initialized either at the time of declaration like:
class Test{
final int num = 10;
}
or it must be declared inside an instance block like:
class Test{
final int x;
{
x=10;
}
}
or
it must be declared BEFORE constructor COMPLETION like:
class Test{
final int x;
Test(){
x=10;
}
}
Keep in mind that we can initialize it inside a consructor block because initialization must be done before constructor completion.
A: The moment the constructor completes execution, the object is 'open for business' - it can be used, its variables can be accessed.
The final keyword on a variable guarantees that its value will never change. This means, if the value is ever read, you can be sure that the variable will always have that value.
Since the variable can be accessed (read) at anytime after the execution of the constructor, it means it must never change after the constructor has executed - just it case it has been read.
Thus, it must, by then, have been set.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11345061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: PHP API For Microsoft Outlook? Is there any way to retrieve contact and add edit list of outlook calender? Please advise me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17650906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add gradient to canvas I need to add a gradient to a canvas. I have tested all solutions, but nothing works.
Original code:
ctx.strokeStyle = params.wheelBorderColor;
ctx.lineWidth = params.wheelBorderWidth;
ctx.font = params.wheelTextFont;
ctx.clearRect(0, 0, 500, 500);
var text = null,
i = 0,
totalJoiner = pplLength;
var width = ctx.measureText(text).width + blur * 2;
for (i = 0; i < totalJoiner; i++) {
text = pplArray[i];
var angle = startAngle + i * arc;
ctx.fillStyle = colorCache.length > totalJoiner ? colorCache[i] : genHex(text);
ctx.beginPath();
// ** arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);
ctx.arc(250, 250, params.outterRadius, angle, angle + arc, false);
ctx.arc(250, 250, params.innerRadius, angle + arc, angle, true);
ctx.stroke();
ctx.fill();
ctx.save();
ctx.fillStyle = params.wheelTextColor;
ctx.translate(250 + Math.cos(angle + arc / 2) * params.textRadius, 250 + Math.sin(angle + arc / 2) * params.textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 1);
ctx.fillText(text, -ctx.measureText(text).width / 2, 6);
ctx.restore();
ctx.closePath();
}
drawArrow();
And i add this code for gradiant and the fill() is already sent to original code
var grd = ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000);
// Add colors
grd.addColorStop(0.000, 'rgba(0, 0, 0, 1.000)');
grd.addColorStop(1.000, 'rgba(255, 255, 255, 1.000)');
// Fill with gradient
ctx.fillStyle = grd;
ctx.fill();
The genHex() is:
color = "#666"; colorCache.push('#'+color); return '#'+color;"
Any guidance would be helpful.
A: Are you drawing a rectangle within your context? Try something like this:
var canvas = document.getElementById('test-canvas');
var ctx = (canvas !== null ? canvas.getContext('2d') : null);
var grd = (ctx !== null ? ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000) : null);
if (grd) {
ctx.rect(0, 0, canvas.width, canvas.height);
grd.addColorStop(0.000, 'rgba(0, 0, 0, 1.000)');
grd.addColorStop(1.000, 'rgba(255, 255, 255, 1.000)');
ctx.fillStyle = grd;
ctx.fill();
}
I have posted a working example at JSFiddle: http://jsfiddle.net/briansexton/e6rC3/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23757338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SwipeRefreshLayout Refresh Listener not calling onRefresh() I currently have a SwipeRefreshLayout that isn't calling its OnRefresh method whenever I pull down. Is something wrong with my code?
public class MainActivity extends AppCompatActivity {
private SwipeRefreshLayout swipe_view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe_view = (SwipeRefreshLayout) findViewById(R.id.this_will_work);
swipe_view.setOnRefreshListener(new OnRefreshListener()
{
@Override
public void onRefresh()
{
Toast.makeText(getApplicationContext(), "OnRefresh() test", Toast.LENGTH_SHORT).show();
}
});
A: You should have a service or something that will be updated like below :
private void refresh() {
startService(new Intent(this, UpdaterService.class));
}
then Refresh :
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
refresh();
}});
//here refreshed Item
//getLoaderManager().initLoader(0, null, this);
if (savedInstanceState == null) {
refresh();
}
and your onRefresh() should contain the same method refresh().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42744587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mysql database for monthly subscriber maintenance i would like to create mysql database or single table to maintain data for some small sport club. Actually we have to pay monthly fee for cleanup and so and the best would be to keep that data within mysql. I need to store the following data (id, name, address) and for each month the date when fee is payed. What would be the best and easiest solution?
A: CREATE TABLE sport_club_members (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
address VARCHAR(100),
payment_due_at TIMESTAMP DEFAULT NOW()
);
This will build you a table.
A: Very basic would be a two table approach.
One Table for your members in pseudo code (make your own thoughts ;-) not copy&paste them)
ID INT auto_increment PrimaryKey
name VARCHAR(100) //maybe store as split name
address TEXT
and another for the received payments
ID INT auto_increment PK
UID INT ForeignKey to members table
payment_date DATE
amount DOUBLE
Then extract the missing payments for a month via any language/program.
This can be expanded with more detail anytime
A: You should just use phpmyadmin to create your tables. You will need 2 tables:
1. Table club_members with the following fields (member_id, name, address).
2. Table monthly_payments with the following fields (member_id, year, month, date_paid, amount).
Then member_id in table monthly_payments will be a foreign key referencing member_id in table club_members
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12141752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to simply find coord's of Image B (smaller ) inside of image A (screenshot /big)? I am trying to make a basic tool which will automatically move the mouse to a menu, and select from a drop-down menu the thing that's been selected.
So, this is the bit, that I'm trying to get my mouse to navigate to, specifically the "saimon" part. I will refer to this screenshot as A
The screenshot of the user's window, is a bigger picture than A. I just want to navigate to A's section within that screen.
Hopefully you understand the objective here.
Anyways, I was trying to do something simple like using an If statement, to see if I would find that icon within the screenshot, and if I did. It would navigate to those coordinates (I could input it manually, by having the user put the menu in a specific location OR grab the coordinates automatically). If it did not match, I would just say an error.
A: This answer uses OCR to find the location X,Y coordinates of the text 'Saimon'
You download TessNet(2)
Tessnet2 is a .NET 2.0 Open Source OCR assembly using Tesseract engine.
You can implement code similar to this:
using System;
namespace OCRTest
{
using System.Drawing;
using tessnet2;
class Program
{
static void Main(string[] args)
{
try
{
var image = new Bitmap(@"C:\OCRTest\saimon.jpg");
var ocr = new Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // If digit only
//@"C:\OCRTest\tessdata" contains the language package, without this the method crash and app breaks
ocr.Init(@"C:\OCRTest\tessdata", "eng", true);
var result = ocr.DoOCR(image, Rectangle.Empty);
foreach (Word word in result){
if(word.contains("aimon")){
Console.WriteLine("" + word.Confidence + " " + word.Text + " " +word.Top+" "+word.Bottom+ " " +word.Left + " " +word.Right);
}
}
Console.ReadLine();
}
catch (Exception exception)
{
}
}
}
}
You should be able to use these coordinates to automate your mouse to click.
To test online with another OCR how OCR works, please provide your screenprint and check their results. OCR is so good these days!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41174465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Using SQL LIKE with another query I have this sql query for searching:
select *
from songs
where name LIKE '%search%'
or author LIKE '%search%'
or tags LIKE '%search%';
At this point everything is OK, but now I need to search only in the songs where the column 'status' = 1. How can I do this?
A: Add it to the where clause and put the ors in braces:
select * from songs where status = 1 and ( name LIKE '%search%' or author LIKE '%search%' or tags LIKE '%search%');
A: You can use parentheses to combine conditions and have an 'and' at the end so that either of the current conditions are true, and the condition you are about to add:
select *
from songs
where
(name LIKE '%search%' or
author LIKE '%search%' or
tags LIKE '%search%'
) and
status=1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28268554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Mysql query I want to know visitors who vote for example ( answer_id (767) ) on what else they vote for When visitor votes, I store information answer_id, ip, etc.
My website visitors vote in multiple polls.
I want to know visitors who vote for example ( answer_id (767) ) on what else they vote for. Based on ip. lets say answer_id=767
Table: poll_stat
`id` int(11) NOT NULL auto_increment,
`question_id` int(11) NOT NULL,
`answer_id` int(11) NOT NULL,
`ip` varchar(255) NOT NULL,
`date` date NOT NULL,
`country` text NOT NULL,
`time` int(11) NOT NULL,
`age` int(11) NOT NULL,
A: I think this will work for you.
select ip, question_id
from poll_stat
where ip in (select ip from poll_stat where answer_id = 767 group by ip)
and answer_id <> 767
edit
Hmm...you might check that there is an INDEX created on the ip column. If that isn't it, perhaps it doesn't like the IN clause. I will rewrite as a join:
select ip, question_id
from poll_stat ps1
inner join (select ip from poll_stat where answer_id = 767 group by ip) ps2
on ps1.ip = ps2.ip
where answer_id <> 767
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12232422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Checked other checkbox on selecting of single checkbox? 1. <p:column align="center">
<f:facet name="header">
<h:outputLabel value="Select" />
</f:facet>
<h:selectBooleanCheckbox id="select">
<p:ajax event="click" update="CoverageList,select" />
</h:selectBooleanCheckbox>
</p:column>
2.<p:column align="center">
<f:facet name="header">
<h:outputLabel value="#{label.coverage}" />
</f:facet>
<h:selectManyCheckbox id="CoverageList" style="width: 120px"
value="#{policy.selectedCoverageCodes}">
<f:selectItems value="#{policy.coverageCodes}" />
</h:selectManyCheckbox>
</p:column>
Need to select multiple checkboxs on clicking of single checkbox....
A: This is a javascript version
var elements = document.getElementsByTagName('input');
for(var i = 0; i< elements.length; i++) {
if (elements[i].type == "checkbox") {
elements[i].checked = !elements[i].checked;
}
}
if you have jQuery use this
$("#CoverageList").click(function() {
var checked_status = this.checked;
$('#actions').find("input").each(function() {
$(this).prop("checked", checked_status);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7291747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Symfony/Doctrine: custom find() function I want to extend the Doctrine_core::getTable('table_name')->find('id') to increment the table_name.view_count field each time it is executed. Is this possible?
A: I think it's not a good practice to put a such functionality into model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4834993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cleaning Urls in a pandas dataframe <There is more code to this but I collected Twitter data using twint. I am using Jupyter Notebooks as well. I have filtered the data that I want to keep for my graph. But in my nx node edges graph, has the full URL of the web pages. I want to get ride of the http://, https:// and the extra stuff after the .com or .org etc. I am getting the error 'DataFrame' object has no attribute 'str' when I try to do a replace to get rid of the 'https://' in the URLs.>
import csv
import twint
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nest_asyncio
import re
nest_asyncio.apply()
NWO_data = pd.read_csv("TwitterLinksNWO.csv")
NWO_data['urls'].replace('[]', np.nan, inplace=True)
NWO_data.dropna(subset=['urls'],inplace=True)
NWO_data.shape
NWO_data = NWO_data.astype({'urls': np.str}, copy=True) #This is suppose to change it from a object data type to a string.
urlsCleaned = NWO_data[["urls"]]
print(urlsCleaned.str.replace('https://','1'))
print(urlsCleaned)
A: Your problem arises because urlsCleaned is a pd.DataFrame not a pd.Series, to solve you have to change the line to:
urlsCleaned = NWO_data["urls"]
Note that they look almost the same, but in your case, it creates a pd.DataFrame with one column, and here it creates an pd.Series.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67169145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When creating HTML emails, should we use html, head, body tags? In my email views, I usually just do something like...
<dl>
<dt>Name</dt>
<dd>Value</dd>
</dl>
Should I be doing it like this?
<html>
<head></head>
<body>
<dl>
<dt>Name</dt>
<dd>Value</dd>
</dl>
</body>
</html>
In other words, like I was marking up a standalone document?
I guess I can safely assume any web based email client will strip it out?
What is the right way?
A: The right way is to follow the HTML standard. You can validate your HTML page here.
Your mail client should follow it and should throw away what's not supported or what's insecure, like JavaScript.
I'll expose some reasons why following standards could be beneficial here:
*
*a webmail willing to show your mail as a full page, could keep your format.
*a webmail will simply strip the tags and attributes it doesn't want. But you can never know which ones.
*It's easier to find (server side) components that follow format standards, and thus are less error prone. Parsers not following standards could possibly break, making your email not getting shown.
A: I don't think there is a right way but trying to make the email viewable in as many email readers as posible.
I usually check the emails in Thunderbird, because Outlook forgives more.
In Thunderbird this is the HTML code for an email (i have an extension that shows the html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000">
This is the body text<br>
<div class="moz-signature"><i><br>
<br>
Regards<br>
Alex<br>
</i></div>
</body>
</html>
BTW, i use plain text email for all my web forms every time I can. I had many issues with blackberry email using html+plain text emails.
A: Whether or not you include the html/head/body tags is entirely irrelevant — they are always optional and will not affect the rendering of the document in any way.
What matters most is whether quirks mode is on or not. Unfortunately, you can’t control that in a webmail setting. Tables and inline styles are your friends. Your best bet is to test in as many webmail and desktop clients as you can.
A: Many of the posts on this thread are rather old, and as a result they are no longer accurate.
These days HTML emails should include a doctype, html and body declaration if you intend to do anything fancy at all.
There are a multitude of guides on this subject which can help you learn how to properly code HTML Email, but most of them disregard the specifics of a doctype, which is how I stumbled on your question.
I suggest you read the following 2 posts which are from reputable teams familiar with the various problems:
campaign monitor's take
email on acid's take
A: Depends entirely on the email client that receives it. In my experience, most email clients that will interpret HTML don't care if you have full body/head/html tags, etc. In fact you don't even need those tags for most browsers. You need to have the head tags to include style/title, etc. Otherwise they are not really necessary, per se. I've never seen them to be necessary.
A: There's 1 thing I know to be true: Using HTML opening and closing tags will help in general spam scoring due to the fact that many such appliance based filters and software firewalls will add a point or so to an email that uses html but does not use the opening and closing tags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3903200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
} |
Q: Can't get MDDropdownMenu and MDDropDownItem to work Whenever I press on the MDDropDownItem the Menu opens but when I select an option nothing happens
How can I solve this?
Thanks in advance
Here is my code:
from kivymd.uix.screen import MDScreen
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.dropdownitem import MDDropDownItem
from kivymd.app import MDApp
class Contents(MDScreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.langlist =MDDropDownItem(pos_hint={'center_x': 0.5, 'center_y': 0.5})
self.langlist.text = 'English'
self.add_widget(self.langlist)
self.langlist.bind(on_release=self.menuopen)
self.langlistmenu = MDDropdownMenu(caller=self.langlist,items=[{'viewclass':'MDMenuItem','text':'English'},{'viewclass':'MDMenuItem','text':'Arabic'}],width_mult=3)
self.langlistmenu.bind(on_release=self.menuclose)
def menuclose(self,instance_menu,instance_menu_item):
print(instance_menu_item.text)
print(instance_menu)
self.langlist.set_item(instance_menu_item.text)
self.langlistmenu.dismiss()
def menuopen(self,instance):
self.langlistmenu.open()
class AndroidApp(MDApp):
def build(self):
#self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = 'Red'
self.theme_cls.primary_hue = 'A400'
return Contents()
AndroidApp().run()
A: I figured out how to do it
Here's the code:
from kivymd.uix.screen import MDScreen
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.dropdownitem import MDDropDownItem
from kivymd.app import MDApp
class Contents(MDScreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.langlist =MDDropDownItem(pos_hint={'right': 0.85, 'top': 0.98})
self.langlist.set_item('English')
self.langlist.md_bg_color = [1,1,1,1]
self.add_widget(self.langlist)
self.langlist.bind(on_release=self.menuopen)
self.langlistmenu = MDDropdownMenu(position='bottom',callback=self.menuclose,caller=self.langlist,items=[{'viewclass':'MDMenuItem','text':'English'},{'viewclass':'MDMenuItem','text':'Français'},{'viewclass':'MDMenuItem','text':'Deutsche'},{'viewclass':'MDMenuItem','text':'русский'},{'viewclass':'MDMenuItem','text':'Español'}],width_mult=4)
def menuclose(self,instance):
self.langlist.set_item(instance.text)
self.langlistmenu.dismiss()
def menuopen(self,instance):
self.langlistmenu.open()
class AndroidApp(MDApp):
def build(self):
#self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = 'Red'
self.theme_cls.primary_hue = 'A400'
return Contents()
AndroidApp().run()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66557295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to display the light box on click of each image? I want to display lightbox on click of each image. I want to keep same class and name for each image. The idea is to make the page dynamic which is why I have kept the same id and class on on image tag.
When I click on the first image the lightbox is getting open but when I keep the same id and class for the second and third image the lightbox is not getting open. I want to display the lightbox on click of each image.
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Trigger/Open The Modal -->
<a href="#" id="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
A: Working code. Try this.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Trigger/Open The Modal -->
<a href="#" id="myBtn" class="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn" class="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn" class="myBtn"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
// btn.onclick = function() {
// modal.style.display = "block";
// }
$(".myBtn").click(function() {
modal.style.display = "block";
});
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
A: <a href="#" id="myBtn" class="popupmodel"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn" class="popupmodel"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<a href="#" id="myBtn" class="popupmodel"><img src="http://theparlour21.se/wp-content/uploads/2015/07/granat-salad.png"></a>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
$(document).ready(function(){
$(document).on("click",".close,.modal", function(){
$(".modal").hide();
});
$(document).on("click",".popupmodel", function(){
$(".modal").show();
});
});
fiddle link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44127363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I automatically check that the nuget versions in a csproj file match the versions in the packages.config file? We have an issue where Visual Studio sometimes fails to install/restore a nuget package correctly and with an out-of-memory error in the Package Manager console, but it's not easily visible. When this occurs the versions in the csproj and packages.config file can go out of sync with no other visible indication in Visual Studio.
I've tried to write an automatic file comparer using regexes, but sometimes the package names do not match so I still have to check everything manually.
Is there reliable way to perform this check? Or to perhaps to recreate the packages.config file based on what is in the csproj file? That way I can just check the source diffs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70277726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sed/awk/perl formatting multiple paragraphs
dzinfo gives me output formatted like this;
User: x0000001
Forced into restricted environment: No
Role Name Avail Restricted Env
--------------- ----- --------------
login/Corp_All Yes None
_Example-Role-- Yes _Example-Role--
ALL_Servers-Win ALL_Servers-Win
/US_All /US_All
Domain_GLOBAL-Ro Yes Domain_GLOBAL-Ro
le-CORE_Group-AL le-CORE_Group-AL
L-MacOS/Domain_ L-MacOS/Domain_
GLOBAL GLOBAL
Effective rights:
Password login
Non password login
Allow normal shell
PAM Application Avail Source Roles
--------------- ----- --------------------
* Yes login/US_All
Privileged commands:
Name Avail Command Source Roles
--------------- ----- -------------------- --------------------
CORP_GLOBAL-Com Yes /usr/bin/getfacl CORP_GLOBAL-Role-COR
mand-CORE_SVR_I E_SVR_INFRA_ALL-LNX/
NFRA_ALL-V042-S CORP_GLOBAL
00042/CORP_GLOB
AL
CORP_GLOBAL-Com Yes /usr/bin/dzdo -l CORP_GLOBAL-Role-COR
mand-CORE_SVR_I E_SVR_INFRA_ALL-LNX/
NFRA_ALL-V042-S CORP_GLOBAL
00048/CORP_GLOB
AL
CORP_GLOBAL-Com Yes /bin/cp temp_auth CORP_GLOBAL-Role-COR
mand-CORE_SVR_I /home/sudocfg/author E_SVR_INFRA_ALL-LNX/
NFRA_ALL-V042-S ized_keys CORP_GLOBAL
00085/CORP_GLOB
AL
What tool would be the best choice to format a report like this? And how could I match/combine and format the columns/lines to something like the following?
User: x0000001
Forced into restricted environment: No
Role Name Avail Restricted Env
--------------- ----- --------------
login/Corp_All Yes None
_Example-Role--ALL_Servers-Win/US_All Yes _Example-Role--ALL_Servers-Win/US_All
Domain_GLOBAL-Role-CORE_Group-ALL-MacOS/Domain_GLOBAL Yes Domain_GLOBAL-Role-CORE_Group-ALL-MacOS/Domain_GLOBAL
Effective rights:
Password login
Non password login
Allow normal shell
PAM Application Avail Source Roles
--------------- ----- --------------------
* Yes login/US_All
Privileged commands:
Name Avail Command Source Roles
--------------- ----- -------------------- --------------------
CORP_GLOBAL-Command-CORE_SVR_INFRA_ALL-V042-S00042/CORP_GLOBAL Yes /usr/bin/getfacl CORP_GLOBAL-Role-CORE_SVR_INFRA_ALL-LNX/CORP_GLOBAL
CORP_GLOBAL-Command-CORE_SVR_INFRA_ALL-V042-S00048/CORP_GLOBAL Yes /usr/bin/dzdo -l CORP_GLOBAL-Role-CORE_SVR_INFRA_ALL-LNX/CORP_GLOBAL
CORP_GLOBAL-Command-CORE_SVR_INFRA_ALL-V042-S00085/CORP_GLOBAL Yes /bin/cp temp_auth /home/sudocfg/authorized_keys CORP_GLOBAL-Role-CORE_SVR_INFRA_ALL-LNX/CORP_GLOBAL
The text in each column can vary greatly, so I'd like to have the width automatically adjust.
I can handle one-liners, but for a report like this? I wouldn't know where to even begin.
A: To get you started, here's basically how you'd start to isolate the individual fields on each line using GNU awk for FIELDWIDTHS:
$ cat tst.awk
BEGIN { origFS=FS }
/---/ {
origFS=FS
split($0,f,/\s+|-+/,s)
FIELDWIDTHS=""
for (i=1; i in s; i++) {
FIELDWIDTHS = (i>1 ? FIELDWIDTHS " " : "") length(s[i])
}
}
/^\s*$/ {
FIELDWIDTHS=""
FS=origFS
}
{
for (i=1; i<=NF; i++) {
printf "<%s>", $i, (i<NF?OFS:ORS)
}
print ""
}
.
$ awk -f tst.awk file
<User:><x0000001>
<Forced><into><restricted><environment:><No>
<Role><Name><Avail><Restricted><Env>
<---------------><-----><-------------->
< ><login/Corp_All >< ><Yes >< ><None >< >
< ><_Example-Role-->< ><Yes >< ><_Example-Role-><->
< ><ALL_Servers-Win>< >< >< ><ALL_Servers-Wi><n>
< ></US_All >< >< >< ></US_All ><>
< ><Domain_GLOBAL-R><o ><Yes >< ><Domain_GLOBAL-><R>
< ><le-CORE_Group-A><L >< >< ><le-CORE_Group-><A>
< ><L-MacOS/Domain_>< >< >< ><L-MacOS/Domain><_>
< ><GLOBAL >< >< >< ><GLOBAL ><>
<Effective><rights:>
<Password><login>
<Non><password><login>
<Allow><normal><shell>
<PAM><Application><Avail><Source><Roles>
<---------------><-----><-------------------->
<* >< ><Yes >< ><login/US_All >< >
<Privileged comm><an><ds:><><><>
< Name >< >< Ava><i><l Command >< >
< -------------><-->< ---><-><- ------------------><->
< ><CORP_GLOBAL-Com>< ><Yes >< ></usr/bin/getfacl >< ><CORP_GLOBAL-Role-COR>< >
< ><mand-CORE_SVR_I>< >< >< >< >< ><E_SVR_INFRA_ALL-LNX/>< >
< ><NFRA_ALL-V042-S>< >< >< >< >< ><CORP_GLOBAL >< >
< ><00042/CORP_GLOB>< >< >< >< >< >< >< >
< ><AL >< >< >< >< >< >< >< >
< ><CORP_GLOBAL-Com>< ><Yes >< ></usr/bin/dzdo -l >< ><CORP_GLOBAL-Role-COR>< >
< ><mand-CORE_SVR_I>< >< >< >< >< ><E_SVR_INFRA_ALL-LNX/>< >
< ><NFRA_ALL-V042-S>< >< >< >< >< ><CORP_GLOBAL >< >
< ><00048/CORP_GLOB>< >< >< >< >< >< >< >
< ><AL >< >< >< >< >< >< >< >
< ><CORP_GLOBAL-Com>< ><Yes >< ></bin/cp temp_auth >< ><CORP_GLOBAL-Role-COR>< >
< ><mand-CORE_SVR_I>< >< >< ></home/sudocfg/author>< ><E_SVR_INFRA_ALL-LNX/>< >
< ><NFRA_ALL-V042-S>< >< >< ><ized_keys >< ><CORP_GLOBAL >< >
< ><00085/CORP_GLOB>< >< >< >< >< >< >< >
< ><AL >< >< >< >< ><><><>
You're going to want to buy the book Effective Awk Programming, 4th Edition, by Arnold Robbins and have it handy for reference as you start tinkering with that to see how it works and then building on it.
A:
I can handle one-liners, but for a report like this? I wouldn't know where to even begin.
Indeed this seems hardly possible with a one-liner (unless it's one very long line). But to begin with, the problem can be analyzed and a possible solution outlined.
*
*Identify what parts of the input constitute the tables (where column lines are to be combined): We could use the lines of hyphens between column headers and text to identify the start of a table, and a short line or an unfitting line, where the gaps between the columns are not blank, to identify the end.
*Read a table in line by line, split each line into the columns (whose margins can be derived from the hyphen lines), and, if the current line is a wrapped continuation line of the preceding line (i. e. if it has empty columns), concatenate each column's texts. In the course of this, the required column widths can be determined from the maximum combined text lengths.
*Write the table out, using the before determined column widths.
The following Perl program implements a solution. Note however that, since it uses seek, it cannot work on piped input, but only on a file.
#!/usr/bin/perl -wn
if (/---/) # here comes a table
{
seek ARGV, $priprior, 0; # set position back to header line
push @gap, $-[1] while /(?<=-) *( )-/g; # find the column gaps
$tabrow = -1; # index of current table row: no rows yet
@maxlng = (0)x($#gap+2); # maximum length of text in each column
while (<>) # read the table, starting with headers
{ # check for end of table:
last if length() <= $gap[-1] or substr($_, $gap[-1], 1) ne ' ';
$offset = 0; # first column start
$contin = 0; # is it a continuation line?
foreach $i (0..$#gap+1)
{ # extract column:
if ($i <= $#gap) # not last column?
{ $column[$i] = substr $_, $offset, $gap[$i]-$offset;
$offset = $gap[$i];
}
else # last column
{ $column[$i] = substr $_, $offset;
}
$column[$i] =~ s/\s+$//; # remove trailing whitespace
$contin += $column[$i] eq '' # column empty?
}
++$tabrow unless $contin;
foreach $i (0..$#gap+1)
{ # ugly fix to restore the space in "temp_auth /home/...", where
# the column is wrapped early: --------------------
# ...
# /bin/cp temp_auth
# /home/sudocfg/author
# ized_keys
$table[$tabrow][$i] .= ' ' if $contin and length($table[1][$i])>
length($table[$tabrow][$i]);
# now that's fixed, proceed with normal unwrapping of the column
$column[$i] =~ s/^ +// if $contin or $i; # remove leading spaces
$table[$tabrow][$i] .= $column[$i];
$maxlng[$i] = length $table[$tabrow][$i] # update maximum length
if $maxlng[$i] < length $table[$tabrow][$i];
}
undef $_; last if eof
}
foreach $e (@table)
{
foreach $i (0..$#gap+1) { printf "%-*s", $maxlng[$i]+1, $$e[$i]; }
print "\n";
}
undef @gap; undef @table;
}
else { print $previous_line if $previous_line }
$previous_line = $_;
$priprior = $prior;
$prior = tell ARGV;
END { print $previous_line if $previous_line }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41171565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter 3.7 create different result from before(3.3) and from doc, based on this command `flutter create --template=package ` based on this flutter doc :
this line flutter create --template=package hello
should produce following content :
*
*LICENSE
*test/hello_test.dart
*hello.iml
*.gitignore
*.metadata
*pubspec.yaml
*tool.
*README.md
*lib/hello.dart
*.idea/modules.xml, .idea/workspace.xml
*CHANGELOG.md
but when update to flutter 3.7
its generate more content like this following image :
it create more content like :
*
*android
*ios
*etc
and give some warning :
This app is using a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to migrate this app to the V2 embedding.
complete log :
PS E:\***\***\****> flutter create --template=package hello
Creating project hello...
Running "flutter pub get" in hello...
Resolving dependencies in hello... (1.8s)
+ async 2.10.0
+ boolean_selector 2.1.1
+ characters 1.2.1
+ clock 1.1.1
+ collection 1.17.0 (1.17.1 available)
+ fake_async 1.3.1
+ flutter 0.0.0 from sdk flutter
+ flutter_lints 2.0.1
+ flutter_test 0.0.0 from sdk flutter
+ js 0.6.5 (0.6.7 available)
+ lints 2.0.1
+ matcher 0.12.13 (0.12.14 available)
+ material_color_utilities 0.2.0
+ meta 1.8.0 (1.9.0 available)
+ path 1.8.2 (1.8.3 available)
+ sky_engine 0.0.99 from sdk flutter
+ source_span 1.9.1
+ stack_trace 1.11.0
+ stream_channel 2.1.1
+ string_scanner 1.2.0
+ term_glyph 1.2.1
+ test_api 0.4.16 (0.4.18 available)
+ vector_math 2.1.4
Changed 23 dependencies in hello!
This app is using a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to migrate this app to the V2 embedding.
Take a look at the docs for migrating an app:
https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects
Wrote 13 files.
All done!
Your package code is in hello\lib\hello.dart
i search online based on that warning, and not single one solution mention about package. my question is Why it is different from before and what should i do about the warning. I need help and your guide, thank you in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75343616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Yii2 RestFull API - Error 404 on production with few actions onlyy I have a problem,
I created many actions for an API using Yii2.
I have met a recent problem: while everything works on localhost, when I upload on the server, the below actions return a 404 error.
I have been trying many different solution (try to create another controller) with no success
The goal of those functions is to upload/delete images.
config/main.php
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => require 'urls.php',
],
config/urls.php
'POST api/controller/<id>/logo-upload' => 'controller-name/logo-upload',
'POST api/controller/<id>/background-image-upload' => 'controller-name/background-image-upload',
'POST api/controller/<id>/gallery-upload' => 'controller-name/update-gallery',
'POST api/controller/<id>/delete-logo' => 'controller-name/delete-logo-image',
'POST api/controller/<id>/delete-background' => 'controller-name/delete-background-image',
'POST api/controller/<id>/gallery/<galleryID>/delete' => 'controller-name/delete-gallery-image',
Here a sample controller I created. I changed some variable names or class names but nothing that doesn't change the logic.
controller-name.php
<?php
namespace frontend\controllers;
use yii\rest\ActiveController;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use yii\helpers\BaseJson;
use yii\data\ActiveDataProvider;
use yii\web\UploadedFile;
use Yii;
class Controller extends RestController
{
public $modelClass = 'common\models\Model';
public function actions()
{
$actions = parent::actions();
unset($actions['delete'], $actions['create'], $actions['update'], $actions['index'], $actions['options']);
return $actions;
}
public function behaviors()
{
return ArrayHelper::merge([
[
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS', 'POST'],
],
],
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index', 'update'], // in a controller
// if in a module, use the following IDs for user actions
// 'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
'languages' => [
'en',
'fr',
],
]
], parent::behaviors());
}
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['POST', 'PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
protected function findModel($id)
{
if (($model = Model::findOne($id)) !== null &&
(Yii::$app->user->identity->isAdmin() || $model->owner_id === Yii::$app->user->id)
) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function actionLogoUpload($id)
{
$card = $this->findModel($id);
$image = Image::upload($card, 'logoImageFile');
if ($image->errors) {
return $result = ["success"=>false, "message"=> $image->getErrors()];
}
if (!empty($image)) {
$card->image_id = $image->id;
if ($card->validate() && $card->save()) {
$result = [
"success"
];
// }
return $result;
} else {
return $result = ["success"=>false, "message"=> $card->getErrors()];
}
}
}
}
Edit
Okay removing Content-type:multipart/form date in the header makes the route working, but obviously the code doesn't work since no file is sent.
A: The problem is likely with your server configuration. You have to configure your server to rewrite unknown paths to your index.php script.
For example, when I've used yii2 with apache, I have the following web/.htaccess file:
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
# ...other settings...
Options +FollowSymLinks
Of course, a lot of the details are dependent on your hosting and server configuration (e.g. are .htaccess files allowed). Yii's docs have more information on configuring different web servers here.
A: Okay turned out there was an extra space in the request. The code is fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61190433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get hex values from string? I have a function with an input parameter "text" , which consists of a string containing unknown number of 2-character Hexadecimal numbers separated by space. I need to read them and put them in separate array indexes or read them in for loop and work with them one by one. Each of these values represents an encrypted char(the hex values are ascii values of the characters). How could i do that? I think i should use sscanf(); but i can't figure out how to do it.
char* bit_decrypt(const char* text){
int size=strlen(text)/3;
unsigned int hex[size];
char*ptr;
for(int i=0; i<size+1; i++){
hex[i] = strtoul(text, &ptr, 16);
printf("%x ",hex[i]);
}
return NULL;
}
output is: "80 80 80 80 80 80 80 80 80 80 80 80"
should be: "80 9c 95 95 96 11 bc 96 b9 95 9d 10"
A: You scan always the first value of text, because you forgot to move the input for strtoul right after the end of the previous scan. That's what the **end-parameter of strtoul is good for: it points to the character right after the last digit of a successful scan. Note: if nothing could have been read in, the end-pointer is equal the input pointer, and this indicates a "wrongly formated number" or the end of the string. See the following program illustrating this. Hope it helps.
int main() {
const char* input = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
const char *current = input;
char *end = NULL;
while (1) {
unsigned long val = strtoul(current, &end, 16);
if (current == end) // invalid input or end of string reached
break;
printf("val: %lX\n", val);
current = end;
}
}
A: This is also possible solution with the use of strchr, and strtoul(tmp,NULL,16);
In your solution remember that size_t arr_len = (len/3) + 1; since the last token is only 2 bytes long.
Input text tokens are converted to bytes and stored in char array:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char text[] = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
size_t len = strlen(text);
size_t arr_len = (len/3) + 1;
printf("len= %zu arr_len= %zu\n", len, arr_len);
printf("Text:\n%s\n", text);
char array[arr_len];
const char *p1 = text;
char tmp[3];
tmp[2] = 0;
printf("Parsing:\n");
for(size_t i=0; i< arr_len; i++)
{
p1 = strchr(p1,' ');
if(p1)
{
tmp[0] = *(p1-2);
tmp[1] = *(p1-1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x ", (unsigned char) array[i]);
p1++;
if(strlen(p1) == 2 ) // the last char
{
i++;
tmp[0] = *(p1);
tmp[1] = *(p1+1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x", (unsigned char) array[i]);
}
}
}
printf("\nArray content:\n");
for(size_t i=0; i< arr_len; i++)
{
printf("%2x ", (unsigned char) array[i]);
}
return 0;
}
Test:
len= 35 arr_len= 12
Text:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Parsing:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Array content:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49342522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: whereIn array to string convertion error - Laravel I am wanting to use the WhereIn function on my Eloquent query, and it requires a PHP array:
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
Currently, the data is being passed into the controller in this format -
array(4) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" }
I am wanting the above data to be casted to (1,4,6) format to utilise the function but I'm unsure how.
This is currently being used in the following code (bedrooms and property_type are shown in the above format):
$bedrooms = Input::get('bedrooms');
$property_type = Input::get('property_type');
$locations = Location::whereHas('coordinate', function ($q) use ($minlat, $maxlat,
$minlng, $maxlng, $bedrooms, $property_type)
{
$q->whereBetween('lat', array($minlat, $maxlat))
->whereBetween('lng', array($minlng, $maxlng))
->whereIn('bedrooms', '=', $bedrooms)
->whereIn('type', '=', $property_type);
})->lists('id');
This returns a Array to string conversion error.
My Laravel version is 4.2.* - dev.
Any help would be hugely appreciated.
A: There is no need to do this. Have you tried it without casting them to ints? If you are not able to do this post what version of laravel you are using so people who come across this later don't do needless work. In laravel 4.2.* the following code will return the proper rows. I have just tested this.
Route::get('/', function(){
$t = DB::table('users')->whereIn('id', array('1','2','3'))->get();
dd($t);
});
This also works.
Route::get('/', function(){
$t = DB::table('users')->whereIn('id', array(1,2,3))->get();
dd($t);
});
Furthermore this code you have
array(4) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" }
And this code are exactly the same. One has just being displayed using var_dump.
array("1", "4", "6")
Unless you are literally storing unserialized arrays in your database in which case you have a ton of other issues.
EDIT: After controller was posted
I don't believe whereIn takes 3 parameters. You are trying to cast '=' to an array in your whereIn statements remove this and it should work or at least get ride of the Array to string error.
Link to whereIn Laravel function.
A: First: I think Laravel can handle string typed items to be put in a sql where clause where the column is an integers.
Second: if it doesn't work you can always 'cast' those strings to integers with the array_map method.
More information here:
http://php.net/manual/en/function.array-map.php
In your example:
$ids = array('1', '4', '6');
$ids = array_map(function ($value) {
return (int) $value;
}, $ids);
$users = DB::table('users')->whereIn('id', $ids)->get();
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26441444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: (iphone) make singleton of custom activity indicator? I'm trying to add my custom activity indicator to my app.
Since there are many places I want to show the indicator,
I thought maybe it's a good idea to make it singleton to access it easily.
I guess I can slightly modify this to make the desired singleton class.
Singleton Class iPhone
One problem is that I need to add the indicator view to some view(as subview) obviously.
And wonder if there is a singleton -like view that I can access from anywhere to add the indicator view as subview.
Thank you
A: you can use singleton, but I would advise you not to use singleton for UIView elements.
UIView elements can only have one superview, so if you use singleton.activityindicator everywhere, you will have to remove it from superview before adding it to new view, so alot of bookkeeping is required. For example, you have to remove it from prev superview when showing it else where, and when you come back to prev superview (through user clicking on some nav control or something), you have to determine if you need to now add it back to the new superview, etc.
I do use singleton for one UIView in my design, that is Ad banner view. I wanted to keep one ad across the app, to have same ad in different nav controllers. However it was big pain in the butt.
Just create one, add to the view, and remove when done.. simpler in my opinion :)
A: You can try to add a UIView to the custom class and then add the activityIndicator to it.
A: Take a UIView Class
inside initWithFrame methode:
//this method create custom activity indicator
UIImage *startImage = [UIImage imageNamed:@"1.png"];
customActivityIndicator = [[UIImageView alloc] //take in in .h file
initWithImage:startImage ];
//Add more images which to be used for the animation
customActivityIndicator.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
nil];
//Set animation duration
customActivityIndicator.animationDuration = 0.5;
//set frame at the middle of the imageview
customActivityIndicator.frame = self.frame;
Take a methode:
// call this methode from the class where u want to animate custom indicator
(void)startAnimating
{
[customActivityIndicatorstartAnimating];
}
Take a methode:
// call this methode from the class where u want to stope animate custom
(void)stopAnimating
{
[customActivityIndicatorstaopAnimating];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5296282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Routes not working for new application I created a new rails application a few days ago and got started by working on the models. I have a user model managed by devise and I am trying to get the login working. I began by setting the root to the user sessions controller like so:
root 'devise/sessions#new'
Then when I go to the root for my application in the browser it shows the "We're sorry, but something went wrong." page. I tried setting up a bogus route like:
get 'test/routes', to: 'devise/sessions#new'
and when I tried navigating to this route, I get the same error page. I checked the logs to see what was going on, and the problem is that nothing is going on. It doesn't seem like the router is even working because no page requests are showing up in the logs. I can't seem to figure out why this is happening and any help would be appreciated!
A: devise_scope :user do
root 'devise/sessions#new' end should solve the issue.
Setting devise
/sessions#new as root is not a good idea.The devise/session#new redirect to '/' if the user is signed in.This will cause a redirect loop if the user is already signed in .Its better if there is some consultation hub controller as root which checks whether the user is signed in and redirect to devise/session#new if he is not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20768140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Property 'changeView' does not exist on type 'CalendarOptions' I'm using Full calendar V5 in angular, and in the dateClick i allways get the error on the changeView.
I want to click on a day, and switch the view to "timeGridDay".
my code is this:
"
dateClick: function(info) {
if(info.view.type=="dayGridMonth"){
this.changeView("timeGridDay",info.dateStr);
}
}
"
A: You need to call changeView on the reference to the calendar object itself.
In the example below that would be named calendar
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth'
});
calendar.render();
});
This needs to be a global variable, not local to a setup function
So the code you want would be, in this case, would be
dateClick: function(info) {
if(info.view.type=="dayGridMonth"){
calendar.changeView("timeGridDay",info.dateStr);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72276622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reload values in com.google.common.base.Supplier on demand I have a Supplier defined as below in one the Services. This supplier loads some values from database.
private final Supplier<Map<CustomClass1, CustomClass2>> sampleSupplier = Suppliers.memoizeWithExpiration(getSampleSupplier(), 1, TimeUnit.DAYS);
I want to reload values in this supplier on demand so that if database is updated within the Time Duration(1 Day), those values will be reloaded into the Supplier. Is there any way I can achieve this?
A: I don't think that this is achievable via memoization, you need a cache instead from guava. It has methods that explicitly invalidate a key. So you would need a database trigger/listener that catches the event of when some entry changes and when that happens call:
Cache.invalidate(key)
and then
cache.put(key, value)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42271143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you update a running docker image on digital ocean droplet? I have a docker image running on port 3000 on my droplet on digital ocean.
I did some updates and created a new image and pushed it to my github packages.
I thought when I push the new image that the old one would just get overriden but Im getting an error saying
"Bind for 0.0.0.0:3000 failed: port is already allocated".
I run the following command when I get the above:
docker run -p 3000:3000 docker.pkg.github.com/UserName/Project/newImageName:1
This made me think that I could remove the old image and add the new one but that does not seem ideal but I have not found a command that can override/update to a new one.
Is this possible, and how?
A: Run the image using --rm parameter (which removes the container upon exit).
docker run --rm -p 3000:3000 docker.pkg.github.com/UserName/Project/newImageName:1
After exiting (stopping the container) you can docker pull to get the latest version of the image and then re-run
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70701924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Safari selenium Windows Could not instantiate class org.openqa.selenium.safari.SafariDriver I have grid node, to launch grid node I have command
Launch grid:
start java -jar selenium-server-standalone-2.47.1.jar -role hub -port 4441
Launch node:
start java -jar selenium-server-standalone-2.47.1.jar -role node -hub http://11.1.1.1:4441/grid/register -port 5541 -browser "browserName=safari, platform=ANY" -Dwebdriver.driver=SafariDriver.safariextz
While I run my selenium tests with maven with command:
<argLine>-Dfile.encoding=UTF-8 -Dwebdriver.remote.url=http://111.1.1.1:4441/wd/hub -Dwebdriver.driver=safari</argLine>
I Get
[main] ERROR net.thucydides.core.webdriver.WebDriverFacade - FAILED TO CREATE NEW WEBDRIVER_DRIVER INSTANCE class org.openqa.selenium
.safari.SafariDriver: Could not instantiate class org.openqa.selenium.safari.SafariDriver
net.thucydides.core.webdriver.UnsupportedDriverException: Could not instantiate class org.openqa.selenium.safari.SafariDriver
I use serenity and cucumber frameworks to execute my tests. Any Ideas what I do wrong?
A: I was also facing issues in initiating safari browser on mac machine, and below solution helped me
if (browserType.equals("safari")) {
// System.setProperty("webdriver.safari.driver", workingDir +
// "//driver//SafariDriverServer.exe");
System.setProperty("webdriver.safari.driver",
"/driver/SafariDriver.safariextz");
System.setProperty("webdriver.safari.noinstall", "true");
DesiredCapabilities desiredCapabilities = DesiredCapabilities
.safari();
SafariOptions safariOptions = new SafariOptions();
safariOptions.setUseCleanSession(true);
safariOptions.getUseCleanSession();
safariOptions.setUseCleanSession(true);
desiredCapabilities.setCapability(SafariOptions.CAPABILITY,
safariOptions);
// deleteCookies();
driver = new EventFiringWebDriver(new SafariDriver());
ThreadDriver.set(driver);
// driver.manage().window().setSize(new Dimension(1024, 850));
getDriver().manage().timeouts().implicitlyWait(3,
TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 30);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39390071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP and MySQL - efficiently handling multiple one to many relationships I am seeking some advice on the best way to retrieve and display my data using MySQL and PHP.
I have 3 tables, all 1 to many relationships as follows:
Each SCHEDULE has many OVERRIDES and each override has many LOCATIONS. I would like to retrieve this data so that it can all be displayed on a single PHP page e.g. list out my SCHEDULES. Within each schedule list the OVERRIDES, and within each override list the LOCATIONS.
Option1 - Is the best way to do this make 3 separate SQL queries and then write these to a PHP object? I could then iterate through each array and check for a match on the parent array.
Option 2 - I have thought quite a bit about joins however doing two right joins will return me a row for every entrance in all 3 tables.
Any thoughts and comments would be appreciated.
Best regards, Ben.
A: If you really want every piece of data, you're going to be retrieving the same number of rows, no matter how you do it. Best to get it all in one query.
SELECT schedule.id, overrides.id, locations.id, locations.name
FROM schedule
JOIN overrides ON overrides.schedule_id = schedule.id
JOIN locations ON locations.override_id = overrides.id
ORDER BY schedule.id, overrides.id, locations.id
By ordering the results like this, you can iterate through the result set and move on to the next schedule whenever the scheduleid changes, and the next location when the locationid changes.
Edit: a possible example of how to turn this data into a 3-dimensional array -
$last_schedule = 0;
$last_override = 0;
$schedules = array();
while ($row = mysql_fetch_array($query_result))
{
$schedule_id = $row[0];
$override_id = $row[1];
$location_id = $row[2];
$location_name = $row[3];
if ($schedule_id != $last_schedule)
{
$schedules[$schedule_id] = array();
}
if ($override_id != $last_override)
{
$schedules[$schedule_id][$override_id] = array();
}
$schedules[$schedule_id][$override_id][$location_id] = $location_name;
$last_schedule = $schedule_id;
$last_override = $override_id;
}
Quite primitive, I imagine your code will look different, but hopefully it makes some sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4820742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: c# Updating datetime column in access OleDbConnection con = new OleDbConnection(@constring);
con.Open();
string cmdstring = "UPDATE table SET date=" + DateTime.Parse(datetxt.Text) +" WHERE id ="+id;
OleDbCommand cmd = new OleDbCommand(cmdstring,con);
cmd.ExecuteNonQuery();
con.Close();
I want to update date column which is stored in access database. But it gives me syntax error(missing operator) in query expression '03.03.2016 00:00:00'
In access date column type is Date/Time.
A: Try with :
string cmdstring = "UPDATE table SET date='" + DateTime.Parse(datetxt.Text).ToString("dd/MM/yyy") +"' WHERE id ="+id;
A: Apparently it seems a problem in the date format . The solution indicated by Beldi Anouar should funcionarte .
Good luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37205656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best C++11 way to measure code execution time for an Embedded system I was trying to find a way to measure code execution time without using the below listed constraints.
In my requirement it's for an embedded system which has very strict conformances.
All I could found was using C headers, unapproved headers by Google C++ coding standards or boost which are excluded from the project conformances.
I looked through the suggested posts which looked similar but couldn't find an answer for what is looked for. Please help!
Constraints are not to use the following,
*
*Boost libraries
*C system headers like sys/time.h
*Unapproved headers like chrono by Google C++ style guide https://google.github.io/styleguide/cppguide.html
*Target platform is Linux
This style checker has list down chrono as unapproved..
https://github.com/google/styleguide/blob/gh-pages/cpplint/cpplint.py
A: If we are talking about C++11 - the only way is to use std::chrono. Google style guide is not an some kind of final authority here (sometimes it is highly questionable).
std::chrono is proven to be good and stable, and even used in game engines in AAA games, see for yourself HERE. Good example for exactly what you need is available HERE
In case if you still don't want it, there are no other C++11 way to do it, but you, probably, want to look on C-style measure, like HERE.
Just for your information - all methods are using system API, and so, <time.h> is included, no way to avoid it.
A: For embedded systems there is a common practice to change GPIO state in your code and then hook an oscilloscope to the pin and look for resulting waveform. This has minimal impact on runtime because changing GPIO is a cheap operation. It does not require any libraries and additional code. But it requires additional hardware.
Note: embedded is quite stretchable notion. GPIO trick is more related for microcontrollers.
A: Is the time measurement necessary in the final product? If not I'd suggest using whatever you like and use a switch to not compile these measurement routines into the final product.
A: Something like this you mean? (for windows platform)
#include <Windows.h>
class stopwatch
{
double PCFreq = 0.0;
double CounterStart = 0; //google style compliant, less accurate
//__int64 CounterStart = 0; //for accuracy
LARGE_INTEGER li;
public:
void StartCounter()
{
if (!QueryPerformanceFrequency(&li))ExitProcess(0);
PCFreq = double(li.QuadPart) / 1000.0;
QueryPerformanceCounter(&li); CounterStart = li.QuadPart;
}
double GetCounter() { QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; }
};
usage:
stopwatch aclock;
aclock.StartCounter(); //start
//....///
cout<<aclock.GetcCounter()<<endl; //output time passed in milliseconds
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40758263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: specifying a file in a classpathresource I am using classpathresource to get the resource of a file . In my code am specifying the path so that the file is picked from there . But its taking a file with same name which is already there in a jar from previous.
i.e.,
I have specified,
ClassPathResource resource = new ClassPathResource("/sw/merlot/config/log4j.xml")
where log4j.xml is the configuration file.
But its taking a log4j.xml which is in a jar -- sw/merlot/lib/keyManager.jar!/log4j.xml
(Both log4j.xml are different [2 different configuration files])
So i changed it to,
ClassPathResource resource = new ClassPathResource("file:///sw/merlot/config/log4j.xml")
But its still not working .
I dont know if the way I have specified the file is correct or not?
I also tried to specify the file using a jar .
ClassPathResource resource = new ClassPathResource("jar:file:///sw/merlot/lib/keyManager111.jar!/log4j.xml")
where keyManager111.jar contains my log4j.xml which i want. But its still not picking from the jar. Its telling file not found at the specified location.
A: What about:
ClassPathResource resource = new ClassPathResource("classpath:/sw/merlot/config/log4j.xml");
or if it is in a different jar file:
ClassPathResource resource = new ClassPathResource("classpath*:/sw/merlot/config/log4j.xml");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5856116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chaining actions sharing data in a do block Ok, suppose I have an IO operation; loadFile :: FilePath -> ByteString which I process with processData :: ByteString -> ProcessedData being this operation pretty expesnive and I want to use this processed data in two actions like so:
main = do
{
bytes <- loadFile "....";
let data = processData bytes
in printf (extractFoo data address1)
printf (extractFoo data address2) -- Compiler error
}
I know I can do this, which is basically not sharing data between both actions:
main = do
{
bytes <- loadFile "....";
let data = processData bytes
in printf (extractFoo data address1);
let data = processData bytes
in printf (extractFoo data address2);
}
How can I share data in both printf? I'm very new to Haskell and I am struggling with the IO monad. I'm trying to understand it but its a slow process up till now.
A: Just remove the curly braces and use a plain let:
main = do
bytes <- loadFile "...."
let d = processData bytes
printf (extractFoo d address1)
printf (extractFoo d address2)
I renamed your data to d since data is a keyword in Haskell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35455614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Chefspec with Hashicorp Vault I'm trying to use ChefSpec to test an implementation of Chef and Hashicorp Vault
Recipe
chef_gem 'vault' do
compile_time true if Chef::Resource::ChefGem.instance_methods(false).include?(:compile_time)
end
require 'vault'
Vault.address = 'https://address:8200'
Vault.token = citadel['foo/bar']
Vault.auth_token.renew_self
Test
require_relative '../spec_helper'
describe 'wrapper::default' do
context 'role is foo' do
let(:chef_run) do
ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '14.04') do |node|
node.default['role'] = 'foo'
const_set(:Vault, Module.new)
end.converge(described_recipe)
end
before(:each) do
allow_any_instance_of(Chef::Recipe).to receive(:require).and_call_original
allow_any_instance_of(Chef::Recipe).to receive(:require).with('vault').and_return(true)
allow_any_instance_of(::Vault).to receive(:address).and_call_original
allow_any_instance_of(::Vault).to receive(:address).with('https://localhost:8200').and_return(true)
end
it 'install vault gem' do
expect(chef_run).to install_chef_gem('vault')
end
end
end
Error
Failure/Error: expect(Chef::Recipe::Vault).to receive(:address).and_call_original
NameError:
uninitialized constant Vault
How do I stub the Vault variables? This is Hashicorp Vault, not chef-vault.
A: i got here and still couldnt figure it out
so i ended up moving my vault code into my own lib which i include in the recipe so i couldnt mock it out during ChefSpec run.
so i have under my-cookbook/libraries/my_vault.rb with this code:
require 'vault'
module MyVault
module Helpers
def get_vault_secret(secret)
Vault.configure do |config|
config.address = "#{node[:vault_url]}"
config.token = "#{node[:vault_token]}"
end
Vault.logical.read(secret)
end
end
end
and in my recipe:
Chef::Recipe.send(:include, MyVault::Helpers)
creds = get_vault_secret("secret/jmx")
user = creds.data[:user]
password = creds.data[:password]
template "/etc/app/jmx.password" do
source "jmx.password.erb"
mode 0600
owner "dev"
group "dev"
variables({
:user => user,
:password => password
})
end
and my spec test:
require 'chefspec'
require 'chefspec/berkshelf'
describe 'app::metrics' do
platform 'ubuntu', '14.04'
before do
response = Object.new
allow(response).to receive_messages(:data => {
:user => "benzi",
:password => "benzi"
})
allow_any_instance_of(Chef::Recipe).to receive(:get_vault_secret).and_return(response)
end
describe 'adds jmx.access to app folder' do
it { is_expected.to create_template('/etc/app/jmx.access')
.with(
user: 'dev',
group: 'dev',
mode: 0644
) }
end
A: I responded to your email already, you want allow_any_instance_of(::Vault) and similar, and you may have to create the module (const_set(:Vault, Module.new)) if it doesn't exist already.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39458691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: QtConcurrent gives longer runtimes for multiple cores I have designed an algorithm and now I'm working on an implementation to solve it on multiple cores. Essentially I'm giving each core the same problem and I'll choose the solution with the best score. However, I'm noticing that using multiple cores slows down the runtime of my code, but I don't understand why. So I created a very simple example that shows the same behaviour. I have a simple Algoritmn class:
algorithm.h
class Algorithm
{
public:
Algorithm() : mDummy(0) {};
void runAlgorithm();
protected:
long mDummy;
};
algorithm.cpp
#include "algorithm.h"
void Algorithm::runAlgorithm()
{
long long k = 0;
for (long long i = 0; i < 200000; ++i)
{
for (long long j = 0; j < 200000; ++j)
{
k = k + i - j;
}
}
mDummy = k;
}
main.cpp
#include "algorithm.h"
#include <QtCore/QCoreApplication>
#include <QtConcurrent/QtConcurrent>
#include <vector>
#include <fstream>
#include <QFuture>
#include <memory>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::ofstream logFile;
logFile.open("AlgorithmLog.log", std::ios::trunc | std::ios::out);
if (!logFile.is_open())
{
return 1;
}
for (int i = 1; i < 8; i++)
{
int cores = i;
logFile << "Start: cores = " << cores << " " << QDateTime::currentDateTime().toString(Qt::ISODate).toLatin1().data() << "\n";
std::vector<std::unique_ptr<Algorithm>> cvAlgorithmRuns;
for (int j = 0; j < cores; ++j)
cvAlgorithmRuns.push_back(std::unique_ptr<Algorithm>(new Algorithm()));
QFuture<void> assyncCalls = QtConcurrent::map(cvAlgorithmRuns, [](std::unique_ptr<Algorithm>& x) { x->runAlgorithm(); });
assyncCalls.waitForFinished();
logFile << "End: " << QDateTime::currentDateTime().toString(Qt::ISODate).toLatin1().data() << "\n";
logFile.flush();
}
logFile.close();
return a.exec();
}
When I run this on my laptop (I'm using VS2015, x64, Qt 5.9.0, 8 logical processors) I get:
Start: cores = 1 2018-06-28T10:48:30 End: 2018-06-28T10:48:44
Start: cores = 2 2018-06-28T10:48:44 End: 2018-06-28T10:48:58
Start: cores = 3 2018-06-28T10:48:58 End: 2018-06-28T10:49:13
Start: cores = 4 2018-06-28T10:49:13 End: 2018-06-28T10:49:28
Start: cores = 5 2018-06-28T10:49:28 End: 2018-06-28T10:49:43
Start: cores = 6 2018-06-28T10:49:43 End: 2018-06-28T10:49:58
Start: cores = 7 2018-06-28T10:49:58 End: 2018-06-28T10:50:13
Which makes sense: the same runtime (between 14 and 15 seconds) for all steps, whether I'm using 1 core or 7 cores.
But when I change the line in algoritm.h from:
protected:
long mDummy;
to:
protected:
double mDummy;
I get these results:
Start: cores = 1 2018-06-28T10:52:30 End: 2018-06-28T10:52:44
Start: cores = 2 2018-06-28T10:52:44 End: 2018-06-28T10:52:59
Start: cores = 3 2018-06-28T10:52:59 End: 2018-06-28T10:53:15
Start: cores = 4 2018-06-28T10:53:15 End: 2018-06-28T10:53:32
Start: cores = 5 2018-06-28T10:53:32 End: 2018-06-28T10:53:53
Start: cores = 6 2018-06-28T10:53:53 End: 2018-06-28T10:54:14
Start: cores = 7 2018-06-28T10:54:14 End: 2018-06-28T10:54:38
Here I start with 14 seconds runtime for 1 core, but the runtime increases to 24 seconds using 7 cores.
Can anybody explain why in the second run the runtime increases when using multiple cores?
A: I believe the problem lies in the actual number of FPUs you have as suggested by @Aconcagua.
"logical processors" aka "hyper threading" is not the same as having twice the cores.
8 cores in hyper threading are still 4 "real" cores. If you look closely at your timings, you will see that the execution times are almost the same until you use more than 4 threads. When you use more than 4 threads, you may start running out of FPUs.
However, to have a better understanding of the issue I would suggest to have a look at the actual assembly code produced.
When we want to measure raw performance, we must keep in mind that our C++ code is just an higher level representation, and the actual executable may be quite different than what we would expect.
The compiler will perform its optimizations, the CPU will execute things out of order, etc...
Therefore, first of all I would recommend to avoid the use of constant limits in your loops. Depending on the case, the compiler may unroll the loop or even replace it entirely with the result of its calculation.
As an example, the code:
int main()
{
int z = 0;
for(int k=0; k < 1000; k++)
z += k;
return z;
}
is compiled by GCC 8.1 with optimizations -O2 as:
main:
mov eax, 499500
ret
As you can see the loop just disappeared!
The compiler replaced it with the actual end result.
Using an example like this to measure performance is dangerous. With the example above, iterating 1000 times or 80000 times is exactly the same, because the loop is replaced with a constant in both cases (of course, if you overflow your loop variabile the compiler can't replace it anymore).
MSVC is not that aggressive, but you never know exactly what the optimizer does, unless you look at the assembly code.
The problem with looking at the produced assembly code is that it can be massive...
A simple way to solve the issue is to use the great compiler explorer. Just type in your C/C++ code, select the compiler you want to use and see the result.
Now, back to your code, I tested it with compiler explorer using MSVC2015 for x86_64.
Without optimizations they assembly code looks almost the same, except for the intrinsic at the end to convert to double (cvtsi2sd).
However, things start to get interesting when we enable optimizations (which is the default when compiling in release mode).
Compiling with the flag -O2, the assembly code produced when mDummy is a long variable (32 bit) is:
Algorithm::runAlgorithm, COMDAT PROC
xor r8d, r8d
mov r9d, r8d
npad 10
$LL4@runAlgorit:
mov rax, r9
mov edx, 100000 ; 000186a0H
npad 8
$LL7@runAlgorit:
dec r8
add r8, rax
add rax, -4
sub rdx, 1
jne SHORT $LL7@runAlgorit
add r9, 2
cmp r9, 400000 ; 00061a80H
jl SHORT $LL4@runAlgorit
mov DWORD PTR [rcx], r8d
ret 0
Algorithm::runAlgorithm ENDP
end when mDummy is a float:
Algorithm::runAlgorithm, COMDAT PROC
mov QWORD PTR [rsp+8], rbx
mov QWORD PTR [rsp+16], rdi
xor r10d, r10d
xor r8d, r8d
$LL4@runAlgorit:
xor edx, edx
xor r11d, r11d
xor ebx, ebx
mov r9, r8
xor edi, edi
npad 4
$LL7@runAlgorit:
add r11, -3
add r10, r9
mov rax, r8
sub r9, 4
sub rax, rdx
dec rax
add rdi, rax
mov rax, r8
sub rax, rdx
add rax, -2
add rbx, rax
mov rax, r8
sub rax, rdx
add rdx, 4
add r11, rax
cmp rdx, 200000 ; 00030d40H
jl SHORT $LL7@runAlgorit
lea rax, QWORD PTR [r11+rbx]
inc r8
add rax, rdi
add r10, rax
cmp r8, 200000 ; 00030d40H
jl SHORT $LL4@runAlgorit
mov rbx, QWORD PTR [rsp+8]
xorps xmm0, xmm0
mov rdi, QWORD PTR [rsp+16]
cvtsi2ss xmm0, r10
movss DWORD PTR [rcx], xmm0
ret 0
Algorithm::runAlgorithm ENDP
Without getting into the details of how these two codes work or why the optimizer behaves differently in the two cases, we can clearly see some differences.
In particular, the second version (the one with mDummy being float):
*
*is slightly longer
*uses more registers
*access memory more often
So aside from the hyper threading issue, the second version is more likely to produce cache misses, and since cache is shared, this can also affect the final execution times.
Moreover, things like turbo boost may kick in as well. Your CPU may be throttling down when stressing it, causing an increase in the overall execution time.
For the records, this is what clang produces with optimizations turned on:
Algorithm::runAlgorithm(): # @Algorithm::runAlgorithm()
mov dword ptr [rdi], 0
ret
Confused? Well... nobody is using mDummy elsewhere so clang decided to remove the whole thing entirely... :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51079939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cross layer in pytorch How can I add a cross layer in pytorch (https://arxiv.org/abs/1708.05123). I would like to add such a cross layer into my neural network that comes before the deep layers as a way to better combine my features that are coming from a range of sources.
Thanks!
A: There is a PyTorch implementation of the DCN architecture from paper you linked in the DeepCTR-Torch library. You can see the implementation here: https://github.com/shenweichen/DeepCTR-Torch/blob/master/deepctr_torch/models/dcn.py
If you pip install deepctr-torch then you can just use the CrossNet layer as a torch.Module:
from deepctr_torch.layers.interaction import CrossNet
crossnet = CrossNet(in_features=512)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71877020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to text() and concatenate values of nested list Im trying get the values of a nested list and concatenate them in each click:
<ul>
<li>item1</li>
<li>item2
<ul>
<li>superitem1
<ul>
<li>eliteitem1</li>
<li>eliteitem2</li>
</ul>
</li>
<li>superitem3</li>
<li>superitem4</li>
</ul>
</li>
<li>item3</li>
<li>item4</li>
</ul>
This is the script I tryed but it doesnt work:
$(document).ready(function(){
var string= "You clicked."
$("li").click(function(){
if($(this).children().length ==0){
var val = $(this).text().trim()
var final1 = string+val
alert (final1 )
}
if($(this).children().length > 1){
var father1= $(this).clone().children().remove().end().text().trim()
var final2 = string+father1
alert (final2)
}
$(this).on('click', '> *', function(event){ //Click of childrens
var son= $(event.target).text().trim()
var final3 = final2+"."+son
event.stopImmediatePropagation()
alert (final3)
})
})
})
I need to concatenate the value of each click with their parent/children.
For example, If you click eliteitem1 make alert with next message:
alert ("You clicked.item2.superitem1.eliteitem1)
A: I wrote an example for you .
$('li').click(function(e) {
var path = [];
var el = $(this);
do {
path.unshift(el.clone().children().remove().end().text().trim());
el = el.parent().closest('li');
} while(el.length != 0);
console.log(path.join('/'));
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>item1</li>
<li>item2
<ul>
<li>superitem1
<ul>
<li>eliteitem1</li>
<li>eliteitem2</li>
</ul>
</li>
<li>superitem3</li>
<li>superitem4</li>
</ul>
</li>
<li>item3</li>
<li>item4</li>
</ul>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43716752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to extract a specific element value from an array in laravel controller I do have the following output in the form of an array
$fetchSubFormDetailData = $this->PMSDS11FetchSubFormDetailTrait($request);
echo 'Data Submitted' ;
print_r($fetchSubFormDetailData);
The result shown because of print_r is as under
Data SubmittedArray
(
[LineId] => 10
[IncomeTo] => 500000.00
)
Now I want to extract IncomeTo from this array into a variable in this controller for validations. I tried using the following ways
$IncomeTo = $fetchSubFormDetailData[0]->IncomeTo;
I am keep on getting the following error in laravel8.
"message": "Undefined array key 0",
"exception": "ErrorException",
How can I extract the value (500000.00) of IncomeTo element from this array in my $IncomeTo variable?
Any help will be appreciated.
A: This should work
$IncomeTo = $fetchSubFormDetailData['IncomeTo'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70764900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to disable a link button in gridview when clicked I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveRow")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
lnkbtn.Enabled = false;
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int TimeSheetId = Convert.ToInt32(e.CommandArgument);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TimeSheetId", TimeSheetId);
con.Open();
cmd.ExecuteNonQuery();
GetManagerTimeSheets();
}
}
}
A: You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}
A: Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
A: try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25926710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the difference between private static variable and private instance variable in a singleton class? What is the difference between private static variable and private instance variable in a singleton class?
I see no semantic difference.
EDIT: Not asking if the variable holding the instance of itself should be static, but other data members.
A: The way I see it, there is only "no semantic difference" if you assume that the singleton is implemented using a static reference to the single instance. The thing is, static is just one way to implement a singleton — it's an implementation detail. You can implement singletons other ways, too.
A: There is no difference really (besides initialization blocks mentioned already). But on the other hand you are not really gaining anything also. You still need to take thread safety into consideration and you still need to make sure you have only one instance of your singleton at a time. The only difference would be if you wanted to publish that member via a public static method. But why on earth would you want to do that - I have no idea.
For me personally it would also be a bit of a "code smell". I mean someone made a singleton and still declared its member as static? What does it tell me? Is there something I don't know? Or maybe there's something wrong with the implementation and it has to be static (but why?!). But I'm a bit paranoid. From what I am also aware of there are no performance reasons why this would be a good option.
A: I'm not sure what you are looking for, so I'll write something and see what you have to say.
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private double weight; // in pounds
private Elvis() { weight = 300.; } // inaccessible
public static Elvis getInstance() { return INSTANCE; }
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weight; }
}
Since there is only one Elvis, you could have made weight a static variable (with static getter and setter). If you make all variables static, then there is no point in defining a singleton INSTANCE since you just have a class with only static variables and methods:
public class Elvis {
private static double weight; // in pounds
static { weight = 300.; } // Could just have set the weight directly above,
// but a static block might be useful for more complex examples.
public static double getWeight() { return weight; }
public static void setWeight(double weight) { this.weight = weight; }
}
I guess this should be avoided since it looks more like a header file in C than OO.
Some might have recognized the Elvis reference from J. Bloch "Effective Java". The recommendation in that book is to implement the singleton pattern with an enum with one member:
public enum Elvis {
INSTANCE;
private double weight = 300.;
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weigth; }
}
Note that it looks somewhat non-standard here with the varying weight since you usually expect enum instances to be immutable.
A: There are differences, though.
For instance, you can't use a static block to initialize the former.
A: Probably it is better to implement it in the singleton, since that way you can override the singleton for tests and similar. Also, you keep your static state in a single place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8828720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting protein sequences by accessing Uniprot (with Python) I have a list of protein id's I'm trying to access the protein sequences from Uniprot with python.
I came across this post :Protein sequence from uniprot protein id python but gives a list of elements and not the actual sequence:
Code
import requests as r
from Bio import SeqIO
from io import StringIO
cID='P04637'
baseUrl="http://www.uniprot.org/uniprot/"
currentUrl=baseUrl+cID+".fasta"
response = r.post(currentUrl)
cData=''.join(response.text)
Seq=StringIO(cData)
pSeq=list(SeqIO.parse(Seq,'fasta'))
which gives output:
output
[SeqRecord(seq=Seq('MQAALIGLNFPLQRRFLSGVLTTTSSAKRCYSGDTGKPYDCTSAEHKKELEECY...SSS', SingleLetterAlphabet()), id='sp|O45228|PROD_CAEEL', name='sp|O45228|PROD_CAEEL', description='sp|O45228|PROD_CAEEL Proline dehydrogenase 1, mitochondrial OS=Caenorhabditis elegans OX=6239 GN=prdh-1 PE=2 SV=2', dbxrefs=[])]
I was just curious on how I can actually get the sequence itself.
A: [record.seq for record in pSeq]
edit:
You'll want str(pSeq[0].seq)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63992865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Checkout git submodule in Azure Pipeline with SSH I try to checkout the git submodules via ssh instead of https (default if you use "Checkout submodules") in an Azure DevOps Pipeline. With the option in the picture it works - but for the developers it's annoying to enter the password all the time if they are working with the repository.
For that I used the following instructions to add the ssh key.
I created a public and a private key, and copied the known_host entry.
That's my YAML file snippet:
stages:
- stage: DeployBackend
jobs:
- job: SSH
steps:
- task: InstallSSHKey@0
inputs:
knownHostsEntry: $(known_host)
sshPublicKey: $(public_key)
sshKeySecureFile: 'private_key_file'
- job: Deploy
steps:
- checkout: self
submodules: true
- script: |
-- here I run all docker commands to build the container and push it to Azure --
displayName: "Deploy"
If I use the SSH keys to clone the repository to my local computer I have no issues. But if I run the pipeline it will crash at the submodule checkout:
Please make sure you have the correct access rights and the repository
exists. fatal: clone of
'[email protected]:v3/repoLink'
into submodule path '/home/vsts/work/1/s/app/submoduleFolder' failed
Failed to clone 'app/submoduleFolder'. Retry scheduled Cloning into
'/home/vsts/work/1/s/app/submoduleFolder'... Host key verification
failed. fatal: Could not read from remote repository.
That's the .gitmodules file in the repo - it works without any issues locally:
[submodule "app/subModuleName"]
path = app/subModuleName
url = [email protected]:v3/***/subModuleName
branch = master
I even wrote the id_rsa, known_hosts and id_rsa.pub files into .ssh with a script, but it seems like they are not even used for ssh verification.
A: The solution is to do all the tasks in one job. Variables are not shared between different job instances.
This works:
jobs:
- job: jobName
steps:
- task: AzureKeyVault@1
inputs:
azureSubscription: '***'
KeyVaultName: '***'
displayName: "Read Secrets from KeyVault"
- task: InstallSSHKey@0
inputs:
knownHostsEntry: $(known_host)
sshPublicKey: $(public_key)
sshKeySecureFile: 'private_key_file'
displayName: "Create SSH files"
- script: |
git clone --recurse-submodules [email protected]:v3/****
git submodule update --init --recursive
docker login -u $(userName) -p $(password) ***
docker build ****
docker push ****
displayName: "Build and Push Docker Container"
A: An alternative is to edit the .gitmodules path to be a relative url, eg url = ../subModuleName:
[submodule "app/subModuleName"]
path = app/subModuleName
url = ../subModuleName
branch = master
The url is now relative to the parent repo's url. So when the ado pipeline clones it via https, it uses the same for the submodule. Developers can clone the repo using either https or ssh, and the submodule will use the same - no need to enter passwords.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58862131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can I use a local path to json with Google Maps API Per the documentation here:
Can I replace:
map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
with a local path such as:
C:\path\file.json ?
or must it be hosted on a server?
Thanks
A: In general, this used to be not allowed by design. It's a violation of the sandbox.
From Wikipedia -> Javascript -> Security:
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-relatedactions, not general-purpose programming tasks like creating files.
However, it's now possible in current browsers using the FILE API specification.
This should in theory allow you to read it using the FileReader interface, although you might need to use something like JSON.parse() (or $.parseJSON if you're using JQuery) to then interpret it in the way you need. Lots more detail and examples of how to do this are here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22559788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the element that is clicked on with a click handler added in a forEach? I need to detect element count number
I have 10 poster elements and I have a forEach loop
I need the poster number that I clicked on, for example if I click on the seventh poster posternumber should be 7
poster.forEach(p => {
p.addEventListener('click',function(){
videoTag.src = xResult[movieLanguageUrl][/*posternumber*/];
});
});
A: Check out the signatur of your forEach consumer function. The secound argument is the index.
poster.forEach((p, idx) => {
p.addEventListener('click',function(){
videoTag.src = xResult[movieLanguageUrl][idx];
});
});
Check out this link.
A: Get the index value on the second parameter of the forEach function and it should work:
poster.forEach((p, index) => {
p.addEventListener('click', () => {
videoTag.src = xResult[movieLanguageUrl][index + 1];
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62934894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to keep scroll position when pressing back button in angular 13, I'm already using RouteReuseStrategy I have a long list of items inside a big scrollable div. Each time when a user click on an item to see the details of item then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button?
Thank you very much!
I'm already know the position of scroll but i couldn't set it. Always the position of scroll reset to 0
A: Add scrollPositionRestoration: "enabled" to your routing module as option.
@NgModule({
imports: [RouterModule.forRoot(routes, {
scrollPositionRestoration: "enabled", //--> add this
})],
exports: [RouterModule]
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74014655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: INSERT INTO query not working in Express.js I'm having trouble inserting data into a MySQL database. Select queries work fine, so I'm assuming that it's something stupid that I've missed, either in the Express code, or, in my HTML. The page I'm running the query from is located at localhost:8080/add, and I'm trying to INSERT INTO. Here's my code:
Javascript
app.get('/add', function(req, res) {
res.sendFile(path.join(__dirname + '/Views/add.htm'));
});
app.post('/add', function(req, res) {
var fName = req.body.fName;
var email = req.body.email;
var id = req.body.id;
var post = {id: id, user: fName, email: email};
console.log(post);//This holds the correct data
connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log('Was not able to add information to database.');
}
});
});
My HTML is simply a submit button and 3 input fields, within in a POST method form. Again, I can connect to the database and read from it with a select query, I just cannot insert into it.
A: Look at the documentation here https://github.com/mysqljs/mysql#escaping-query-values.
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log(result);
console.log('Was not able to add information to database.');
}
});
Valid mysql statement is SET instead of Values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40135845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get PhpStorm to understand different SQL dialects in HEREDOC in the same project My PHP 7.3 application connects to MS SQL Server or MariaDB, depending on being run under Windows or Linux.
For my queries, I sometimes write queries in SQL Server syntax and sometimes in MySQL syntax. For code validation etc. I use PhpStorm's language injection via HEREDOC
Of course, only the dialect that is configured in the project, is validated correctly.
Example:
switch ($dt_type) {
case 'MSSQL':
$sql_string = <<<SQL
[MSSQL query here]
SQL;
case 'MYSQL':
case 'MSSQL':
$sql_string = <<<SQL
[MYSQL query here]
SQL;
}
I configured the MSSQL dialect in my project, so PhpStorm (correctly, expectedly) marks my MySQL queries as invalid and quirks the syntax highlighting.
Is there a way to tell PhpStorm, that a specific string should be validated with a different SQL dialect, for example by declaring it in a comment just before that string declaration? I tried the @lang annotation, and language injection comments.. without any success.
I am aware it might not be possible, but maybe someone knows a trick?
A: SQL is used to apply the current SQL Dialect for that file (in case if you do not know: you can configure the IDE to have different dialects on per file/folder basis).
To have two dialects in the same file:
*
*Do not use SQL as an identifier if you will be changing it across the project (as it will use current SQL Dialect for that file).
I mean: you can use it, not an issue; but do not get lost/confused if you change the dialect later for that folder/file or for the whole project.
*Create and use more specific identifiers instead that will instruct the IDE to use a specific dialect there.
It's easy: just clone and adjust a bit a Language Injection rule for the bundled SQL identifier:
*
*Settings (Preferences on macOS) | Editor | Language Injections
*Clone existing rule for <<<SQL and adjust as needed (or create new one from scratch using the right type)
As you may see from this example, string for PostgreSQL complains on syntax (there is no DB attached to the project, hence unknown table table):
In-place language injection via @lang also works. NOTE that the injection must be placed just before the string content, not before the variable etc.
$sql1 = /** @lang MySQL */'SELECT * FROM `table`';
$sql2 = /** @lang PostgreSQL */'SELECT * FROM `table`';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57919199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Cucumber ordering of Given, When, Then (Given, When, Then, When, Then) As an End-to-end Automation Tester I have always assumed that Given, When, Then statements (incorporated in the Gherkin Language when using Cucumber) should only ever appear in the order of 1. Given, 2. When, 3. Then.
i.e. A test should not follow, for example, Given, When, Then, When, Then. And instead should follow Given, When, Then only.
The reason for this assumption was along the lines of a single test only testing one area of the application.
However, I noticed on some gherkin examples on the web, that they use the following ordering sometimes: Given, When, Then, When, Then.
Does anyone know if this moving back to Whens after writing a Then is acceptable best practice? I appreciate the test will still work, just wondering if this is good or bad practice.
A: Although scenarios can be written in that way, it is not best practice. I for one, have made that mistake and it can cause problems in reports and maintenance.
One reason would be that When declares an action and Then verifies the result of that action. Having When - Then twice goes against the individual behavior of a scenario.
Can also get confusing for someone who reads the scenario :)
Here's a little post regarding this
A: There is alot of really bad Gherkin on the web. Also there is a range of opinions about what good Gherkin is.
My opinion is that When Then When Then is an anti-pattern. Its likely that one of the following is required
*
*You need a better Given to incorporate the first When Then
or
*You need to split the scenario in two.
In general most When's in scenario's become Given's in later scenario's, as you build on existing behaviour to define and create new behaviour.
A: Syntactically Interchangeable; Linguistically Different
The Gherkin syntax currently includes six keywords for describing feature steps:
*
*Given
*When
*Then
*And
*But
**
The keywords are there for human consumption and the ease of conveying business logic. However, the Gherkin language itself treats the keywords as interchangeable symbols, so you could just as grammatically (from a Gherkin point of view) write tortured English like:
But for a dollar held
Then another dollar more
Given ownership of two dollars am I.
This is perfectly valid Gherkin, but a terrible representation of counting money. So, if all the words are interchangeable, why have so many of them?
The wiki is quite clear that they provide a set of conventions to facilitate communication in a more natural style, and the wiki even gives a few examples of how the words are meant to be differentiated. The wiki also specifically says:
Cucumber doesn’t technically distinguish between these...[kinds] of steps. However, we strongly recommend that you do! These words have been carefully selected for their purpose, and you should know what the purpose is to get into the BDD mindset.
In other words, use the Gherkin terms to communicate in (relatively) natural language about your feature, and bury the arcana in step definitions. Use whatever keyword fits most naturally in the linguistic flow, and don't sweat a well-written scenario that doesn't rigidly adhere to a convention that may not apply in all cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45059024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Template or function arguments as implementation details in doxygen? In doxygen is there any common way to specify that some C++ template parameters of function parameters are implementation details and should not be specified by the user ?
For example, a template parameter used as recursion level counter in metaprogramming technique or a SFINAE parameter in a function ?
For example :
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
/// \tparam Current Recursion level counter. SHOULD NOT BE EXPLICITELY SPECIFIED !!!
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunction();
Is there any doxygen normalized option equivalent to "SHOULD NOT BE EXPLICITELY SPECIFIED !!!" ?
A: It seems to me that the whole template is an implementation detail of a different interface:
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunctionImpl();
template<bool MyFlag, unsigned int Limit> myFunction() {
myFunctionImpl<MyFlag, Limit, 0>();
}
Now it becomes easier to document: myFunction() (and all it's arguments) are part of the interface, which does not include the iteration counter. myFunctionImpl() is the implementation of that interface and does not need to be documented at all (or only minimally with a comment stating that it is an implementation detail and user code should not depend on it or use it directly). If you want, you can enclose the implementation in an #ifdef block so that the doxygen preprocessor removes it and it does not appear in the generated documentation.
A: One option to convey that a parameter should not be specified would be to hide it in the documentation. For example you could conditionally compile out the internal parameters:
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
template<bool MyFlag, unsigned int Limit
#if !defined(DOXYGEN)
, unsigned int Current = 0
#endif
> myFunction();
This would prevent them from appearing in the documentation, but they would still be available to the implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12434100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to remove black canvas from image in TensorFlow I'm currenly trying working with tensorflow dataset 'tf_flowers', and noticed that a lot of images consist mostly of black canvas, like this:
flower1
flower2
Is there any easy way to remove/or filter it out? Preferably it should work on batches, and compile into a graph with @tf.function, as I plan to use it also for bigger datasets with dataset.map(...)
A: The black pixels are just because of padding. This is a simple operation that allows you to have network inputs having the same size (i.e. you have batches containing images with the of size: 223x221 because smaller images are padded with black pixels).
An alternative to padding that removes the need of adding black pixels to the image, is that of preprocessing the images by:
*
*removing padding via cropping operation
*resizing the cropped images to the same size (e.g. 223x221)
You can do all of these operations in simple python, thanks to tensorflow map function. First, define your python function
def py_preprocess_image(numpy_image):
input_size = numpy_image.shape # this is (223, 221)
image_proc = crop_by_removing_padding(numpy_image)
image_proc = resize(image_proc, size=input_size)
return image_proc
Then, given your tensorflow dataset train_data, map the above python function on each input:
# train_data is your tensorflow dataset
train_data = train_data.map(
lambda x: tf.py_func(preprocess_image,
inp = [x], Tout=[tf.float32]),
num_parallel_calls=num_threads
)
Now, you only need to define crop_by_removing_padding and resize, which operate on ordinary numpy arrays and can thus be written in pure python code. For example:
def crop_by_removing_padding(img):
xmax, ymax = np.max(np.argwhere(img), axis=0)
img_crop = img[:xmax + 1, :ymax + 1]
return img_crop
def resize(img, new_size):
img_rs = cv2.resize(img, (new_size[1], new_size[0]), interpolation=cv2.INTER_CUBIC)
return img_rs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70646092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hazelcast file persistence (MapStore implementation) I am using Hazelcast for clustered data distribution. I read in the documentation about data persistence, using the interfaces MapStore and MapLoader. I need to implement these interfaces and write the class name in the hazelcast.xml file.
Is there any example of implementation of these interfaces for file persistence with hazelcast? Does anyone know about any source code or jar file that I can download and work with?
Thanks
A: You can implement your own just using ObjectOutputStream and ObjectInputStream.
You can create a directory with map's name.
store(key, value) operation creates a file with name key.dat, with content of serialized value.
load(key) method reads "key.dat" file into an object and returns.
Here usage examples of ObjectOutputStream and ObjectInputStream
http://www.mkyong.com/java/how-to-write-an-object-to-file-in-java/
http://www.mkyong.com/java/how-to-read-an-object-from-file-in-java/
Then you should add this implementation class to your class path and set it in your hazelcast.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10453559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: navLinkDayClick of FullCalendar Did anyone use navLinkDayClick of FullCalendar and call a custom event (by fetching data from database) based on the date selection?
I am using eventClick to populate the calendar data however I am unable to do so for individual dates after setting the navLinks to true.
Everything above navLinkDayClick works fine.
function FetchEventAndRenderCalendar() {method contains to fetch all event from database}
function FetchTotalAmount() { method calls a SP to get the total amount for that day of the calendar}. This also contains the method to generate the calendar which is given below.
function GenerateCalender(events) - events are the ones that are fetched in the first method.
function GenerateCalender(events) {
..................
..................
events: events,
eventClick: function (calEvent) {
var selectedCalendarEvent = calEvent;
$('#calendarModal #eventTitle').text(calEvent.title);
..................
..................
navLinks: true,
navLinkDayClick: function() {
how to use this to show the total amount for that day of the calendar when the date is selected?
}
A: navLinkDayClick in FullCalendar v3.8 -
navLinks: true,
navLinkDayClick: function (date) {
selectedDate = date.format("DD-MMM-YYYY");
selectedAmountEvent = amounts.find(item => item.paymentDate.format("DD-MMM-YYYY") === selectedDate);
var $AmountData = $('<div/>');
$AmountData.append($('<p/>').html('<b>Payment Date: </b>' + selectedAmountEvent.paymentDate.format("DD-MMM-YYYY")));
if (selectedAmountEvent.totalAmount < 0) {
$AmountData.append($('<p/>').html('<b style="color:red;">Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + '</b >'));
}
else {
$AmountData.append($('<p/>').html('<b style="color:green;">Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + '</b >'));
}
$('#eventModal #AmountDetails').empty().html($AmountData);
$('#eventModal').modal();
}
amounts is an array holding the data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74872591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits