text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Can I detect the integrity of the picture in the PDF file use Itextsharp There are some pdf files.And there are pictures in PDF that are incomplete.Can i Check if PDF has incomplete pictures use ITextsharp?
The Sample Pdf
The bad pdf looks like this
Thanks a lot!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47507432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How i can receive variable from another thread in Jmeter in the first thread, I received JSON (format - {"id":6054,"name":"Jmeter created chat","description":"jmeter created test"})
I want to use it in the second thread variable '6054'
I use BeanShell Assertion with code:
${__setProperty(("id":"(.+?)"), ${chat_id)};
but it, of course, doesn't work, please tell me the right way..
many thanks
A: *
*It won't work because your __setProperty() function call doesn't make sense at all and it's syntactically incorrect
*Since JMeter 3.1 you're supposed to use JSR223 Test Elements and Groovy language for scripting
So
*
*Remove your Beanshell Assertion
*Add JSR223 PostProcessor as a child of the request which returns the above response
*Put the following code into "Script" area:
props.put('chat_id', new groovy.json.JsonSlurper().parse(prev.getResponseData()).id as String)
*In 2nd Thread Group access the value using __P() function as:
${__P(chat_id,)}
Demo:
More information regarding what these prev and props guys mean can be found in the Top 8 JMeter Java Classes You Should Be Using with Groovy article
P.S. You may find Inter-Thread Communication Plugin easier to use
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66479591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change default value in counter-increment? I think the code is counting the "Rank" header as a row and assigning 1 to it. How can I change the first number of the counter-increment? I would like the table to start from 0 so that the "Rank" header is assigned 0 and the next row is 1, and so on and so forth.
http://oi59.tinypic.com/5bsabc.jpg
CSS File
tr.odd {background-color: #FFFFFF}
tr.even {background-color: #F2F2F2}
table {
counter-reset: rowNumber;
}
table tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
text-align: center;
}
JSP File
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="<c:url value='/css/egovframework/leaderboard.css'/>" />
<form id="listForm" name="listForm" method="post">
<input type="hidden" name="id"/>
</form>
<h1 style="text-align:center;font-size:56px; font-family: Mistral;margin-top:-45px;">Leaderboard</h1>
<body style="font-family:Arial;font-size:14px;text-align:center;color:#000000;">
<div id="table">
<table bordercolor="#FFFFFF" cellpadding="12px" cellspacing="2px" align="center" style="margin-top:-21px;">
<colgroup>
<col style="width:50px">
<col style="width:500px">
<col style="width:150px">
<col style="width:100px">
</colgroup>
<tr>
<th style="padding-top: 5px; padding-bottom: 5px; margin-bottom:-10px; width:50px; height:35px; text-align:left; font-family:Arial; font-size:14px; color:#000000; margin-top: 50px; color: #FFFFFF; border:0px; background-color: #32CD32;">Rank</th>
<th style="padding-top: 5px; padding-bottom: 5px; margin-bottom:-10px; width:100px; height:35px; text-align:left; font-family:Arial; font-size:14px; color:#000000; margin-top: 50px; color: #FFFFFF; border:0px; background-color: #32CD32;">Name</th>
<th style="padding-top: 5px; padding-bottom: 5px; margin-bottom:-10px; width:150px; height:35px; text-align:left; font-family:Arial; font-size:14px; color:#000000; margin-top: 50px; color: #FFFFFF; border:0px; background-color: #32CD32;">Points</th>
<th style="padding-top: 5px; padding-bottom: 5px; margin-bottom:-10px; width:100px; height:35px; text-align:left; font-family:Arial; font-size:14px; color:#000000; margin-top: 50px; color: #FFFFFF; border:0px; background-color: #32CD32;">Wins</th>
</tr>
<c:forEach var="item" items="${leaderboard}" varStatus="loopStatus">
<tr class="${loopStatus.index % 2 == 0 ? 'even' : 'odd'}">
<td align="center" class="listtd" style="font-size:14px; border:2px; bordercolor:#000000;">
</td>
<td align="left" class="listtd" style="font-size:14px; border:2px; bordercolor:#000000; cursor:pointer;" onclick="javascript:selectPlayer('${item.id}');">
<c:out value="${item.playersLastName}"/>, <c:out value="${item.playersFirstName}"/>
</td>
<td align="center" class="listtd" style="font-size:14px; border:2px; bordercolor:#000000;">
<c:out value="${item.playersPoints}"/>
</td>
<td align="center" class="listtd" style="font-size:14px; border:2px; bordercolor:#000000;">
<c:out value="${item.playersWins}"/>
</td>
</tr>
</c:forEach>
</table>
<br/>
<br/>
<br/>
</div>
</body>
</html>
A: CSS counter's default value is always 0 and that's not the problem in your case. The problem is that you are incrementing the value to 1 when the first tr is encountered itself.
There are multiple ways in which you can solve this:
*
*Assign the initial value of the counter as -1 during counter-reset property. This means that when the first tr is encountered the counter value increments from -1 to 0 and so it looks as though the header row is not numbered.
tr.odd {
background-color: #FFFFFF
}
tr.even {
background-color: #F2F2F2
}
table {
counter-reset: rowNumber -1;
}
table tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
text-align: center;
}
<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
<th>Wins</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
*Increment counter value only from the second tr that is encountered. This can be done using the + (adjacent sibling selector) or ~ (general sibling selector) or nth-child(n+2). Using one of these would mean the selector would be matched only by the second and subsequent tr within the table.
tr.odd {
background-color: #FFFFFF
}
tr.even {
background-color: #F2F2F2
}
table {
counter-reset: rowNumber;
}
table tr + tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
text-align: center;
}
<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
<th>Wins</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
*Best and recommended solution: Wrap the headers inside a thead, the contents inside tbody and modify the selector within which the counter is incremented. This is recommended because it gives a proper structure to the table and doesn't look hackish.
tr.odd {
background-color: #FFFFFF
}
tr.even {
background-color: #F2F2F2
}
table {
counter-reset: rowNumber;
}
table tbody tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
text-align: center;
}
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
<th>Wins</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31835217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I have to create a CI CD pipeline to integrate repos in azure to linux server My azure repos contains all the folders , and changes will be made by the users in the azure repos.
I want to create CI CD pipeline in azure repos to integrate azure repos and the linux server. Whenever some changes done in the azure repos should reflect in the linux server.
I want to know, how to implement the above scenerio.
A: According to your description, you can try to install a new self-hosted agent in your Linux server.
And then in your CI pipeline, you can use the git clone command to clone the repo in your Linux server.
You can also use the copy files task to copy the folder of the repo the to the UNC path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74872051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: snowpack: reference files outside of project folder Our team develops a bunch of JavaScript browser apps. These apps share functionality (core) and Web Components (shared). The folder structure is:
/apps
/app-1
/app-2
...
/core
/shared
Each folder contains a src folder.
Considering using snowpack in the folder app-1 I want to reference js files in /core/src or /shared/src both for development (using snowpack dev) and packaging (using snowpack build)
*
*is this possible?
*are there best practices how to achieve this?
*are there examples for such a situation (or a similar one)
What I tried:
Step 1: I used paths like this: ../../core/src/router.js. This didn't work, maybe because the resources were outside of the webroot of the test server (snowpack dev).
Step 2: I created two symlinks:
apps/app-1/src/@core -> ../../../core/src
apps/app-1/src/@shared -> ../../../shared/src
Now the local server found all the resources. The build process however found only those files, that were direct children of core/src or shared/src, but not any file within a subfolder as e.g. shared/src/component/filter.js.
Any ideas or thoughts?
Appendix
The snowpack.config.json of app-1:
{
"devOptions": {
"port": 8082,
"open": "none"
},
"mount": {
"public": "/",
"src": "/_dist_"
},
"plugins": [
"@snowpack/plugin-babel",
"@snowpack/plugin-dotenv",
"@snowpack/plugin-sass"
]
}
Example for import in app-1/src/handler:
import { loadRoute } from '../@core/router' // works fine
import '../@shared/component/filter' // does not work
// or:
import { loadRoute } from '../@core/router.js' // works fine, too
import '../@shared/component/filter.js' // does not work neither
A: You can solve your problem just adding:
workspaceRoot: '..',
to your snowpack.config.js file.
Basically it tells snowpack to process everything from the parent folder (..) through it's pipeline. It will pick up dependencies and process everything.
In your case, you could import files from shared in app-1 by using relative paths, and without creating any symlinks:
import something from '../shared/something';
You can find more about workspaceRoot property in snowpack's documentation.
A: You should be able to specify a relative path to the folder in your mount object as another key:
{
"mount": {
"../../shared": "/_dist_"
}
}
this should serve your files from the shared directory from the /_dist_ folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65005200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: parse method in xml throws IllegalArgumentException in Clojure I'm following this article for parsing XML in clojure. In the REPL, I enter the following things:
(require '[clojure.java.io :as io])
(require '[clojure.xml :as xml])
(require '[clojure.zip :as zip])
(-> "example.nzb" io/resource io/file xml/parse zip/xml-zip)
I get a IllegalArgumentException InputStream cannot be null javax.xml.parsers.SAXParser.parse (SAXParser.java) on executing that. I figured out that the exception was being caused by xml/parse method:
(xml/parse (io/file (io/resource "example.nzb")))
A: The expression mentioned in the question works. Just make sure that you have included the "example.nzb" file within your project and also make sure that you restart the REPL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17547146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Handshake problem on websocket connection when using Laravel Echo Server as Pusher replacement I want to use Laravel Echo Server as Pusher replacement
I am seeking the Laracast tutorial series for Laravel broadcasting: https://laracasts.com/series/get-real-with-laravel-echo.
I have succesfully created a testing javascript client that listens to the events for channel orders. This is the client code:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});
window.Echo.channel('orders')
.listen('OrderStatusUpdate', e => {
console.log("Status has been updated behind the scenes.")
console.log(e);
});
But the company where I work requires to have their own websocket resource, so we cannot depends upon Pusher.
Then, we are working on Laravel Echo Server: https://github.com/tlaverdure/Laravel-Echo-Server. Almost everything is working. We have changed the config/broadcasting.php options to fit to Laravel Echo Server. And successfully we can see the events being emitted inside laravel echo log, just changing some configuratons parameters in config/broadcasting.php:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => false,
'host' => '192.168.15.36',
'port' => 6001,
'scheme' => 'http'
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
The address 192.168.15.36 is the local ip address.
Also changed the client code to deal with the changes:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
forceTLS: false,
wsHost: '192.168.15.36',
wsPort: 6001,
encrypted: false,
enabledTransports: ['ws']
});
window.Echo.channel('orders')
.listen('OrderStatusUpdate', e => {
console.log("Status has been updated behind the scenes.")
console.log(e);
});
And the .env is:
PUSHER_APP_ID=5073cdd7d79e501f
PUSHER_APP_KEY=3ad3a4d1eb46d4d4794533414dce747a
PUSHER_APP_SECRET=
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
But in the client javascript (using Chrome) I see an error message in the browser console: WebSocket connection to 'ws://192.168.15.36:6001/app/3ad3a4d1eb46d4d4794533414dce747a?protocol=7&client=js&version=7.0.6&flash=false' failed: Connection closed before receiving a handshake response.
How to solve this problem? Is there something that is needed furthermore to make Laravel Echo Server works as a Pusher replacement?
May worth show here the laravel echo server settings as well:
{
"authHost": "http://192.168.15.36",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "5073cdd7d79e501f",
"key": "3ad3a4d1eb46d4d4794533414dce747a"
}
],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "http://192.168.15.36:80",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71776668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using AsyncTask in ListView adapter (Android Studio) I am developing an app where I am using List View adapter to inflate my list view items. What I observed is that my GUI is not that responsive because I am inflating image view along with text view in each of my list items. And the number of items depend on the number of images in the users device. So it is doing a lot of work and I am also getting message saying "Skipped ~63 frames..." like that.
Below is my complete code of the List View adapter class file named Adapter_PhotosFolder.java:
public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) {
super(context, R.layout.adapter_photosfolder, al_menu);
this.al_menu = al_menu;
this.context = context;
}
@Override
public int getCount() {
//Log.e("ADAPTER LIST SIZE", al_menu.size() + "");
return al_menu.size();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getViewTypeCount() {
if (al_menu.size() > 0) {
return al_menu.size();
} else {
return 1;
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.apftv1);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.apftv2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.apfiv);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder());
viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+"");
Glide.with(context).load(al_menu.get(position).getAl_imagepath().get(0))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
If I am not wrong we can use thread or preferably an AsyncTask to avoid GUI freezing. I could not figure out how to implement that in my case.
My Question : Can you tell me how can I use an AsynTask in my case to make it smooth.
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62653426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Random to Multi-List Number from One List I have an array:
int arr[] = {1, 2, 3, 4}
How can I randomize arr[] to multi-list with No Duplicates?
FROM
arr[] = { 1, 2, 3, 4 }
TO
arr1[] = {1, 2, 3, 4}
arr2[] = {2, 1, 4, 3}
arr3[] = {3, 4, 1, 2}
arr4[] = {4, 3, 2, 1}
A: In this case, it is preferable to use a List<Integer> instead of int[]
List<Integer> arr = new ArrayList<Integer>();
Random random = new Random();
int randonint = arr.remove(random.nextint(arr.getSize()));
Every time this code is runned, it will grab a random int from the list arr, then you can add it to a different List/Array
So, if you want to take all values from one list, and randomly place them to 3 other lists, use the following code:
List<Integer> arr1 = new ArrayList<Integer>();
List<Integer> to1 = new ArrayList<Integer>();
List<Integer> to2 = new ArrayList<Integer>();
List<Integer> to3 = new ArrayList<Integer>();
Random random = new Random();
for (int i = 1 ; i <= 10 ; i++) {
arr1.add(i);
}
for (int count = 0 ; count < arr1.size() ; count++) {
List<Integer> arr = new ArrayList<Integer>();
int randomvalue = arr.remove(random.nextint(arr.getSize()));
switch (random.nextInt(3)) {
case 0:
to1.add(randomvalue);
case 1:
to2.add(randomvalue);
case 2:
to2.add(randomvalue);
}
}
A: public static void GenerateRandomArray()
{
var inputArray = new[] {1, 2, 3, 4};
var outputArray = GetRandomArray(inputArray);
PrintArray(outputArray);
}
private static void PrintArray(int[,] outputArray)
{
for (var i = 0; i < outputArray.GetLength(0); i += 1)
{
for (var j = 0; j < outputArray.GetLength(1); j += 1)
{
Console.Write(outputArray[i, j]);
}
Console.WriteLine();
}
}
private static int[,] GetRandomArray(int[] inputArray)
{
var lengthOfArray = inputArray.Length;
var outputArray = new int[lengthOfArray,lengthOfArray];
for (var i = 0; i < lengthOfArray; i++)
{
var counterShifter = i;
for (var j = 0; j < lengthOfArray;j++)
{
outputArray[i, j] = inputArray[counterShifter];
counterShifter = counterShifter + 1 < lengthOfArray
? counterShifter + 1 :
0;
}
}
return outputArray;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27455632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hash Checking in setup.py install requires According to pip documentation, it is possible to specify the hash of a requirement in the requirements.txt file.
Is it possible to get the same by specifying the hash in the setup.py so that the hash is checked when someone simply does pip install <package>?.
I'm specifying the requirements in the setup.py by passing the install_requires keyword argument to the setup function in the distutils package.
from distutils.core import setup
from setuptools import find_packages
setup(name='<package-name>',
...
...
install_requires=['ecdsa==0.13', 'base58==0.2.5']
Maybe there is another way to achieve the same but i couldn't find any documentation.
A: Currently, I don't believe there is a simple way to specify a hash check within setup.py. My solution around it is to simply use virtualenv with hashed dependencies in requirements.txt. Once installed in the virtual environment you can run pip setup.py install and it will check the local environment (which is your virtual environment) and the packages installed is hashed.
Inside requirements.txt your hashed packages will look something like this:
requests==2.19.1 \
--hash=sha256:63b52e3c866428a224f97cab011de738c36aec0185aa91cfacd418b5d58911d1 \
--hash=sha256:ec22d826a36ed72a7358ff3fe56cbd4ba69dd7a6718ffd450ff0e9df7a47ce6a
Activate your virtualenv and install requirements.txt file:
pip install -r requirements.txt --require-hashes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46835953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Is there a way to output the contents of the queue after removing an item? I'm just working on writing code for queues (specifically linear ones) and I'm trying to remove an item from my queue. When outputting the queue after removing an item, the contents in the queue have not changed and all the items are still there. Is there any way to get around this?
I've tried printing out the queue after each item has been removed and still, the output does not change.
import sys
class Queue:
def __init__(self):
self.head = 0
self.tail = 0
self.MaxSize = 4
self.queue = []
def size(self):
return self.tail - self.head
def enqueue(self,data):
if self.size() > self.MaxSize:
return("Queue Full")
else:
self.queue.append(data)
self.tail += 1
return True
def dequeue(self):
if self.size() <= 0:
self.reset()
return("Queue Empty")
data = self.queue[self.head]
self.head += 1
return data
def reset(self):
self.head = 0
self.tail = 0
self.queue = []
q = Queue()
def addOrRemove():
print("Current Queue Size - ", q.size())
print()
addRemove = input("Add(A), Remove(R), End(E), View(V) ")
addRemove = addRemove.upper()
while True:
if addRemove == 'A':
add = input("Enter input - ")
q.enqueue(add)
if q.size() > q.MaxSize:
print("Queue Full")
addOrRemove()
elif addRemove == 'R':
q.dequeue()
print(q.queue)
if q.size() <= 0:
print("Queue Empty")
q.reset()
addOrRemove()
elif addRemove == 'E':
sys.exit()
elif addRemove == 'V':
print(" ".join(q.queue))
addOrRemove()
else:
print("Invalid input")
addOrRemove()
return False
addOrRemove()
Add 'milk', 'sugar' and 'eggs' to the queue. Removing an item should remove 'milk' and printing the queue should output 'sugar' and 'eggs', but the actual output is still 'milk', 'sugar' and 'eggs'.
A: The issue here isn't your printing, it's your queue. Look at your dequeue() method:
def dequeue(self):
if self.size() <= 0:
self.reset()
return("Queue Empty")
data = self.queue[self.head]
self.head += 1
return data
At no point are you removing anything from self.queue, so naturally when you try to print it it'll not have changed.
The solution here, is instead of
data = self.queue[self.head]
which is itself a logic error (what if there are only 3 elements in self.queue and self.head == 5? You'd get an error), do
data = self.queue.pop(0)
which removes the first element from self.queue and returns it. Since in enqueue() you're adding to the end of the list and in dequeue() you'll be removing from the beginning of the list, it's a valid queue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56461488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use join on a result of another join with a new field i have 2 tables vehicle1 which contains details of different types of vehicle and have a unique lot_ and another table wishlist which have two fields lot# and a userid
what im trying to do is return a vehicle1 table with an extra field say flag added to it with values either 1 or 0 corresponding to if the userid has added that vehicle into wishlist or not
i've used this
ALTER PROCEDURE [dbo].[get_AllVehicleModified]
@user varchar(50),
@limit varchar(30)
AS
BEGIN
SELECT ad.*
FROM (
SELECT *,CASE WHEN t1.lot# IN (t2.lot_) THEN 1 ELSE 0 END Flag
FROM vehicle1 t1
FULL OUTER JOIN wishlist t2 ON t1.lot#=t2.lot_ WHERE t2.userid=@user ) ad
ORDER BY lot#
OFFSET (@limit - 1)*10 ROWS
FETCH NEXT 10 ROWS ONLY;
END
this query contains a result with a new field flag containing 1 and only those vehicles which were in wishlist
however i want the whole vehicle1 table which contains 0 in the remaining
how can i achieve this?
A: I think that you want a left join and conditional logic:
select v.*, case when w.lot# is null then 0 else 1 end flag
from vehicle v
left join whishlist w on w.userid = @user and w.lot# = v.lot_
You can easily integrate this query in your stored procedure and add the row-limiting clause.
A: I recommend using EXISTS:
SELECT v.*,
(CASE WHEN EXISTS (SELECT 1
FROM wishlist wl
WHERE v.lot# = wl.lot_ AND
wl.userid = @user
)
THEN 1 ELSE 0
END) as Flag
FROM vehicle1 v
ORDER BY v.lot#
OFFSET (@limit - 1)*10 ROWS
FETCH NEXT 10 ROWS ONLY;
I think it better captures the logic that you want. I also suspect that it might work better with ORDER BY and FETCH.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61254517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generate different fields depends on DOM elements in angularjs So i have an application that should take the html of one page which contains different custom directives.
and there is another page which will load the html of the first page and generate input fields according to the number of the custom directive (cms-input) existing in the first page and to the type specified.
so for example here is the first html page
<cms-input type='text' size='14' default='header' label='Header' ></cms:input>
<cms-input type='textfield' size='50' default='paragraph' label='Paragraph'> </cms:input>
the second page should load the first page and generate the fields :
<label>Header</label>
<input type='text' value='header'>
<label>Paragraph</label>
<textarea>paragraph</textarea>
A: Thats what directives are designed for, point is to figure out best way to pass and evaluate those attributes of fields, in plnkr i made a possible solution.
Here you have a starting point:
PLNKR
app.directive('cmsInput', function() {
return {
restrict: 'E',
template: '<label ng-if=(exists(label))>{{label}}</label>',
controller: function($scope) {
$scope.exists = function(a) {
if(a && a.length>0) {
return true;
}
return false;
}
},
link: function(scope, elem, attr) {
scope.label = attr.label;
}
}
})
It requires work, but you'll get the point.
EDIT:
You could use 'scope' field of directives to bind values, but for purpose of finding solution I wanted to make it as clear as possible.
EDIT2:
Angular directive is being define with a rule "camelCase" in javascript(directive name) is eaxctly "camel-case" in html, as a directive call.
Angular matches correct js code to called directive and puts exactly in that place in DOM your template. One of the parameters of link method are attributes, those are the same values that you have in html, so under:
'attr.label' you get value of 'label' in html, in this case string "header".
The template attribute of directive is a string with bindigs to variables that were set in scope and and when we combine it all together we get:
*
*Angular "finds" a directive
*Directive code is being fired
*Link function is being called - inside which we set to field named "label" value of attribute named "label"
*Template compiles - under {{ }} markers correct variables are being set.
*vio'la - in place of this cms-input element you get normal html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28026703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Get number of times an object is referenced in a ManyToManyField I have some models that look like this:
class UserProfile(models.Model):
user = models.OneToOneField(User)
favorite_books = models.ManyToManyField(Book)
# ...
class Book(models.Model):
title = models.CharField(max_length=255)
How can I tell how many times a Book has been favorited?
A: You can query the "through" table directly with the ORM:
UserProfile.favorite_books.through.objects.filter(book_id=book.id).count()
A: You'll need to replace appname_* with the name of the M2M table in your DB, but you can do something like this:
from django.db import connections
cursor = connections['default'].cursor()
cursor.execute("""
SELECT count(*) FROM appname_userprofile_books
WHERE book_id = {book_id};
""".format(book_id=book_id))
favorited_count_list = cursor.fetchall()
You can then pull the number from favorited_count_list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11979015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is ScreenManager compatible with DropDown in Kivy? I want to generate a dropdown-list in my second screen managed by Kivys ScreenManager. If I do so, I get this traceback:
...
File "C:/Users/ORANG/PycharmProjects/waldi/playground/cw.py", line 76, in on_text
instance.drop_down.open(instance)
File "C:\Kivy-1.9.0-py2.7-win32-x64\kivy27\kivy\uix\dropdown.py", line 215, in open
'Cannot open a dropdown list on a hidden widget')
kivy.uix.dropdown.DropDownException: Cannot open a dropdown list on a hidden widget
This is the code, which is basically the same as in this
example, just embedded in a screenmanager scenario simple as can be:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput
from kivy.properties import ListProperty, StringProperty
import re
from kivy.lang import Builder
Builder.load_string('''
<Lieferant>:
ComboLayout:
Label:
text: 'Label'
ComboEdit:
size_hint: .5, .3
pos_hint: {'center':(.5, .5)}
# `args` is the keyword for arguments passed to `on_text` in kv language
on_text: self.parent.on_text(self, args[1])
''')
class ComboEdit(TextInput):
"""
This class defines a Editable Combo-Box in the traditional sense
that shows it's options
"""
options = ListProperty(('',))
'''
:data:`options` defines the list of options that will be displayed when
touch is released from this widget.
'''
def __init__(self, **kw):
ddn = self.drop_down = DropDown()
ddn.bind(on_select=self.on_select)
super(ComboEdit, self).__init__(**kw)
def on_options(self, instance, value):
ddn = self.drop_down
# clear old options
ddn.clear_widgets()
for option in value:
# create a button for each option
but = Button(text=option,
size_hint_y=None,
height='36sp',
# and make sure the press of the button calls select
# will results in calling `self.on_select`
on_release=lambda btn: ddn.select(btn.text))
ddn.add_widget(but)
def on_select(self, instance, value):
# on selection of Drop down Item... do what you want here
# update text of selection to the edit box
self.text = value
class ComboLayout(BoxLayout):
rtsstr = StringProperty("".join(("Substrate1,,,Substrate1,,,Substrate1,,,",
"Substrate1,,,Substrate1,,,Substrate_coating",
",,,silicon,,,silicon_Substrate,,,substrate_",
"silicon,,,")))
def on_text(self, instance, value):
if value == '':
instance.options = []
else:
match = re.findall("(?<=,{3})(?:(?!,{3}).)*?%s.*?(?=,{3})" % value, \
self.rtsstr, re.IGNORECASE)
# using a set to remove duplicates, if any.
instance.options = list(set(match))
instance.drop_down.open(instance)
class Intro(Screen):
pass
class Lieferant(Screen):
pass
class CWApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(Intro(name='Intro'))
sm.add_widget(Lieferant(name='Lieferant'))
return sm
if __name__ == '__main__':
CWApp().run()
Is it possible to combine them? How would you do this?
This code is running if I just comment this line out, which adds a screen before the screen with the dropdown:
sm.add_widget(Intro(name='Intro'))
A: Ok - for this question I got the "Tumbleweed Badget" - LOL
I admit it's a very special one and makes obvious, how much I am a beginner here. So I asked another question based on the same problem and spend some effort to make it easier to understand the code and to reproduce it. This paid off! Look here for the solution if you tumble once into that kind of problem: Is it a bug in Kivy? DropDown + ScreenManager not working as expected
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33930379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check if a water body is near a given coordinate. (very often) I'm doing a project where I want to identify water bodies on satellite images via machine learning.
I'm still figuring out how to generate my dataset of a satellite image + a water mask of the same area.
The procedure I thought of is:
*
*Draw a random coordinate (longitude,latitude) inside of european land using the country borders of Natural Earth (with Numpy and Geopandas)
*Check if there is some water body in a specified range around this coordinate using OpenStreetMap or Mapbox Vector Tiles API. If not return to 1.
*Generate a satellite image of this location using the Mapbox Raster Tiles API
*Generate a mask of waterbodies of this location using the Mapbox Static Tiles API and a custom made Mapbox Style where only water is shown.
At the moment I am most concerned about step 2. because I don't know where I can easily get the information and don't have problems with a request limit.
I want to make a dataset of around 100000 image pairs and because of the low water to land ratio I expect many more requests for the 2. step.
The Mapbox Vector Tiles API has a limit of 200000 requests per month.(see here)
And the Overpass API has a limit of around 10000 requests per day.
I found the OSM Water Layer but I have no idea how to use it and check if there is water in a given area.
Has anyone an idea how I could manage to do step 2.? I am using Python.
A: The most efficient way might be to import the OSM data of the specific area to a local postGIS database using Osm2pgsql or ImpOsm and do your analytics there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67916246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: expression must have integral type I get that compilation error because of this line which intended to increase the pointer by 0x200 (to point to the next segment)
Flash_ptr = Flash_ptr + (unsigned char *) 0x200;
I'v seen this but I didn't use any illegal symbol!
P.S. The initialization of the pointer:
unsigned char * Flash_ptr = (unsigned char *) 0x20000;
A: You can't add two pointers. You can add an integer to a pointer, and you can subtract two pointers to get an integer difference, but adding two pointers makes no sense. To solve your problem therefore you just need to remove the cast:
Flash_ptr = Flash_ptr + 0x200;
This increments Flash_ptr by 0x200 elements, but since Flash_ptr is of type unsigned char * then this just translates to an increment of 0x200 bytes.
In order to make this part of a loop and check for an upper bound you would do something like this:
while (Flash_ptr < (unsigned char *)0x50000) // loop until Flash_ptr >= 0x50000
{
// ... do something with Flash_ptr ...
Flash_ptr += 0x200;
}
A: You cannot add two pointers. What you can do is to increment the address held by the pointer. Remove the (unsigned char *)cast.
If you're interested, read more about pointer arithmatic here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25761789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: C++ column chart is reversed I'm stumped on why my columns are reversed. The actual column graph (asterisks only) needs to be flipped horizontally. (The population in 1900 is 2000 and the population in 2040 is 24000.)
Here is what it currently looks like:
Population column chart
24000 **
23000 **
22000 ** **
21000 ** **
20000 ** **
19000 ** **
18000 ** ** **
17000 ** ** **
16000 ** ** **
15000 ** ** **
14000 ** ** ** **
13000 ** ** ** **
12000 ** ** ** **
11000 ** ** ** **
10000 ** ** ** **
9000 ** ** ** ** **
8000 ** ** ** ** **
7000 ** ** ** ** **
6000 ** ** ** ** **
5000 ** ** ** ** ** **
4000 ** ** ** ** ** ** **
3000 ** ** ** ** ** ** **
2000 ** ** ** ** ** ** ** **
1000 ** ** ** ** ** ** ** **
1900 1920 1940 1960 1980 2000 2020 2040
And here's the code:
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int population_size = 8; //Available for changes.
int year = 1900;
int population[population_size];
bool haveFile = true;
const string inFileName = "people.txt";
ifstream inFile("people.txt"); //Defines input file and opens
cout << "Population column chart" << endl;
cout << endl;
if (inFile){
// cout << "Open of " << inFileName << " was successful.\n";
int count = 0;
while (!inFile.eof()) {
inFile >> population[count];
count++;
if (inFile.eof()) break;}
int min = 1000; //Define minimum y-axis amount
int max = 0; //Initialize max value to 0
for (int i=0; i<count; i++){ //Find the maximum population
if(population[i]> max);
max = population[i];
}
//This block creates the y-axis legend and rows of stars
for (int num = max; num >= min; num = num - 1000){
cout << setw(5) << num << " ";
for (int year_counter = 0; year_counter <= count-1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";
cout << endl;
}
//This block creates the x-axis legend
cout << " ";
for (int k = 1; k <= count; k++){
cout << setw(6) << year;
year += 20;
}
}
}
The problem is in this area of code:
for (int year_counter = 0; year_counter <= count-1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";
population[0] should be a value of 2000, but it is 24000. Is there a problem with my array being somehow reversed?
Thanks in advance
A: if(population[i]> max);
max = population[i];
should be
if(population[i]> max)
max = population[i];
Try that and see.
OK, I think I see what's up now. You are trying to print populations for the various years. Each column is essentially 6 characters wide ("\*\*" set in a setw(3), plus a " "). Trouble is, you only print that column if it's going to get the "**"; otherwise you print nothing. So all the columns with "\*\*" are jammed to the left.
Solution is to always print the column, for each row, whether it gets a "**" or not:
for (int year_counter = 0; year_counter <= count - 1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";
else //NEW
cout << setw(3) << " " << " "; //NEW
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37759344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS background repeat not working when called inside folder I have a folder called projects on my desktop and inside the folder I have a file called index.html and a folder called images containing all the images. When I try to call the background: url("images/shadow1.PNG") repeat-y; it doesnt seem to work for some reason, anyone have any ideas why ?
If I put the documents on my desktop the index and images folder and try running the background: url(shadow1.PNG) repeat-y; it works just fine.
Hope that made sense, any information and code examples on how to fix this would be great.
Thanks!
A: in css file change the background: url("images/shadow1.PNG") to background: url("../images/shadow1.PNG")
It has to return to the root folder (projects) using ../ and then enter the image folder to find the image.
A: Adding on Sotiris answer. The CSS 'locates' files starting from it's own location. This means you have to navigate to the image from the CSS' directory.
For example: your image reside in /trunk/images and the css in /files/css (I wouldn't suggest those folder names) you would have to go back 2 directories into the /trunk/images directory:
.something
{
background: url(../../trunk/images/image.png) 0 0 no-repeat;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4125370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any use for the determinant of a 4x4 matrix in computer graphics? In most graphics libraries I've seen, there's some function that returns the determinant from 3x3 and 4x4 matrices, but I have no idea when you'd actually need to use the determinant in 3D computer graphics.
What are some examples of using a determinant in 3D graphics programming?
A: Off the top of my head...
If the determinant is 0 then the matrix cannot be inverted, which can be useful to know.
If the determinant is negative, then objects transformed by the matrix will reversed as if in a mirror (left handedness becomes right handedness and vice-versa)
For 3x3 matrices, the volume of an object will be multiplied by the determinant when it is transformed by the matrix. Knowing this could be useful for determining, for example, the level of detail / number of polygons to use when rendering an object.
A: In 3D vector graphics
there are used 4x4 homogenuous transform matrices and we need booth direct and inverse matrices which can be computed by (sub)determinants. But for orthogonal matrices there are faster and more accurate methods like
*
*full pseudo inverse matrix.
Many intersection tests use determinants (or can be converted to use them) especially for quadratic equations (ellipsoids,...) for example:
*
*ray and ellipsoid intersection accuracy improvement
as Matt Timmermans suggested you can decide if your matrix is invertible or left/right handed which is useful to detect errors in matrices (accuracy degradation) or porting skeletons in between formats or engines etc.
And I am sure there area lot of other uses for it in vector math (IIRC IGES use them for rotational surfaces, cross product is determinant,...)
A: The incircle test is a key primitive for computing Voronoi diagrams and Delaunay triangulations. It is given by the sign of a 4x4 determinant.
(picture from https://www.cs.cmu.edu/~quake/robust.html)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51831683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mysql not working with python 3.6 and django 1.9 I am trying to connect mysql db with django 1.9 and python version is 3.6. With database connection string I am getting the below error. If I comment out the database connection string the site is loading fine. Can anybody tell what is wrong in this.
[Wed Apr 05 07:01:08.287609 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] mod_wsgi (pid=29791): Target WSGI script '/home/abhadran/test/mysite/mysite/wsgi.py' cannot be loaded as Python module.
[Wed Apr 05 07:01:08.287675 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] mod_wsgi (pid=29791): Exception occurred processing WSGI script '/home/abhadran/test/mysite/mysite/wsgi.py'.
[Wed Apr 05 07:01:08.287705 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] Traceback (most recent call last):
[Wed Apr 05 07:01:08.287740 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/test/mysite/mysite/wsgi.py", line 20, in <module>
[Wed Apr 05 07:01:08.287787 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] application = get_wsgi_application()
[Wed Apr 05 07:01:08.287798 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Wed Apr 05 07:01:08.290733 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] django.setup(set_prefix=False)
[Wed Apr 05 07:01:08.290756 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
[Wed Apr 05 07:01:08.290779 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] apps.populate(settings.INSTALLED_APPS)
[Wed Apr 05 07:01:08.290790 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/apps/registry.py", line 78, in populate
[Wed Apr 05 07:01:08.291738 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] raise RuntimeError("populate() isn't reentrant")
[Wed Apr 05 07:01:08.291768 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] RuntimeError: populate() isn't reentrant
My pip freeze
Django==1.9.12
django-tastypie==0.13.3
mod-wsgi==4.5.15
mysql-connector-python==2.0.4
mysqlclient==1.3.10
PyMySQL==0.6
python-dateutil==2.6.0
python-mimeparse==1.6.0
requests==2.13.0
six==1.10.0
DB Settings we are using to try to connect to the Mysql
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'AAAAAAAAAAAAAAAAA',
'NAME': 'ZZZZZZZZZZZZZZZZ',
'USER': 'YYYYYYYYYYYYYYYY',
'PASSWORD': 'XXXXXXXXXXXX',
'PORT': '3306',
'OPTIONS': {
'init_command': 'SET storage_engine=INNODB',
},
}
}
A: Usually, this error means there is an error in the Django project somewhere. It could be hard to locate.
You can try multiple solutions like:
1. Restart Apache
2. Execute makemigrations and migrate Django commands
3. Modify your wsgi.py file so you can manage the exception
A little note, in the line File "/home/abhadran/myenv/lib/python3.6/site-packages/django/apps/registry.py" indicate that you're using Python 3.6 and not Python 3.5 as you mentioned in your description.
Python 3.6 is officially supported until Django 1.11, so you maybe must upgrade your Django version or downgrade your Python in your venv.
Related posts:
- Post 1
- Post 2
- Post 3
- Post 4
- Post 5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43224200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Execute python scripts from bash file via crontab Set-up
I have 2 simple python 3.x files on my desktop:
1) cronjob_test.py
#!Applications/anaconda/bin/python
# -*- coding: utf-8 -*-
import os
os.makedirs('/Users/myself/Desktop/TESTFOLDER')
2) cronjob_test_copy.py
#!Applications/anaconda/bin/python
# -*- coding: utf-8 -*-
import os
os.makedirs('/Users/myself/Desktop/TESTFOLDER2')
Both .py are executed via bashfile A,
#!/bin/bash
cd /Users/myself/Desktop
PATH=$PATH:/usr/local/bin
export PATH
/Applications/anaconda/bin/python cronjob_test.py
/Applications/anaconda/bin/python cronjob_test_copy.py
Problem
When I execute bash file A from the MacOSX Terminal, everything works fine: I end up with the 2 folders on my desktop.
However, when I try to execute A from crontab, nothing happens.
My crontab command is,
25 15 * * * cd /Users/myself/Desktop ** bash A
What am I doing wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49858760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Take screenshot of specific part of screen I'm trying to take a screenshot of a specific part of the screen. Here is the coordinates of the part of the screen i want to 'cut' :
Left : 442
Top : 440
Right : 792
Bottom : 520
That is, a rectangle of width 350px and height of 80px. But i don't know how to use CopyRect to achieve this task, instead i'm getting a blank image. Here is my code :
function screenshot: boolean;
var
Bild : TBitmap;
c: TCanvas;
rect_source, rect_destination : TRect;
begin
c := TCanvas.Create;
bild := tbitmap.Create;
c.Handle := GetWindowDC(GetDesktopWindow);
try
rect_source := Rect(0, 0, Screen.Width, Screen.Height);
rect_destination := Rect(442,440,792,520);
Bild.Width := 350;
Bild.Height := 80;
Bild.Canvas.CopyRect(rect_destination, c, rect_source);
Bild.savetofile('c:\users\admin\desktop\screen.bmp');
finally
ReleaseDC(0, c.Handle);
Bild.free;
c.Free;
end;
end;
A: What you are doing here is copying the whole screen and draw it at coordinate Rect(442,440,792,520); in your new bitmap... Which is off its canvas.
The coordinate Rect(442,440,792,520) correspond to the part you want to get from the source bitmap. You want to copy it "inside" your new bitmap, so within the rect Rect(0,0,350,80)
You can simply adjust your rect like this :
rect_source := Rect(442,440,792,520);
rect_destination := Rect(0,0,350,80);
The rest of your code seems correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38700163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: NSView - Drawing 2-Color Checkers I have a subclass of NSView where I need to draw two-color checkers (squares of alternating colors). The following is what I have.
- (void)drawRect:(NSRect)rect {
NSInteger k = 1;
for (int j = 0; j < self.frame.size.width; j += 20) {
for (int i = 0; i < self.frame.size.height; i +=20) {
if (k%2 == 0) {
[[NSColor whiteColor] set];
}
else {
[[NSColor lightGrayColor] set];
}
[NSBezierPath fillRect:NSMakeRect(j,i,20,20)];
k++;
}
}
}
If I run it, I get squares of alternating colors. If I change the frame height, I sometimes get stripes of alternating colors. How can I improve the code above?
Thanks.
A: A different way to draw a checkerboard pattern is to make a 2x2 checkerboard in a drawing program, add that to your project as a resource, pass that image to +[NSColor colorWithPatternImage:], and then you can just fill an area with that color.
A: OK, so the problem is that a row might have an odd number of squares in it, in which case the next row shows the same pattern again. Here's how I would fix it; I also changed your use of NSBezierPath to NSRectFill() since the latter is both conceptually simpler and likely to be faster.
- (void)drawRect:(NSRect)rect {
for (int j = 0; j * 20 < self.frame.size.width; j++) {
for (int i = 0; i * 20 < self.frame.size.height; i++) {
if (((i^j) & 1) == 0)
[[NSColor whiteColor] set];
else
[[NSColor lightGrayColor] set];
NSRectFill(NSMakeRect(j*20,i*20,20,20));
}
}
}
The (i^j) & 1 uses bitwise exclusive-or (the ^ operator) and then bitwise and (the & operator) to combine the odd-even state of both the row and column indices. There would be various ways to optimize away the multiplies, but this code seems like the clearest way to do it.
A somewhat cleaner version that would run faster and would perhaps avoid some drawing artifacts would involve clearing to one color first and then drawing only squares of the opposite color:
- (void)drawRect:(NSRect)rect {
[[NSColor whiteColor] set];
NSRectFill(rect);
[[NSColor lightGrayColor] set];
for (int j = 0; j * 20 < self.frame.size.width; j++)
for (int i = 0; i * 20 < self.frame.size.height; i++)
if ((i^j) & 1)
NSRectFill(NSMakeRect(j*20,i*20,20,20));
}
A: Keep in mind that your view is not redrawn just because it is resized! So your checkerboard gets squeezed or stretched together with the view. It is up to you to call setNeedsDisplay.
A: Your method of determining square color alternates the color down a column and then continues with the next column. If you have an even number of rows each row will start with the same color, giving you stripes.
Think simple, you only need two states - black or white - so instead of integers, addition, and odd/even tests to reduce an integer to one of two values just start with a type with only two values, that is Boolean.
To deal with the issue of an odd or even number of rows use two variables, one to track the color of the first square in the column - this will flip each iteration of your outer loop, and one to track the color of the current square - for each column this starts with the value of the first variable and flips each iteration of the inner loop.
In code outline, before the outer loop:
BOOL colStartsWhite = YES; // or NO, you decide - this is the corner color
Inside the outer loop:
BOOL squareIsWhite = colStartsWhite; // inner tracker
colStartsWhite = !colStartsWhite; // flip ready for next column
Inside the inner loop:
if (squareIsWhite) ... else ... // fill the square
squareIsWhite = !squareIsWhite; // flip for next square
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32539299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PDO based query with space in criteria string not working in PHP My code looks like this
$eventname = "music festival 5";
$stmt = $pdo->prepare('SELECT * FROM events WHERE eventname=?');
$stmt->execute([$eventname]);
$row = $stmt->fetchAll();
The above gives no result. When I change the following line, it works:-
$stmt = $pdo->prepare('SELECT * FROM events WHERE eventname="music festival 5"');
What could be the issue? Please suggest.
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60263301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you append to the end of a gzipped file in Java? Here is what I've tried
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression {
public static void main(String[] args) throws IOException {
File file = new File("gziptest.zip");
try ( OutputStream os = new GZIPOutputStream(new FileOutputStream(file, true))) {
os.write("test".getBytes());
}
try ( GZIPInputStream inStream = new GZIPInputStream(new FileInputStream(file))) {
while (inStream.available() > 0) {
System.out.print((char) inStream.read());
}
}
}
}
Based on what I've read, this should append "test" to the end of gziptest.zip, but when I run the code, the file doesn't get modified at all. The strange thing is that if I change FileOutputStream(file, true) to FileOutputStream(file, false), the file does get modified, but its original contents are overriden which is of course not what I want.
I am using JDK 14.0.1.
A: A couple of things here.
*
*Zip and GZip are different.. If you are doing a gzip test, your file should have the extension .gz, not .zip
*To properly append "test" to the end of the gzip data, you should first use a GZIPInputStream to read in from the file, then tack "test" onto the uncompressed text, and then send it back out through GZipOutputStream
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63161668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reinitializing datatable and individual filter columns I need to initialize a Datatable and load data when a button is clicked. It works but it's creating a duplicate header under the filter columns. I have tried to destroy the Datatable but still no luck.. Hope someone can help.
I tried checking if the datatable exists then destroying the DT with the following: Also added destroy:true;
var table = $('#kt_table_1').DataTable().clear().destroy();
$('#kt_table_1 tbody').empty();
$('#kt_table_1 thead th').empty();
$("thead", table).remove();
$("thead .filter", table).empty();
var KTDatatablesSearchOptionsColumnSearch = function() {
$.fn.dataTable.Api.register('column().title()', function() {
return $(this.header()).text().trim();
});
var initTable1 = function() {
if ($.fn.dataTable.isDataTable('#kt_table_1')) {
console.log("yes exists");
}
// begin first table
var table = $('#kt_table_1').DataTable({
responsive: true,
select: {
style: 'multi',
selector: 'td:first-child .kt-checkable',
},
headerCallback: function(thead, data, start, end, display) {
thead.getElementsByTagName('th')[0].innerHTML = `
<label class="kt-checkbox kt-checkbox--single kt-checkbox--solid kt-checkbox--brand">
<input type="checkbox" value="" class="kt-group-checkable">
<span></span>
</label>`;
},
buttons: [
'print',
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
],
// Pagination settings
dom: `<'row'<'col-sm-12'tr>>
<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>`,
// read more: https://datatables.net/examples/basic_init/dom.html
lengthMenu: [5, 10, 25, 50],
pageLength: 10,
language: {
'lengthMenu': 'Display _MENU_',
},
searchDelay: 500,
processing: true,
serverSide: true,
destroy: true,
ajax: {
url: './demo2/contents/encargos/server.php',
type: 'POST',
data: {
// parameters for custom backend script demo
columnsDef: [
'RecordID', 'OrderID', 'Country', 'ShipCity', 'CompanyAgent', 'ShipDate', 'Status', 'Type', 'Actions', 'url'
],
},
},
columns: [{
data: 'RecordID'
},
{
data: 'OrderID'
},
{
data: 'Country'
},
{
data: 'ShipCity'
},
{
data: 'CompanyAgent'
},
{
data: 'ShipDate'
},
{
data: 'Status'
},
{
data: 'Type'
},
{
data: 'Actions',
responsivePriority: -1
},
],
initComplete: function() {
var thisTable = this;
var rowFilter = $('<tr class="filter"></tr>').appendTo($(table.table().header()));
this.api().columns().every(function() {
var column = this;
var input;
switch (column.title()) {
case 'Record ID':
case 'Order ID':
case 'Ship City':
case 'Company Agent':
input = $(`<input type="text" class="form-control form-control-sm form-filter kt-input" data-col-index="` + column.index() + `"/>`);
break;
case 'Country':
input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
<option value="">Select</option></select>`);
column.data().unique().sort().each(function(d, j) {
$(input).append('<option value="' + d + '">' + d + '</option>');
});
break;
case 'Status':
var status = {
1: {
'title': 'Pending',
'class': 'kt-badge--brand'
},
2: {
'title': 'Delivered',
'class': ' kt-badge--danger'
},
3: {
'title': 'Canceled',
'class': ' kt-badge--primary'
},
4: {
'title': 'Success',
'class': ' kt-badge--success'
},
5: {
'title': 'Info',
'class': ' kt-badge--info'
},
6: {
'title': 'Danger',
'class': ' kt-badge--danger'
},
7: {
'title': 'Warning',
'class': ' kt-badge--warning'
},
};
input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
<option value="">Select</option></select>`);
column.data().unique().sort().each(function(d, j) {
$(input).append('<option value="' + d + '">' + status[d].title + '</option>');
});
break;
case 'Type':
var status = {
1: {
'title': 'Online',
'state': 'danger'
},
2: {
'title': 'Retail',
'state': 'primary'
},
3: {
'title': 'Direct',
'state': 'success'
},
};
input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
<option value="">Select</option></select>`);
column.data().unique().sort().each(function(d, j) {
$(input).append('<option value="' + d + '">' + status[d].title + '</option>');
});
break;
case 'Ship Date':
input = $(`
<div class="input-group date">
<input type="text" class="form-control form-control-sm kt-input" readonly placeholder="From" data-date-format="dd-mm-yyyy" id="kt_datepicker_1"
data-col-index="` + column.index() + `"/>
<div class="input-group-append">
<span class="input-group-text"><i class="la la-calendar-o glyphicon-th"></i></span>
</div>
</div>
<div class="input-group date">
<input type="text" class="form-control form-control-sm kt-input" readonly placeholder="To" data-date-format="dd-mm-yyyy" id="kt_datepicker_2"
data-col-index="` + column.index() + `"/>
<div class="input-group-append">
<span class="input-group-text"><i class="la la-calendar-o glyphicon-th"></i></span>
</div>
</div>`);
break;
case 'Actions':
var search = $(`<button class="btn btn-brand kt-btn btn-sm kt-btn--icon">
<span>
<i class="la la-search"></i>
<span>Search</span>
</span>
</button>`);
var reset = $(`<button class="btn btn-secondary kt-btn btn-sm kt-btn--icon">
<span>
<i class="la la-close"></i>
<span>Reset</span>
</span>
</button>`);
$('<th>').append(search).append(reset).appendTo(rowFilter);
$(search).on('click', function(e) {
e.preventDefault();
var params = {};
$(rowFilter).find('.kt-input').each(function() {
var i = $(this).data('col-index');
if (params[i]) {
params[i] += '|' + $(this).val();
} else {
params[i] = $(this).val();
}
});
$.each(params, function(i, val) {
// apply search params to datatable
table.column(i).search(val ? val : '', false, false);
});
table.table().draw();
});
$(reset).on('click', function(e) {
e.preventDefault();
$(rowFilter).find('.kt-input').each(function(i) {
$(this).val('');
table.column($(this).data('col-index')).search('', false, false);
});
table.table().draw();
});
break;
}
if (column.title() !== 'Actions') {
$(input).appendTo($('<th>').appendTo(rowFilter));
}
});
// hide search column for responsive table
var hideSearchColumnResponsive = function() {
thisTable.api().columns().every(function() {
var column = this
if (column.responsiveHidden()) {
$(rowFilter).find('th').eq(column.index()).show();
} else {
$(rowFilter).find('th').eq(column.index()).hide();
}
})
};
// init on datatable load
hideSearchColumnResponsive();
// recheck on window resize
window.onresize = hideSearchColumnResponsive;
$('#kt_datepicker_1,#kt_datepicker_2').datepicker({
autoclose: true
});
},
columnDefs: [{
targets: 0,
orderable: false,
render: function(data, type, full, meta) {
return '<label class="kt-checkbox kt-checkbox--single kt-checkbox--solid kt-checkbox--brand"><input type="checkbox" value="' + data + '" class="kt-checkable"><span></span></label>';
},
},
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
console.log(full);
var id = full['RecordID'];
var url = full['url'];
return `
<span class="dropdown">
<a href="#" class="btn btn-sm btn-clean btn-icon btn-icon-md" data-toggle="dropdown" aria-expanded="true">
<i class="la la-ellipsis-h"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="` + url + `/edit.php"><i class="la la-edit"></i> Edit Details</a>
<a class="dropdown-item" href="#"><i class="la la-leaf"></i> Update Status</a>
<a class="dropdown-item" href="#"><i class="la la-print"></i> Generate Report</a>
</div>
</span>
<a href="#" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="View">
<i class="la la-edit"></i>
</a>`;
},
},
{
targets: 5,
width: '150px',
},
{
targets: 6,
render: function(data, type, full, meta) {
var status = {
1: {
'title': 'Pending',
'class': 'kt-badge--brand'
},
2: {
'title': 'Delivered',
'class': ' kt-badge--danger'
},
3: {
'title': 'Canceled',
'class': ' kt-badge--primary'
},
4: {
'title': 'Success',
'class': ' kt-badge--success'
},
5: {
'title': 'Info',
'class': ' kt-badge--info'
},
6: {
'title': 'Danger',
'class': ' kt-badge--danger'
},
7: {
'title': 'Warning',
'class': ' kt-badge--warning'
},
};
if (typeof status[data] === 'undefined') {
return data;
}
return '<span class="kt-badge ' + status[data].class + ' kt-badge--inline kt-badge--pill">' + status[data].title + '</span>';
},
},
{
targets: 7,
render: function(data, type, full, meta) {
var status = {
1: {
'title': 'Online',
'state': 'danger'
},
2: {
'title': 'Retail',
'state': 'primary'
},
3: {
'title': 'Direct',
'state': 'success'
},
};
if (typeof status[data] === 'undefined') {
return data;
}
return '<span class="kt-badge kt-badge--' + status[data].state + ' kt-badge--dot"></span> ' +
'<span class="kt-font-bold kt-font-' + status[data].state + '">' + status[data].title + '</span>';
},
},
{
targets: 8,
orderable: false,
},
],
});
table.on('change', '.kt-group-checkable', function() {
var set = $(this).closest('table').find('td:first-child .kt-checkable');
var checked = $(this).is(':checked');
$(set).each(function() {
if (checked) {
$(this).prop('checked', true);
table.rows($(this).closest('tr')).select();
} else {
$(this).prop('checked', false);
table.rows($(this).closest('tr')).deselect();
}
});
});
$('#export_print').on('click', function(e) {
e.preventDefault();
table.button(0).trigger();
});
$('#export_copy').on('click', function(e) {
e.preventDefault();
table.button(1).trigger();
});
$('#export_excel').on('click', function(e) {
e.preventDefault();
table.button(2).trigger();
});
$('#export_csv').on('click', function(e) {
e.preventDefault();
table.button(3).trigger();
});
$('#export_pdf').on('click', function(e) {
e.preventDefault();
table.button(4).trigger();
});
$('#action_delete').on('click', function(e) {
e.preventDefault();
var count = table.rows({
selected: true
}).count();
if (count > 0) { // at-least one checkbox checked
var ids = [];
$('.kt-checkable').each(function() {
if ($(this).is(':checked')) {
ids.push($(this).val());
}
});
var ids_string = ids.toString(); // array to string conversion
if (confirm("Eliminar " + ids_string + " ?")) {
$.ajax({
type: "POST",
url: "./demo2/modules/production/encargos/delete_group.php",
data: {
data_ids: ids_string
},
dataType: "json",
success: function(result) {
console.log(result);
table.ajax.reload();
NotifyPage('Eliminado correctamente', 'danger');
},
async: false
});
}
}
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
},
};
}();
jQuery(document).ready(function() {
KTDatatablesSearchOptionsColumnSearch.init();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57874895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Input type file in Chrome will not popup when served via https File input boxes aren't working in Chrome for me, I have reduced this down to pretty much just a single input box, and it still doesn't work. Works in IE and FireFox, and Edge. What can I do to get this to work? Using version 88.0.4324.190. It works in Chrome if I just get the file from the file system or via IIS and a http connection, but it doesn't work if the connection is https, despite there being no certificate problems.
<!DOCTYPE html>
<html>
<head>
<title>
Input type file not working
</title>
</head>
<body>
<form name="aspnetForm" method="post" action="./test.aspx" id="aspnetForm" enctype="multipart/form-data">
<input type="file" name="atest" id="atestid" />
</form>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66497413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript cant find my function in a promise I want to debug a function that returns a promise and for that I need a sleep function. I found this one:
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
and it works when used outside of a promise. However when I want to use it in a promise, I get the error, that sleep was not found. This is my code:
async function f(filename) {
return new Promise((resolve, reject) => {
await sleep(1000);
/*
rest of function
*/
});
}
A: Try to replace return new Promise((resolve, reject) => {}) in function f with return new Promise(async(resolve, reject) => {}). I hope it will solve your problem
async function f(filename) {
return new Promise(async (resolve, reject) => {
await sleep(1000);
/*
rest of function
*/
});
}
A:
However when I want to use it in a promise
You should never create another promise inside the new Promise executor. Instead, call the sleep function inside the surrounding function f (which you already marked as async, presumably to use the await keyword):
async function f(filename) {
await sleep(1000);
return new Promise((resolve, reject) => {
/* rest of function */
});
}
Your problem was also that the (resolve, reject) => {…} function is not async, so trying to use await inside there was a syntax error (in strict mode) and might also have caused the error message about the unexpected sleep token after the await.
A: Hi try using below code add async in the return code because you are using await inside the return
function sleep(ms) {
return new Promise((resolve) => {
console.log('inside sleep');
setTimeout(resolve, ms);
});
}
function f(filename) {
return new Promise( async(resolve, reject) => {
await sleep(7000);
/*
rest of function
*/
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62490266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make WhatsApp for iOS fetch image for preview set in og tag in my website? I am trying to set og:image tag for my website so that users can see the thumbnail image when the website link is shared. Now the thumbnail is working fine facebook, twitter and Linkedin. But when I share the link on WhatsApp it only works for android. In the case of WhatsApp for ios, it tries to load the image but fails and only website description is sent with the website link.
I have already followed all the answers available on this forum.The image I am trying to use for thumbnail is 669 × 378 px and is 89KB in size. There are no errors according to the facebook debugger. My website is in WordPress, so I was using Yoast SEO earlier but to solve this problem I tried by adding meta tags manually as well, but nothing works for WhatsApp for IOS.
These are the metatags found by facebook debugger for my website https://www.indiadappfest.com
These are the raw tags that we found
Meta Tag <meta property="og:locale" content="en_US" />
Meta Tag <meta property="og:type" content="website" />
Meta Tag <meta property="og:title" content="India Dapp Fest 2019 | Asia's top-notch revelation on blockchain based applications" />
Meta Tag <meta property="og:description" content="India Dapp Fest is a top-notch conference focussed on blockchain, enabling conscious decentralization and inturn, ushering in a change to pave the path for future work assemblies" />
Meta Tag <meta property="og:url" content="https://www.indiadappfest.com" />
Meta Tag <meta property="og:site_name" content="India Dapp Fest 2019" />
Meta Tag <meta property="og:image" content="https://www.indiadappfest.com/wp-content/uploads/2019/03/thumbnail-2-low-resolution.jpg" />
Meta Tag <meta property="og:image:secure_url" content="https://www.indiadappfest.com/wp-content/uploads/2019/03/thumbnail-2-low-resolution.jpg" />
Meta Tag <meta property="og:updated_time" content="1553416119" />
Someone, please help me to fix it for ios.
A: As per the open graph documentation you should use 1:1 i.e square images, apart from that remove the yoast seo plugin and add the meta tags manually (i used a plugin called scripts and styles). This helped me solve the problem for the thumbnail in WhatsApp for ios. You might also want to add another meta tag with a rectangular image as Facebook will skew the 1:1 image when you'll share it on Facebook.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55322164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change meta description/keywords dynamically with php Im trying to grab some info from the db and use it as meta desc and keyword. But something isnt working as it supposed to.
EDIT: after alot of help i got it semi working. If there is no blogID i want it to fallback on the other part... that part of the script aint working, any ideas?
<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "**********", "********");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id ORDER BY blogID DESC";
$stmt = $conn->prepare($sql);
$stmt->execute (array($id));
while($metta = $stmt->fetch(PDO::FETCH_BOTH) )
if (isset($metta['blogID']) && !empty($metta['blogID'])) {
$keywords = $metta['keywords'];
$description = $metta['description'];
} else {
$keywords = "blalbalbalblabla";
$description = "blabla";
}
?>
A: It might not be the prettiest code... but it works!
<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "*****", "*******");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id";
$stmt = $conn->prepare($sql);
$stmt->execute (array($id));
$metta = $stmt->fetch(PDO::FETCH_BOTH);
if (isset($_GET['postID'])) {
$keywords = $metta['keywords'];
$description = $metta['description'];
}
sqlsrv_close($con);
?>
<meta name="description" content="<?= isset($description) ? $description : 'blablabla'; ?>">
<meta name="keywords" content="<?= isset($keywords) ? $keywords : 'blablabla'; ?>">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38251831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Java tutorial method example Here there is a snippet taken from here:
import static java.nio.file.StandardOpenOption.*;
Path logfile = ...;
// Convert the string to a
// byte array.
String s = ...;
byte data[] = s.getBytes();
try (OutputStream out = new BufferedOutputStream(
logfile.newOutputStream(CREATE, APPEND))) {
...
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
}
However I cannot compile the logfile (which is a Path object) with newOutputStream method... only with Files.newOutputStream(path,StandardOpenOption..);
A: Path only contains information about where a file (or other thing) is located, it does not provide any information on how to process it. As you know the Path is a file then you can use the File class to process it, in this case to open a stream on it.
In language terms Path does not have a newOutputStream method so it will fail to compile.
From Oracle documentation on Path
Paths may be used with the Files class to operate on files, directories, and other types of files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17133304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert csv file data into mysql table which contains more columns I want to add the data from a csv file to a table in the DB but the table contains more columns than the file. The query should be such that some of the columns are filled by the csv file and some others should be filled with a specific value in the query. Lets say my csv file have data written in the format: "value1,value2" in every line. I want to add the data in a table containing 3 columns. First two columns should be filled with data from the file and in the third column should be the value "1". So far I have the following query which only fills the 2 columns of the table with data from the csv file:
LOAD DATA LOCAL INFILE 'target_file'
INTO TABLE table_name FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' (col1,col2);
A: You can mark default value "1" for the third field and then import the csv file. Or you can mark the fields as nullable that are not included in the csv file, then execute a query to update the null values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44460105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Scala REPL on SBT call people's own scripts? (Like OptiML?) I know sbt console will open an interactive Scala REPL and load in all the library dependencies so people can test Scala code right there. However, I wonder if there's anyway to use and treat in a way so that people can interact with my programs directly, instead of interacting with libraries.
For example, if I write a Vector class, how can someone call it from sbt console or any other Scala REPL interface??
Think of it as that you are trying to write a Scala library but you want to provide a simple REPL interface for people to interact with it, like R, instead of asking people to add the library as dependency.
The effect is similar as described here: http://stanford-ppl.github.io/Delite/optiml/getting_started.html
A: Maybe this will help.
You can use initialCommands key in sbt to do this
So in build.sbt if you put
initialCommands in console := """import my.project._
val myObj = MyObject("Hello", "World")
"""
after you type 'console', you can start using myObj or the classes in my.project
http://www.scala-sbt.org/0.13.5/docs/Howto/scala.html#initial
A: Yes you can, but you cannot use modified code without reloading the REPL. Just run:
sbt "~ ; console"
And then import your classes with import your.package._ and use them from there.
If you make any changes to your library code, just hit CTRL+D or :quit and it will detect file changes, compile them and enter the REPL again. You can then use the history (navigating with the arrows up/down) to execute anything from the previous session again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29167281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I remove the top margin in a web page? I have had this problem with every web page I have created. There is always a top margin above the 'main container' div I use to place my content in the center of the page. I am using a css style sheet and have set margins and padding in the body to 0px and set the margin and padding to 0 in the div:
body{
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
padding: 0;
color: black;
font-size: 10pt;
font-family: "Trebuchet MS", sans-serif;
background-color: #E2E2E2;
}
div.mainContainer{
height: auto;
width: 68em;
background-color: #FFFFFF;
margin: 0 auto;
padding: 0;
}
I have looked online many times, but all I can see to do is set these margin and padding attributes. Is there something else I should be doing? The margin exists in IE and Firefox.
Here is a more thorough look at the code (it is in the beginning stages of creation, so there isn't much in it...)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title></title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable -->
<link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="mainContainer">
<p>Here is the information</p>
</div>
</body>
</html>
Here is the CSS:
@charset "utf-8";
/* CSS Document */
body{
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
padding: 0;
color: black;
font-size: 10pt;
font-family: "Trebuchet MS", sans-serif;
background-color: #E2E2E2;
}
/* ---Section Dividers --------------------------------------------------------------*/
div.mainContainer{
position: relative;
height: auto;
width: 68em;
background-color: #FFFFFF;
margin: 0 auto;
padding: 0;
}
div.header{
padding: 0;
margin: 0;
}
div.leftSidebar{
float: left;
width: 22%;
height: 40em;
margin: 0;
}
div.mainContent{
margin-left: 25%;
}
div.footer{
clear: both;
padding-bottom: 0em;
margin: 0;
}
/* Hide from IE5-mac. Only IE-win sees this. \*/
* html div.leftSidebar { margin-right: 5px; }
* html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */
A: You can prevent the effects of margin collapsing with:
body { overflow: hidden }
That will make the body margins remain accurate.
A: I had similar problem, got this resolved by the following CSS:
body {
margin: 0 !important;
padding: 0 !important;
}
A: I had same problem. It was resolved by following css line;
h1{margin-top:0px}
My main div contained h1 tag in the beginning.
A: The best way to reset margins for all elements is to use the css asterisk rule.
Add this to the top of your css under the @charset:
* {
margin: 0px;
padding: 0px;
}
This will take away all the preset margins and padding with all elements body,h1,h2,p,etc.
Now you can make the top or header of your page flush with the browser along with any images or text in other divs.
A: I have been having a similar issue. I wanted a percentage height and top-margin for my container div, but the body would take on the margin of the container div.
I think I figured out a solution.
Here is my original (problem) code:
html {
height:100%;
}
body {
height:100%;
margin-top:0%;
padding:0%;
}
#pageContainer {
position:relative;
width:96%; /* 100% - (margin * 2) */
height:96%; /* 100% - (margin * 2) */
margin:2% auto 0% auto;
padding:0%;
}
My solution was to set the height of the body the same as the height of the container.
html {
height:100%;
}
body {
height:96%; /* 100% * (pageContainer*2) */
margin-top:0%;
padding:0%;
}
#pageContainer {
position:relative;
width:96%; /* 100% - (margin * 2) */
height:96%; /* 100% - (margin * 2) */
margin:2% auto 0% auto;
padding:0%;
}
I haven't tested it in every browser, but this seems to work.
A: The same issue has been driving me crazy for several hours. What I found and you may want to check is html encoding. In my html file I declared utf-8 encoding and used Notepad++ to enter html code in utf-8 format. What I DID forget of was UTF-8 BOM and No BOM difference. It seems when utf-8 declared html file is written as UTF-8 BOM there is some invisible extra character at the begining of the file. The character (non-printable I guess) effects in one row of "text" at the top of the rendered page. And you cannot see the difference in source-view of the browser (Chrome in my case). Both nice and spoiled files seem identical to the very character, still one of them renders nicely and the other one shows this freaking upper margin.
To wrap it up the solution is to convert the file to UTF-8 NO BOM and one can do it in i.e. Notepad++.
A: A lot of elements in CSS have default padding and margins set on them. So, when you start building a new site, it's always good to have a reset.css file ready. Add this to make to rub the default values, so you have more control over your web page.
/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
margin:0;
padding:0;
}
html,body {
margin:0;
padding:0;
}
/* Extra options you might want to consider*/
table {
border-collapse:collapse;
border-spacing:0;
}
fieldset,img {
border:0;
}
input{
border:1px solid #b0b0b0;
padding:3px 5px 4px;
color:#979797;
width:190px;
}
address,caption,cite,code,dfn,th,var {
font-style:normal;
font-weight:normal;
}
ol,ul {
list-style:none;
}
caption,th {
text-align:left;
}
h1,h2,h3,h4,h5,h6 {
font-size:100%;
font-weight:normal;
}
q:before,q:after {
content:'';
}
abbr,acronym {
border:0;
}
I hope this helps all fellow developers this is something that bugged for me a while when I was learning.
A: Is your first element h1 or similar? That element's margin-top could be causing what seems like a margin on body.
A: Here is the code that everyone was asking for -- its at the very beginning of development so there isn't much in it yet, which may be helpful...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title></title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable -->
<link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="mainContainer">
<div class="header"> </div>
<div class="mainContent"> </div>
<div class="footer"> </div>
</div>
</body>
</html>
Here is the css:
@charset "utf-8";
/* CSS Document */
body{
margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;
padding: 0;
color: black; font-size: 10pt; font-family: "Trebuchet MS", sans-serif;
background-color: #E2E2E2;}
html{padding: 0; margin: 0;}
/* ---Section Dividers -----------------------------------------------*/
div.mainContainer{
height: auto; width: 68em;
background-color: #FFFFFF;
margin: 0 auto; padding: 0;}
div.header{padding: 0; margin-bottom: 1em;}
div.leftSidebar{
float: left;
width: 22%; height: 40em;
margin: 0;}
div.mainContent{margin-left: 25%;}
div.footer{
clear: both;
padding-bottom: 0em; margin: 0;}
/* Hide from IE5-mac. Only IE-win sees this. \*/
* html div.leftSidebar { margin-right: 5px; }
* html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */
A: Try margin -10px:
body { margin-top:-10px; }
A: For opera just add this in header
<link rel='stylesheet' media='handheld' href='body.css' />
This makes opera use most of your customised css.
A: It is a <p> element that creates the top margin. You removed all top margins except of that element.
A: same problem, h1 was causing it to have that massive margin-top. after that you can use body{margin: 0;} and its looks good. another way is using *{margin: 0;} but it might mess up margins of other elements for you.
A: I had this exact same problem. For me, this was the only thing that worked:
div.mainContainer { padding-top: 1px; }
It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me. I also had an h1 at the top of my page
A:
body{
margin:0;
padding:0;
}
<span>Example</span>
A: I tried almost every online technique, but i still got the top space in my website, when ever i open it with opera mini mobile phone browser, so i decided to try fix it on my own, and i got it right!
i realize when even you display a page in a single layout, it fits the website to the screen, and some css functions are disabled, since margin, padding, float and position functions are disabled automatically when you fit to screen, and the body always add inbuilt padding at the top. so i decieded to look for at least one function that works, guess what? "display". let me show you how!
<html>
<head>
<style>
body {
display: inline;
}
#top {
display: inline-block;
}
</style>
</head>
<body>
<div id="top">
<!-- your code goes here! -->
eg: <div id="header"></div>
<div id="container"></div> and so on..
<!-- your code goes here! -->
</div>
</body>
</html>
If you notice, the body{display:inline;} removes the inbuilt padding in the body, but without #top{display:inline-block;}, the div still wont display well, so you must include the <div id="top">
element before any code on your page! so simple.. hope this helps? you can thank me if it works, http://www.facebook.com/exploxi
A: you may also check if:
{float: left;}
and
{clear: both;}
are used correctly in your css.
A: style="text-align:center;margin-top:0;" cz-shortcut-listen="true"
paste this at your body tag!
this will remove the top margin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2489070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
}
|
Q: Return a value / cancel installation with vbscript custom action I have a custom action in my installer that opens a message box using a vbscript custom action.
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
<![CDATA[
Dim i
If session.Property("REMINDEX_SHORTCUT") = "" Then
i = MsgBox(session.Property("TextProp"), 1)
End If
]]>
</CustomAction>
I want to cancel the installation if the value of i = 2 (if cancel is pressed in the message box). I think I can get the installation to cancel if my script returns a value of 3, but it only ever returns 0. I've tried this:
Dim i
If session.Property("REMINDEX_SHORTCUT") = "" Then
i = MsgBox(session.Property("TextProp"), 1)
End If
If i = 2 Then
return 3
End If
which throws some error about 'type mismatch'.
I also tried this when I got desperate:
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
<![CDATA[
Dim i
If session.Property("REMINDEX_SHORTCUT") = "" Then
i = MsgBox(session.Property("TextProp"), 1)
End If
If i = 2 Then
EXENotFound = 3
End If
]]>
</CustomAction>
I've done extensive research online but have not been able to find how to cancel the installation from a custom action or even how to simply return 3 manually.
Any suggestions would be greatly appreciated
A: I only dabbled with WiX a little, and it's been some years since then, but I think you need to put your code in a function:
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
<![CDATA[
Function AskUser
AskUser = 0
If session.Property("REMINDEX_SHORTCUT") = "" Then
AskUser = MsgBox(session.Property("TextProp"), 1)
End If
End Function
]]>
</CustomAction>
A: If you're in the UI sequence, then the correct way to do this is to show a standard dialog built using your MSI development tool, and wire up the Cancel logic if that's one of the choices. That's mostly covered by other answers. The correct way to show a message in the execute sequence (from a custom action) is to call MsiProcessMessage (or installer object or DTF managed CA equivalents). Return IDCANCEL if appropriate.
https://msdn.microsoft.com/en-us/library/aa370354(v=vs.85).aspx
http://microsoft.public.platformsdk.msi.narkive.com/oKHfPSZc/using-msiprocessmessage-in-a-c-custom-action
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17331894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting current user for required model field I have a model where one of the required fields is the currently signed in user. I do the following when creating a new record for the model:
views.py
def post(self, request):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_position = bound_form.save()
The problem is that this only works when the user has selected them self on the form. I need a way to set the current user automatically and simply don't display the user field on the form. I have tried this:
def post(self, request):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_position = bound_form.save(commit=False)
new_position.user = request.user
new_position.save()
However this does not work because the bound_form is not valid because it is missing a user which is a required field on the model. Where else can the user be set before trying to save the form? In the template, or the get method of the view?
A: You should use exclude=('user',) in class Meta: of your form. @Daniel Roseman is also right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38149319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Null safety operator for function variable in Kotlin In my Kotlin app I have nullable variable like this
private var myCallback : (() -> Unit)? = null
Is it possible to use null safety operator ? to call it? This gives me a compilation error.
myCallback?()
I found only this ugly way for a call if it is not null
if(myCallback != null)
myCallback!!()
A: You can call it as follows:
myCallback?.invoke()
The () syntax on variables of function types is simply syntax sugar for the invoke() operator, which can be called using the regular safe call syntax if you expand it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51865648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Creating a simple Node.js web service for use with AJAX I have a basic Node.js http server set up as per the docs, I'm trying to create a very simple web service I can talk to with Javascript (AJAX) which I'll then hook up to Arduino. It's a test piece, I may go down the road of something else but this is proving to be fun. Anyway, here is the server-side javascript:
var http = require('http');
var _return = 'Bing Bong';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/jsonp'});
//do stuff
res.end('_return(\'Hello :-)\' + _return)');
}).listen(process.env.VMC_APP_PORT || 1337, null);
And this is the client side:
function experimentFive(node) {
console.log('X5 Func started');
console.log('Calling Node.js service');
var nodeURL = node;
$.ajax({
url: nodeURL,
dataType: "jsonp",
jsonpCallback: "_return",
cache: false,
timeout: 50000,
success: function(data) {
console.log('Data is: ' + data);
$("#nodeString").text(" ");
$("#nodeString").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error : ' + textStatus + " " + errorThrown);
}
});
}
experimentFive('http://fingerpuk.eu01.aws.af.cm/');
This works, I get the data back but not as I'd expect. What I'd like to be able to do is change some data server side and receive that back. I get back the string in the res.end plus:
function () {
responseContainer = arguments;
}
Instead of the variable's data. No matter how I try to get that data back, it is either undefined or this response.
From research I think the variable is not having it's data set before the callback fires, so it's empty. But if I set an initial value the data is still undefined.
Am I missing something very simple here? Should I just go back to C#?
Cheers.
A: One possible way of accomplishing this would be to use ExpressJS with NodeJS to handle routing your endpoints. By doing this you can set up routes such as GET /media/movies/, fire an AJAX request to this route, then have it return JSON data that you can handle on your app.
Here's an example of ExpressJS routing in an app that I made:
var groups = require('../app/controllers/groups');
// find a group by email
app.post('/groups/find', groups.searchGroupsByEmail);
Here is a great tutorial that I used when getting started with Express. It walks through the entire process from installing Node.JS (which you've already done) to setting up the ExpressJS routing to handle incoming HTTP requests.
Creating a REST API using Node.js, Express, and MongoDB
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17532924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Keyboard Issues with Ionic4 I have developed an android application using Ionic4. The issue I am facing is when the keyboard appears it covers the Input field, screen is not moving up.
I have solved this issue in Ionic 3 by the following lines of code. But this does not works in Ionic4. Somebody please help.
imports: [
IonicModule.forRoot(MyApp, {
scrollAssist: true,
autoFocusAssist: true
})
],
HTML
<div class="field-container">
<form [formGroup]="credentialsForm" class="width-100">
<ion-list>
<ion-item no-padding class="transparent-border">
<div class="logo-div">
<img src="assets/icon/favicon.png" class="app-logo">
</div>
</ion-item>
<ion-item no-padding>
<ion-label position="floating" color="primary">Username</ion-label>
<ion-input type="text" color="primary" mode="ios" maxLength="5" formControlName="userName" required></ion-input>
</ion-item>
<span class="validation-errors" *ngIf="!credentialsForm.controls.userName.valid && (credentialsForm.controls.userName.dirty || onSaveAttempt)">Username
is mandatory</span>
<ion-item no-padding>
<ion-label position="floating" color="primary">Password</ion-label>
<ion-input color="primary" type="password" mode="ios" formControlName="password" required></ion-input>
</ion-item>
<span class="validation-errors" *ngIf="!credentialsForm.controls.password.valid && (credentialsForm.controls.password.dirty || onSaveAttempt)">Password
is mandatory</span>
<ion-item no-padding class="transparent-border">
<div style="overflow: hidden;width: 100%">
<p class="create-account" (click)="doRegistrationNavigation()">Create an Account</p>
<p class="forgot-password">Forgot password?</p>
</div>
</ion-item>
</ion-list>
</form>
<ion-button (click)="doLogin()" expand="block" shape="round" class="signin-button" color="vibrant">Sign
In</ion-button>
</div>
A: Try this
ngAfterViewInit(): void {
window.addEventListener('keyboardDidShow', this.customScroll);
}
private customScroll() {
this.content.scrollTo(0, 100); // 100 replaced by your value
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55460943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQL: "Where" or "AND" what performs better on large database? I have this SQL query. It runs on the same table and creates a dataset with three columns. My concern is whether I should Use 'WHERE' clause or 'AND'. I have this feeling that 'AND' will be more efficient and faster than 'WHERE'. Please advise.
1st one is with 'WHERE' and 2nd one is without it.
*
*SELECT DISTINCT t1.rpsrespondent AS id_num,t1.rpscontent AS PID, t2.RpsContent AS SeqNo
FROM table t1
INNER JOIN table t2 ON t1.rpsrespondent=t2.rpsrespondent
INNER JOIN table t3 ON t3.rpsrespondent=t1.rpsrespondent
WHERE t1.RpsQuestion='PID' AND t2.RpsQuestion = 'VISITID'
AND t3.rpsquestion ='INT99' AND t3.rpscontent in('36','37')
*SELECT DISTINCT t1.rpsrespondent AS id_num,t1.rpscontent AS PID, t2.RpsContent AS SeqNo
FROM table t1
INNER JOIN table t2 ON t1.rpsrespondent=t2.rpsrespondent
AND t1.RpsQuestion='PID' AND t2.RpsQuestion = 'VISITID'
INNER JOIN table t3 ON t3.rpsrespondent=t1.rpsrespondent
AND t3.rpsquestion ='INT99' AND t3.rpscontent in('36','37')
A: With an INNER JOIN, it makes no difference if predicates are specified in the JOIN or WHERE clauses. The queries are semantically identical so the SQL Server optimizer should generate the same (optimal) executional plan. You will get the same performance as a result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29087640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Slow add column I have an 8 million row table in an RDS mysql instance which is read replicated.
When adding a new column (int / length 2 / default 0) the primary DB reached 100% and hung until reboot.
So, I ran a test on my local machine - same table / same new column (not read replicated) and the change was instant.
Please advise why such an issue would occur? Any ideas welcome
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74110629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django admin, change current value of ForeignKey widget in my Django admin application I have one ForeignKey field with its relative widget in change page.
I wish to add a link to change view of current selected product instead of simple text of current product.
My models is composed of: WeddingList, Product and WeddingListProducts for m2m relationship...
In my admin.py the ProductAdmin class is an inline of WeddingListAdmin class.
This is my admin.py
class WeddingListProductsInline(admin.TabularInline):
model = WeddingListProducts
form = WeddingListProductsAdminForm
extra = 0
class WeddingListAdmin(admin.ModelAdmin):
inlines = (WeddingListProductsInline,)
Thanks in advance for help!
A: Ok, I've solved my problem.
My solution is to override admin/edit_inline.html template with these code:
<td class="original">
{% if inline_admin_form.original or inline_admin_form.show_url %}
<p>
{% if inline_admin_form.original %}
<a href="{% url 'admin:MyApp_product_change' inline_admin_form.original.product.id %}">
{{ inline_admin_form.original }}
</a>
{% endif %}
</p>
{% endif %}
and set the template attribute of my ModelAdmin class to corresponding url of new template.
admin.py
class MyModelInline(admin.TabularInline):
template = "admin/myapp/mymodel/edit_inline/tabular.html"
Please comment for any better solutions! Bye ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22384279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bootbox alert not on focus I'm calling bootbox confirm function, but it isn't on focus. All my page get this gray effect, including the bootbox window. What am I doing wrong?
Here's how I am calling bootbox confirm function:
$(".js-delete").on("click", function () {
var tr = $(this).closest('tr');
var button = $(this);
bootbox.confirm("Você tem certeza que deseja deletar esse registro de cliente?", function (result) {
if (result) {
$.ajax({
type: "POST",
url: "@Url.Action("Delete","Customers")",
ajaxasync: true,
data: { id: button.attr("customer-id") },
success: tr.remove()
});
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48387566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: network graph using igraph() from lm() regression output I'd like to get a visual overview of the output of a linear regression model.
I'd like to be build a network plot with unidirectional edges using the output from a regression model, and I'd like to only include predictors with a p-value <0.05 (so to end up with a structure like the one I've plotted manually below).
Ideally, I'd also like the edges to be green when there is a positive association, red when there is a negative association, and to be thicker when there is a strong association.
It's my first time working with network/network-like graphs, and I'm at loss. Any help would be much appreciated.
# PACKAGES
library(dplyr)
library(broom)
library(igraph)
# DATA
mtcars
# MODEL AND OUTPUT
mymodel = mtcars %>% do(myfit = lm(mpg ~ wt + gear +carb, data = .))
mymodCoef = tidy(mymodel, myfit)
mymodCoef <- as.data.frame(mymodCoef)
# WHAT I'D LIKE TO PLOT TO LOOK LIKE
plot(graph_from_literal(wt--+mpg, carb--+mpg))
A: You need to create a data frame representing an edge list in the format of:
*
*column1 = node where the edge is coming from
*column2 = node where the edge is going to
*columnn... = attributes you want to store in the edge
Then you will need to input that df into graph_from_data_frame
Two of the attributes you can store in the edge list are color and width which will automatically be plotted in igraph's base plot function.
edge_list <- mymodCoef %>%
mutate(source = term,
target = 'mpg',
color = sapply(statistic, function(x){ifelse(x<0, 'red', 'green')}),
width = abs(statistic)/(max(abs(statistic))) * 10) %>%
filter(p.value <= .05) %>%
select(source, target, color, statistic, width)
g <- graph_from_data_frame(edge_list, directed = F)
plot(g)
If you wanted to explicitly plot the color and width, then
plot(g, edge.width = E(g)$width, edge.color = E(g)$color)
Sometimes you'll need to play around with scales - for instance, the difference in statistic scores are at most 2 and will look identical if you used the raw statistic score as the line width. If you want to get scaling for free, then you can use ggraph:
library(ggraph)
ggraph(g) +
geom_edge_link(aes(edge_colour = color,
edge_width = abs(statistic))) +
geom_node_text(aes(label = name)) +
scale_edge_color_manual(values = c('green' = 'green', 'red' = 'red'))
If you want to learn more about plotting with igraph, then some of the best tutorials for plotting in igraph can be found in Katherine Ognyanova's website: http://kateto.net/netscix2016
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49718725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: traversing an array one less time each time Lets say I have an array of [1,2,3,4,5]
I want to attempt to traverse the array one less each time, while adding the numbers.
First time:
1+2+3+4+5 = 15
Second time:
2+3+4+5 = 14
Third time:
3+4+5 = 12
Fourth time:
4+5 = 9
Fifth time:
5 = 5
any help would be greatly appreciated!
Thank you so much.
-AbysssCoder
A: Since you tagged your question with MATLAB...
>> x = [1,2,3,4,5]; % define array
>> cumsum(x, 'reverse') % cumulative sum in reverse order
ans =
15 14 12 9 5
A: int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
int sum = 0;
for (int j = i; j < arr.length; j++) {
sum += arr[j];
}
System.out.println(sum);
}
Something like this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59277013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hash three 32-bit integers into a 64-bit integer? Looking for some ways to hash three 32-bit integers into a single 64-bit integer. Interested in knowing a fast way of doing this but with as few collisions as possible. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72060840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Advice on reading indexes I'm trying to figure out the right way to read lucene index only once whilst running the application multiple times, how can I do that in java?
Because indexed data will not change so reading them each time would not be necessary. Can someone explain me the logic of it reading them only once? thank you
UPDATE :
public List initTableObject() throws IOException {
Directory fSDirectory = FSDirectory.open(new File(INDEX_NAME));
List<String>termList = new ArrayList<String>();
RAMDirectory directory = new RAMDirectory(fSDirectory);
IndexReader iReader = IndexReader.open(fSDirectory);
FilterIndexReader fReader = new FilterIndexReader(iReader);
// int numOfDocs = fReader.numDocs();
TermEnum terms = fReader.terms();
while (terms.next()){
Term term = terms.term();
String termText = term.text();
termList.add(termText);
}
iReader.close();
return termList;
}
I'm really new with lucene and this, so here is what I've got so far I'm just not there yet with RAMDirectory.
This method retrieves list because I need this index list to compare with some files that I have. How can I store this list to the RAM so I can use it in my other part of application for comparison ?
A: I think the answer on this question might be of use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2981376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a best practice for where to log when running multiple instances of an application with Docker? I am trying to create an application that will be run on multiple Docker instances on multiple machines. Since my containers will be running nginx as their command, docker logs would show the output of nginx logs, which is fine. However, that begs the question: where should my application log?
The options I have thought about are the following.
Log on the host file system
As far as I can tell, to be able to identify which Docker container has written to the log, I must create something like /var/logs/myapplication, and create a folder for each container, and tell my application inside the container to write into that directory. For example, I would have to create /var/logs/myapplication/instance-1 and mount that as a volume inside my Docker container.
The problem in this approach is that it's hard to collect logs. I will have to ssh to different machines, go in the /var/logs/myapplication directory of each machine and get the logs out to read them. It's perfectly fine when I know there's a question, but confusing when I am trying to monitor the whole system.
Logging in the database
In this method, all Docker containers will write to a database, and one of the columns of the database will be container_name so that I can filter logs based on container name.
The problem with this approach is that I haven't ever used a database for keeping logs, and I'm not really sure if they are meant to be used like this.
Back to the original question
So my question is, is there a proven best-practice for logging when you have multiple machines with multiple containers on each?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36929689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to include and exclude checkboxes from being calculated? Netbeans IDE I was wondering if there is a way I can write a code where I have 6 checkboxes and I want to have them calculated as a final sum, I want to write it to have the selected ones included into the calculation only. I asked my teacher about it and all I got was the we did this in class crap but no we didn't, he sent me this code to use but it's not excluding the checkboxes it's all or nothing.
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox1.isSelected() == true) {jCheckBox1.setText("50");}
}
private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox2.isSelected() == true) {jCheckBox2.setText("50");}
}
private void jCheckBox3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox3.isSelected() == true) {jCheckBox3.setText("50");}
}
private void jCheckBox4ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox4.isSelected() == true) {jCheckBox4.setText("50");}
}
private void jCheckBox5ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox5.isSelected() == true) {jCheckBox5.setText("50");}
}
private void jCheckBox6ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox6.isSelected() == true) {jCheckBox6.setText("50");}
}
And then he told me to declare variables so I did what he told me in this code
double Box1, Box2, Box3, Box4, Box5, Box6;
Box1 = Double.parseDouble(jCheckBox1.getText());
Box2 = Double.parseDouble(jCheckBox2.getText());
Box3 = Double.parseDouble(jCheckBox3.getText());
Box4 = Double.parseDouble(jCheckBox4.getText());
Box5 = Double.parseDouble(jCheckBox5.getText());
Box6 = Double.parseDouble(jCheckBox6.getText());
sum = Box1+Box2+Box3+Box4+Box5+Box6;
I have tried getting it into the next form with a few selected boxes but all I get is a huge red error and it's getting me frustrated.
A: See,you are defining the cases--- if the checkboxes have been selected, but what about them if they aren't selected!These might be picking some Garbage values as per your bottom piece of code!
So,you better provide an else statement along with each if-statement. Also,there is no need to write actionPerformed() for each of the Checkboxes! It would be achieved even using a single JButton.Else you'll have several problems implementing that as to how to set Default values and all!
You can try this.I think it'll work fine. :-
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Double cb1,cb2,cb3,cb4,cb5,cb6;
Double total=0d;
if (jCheckBox1.isSelected() == true) {jCheckBox1.setText("50");}
else jCheckBox1.setText("");
if (jCheckBox2.isSelected() == true) {jCheckBox2.setText("50");}
else jCheckBox2.setText("");
if (jCheckBox3.isSelected() == true) {jCheckBox3.setText("50");}
else jCheckBox3.setText("");
if (jCheckBox4.isSelected() == true) {jCheckBox4.setText("50");}
else jCheckBox4.setText("");
if (jCheckBox5.isSelected() == true) {jCheckBox5.setText("50");}
else jCheckBox5.setText("");
if (jCheckBox6.isSelected() == true) {jCheckBox6.setText("50");}
else jCheckBox6.setText("");
cb1=Double.parseDouble((jCheckBox1.getText().equals(""))?"0":"50");
cb2=Double.parseDouble((jCheckBox2.getText().equals(""))?"0":"50");
cb3=Double.parseDouble((jCheckBox3.getText().equals(""))?"0":"50");
cb4=Double.parseDouble((jCheckBox4.getText().equals(""))?"0":"50");
cb5=Double.parseDouble((jCheckBox5.getText().equals(""))?"0":"50");
cb6=Double.parseDouble((jCheckBox6.getText().equals(""))?"0":"50");
total=cb1+cb2+cb3+cb4+cb5+cb6;
jLabel1.setText("The total comes out to be :- "+total);
}
A: Use an else in your Ifs and set the text to "0" if it's not selected.
Also, when you initialize your checkboxes, set a default text of "0".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24231925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ActionPerformed and ActionListener My program asks the user: How many course have you completed? So, the users has to enter the number of courses completed on a JTextField component. My program then converts the String that has been entered in the JTextField into a Integer. When I run my program, I get a numberformatException. I tried debugging, and I noticed that my program converts the String into a Integer before the user can write anything. The program doesn't wait for the user to type anything. How can I make so my program waits for the user to enter a number before continuing to execute the code?
public class content extends JPanel implements ActionListener
{
String number = "";
JTextField NumtextField = new JTextField(5);
@Override
public void actionPerformed(ActionEvent e)
{
number = NumtextField.getNumtextField().getText();
}
int size = Integer.parseInt(number);
}
A: Move int size = Integer.parseInt(number); inside actionPerformed:
public void actionPerformed(ActionEvent e){
number = NumtextField.getNumtextField().getText();
int size = Integer.parseInt(number);
}
When the program starts, its trying to parse "", which is not a valid number string hence why you are getting an exception.
Also maybe you should put that inside a try{}catch{} block, so in case you get an exception in real time you can handle it:
try {
int size = Integer.parseInt(number);
}
catch (NumberFormatException e) {
System.out.println("Thats not a valid number");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16113148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: find numbers in array that add up to a given number c++ I am writing this code that takes the input file and sorts all the integers from that file into an array. Then it takes the sum chosen by the user and goes through all the combinations (one by one /professors orders/) to find a pair that equal the desired sum. some of the code is funky because we are required to use a C++03 compiler -sigh-. The program has no errors but when I run it it says
There were 1600 checks made to find the products of your desired sum and
the two numbers that add to your sum are 40 and 40
Segmentation fault (core dumped)
(the desired sum was not one that could have been found in the input file so it should have said " the program did not find any matches. try again. ")
The code is very messy and Im sorry but I have spent hours moving stuff around and adding new things or trying something new to try and make it work.
I have a feeling it is a problem with how I am declaring the boolean variables or maybe how I am passing them.
int x, i, n1, n2, pos1 = 0, pos2 = 0,accesses = 0;
bool fail = false;
int readSortedArray (int array[20], int count, istream& infile)
{
count = 0;
while(infile >> array[count])
{
count++;
}
return count;
}
int findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail, istream& infile)
{
bool found = true;
while(found == true)
{
for( i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for( x = 0; x < count; x++)
{
pos2++; accesses ++;
n2 = array[x];
if(sum == n1 + n2)
{
found = false;
fail = false;
}
if(sum != n1 + n2)
{
fail = true;
}
}
}
}
return fail;
}
int main ()
{
int array[20];
int answer, sum, count = 0;
std::string input_filename;
ifstream infile;
cout << "Please enter name of the input file: ";
cin >> input_filename;
infile.open(input_filename.c_str());
if (!infile)
{
cout << "Could not open input file one\n";
return 0;
}
cout << "Please enter the prefered sum ";
cin >> sum;
count = readSortedArray(array, count, infile);
fail = findproducts(array, n1, n2, count, sum, accesses, fail, infile);
cout << "There were " << accesses << " checks made to find the products of your desired sum and" << endl;
if(fail == true)
{
cout << " the program did not find any matches. try again. ";
}
if(fail == false)
{
cout << endl << "the two numbers that add to your sum are " << n1 << " and " << n2 << endl << ". These were found in position " << pos1 << " and " << pos2;
}
return 0;
}
A: I incorporated Karan S Warraich's comment about the bool type. I also removed the file parameter to findProducts. But the big issue was the while loop ran forever when it did not find anything. I got rid of it. Also, it was important to get out of the for before the good numbers were lost again and fail was reset. As you note, a number of code cleanups are possible (like found now does nothing, and fail need not be set within findproducts), but here is something that works
bool findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail)
{
bool found = true;
for( i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for( x = 0; x < count; x++)
{
pos2++; accesses++;
n2 = array[x];
if(sum == n1 + n2)
{
found = false;
fail = false;
return false;
}
}
}
return true;
}
A: In your findproduct function you are returning bool value while your function is of int type that is either make your function a bool return type or return 1 for true and 0 for false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43024970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySql soterd procedure IF ELSE and while loop I want to create a stored procedure in MySQL where I loop through the records and return rows if certain condition is true.
For eg: I have a table with columns PRIMARY, TRANSTYPE, DATE, AMOUNT. Now PRIMARY can be either 0 or 1 and TRANSTYPE can BE A,B,C.
Now what I want to do is return row where PRIMARY="0" if TRANSTYPE = "A" and return row where PRIMARY="1" if TRANSTYPE = "B" or TRANSTYPE = "C"
Currently I am doing this with PHP, but I want to do it with MySql stored procedure.
A: SELECT * FROM <table>
WHERE
(PRIMARY="0" AND TRANSTYPE = "A") OR
(PRIMARY="1" AND TRANSTYPE = "B") OR
(PRIMARY="1" AND TRANSTYPE = "C")
A: you can do
CREATE PROCEDURE PROC_NAME()
BEGIN
select * from table
where (TRANSTYPE = 'A' and PRIMARY = '0')
or (TRANSTYPE in ('B','C') and PRIMARY = '1');
END;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14050484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Print proper mathematical formatting When I use sympy to get the square root of 8, the output is ugly:
2*2**(1/2)
import sympy
In [2]: sympy.sqrt(8)
Out[2]: 2*2**(1/2)
Is there any way to make sympy print output in proper mathematical notation (i.e. using the proper symbol for square root) ?
UPDATE:
when I follow the suggestions from @pqnet:
from sympy import *
x, y, z = symbols('x y z')
init_printing()
init_session()
I get following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-21d886bf3e54> in <module>()
2 x, y, z = symbols('x y z')
3 init_printing()
----> 4 init_session()
/usr/lib/python2.7/dist-packages/sympy/interactive/session.pyc in init_session(ipython, pretty_print, order, use_unicode, quiet, argv)
154 # and False means don't add the line to IPython's history.
155 ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
--> 156 mainloop = ip.mainloop
157 else:
158 mainloop = ip.interact
AttributeError: 'ZMQInteractiveShell' object has no attribute 'mainloop'
A: The simplest way to do it is this:
sympy.pprint(sympy.sqrt(8))
For me (using rxvt-unicode and ipython) it gives
___
2⋅╲╱ 2
A: In an ipython notebook you can enable Sympy's graphical math typesetting with the init_printing function:
import sympy
sympy.init_printing(use_latex='mathjax')
After that, sympy will intercept the output of each cell and format it using math fonts and symbols. Try:
sympy.sqrt(8)
See also:
*
*Printing section in the Sympy Tutorial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25326334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot reopen Jupyter notebooks on Google Cloud Dataproc cluster after stopping cluster I was using Google Cloud Dataproc to run a Jupyter notebook (following these instructions: https://cloud.google.com/dataproc/docs/tutorials/jupyter-notebook).
I ran a notebook, saved it, and then at some point later on, stopped the cluster (using the GUI). Then later I restarted the cluster and tried to run Jupyter notebook again with the same instructions but in the last step, when I try to open Jupyter in Chrome I get:
"This site can't be reached. The webpage at http://<my-cluster-name>:8123/ might be temporarily down or it may have moved permanently to a new web address. ERR_SOCKS_CONNECTION_FAILED."
Also (I don't know if this helps) in the terminal window where I configured my browser, I have a message:
ERROR:child_thread_impl.cc(762)] Request for unknown Channel-associated interface: ui::mojom::GpuMain
Google Chrome[695:8548] NSWindow warning: adding an unknown subview: <FullSizeContentView: 0x7fdfd3e291e0>. Break on NSLog to debug.
Google Chrome[695:8548] Call stack:
(
"+callStackSymbols disabled for performance reasons"
)
In the terminal window where I ssh-ed to my cluster I have these messages:
channel 3: open failed: connect failed: Connection refused
channel 4: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 6: open failed: connect failed: Connection refused
channel 12: open failed: connect failed: Connection refused
channel 12: open failed: administratively prohibited: open failed
channel 13: open failed: administratively prohibited: open failed
channel 14: open failed: administratively prohibited: open failed
channel 14: open failed: connect failed: Connection refused
channel 8: open failed: connect failed: Connection refused
Also, earlier BEFORE I had stopped the cluster I could close the jupyter notebooks, disconnect from the cluster, and reopen the jupyter notebook. I only ran into this problem after I had stopped the cluster. Any ideas what might be going on?
A: This is because the current initialization action explicitly launches the jupyter notebook service calling launch-jupyter-kernel.sh. Initialization actions aren't the same as GCE startup-scripts in that they don't re-run on startup; the intent normally is that initialization actions need not be idempotent, but instead if they want to restart on startup need to add some init.d/systemd configs to do so explicitly.
For the one-off case, you can just SSH into the master, then do:
sudo su
source /etc/profile.d/conda.sh
nohup jupyter notebook --allow-root --no-browser >> /var/log/jupyter_notebook.log 2>&1 &
If you want this to happen automatically on startup, you can try to put that in a startup script via GCE metadata, though if you're doing that at cluster creation time you'll need to make sure it doesn't collide with the Dataproc initialization action (also, startup scripts might run before the dataproc init action, so the first attempt you might just want to allow to fail silently).
Longer term, we should update the initialization action to add the entry into init.d/systemd so that the init action itself configures auto restart on reboot. There's no one dedicated to this at the moment, but if you or anyone you know is up to the task, contributions are always well appreciated; I filed https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/issues/108 to track this feature.
A: I fixed the problem by connecting to master machine using ssh and created a systemd service(followed dennis-huo's comment above).
*
*go to /usr/lib/systemd/system
*sudo su
*create a systemd unit file called "jupyter-notebook.service" with content
[Unit]
Description=Start Jupyter Notebook Server at reboot
[Service]
Type=simple
ExecStart=/opt/conda/bin/jupyter notebook --allow-root --no-browser
[Install]
WantedBy=multi-user.target
*systemctl daemon-reload
*systemctl enable jupyter-notebook.service
*systemctl start jupyter-notebook.service
Next step will be to include above code into dataproc-initialization-actions.
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43413442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calculating the closest color in a dictionary to an input I have a dictionary of colors (below) and a color such as #4a7dac which is 'steelblue'. I want to find the name of the closest hex colour in the dictinary to this colour. So the algorithm would decide on #0000ff and return 'blue'.
colors= {
"red":"#FF0000",
"yellow":"#FFFF00",
"green":"#008000",
"blue":"#0000FF",
"black":"#000000",
"white":"#FFFFFF",
"gray":"#808080",
}
I have thought about calculating some sort of 'distance' between colors, but don't know how to go about writing this.
A: We can create a function that takes two hex strings and returns the sum of the differences between the individual colour components. If you can't understand how the following works, just comment.
def diff(h1, h2):
def hexs_to_ints(s):
return [int(s[i:i+2], 16) for i in range(1,7,2)]
return sum(abs(i - j) for i, j in zip(*map(hexs_to_ints, (h1, h2))))
And we can test it:
>>> diff('#ff00ff', '#0000ff')
255
>>> diff('#0000ff', '#00000a')
245
So now, we can create a function that uses this function to complete the task:
def get_col_name(hex, colors):
return min([(n,diff(hex,c)) for n,c in colors.items()], key=lambda t: t[1])[0]
Unfortunately, this doesn't work for your colors, since it chooses gray which is [128, 128, 128] so very near to steelblue which is [74, 125, 172] - nearer than blue which is [0, 0, 255]. This means the difference is smaller to gray that to blue. I'll try to think of a better method, but maybe someone has some insight and can drop a comment?
A: How about converting them into RGB and find the dominatant color?
For example
RED FF0000 rgb(255,0,0)
BLUE 0000FF rgb(0,0,255)
steelblue 4A7DAC rgb(74,125,172)
You can most likely achieve this target with the RGB rather than the HEX
The rest you can see this algo: https://stackoverflow.com/a/9018100/6198978
EDIT
The thing is RGB and HEX calculation will not be able to work with Grey color as every color just has closest distance to the grey. For that purpose you can use the HSV values of the color, I am editing the code with the HSV implemented as well :D
Learned alot :D
I was having fun with it here you go:
import math
colors= {
"red":"#FF0000",
"yellow":"#FFFF00",
"green":"#008000",
"blue":"#0000FF",
"black":"#000000",
"white":"#FFFFFF",
"grey": "#808080"
}
# function for HSV TAKEN FROM HERE: https://gist.github.com/mathebox/e0805f72e7db3269ec22
def rgb_to_hsv(r, g, b):
r = float(r)
g = float(g)
b = float(b)
high = max(r, g, b)
low = min(r, g, b)
h, s, v = high, high, high
d = high - low
s = 0 if high == 0 else d/high
if high == low:
h = 0.0
else:
h = {
r: (g - b) / d + (6 if g < b else 0),
g: (b - r) / d + 2,
b: (r - g) / d + 4,
}[high]
h /= 6
return h, s, v
# COLOR YOU WANT TO TEST TESTED
check = "#808000".lstrip('#')
checkRGB = tuple(int(check[i:i+2], 16) for i in (0, 2 ,4))
checkHSV = rgb_to_hsv(checkRGB[0], checkRGB[1], checkRGB[2])
colorsRGB = {}
colorsHSV = {}
for c, v in colors.items():
h = v.lstrip('#')
colorsRGB[c] = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
for c, v in colorsRGB.items():
colorsHSV[c] = tuple(rgb_to_hsv(v[0], v[1], v[2]))
def colourdistanceRGB(color1, color2):
r = float(color2[0] - color1[0])
g = float(color2[1] - color1[1])
b = float(color2[2] - color1[2])
return math.sqrt( ((abs(r))**2) + ((abs(g))**2) + ((abs(b))**2) )
def colourdistanceHSV(color1, color2):
dh = min(abs(color2[0]-color1[0]), 360-abs(color2[0]-color1[0])) / 180.0
ds = abs(color2[1]-color1[1])
dv = abs(color2[2]-color1[2]) / 255.0
return math.sqrt(dh*dh+ds*ds+dv*dv)
resultRGB = {}
resultHSV = {}
for k, v in colorsRGB.items():
resultRGB[k]=colourdistanceRGB(v, checkRGB)
for k,v in colorsHSV.items():
resultHSV[k]=colourdistanceHSV(v, checkHSV)
#THIS WILL NOT WORK FOR GREY
print("RESULT WITH RGB FORMULA")
print(resultRGB)
print(min(resultRGB, key=resultRGB.get))
#THIS WILL WORK FOR EVEN GREY
print(resultHSV)
print(min(resultHSV, key=resultHSV.get))
#OUTPUT FOR RGB
#check = "#808000" output=GREY
#check = "#4A7DAC" output=GREY :D
#OUTPUT FOR RGB
#check = "#808000" output=GREEN
#check = "#4A7DAC" output=BLUE:D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52078258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: 'input' is not defined Pylance(reportUndefinedVariable)
it just started happening, now all "input()" gets yellow underline
But code works properly
A: a=int(input())
if u r keeping any integer values.
A: That happens because you are using input. Use raw_input instead. raw_input is what you have to use with python 2.
A: This problem does not occur in my pylance.
It seems that there are some errors in your vscode's pylance. It doesn't recognize the input() method.
You can try to update the pylance in the extension store or add the following code in settings.json:
"python.analysis.diagnosticSeverityOverrides": {
"reportUndefinedVariable": "none"
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74717107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Check if NSAlert is currently showing up I am using an NSAlert to display error messages on the main screen of my app.
Basically, the NSAlert is a property of my main view controller
class ViewController: NSViewController {
var alert: NSAlert?
...
}
And when I receive some notifications, I display some messages
func operationDidFail(notification: NSNotification)
{
dispatch_async(dispatch_get_main_queue(), {
self.alert = NSAlert()
self.alert.messageText = "Operation failed"
alert.runModal();
})
}
Now, if I get several notifications, the alert shows up for every notification. I mean, it shows up with the first message, I click on "Ok", it disappears and then shows up again with the second message etc... Which is a normal behaviour.
What I would like to achieve is to avoid this sequence of error message. I actually only care about the first one.
Is there a way to know if my alert view is currently being displayed ?
Something like alert.isVisible as on iOS's UIAlertView ?
A: From your code, I suspect that notification is triggered in background thread. In this case, any checks that alert is visible right now will not help. Your code will not start subsequent block execution until first block will finish, because runModal method will block, running NSRunLoop in modal mode.
To fix your problem, you can introduce atomic bool property and check it before dispatch_async.
Objective-C solution:
- (void)operationDidFail:(NSNotification *)note {
if (!self.alertDispatched) {
self.alertDispatched = YES;
dispatch_async(dispatch_get_main_queue(), ^{
self.alert = [NSAlert new];
self.alert.messageText = @"Operation failed";
[self.alert runModal];
self.alertDispatched = NO;
});
}
}
Same code using Swift:
func operationDidFail(notification: NSNotification)
{
if !self.alertDispatched {
self.alertDispatched = true
dispatch_async(dispatch_get_main_queue(), {
self.alert = NSAlert()
self.alert.messageText = "Operation failed"
self.alert.runModal();
self.alertDispatched = false
})
}
}
A: Instead of run modal you could try
- beginSheetModalForWindow:completionHandler:
source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAlert_Class/#//apple_ref/occ/instm/NSAlert/beginSheetModalForWindow:completionHandler:
In the completion handler set the alert property to nil.
And only show the alert if the alert property is nil ( which would be every first time after dismissing the alert).
EDIT : I don't see the documentation say anything about any kind of flag you look for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36157382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Makefile and Bash script for C++ with command line arguments For my homework, I just wrote a c++ program that should supply a command line argument(e.g. -l) when you run it. Now, I need to compile and run my program in Unix. So, I need a makefile and a bash script(the name is cddb) to invoke my program.
My question is that the sequence of two files. The requirement is like I should enter cddb -l to run the program. So, is it like I should write a bash script which invokes the makefile and pass the argument to makefile. Then the makefile taken the argument and compile and run my cpp file?
A: The idea of command line arguments is to change the behaviour of your executable file at run time, so you don't need to re-compile your source code if you want slightly different behaviour.
Just call your program like ./cddb -l and parse the command line arguments in your source code. To parse the arguments you can use the argv and argc variables declared in the main function signature.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37674785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I make window.onbeforeunload wait for animation? Consider the following JavaScript code, with an animation library (i.e. scriptaculous) to boot.
window.onbeforeunload = function(event) {
document.body.fade();
}
Leaving the page is instantaneous and doesn't wait for the animation to complete. Even though everywhere I look people say JS doesn't support threads, something is running in parallel here, because it seems the one will not wait for the other. Am I right about the threads, and is there any way to achieve what I'm trying to do here?
A: A bit late but I think give an answer is interesting for futur SO users.
So there is multiple way to sync your code to this and so you should add a custom waiter.
window.onbeforeunload = function(event) {
document.body.fade();
while ((new Date()).getTime() < (new Date()).getTime()) + (1 *1000));
}
I guess you could also try with promises:
function sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
return resolve(null);
}, time);
});
}
window.onbeforeunload = async function(event) {
document.body.fade();
await sleep(1 * 1000);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9405121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Use plain mode to access kafka I have a Kafka cluster on OpenShift cloud, a customer outside of cloud send message to Kafka cluster, then we set authentication and authorization for Kafka cluster and topic, ans create an user.
Now from external customer can publish messages to kafka topic via SSL or SASL via port 9094, now app inside OpenShift want to consume messages via port 9092 with plain mode, that means, app inside OpenShift doesn't want to use any authentication or authorization to access that topic, do you think if it is possible?
This is my Kafka cluster listener
kafka:
authorization:
type: simple
listeners:
external:
authentication:
type: tls
port: 9094
tls: true
type: route
plain:
port: 9092
tls: false
type: internal
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66510381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inheriting from bad template instantiations in C++ Consider the following code:
struct Foo
{
Foo operator+(const Foo &rhs) const;
// notice lack of: Foo operator*(const Foo &rhs) const;
};
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { return x * y; }
};
I have two questions:
*
*Can I inherit from Bar<Foo> and override mul() to something meaningful?
*Can I inherit from Bar<Foo> without overriding mul() if I never use mul() anywhere?
A: *
*Bar<Foo>::mul() isn't a virtual function, so it cannot be overridden.
*Yes, if you don't use a template member function then it does not get instantiated and you don't get any errors that would result from instantiating it.
You can hide Bar<Foo>::mul() by providing a function of the same signature in a subclass, and because of 2, Bar<Foo>::mul() won't be instantiated. However this is probably not a good practice. Readers are likely to get confused about the hiding vs. overriding, and there's not much benefit to doing this over simply using a different function name and never using mul(), or providing an explicit specialization of Bar for Foo.
A: *
*sure
*sure
Templates are really a kind of smart preprocessor, they're not compiled. If you don't use something, you can write complete (syntactically correct) rubbish, i.e you may inherit from
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { return x.who cares what-s in here; }
};
P.S. since your + operator is used in a const function, it should be declared as const too.
EDIT: OK, not all compilers support this, here's one that compiles with gcc:
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { T::was_brillig & T::he::slith(y.toves).WTF?!0:-0; }
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11263635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send image in PHP mail function I want to send image in mail.How to add image so that it will show in the email
I want to add image to the CLIENT MESSAGE BODY.
How to use html in client message body?
Here is my code :
<?php
/* subject and email varialbles*/
$emailSbuject = 'Enquiry';
$webMaster = '[email protected]';
$emailSbuject2 = 'Thank you';
$client = ' $emailFeild\r\n';
/*gathering data variables*/
$nameFeild = $_POST['name'];
$cityFeild = $_POST['city'];
$countryFeild = $_POST['country'];
$emailFeild = $_POST['email'];
$phoneFeild = $_POST['phone'];
$otherFeild = $_POST['other'];
$questionFeild = $_POST['question'];
$commentFeild = $_POST['comment'];
$phone1Feild = $_POST['phone1'];
$hear1Feild = $_POST['hear1'];
$hear2Feild = $_POST['hear2'];
$hear3Feild = $_POST['hear3'];
$hear4Feild = $_POST['hear4'];
$referralFeild = $_POST['referral'];
$otherhearFeild = $_POST['otherhear'];
// admin message body
$body= <<<EOD
Contact Form Details of $nameFeild
Name: $nameFeild \n
City: $cityFeild \n
Country: $countryFeild \n
Email: $emailFeild \n
Contact Phone: $phoneFeild \n
Other Phone: $otherFeild \n
Question: $questionFeild \n
Comment: $commentFeild \n
Contact Over: $phone1Feild \n
Known Us through: \n
$hear1Feild
$hear2Feild
$hear3Feild
$hear4Feild
$referralFeild
$otherhearFeild
EOD;
// Client message body
$body2 = <<<EOD
Dear $nameFeild
Thank u for contacting IntaxFin. One of our representatives will contact you the soonest. If you have more questions or information needed, please let us know. We are happy to serve you! \n
-From
IntaxFin Team \n http://www.intaxfin.com \n
Like us on Facebook \n
Follow us on Twitter \n
Connect with us on LinkedIn \n
------------------------------------------------------------------------------------------------- e-mail was automatically sent by IntaxFin Administration Directory and is for your reference. Please do not reply to this e-mail address.
Powered by HexCode Technologies Pvt. Ltd.
EOD;
$headers = "From: $emailFeild\r\n";
$header = "From: [email protected]\r\n";
$success = mail($webMaster,$emailSbuject,$body,$headers);
$success1 = @mail($emailFeild,$emailSbuject2,$body2,$header);
/*Result*/
$theResults = <<<EOD
EOD;
echo "$theResults";
header("Location: http://www.intaxfin.com/thankyou.html");
exit;
?>
A: You cannot display images on text/plain emails as shown above. You must send it as text/html.
So you first have to extend your headers like this:
$header = "From: [email protected]\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";
Then you must update your mailcontent replacing \n or linebreaks with html tags <br> or even <p>
Then you also can include image tags having the image you want to show in the email
<img src="http://www.yourserver.com/myimages/image1.jpg">
This will be downloaded from your webserver when recipient opens it.
.
BUT the much better way will be to use phpMailer Class
Using this, you will be able to include any images IN your email, without need to download it from any website. It is easy to learn and absolutely customizable.
By the way: You should use quotation marks for your $body and $body2 values...
$body= "<<<EOD
Contact Form Details of $nameFeild
Name: $nameFeild \n
City: $cityFeild \n
Country: $countryFeild \n"
A: $headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = "<html><head>
<title>Your email at the time</title>
</head>
<body>
<img src=\"http://www.myserver.com/images_folder/my_image.jpg\">
</body>"
mail($email_to, $email_subject , $message,$headers);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26423942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# prefixing parameter names with @
Possible Duplicate:
What does the @ symbol before a variable name mean in C#?
Duplicate:
What does the @ symbol before a variable name mean in C#?
Sometimes I see some C# code where a method-parameter is prefixed with an @, like this:
public static void SomeStaticMethod( SomeType @parameterName ) { }
What is the meaning of this ? Does it has some significant special meaning ?
I am creating an EventListener in NHibernate, and when I let VS.NET generate the interface methods, it generates the OnPostLoad method like this:
public class PostLoadEventListener : IPostLoadEventListener
{
public void OnPostLoad( PostLoadEvent @event )
{
}
}
Why is this ?
A: The @ prefix allows you to use reserved words like class, interface, events, etc as variable names in C#. So you can do
int @int = 1
A: event is a C# keyword, the @ is an escape character that allows you to use a keyword as a variable name.
A: Try and make a variable named class and see what happens -- You'll notice you get an error.
This lets you used reserved words as variable names.
Unrelated, you'll also notice strings prefixed with @ as well -- This isn't the same thing...
string says = @"He said ""This literal string lets me use \ normally
and even line breaks"".";
This allows you to use 'literal' value of the string, meaning you can have new lines or characters without escapes, etc...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1038674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: How to combine and if statement with a formula to concatenate? Trying to combine two formulas together but can't figure out how to get them to work. The concatenate formula is
=IF(OR(UPPER(D6)="",UPPER(D6)="N"),A6,A6&" - "&D6)
The formula was created so that if "Y" was entered in a checkbox (yes), then it would combine two different parts to create a result in a separate box. If "N" is entered then it would not concatenate.
The formula was originally
=IF(OR((AND((A6<>""),(D6<>""))),(AND((B6<>""),(D6<>"")))),IF(A6="",B6,A6),"")
I'm trying to figure out how to put a concatenate formula somewhere in this one, haven't had any luck so far.. Thank you.
A: Most Excel worksheet formulas are not case sensitive, so you don't need UPPER().
Your original formula has a logic error. It can only return TRUE if A is NOT blank. But in the TRUE part, you have another IF statement that is only TRUE if A6 is blank. That situation never happens.
How complicated the formula will be depends on what the logic is. If the result should always be one thing for "n" or a blank input, and another thing for a "y" input, maybe you only need to test for "y" instead of testing for "" and "n".
=if(and(A1="y",B1="y"),X&" - "&Y,X)
If that does not answer your question, please edit your question, provide a data sample and the desired result and explain the logic. Then post a comment, so people get alerted about the update.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63002737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript - Regex/replace optimization I have a script which allows to replace undesired HTML tags and escape quotes to "improve" security and prevent mainly script tag and onload injection, etc.... This script is used to "texturize" content retrieved from innerHTML.
However, it multiples near by 3 my execution time (in a loop). I would like to know if there is a better way or better regex to do it:
function safe_content( text ) {
text = text.replace( /<script[^>]*>.*?<\/script>/gi, '' );
text = text.replace( /(<p[^>]*>|<\/p>)/g, '' );
text = text.replace( /'/g, '’' ).replace( /'/g, '’' ).replace( /[\u2019]/g, '’' );
text = text.replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /[\u201D]/g, '”' );
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
EDIT: here a fiddle: https://fiddle.jshell.net/srnoe3s4/1/. Fiddle don't like script tags in javascript string apparently so I didn't add it.
A: I'll just deal with performance and naive security checks since writing a sanitizer is not something you can do on the corner of a table. If you want to save time, avoid calling multiple times replace() if you replace with the same value, which leads you to this:
function safe_content( text ) {
text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
text = text.replace( /'|'|[\u2019]/g, '’');
text = text.replace( /"|"|"|[\u201D]/g, '”' )
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
If you take into account dan1111's comment about weird string input that will break this implementation, you can add while(/foo/.test(input)) to avoid the issue:
function safe_content( text ) {
while(/<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi.test(text))
text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
while(/'|'|[\u2019]/g.test(text))
text = text.replace( /'|'|[\u2019]/g, '’');
while(/"|"|"|[\u201D]/g.test(text))
text = text.replace( /"|"|"|[\u201D]/g, '”' )
while(/([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g.test(text))
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
in standard tests cases, this will not be a lot slower than the previous code. But if the input enter in the scope of dan1111's comment, it might be slower. See perf demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43539050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Spring Boot SAML 2.0 support I’m implementing sample application which is supposed to combine SAML 2.0, Oauth 2.0 and UMA 2.0. I’ve generated Spring Boot template using initializr.
I’m stuck at the beginning by saml2ogin(). It looks like SAML 2.0 support is missed. RelyingPartyRegistrationRepository is not available. When I browse imports in HttpSecurity class, I have org.springframework.security.saml2 – Cannot resolve symbol “saml2”.
According to the documentation:
https://docs.spring.io/spring-security/site/docs/5.3.x/reference/html5/
SAML 2.0 support should by bundled in spring-boot-starter-security
Have I missed something?
My build.gradle:
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}
A: implementation 'org.springframework.security:spring-security-saml2-service-provider'
As far as I can tell that dependency is marked as optional, so it has to be included explicitly.
https://github.com/spring-projects/spring-security/blob/master/config/spring-security-config.gradle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61074914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Modifying XML file, replacement elements I were trying use those code to Modify XML files in C#.
XDocument doc = XDocument.Load(@"movies.xml");
String target = textBox1.Text;
var node = doc.Descendants("movie").FirstOrDefault(movie => movie.Element("title").Value == target);
node.SetElementValue("title", this.textBox1.Text);
node.SetElementValue("year", this.comboBox1.Text);
Console.WriteLine(node);
doc.Save(@"movies.xml");
the problem is: when I change 'year' element, everything works perfectly. However, when I change the title which I used as a keyword to search in XML file. The code does not do it in this way. Return a NULL error.
My XML file:
<movielist>
<movie>
<title>a movie name</title>
<year>2015</year>
</movie>
<movie>
<title>Another movie name</title>
<year>2000</year>
</movie>
</movielist>
How can I fix it?
A: Ok, I fixed. String target should be out of the function( like put it in main). If not, It will always overwritten.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34083422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: twitter bootstrap layout strange behaviour I have a strange behaviour in screen layout, I do not understand the possible cause:(
I have a vertical grey line on the left and the right of the screen,
See screenshot here:
BTW, I developed using Rails 3 and using Twitter Bootstrap 2.3.2
In facts I do not foresee / I do not want these lines ... I presume it could be some CSS setting (on my one customization css code...), sorry for my ignorance there,
watching the shot here do suggest you something about why the grey vertical line on the left marging and the right margin of the screen layout ?
thanks a lot
giorgio
scss customization file used: http://solyaris4.altervista.org/custom.css.scss
A: Without looking at any CSS and HTML code it is pretty difficult to tell.
But since it looks like you are using the Google Chrome browser, hover over the grey stripe with your mouse, right-click and select Inspect Element. You can then review the html and css code related to what you are looking at. You can also open the Chrome dev console at any time by hitting the CTRL-SHIFT-i keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17928639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add a dynamic button in an external java class? I am having problems with creating public void onCreate(Bundle SavedInstanceState) in another java class.For this reason i cant create a dynamic button in java.I don't know what to do..
this is my java class
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
public static final int WIDTH = 856;
public static final int HEIGHT = 480;
public static final int MOVESPEED = -5;
private long smokeStartTime;
private long missileStartTime;
private MainThread thread;
private Background bg;
private Player player;
private ArrayList<Smokepuff> smoke;
private ArrayList<Missile> missiles;
private ArrayList<TopBorder> topborder;
private ArrayList<BotBorder> botborder;
private Random rand = new Random();
private int maxBorderHeight;
private int minBorderHeight;
private boolean topDown = true;
private boolean botDown = true;
private boolean newGameCreated;
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
}
this is my main java which has contentView of this java class..
public class Game extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GamePanel(this));
}
Please help me to find a solution and create a dynamic button in the GamePanel java class.
A: //in your activity add this for button
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52904017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to determine first and last call of module scoped fixture within session? I have a module scoped fixture that requires to know if it is called for the first or for the last time within a session, is there a way to get this information within fixture?
This is required for managing lifecycle of a shared resource that depends on module scoped options which basically should look like this:
@pytest.fixture(scope='module', autouse=True)
def module_runner():
if not session_start and resource_reload_condition:
shared_resource.dispatch()
shared_resource.set_module_level_options()
if resource_reload_condition:
shared_resource.provision()
yield
if resource_reload_condition:
shared_resource.dispatch()
shared_resource.rollback_module_level_options()
if not session_end and resource_reload_condition:
shared_resource.provision()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48749427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to detect Web Cam is attached or not Using java How to detect whether the Web cam is attached to computer or not by using Java?
A: JMF (Java Media Framework) should be able to detect any media, including a webcam.
Potentially through CaptureDeviceManager.getDeviceList();
For "installing JMF on Linux", one way is simply to:
*
*download it.
*Change directories to the install location.
*Run the command
:
% /bin/sh ./jmf-2_1_1e-linux-i586.bin
A: Here is a piece of code I use in a simple Webcam client with JMF:
Format format = new RGBFormat();
MediaLocator cameraLocator = null;
// get device list
Vector deviceList = CaptureDeviceManager.getDeviceList(format);
// if devices available
if(deviceList != null && deviceList.size() > 0) {
// pick first
CaptureDeviceInfo device = (CaptureDeviceInfo) deviceList.get(0);
cameraLocator = device.getLocator();
}
It picks the first available webcam. Of course, after having the webcam you can store the cameraLocator and try to re-open it on the 2nd run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1388997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Angular JS, scope updates in Async callback I've got a series of 2 AJAX requests, with the latter depending on the results of the first. I've put them into the promise of the first returned object. ie.
var productResource = $resource('http://urlhere');
$scope.product = productResource.get();
$scope.product.$promise.then(function(data) {
var depResource = $resource('http://deps/' + data.code );
$scope.deps = depResource.get();
$scope.$apply();
});
I can see the resource is hit with the appropriate data pulled down in my network tab, but my HTML is not updated. I've just got it within {{ }} brackets to see the results. ie.
Prod - {{ product }}
Deps - {{ deps }}
product resolves the product recieved, but deps remain blank. Why is this?
A: you don't need to $apply since everything is inside the angular event loop what you need is not to destroy the reference to your binding by reassigning the product object.
when you linked your html product either didn't existed or was pointing to an mem address.
when you did
$scope.product = productResource.get();
you reassigned that variable to a different address so the binding was broken. but your html was not rebinded to the new address, this is more likely your problem, you can try making the variable null before reassigning it, not sure thats going to work, or you could make products initially an empty object and then extend it with
productResource.get();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23979478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Destroy a session I Want to destroy a session in my project such that when I click on Logout, it goes to a page "KillSession.jsp" , in that file I've written "session.invalidate();" and then I redirect the user to the Login page.
But if I use the back button on my browser, it goes back to the page I have visited before even when I've logged out.
What to do?
A: Your browser caches it, You need to add header to force your browser not to force it
A: Make sure that you don't cache the last page before you log out. You could do something like:
response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires", 0);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12394614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extracting data from SQL Server using pyodbc import subprocess
import pyodbc
c = dbconn.cursor()
server = r".\SQLEXPRESS01"
database = "test"
dbconn = pyodbc.connect("driver={SQL Server Native Client 11.0};server=" + server + "; database="+ database +"; trusted_connection=yes;",
autocommit=True)
\\unable to write code for table name loop \\
out_path = f"D:\\Projects\\ReferenceModel\\DataFiles\\IN_Download\\Format_Files\\{table_name}.fmt"
bcp_command = f"bcp {table_name} format nul -c -t, -f {out_path} -S {server} -d {database} -T"
cmd_args = f"/c {bcp_command}"
subprocess.call(["cmd.exe", cmd_args])
I am trying to extract table names (suppose 50 tables) of all tables in my database test using pyodbc, but I'm having trouble doing that. I am trying to get table names from database (test) in such a way that I don't have to hard-code it (like I am doing now). Can anyone help me with the code?
Note: trying to use the cursor command to move through all the table names in my database
A: You should be able to invoke bcp.exe directly rather than trying to use cmd.exe /c. This should be all you need...
import subprocess
import pyodbc
server = r".\SQLEXPRESS01"
database = "test"
connection = f"driver={{SQL Server Native Client 11.0}};server={server};database={database};trusted_connection=yes;"
dbconn = pyodbc.connect(connection, autocommit=True)
cursor = dbconn.cursor()
cursor.execute("SELECT name FROM sys.tables")
for row in cursor:
table_name = row[0]
out_path = f"D:\\Projects\\ReferenceModel\\DataFiles\\IN_Download\\Format_Files\\{table_name}.fmt"
args = [ "bcp.exe", f"{database}.dbo.{table_name}", "format", "nul", "-c", "-t,", f"-f{out_path}", f"-S{server}", "-T"]
subprocess.call(args)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62527576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Saving canvas drawing to sd card I m currently working on canvas drawing in which i hv a canvas with white colored background ( with canvas.drawColor(Color.WHITE);) and a sketched image of cartoons comics that allows to paint with some colors. The problem is that when i go to save the canvas image only a black screen with color done get saved neither the canvas white background nor the sketched image is appeared..
I m using this code for saving canvas
public void saveAsJpg (File f)
{
String fname = f.getAbsolutePath ();
FileOutputStream fos = null;
try
{
fos = new FileOutputStream (f);
mBitmap.compress (CompressFormat.JPEG, 95, fos);
Toast.makeText (getApplicationContext(), "Saved " + fname, Toast.LENGTH_LONG).show ();
}
catch (Throwable ex)
{
Toast.makeText (getApplicationContext(), "Error: " + ex.getMessage (), Toast.LENGTH_LONG).show ();
ex.printStackTrace ();
}
}
Please help,,,,
Thnx in advance
A: Have you tried this?
Write in your manifest file this permittion. . .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
A:
I got my drawing get saved. The changes i need to made in code is to create a bitmap along-with the canvas by command mCanvas = new Canvas( mBitmap );, which turn my canvas background as the image background..
Previously i had only started to painting the canvas which has black color background by default.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5295041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send a handleSubmit on react hook form in typescript? I am doing a form sign-up using typescript and react, however, I am facing a typing error when I try to submit handleSignup function. Here is my code:
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { api } from "../../services/api";
export const Signup = () => {
const schema = yup.object().shape({
name: yup.string(),
email: yup.string(),
password: yup.string(),
address: yup.object().shape({
zipCode: yup.string(),
number: yup.number(),
complement: yup.string(),
})
})
interface signUpCredentials {
name: string
email: string
password: string
address: {
zipCode: string
number: number
complement: string
}
}
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
resolver: yupResolver(schema)
})
const handleSignup = ({ address, email, name, password }: signUpCredentials ) => {
api
.post("/users/signup", { address, email, name, password })
.then((response) => {
console.log("Created")
})
.catch((err) => {
console.error("Not created")
})
}
return (
<form
onSubmit={handleSubmit(handleSignup)}
>
<input
{...register("name")}
placeholder="name"
/>
<input
{...register("email")}
placeholder="email"
/>
<input
{...register("password")}
placeholder="password"
/>
<input
{...register("address.zipCode")}
placeholder="zipCode"
/>
<input
{...register("address.number")}
placeholder="number"
/>
<input
{...register("address.complement")}
placeholder="complement"
/>
<button type="submit" >
Submit
</button>
</form>
)
}
The problem that I am facing is exactly *
onSubmit={handleSubmit(handleSignup)}
*
*
I am receiving:
Argument of type '({ address, email, name, password }: signUpCredentials) => void' is not assignable to parameter of type 'SubmitHandler'.
Types of parameters '__0' and 'data' are incompatible.
Type '{ [x: string]: any; }' is missing the following properties from type 'signUpCredentials': name, email, password, addressts(2345)
A: You have not specified the type variable signUpCredentials to the useForm hook, and you should change the onSubmit handler to handleSignup and call the handleSubmit inside that. So, your code should look like this,
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { api } from "../../services/api";
export const Signup = () => {
const schema = yup.object().shape({
name: yup.string(),
email: yup.string(),
password: yup.string(),
address: yup.object().shape({
zipCode: yup.string(),
number: yup.number(),
complement: yup.string(),
})
})
interface signUpCredentials {
name: string
email: string
password: string
address: {
zipCode: string
number: number
complement: string
}
}
const {
register,
formState: { errors },
handleSubmit,
} = useForm<signUpCredentials>({
resolver: yupResolver(schema)
})
const handleSignup = handleSubmit(data: signUpCredentials) => {
console.log(data)
// do api stuff here
}
return (
<form
onSubmit={handleSignup}
>
<input
{...register("name")}
placeholder="name"
/>
<input
{...register("email")}
placeholder="email"
/>
<input
{...register("password")}
placeholder="password"
/>
<input
{...register("address.zipCode")}
placeholder="zipCode"
/>
<input
{...register("address.number")}
placeholder="number"
/>
<input
{...register("address.complement")}
placeholder="complement"
/>
<button type="submit" >
Submit
</button>
</form>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
For a better understanding, I created a Code Sandbox link where I have removed the import statement to services as we don't have that, and you can see the function is called without any warnings/errors by checking the console.
Ref: React Hook form (TS)
A: No need to change the onSubmit as mentioned by @sri-vineeth.
Just use SubmitHandler type.
const handleSignup: SubmitHandler<SignUpCredentials> = ({ address, email, name, password }) => {
...
}
Also please note that interfaces and types should use PascalCase. Therefore change signUpCredentials to SignUpCredentials.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72638620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mPDF how to leave all content on a single page I want to export an HTML to pdf using mPDF, but I want everything to be on a single page, without any page breaks.
How can I do that?
A: "mPDF has limited scope to control when automatic page-breaks occur, and does not have ‘widows’ or ‘orphans’ protection."
https://mpdf.github.io/paging/page-breaks.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70008061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to stick object inside fov I'm trying to figure out how to position an object inside the edge of the camera's fov if it goes outside of it.
I've looked at this: Three.js - Width of view
But if I plug in the values, it returns 5.12 if the screen width is 512, and 3.12 for height if the screen height is 320.
I have the camera positioned -150 on the z axis, and the objects are located at 0 on the z axis.
I was hoping it would tell me how much x and y distance there is visible in the fov where z axis is 0 if camera is looking along the z axis. That way I could position objects if they go outside the limits.
Anyone know how to get this data?
A: Okay, I found the answer. Had to use some trigonometry.
h = tan(fov/2)*dist
dist is the distance to the object from the camera. h is half of the screen space in y axis.
to get x axis multiply by (screenwidth/screenheight)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33641184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set "reset all code reviewer votes" in Azure Devops using CLI Currently trying to automate branch policy creation in AzureDevOps using the Azure CLI with Windows Powershell, is there a way to enable "Reset all code reviewer votes" when new changes are applied through the CLI?
currently have the following:
az repos policy approver-count create --allow-downvotes false --blocking true --branch dev --creator-vote-counts true --enabled true --minimum-approver-count 1 --repository-id $repoID --reset-on-source-push true
and so far it only ticks/enables the "Reset all approval votes (does not reset votes to reject or wait)" option
Thanks in advance!
A: Hi one of the options is to use Azure DevOps REST API of Policy Configuration, however you need to construct JObject arrays and use PUT Request.
what you need is on the resetOnSourcePush and maybecreatorVoteCounts
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68288440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rotativa multiple PDF generation I am using rotativa to generate PDF.I want to generate multiple PDF based on the number of records in the list below code generate only one pdf.
public ActionResult PreviewPDF(string month,string year)
{
string basePath = ConfigurationManager.AppSettings["PDFPath"];
string fullPath = string.Empty;
string message = CreatePath(basePath, month, year, out fullPath);
if(message.Trim()=="")
{
List<FundMaster> lstFundMaster = commonRepo.GetFundMaster();
foreach(FundMaster fund in lstFundMaster)
{
return RedirectToAction("PDFFactSheetData", "FactSheet", new { fundCode = fund.FundCode, filePath = fullPath });
}
}
return Json(message, JsonRequestBehavior.AllowGet);
}
above action will be called when i click on Preview PDF button where in based on the numbers of records in lstFundMaster List i want to generate a PDFs.Below action is responsible to generate the PDF
public ActionResult PDFFactSheetData(string fundCode="BAL",string filePath="")
{
FactSheet factSheetData = new FactSheet();
factSheetData = factsheetRepo.GetFactSheetData(fundCode);
FundInvestmentStyle investmentStyle = factSheetData.InvestmentStyle;
string pdfFileName = fundCode + ".pdf";
string fullFilePath = Path.Combine(filePath, pdfFileName);
return new ViewAsPdf(templateName, factSheetData) { FileName = pdfFileName, PageSize = Rotativa.Options.Size.A4, SaveOnServerPath = fullFilePath };
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45707565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Load Datetime column in SQL server 2012 using SSIS I'm looking to load a transaction file from a flat file to database. the file contain datetime column which is displayed like this "20160307092701" and I want to display it in the database like "2016-03-07-09-27:01" using SSIS.
I choose my database column to be set as smalldatetime and on the source file and I convert it DT_DBTIME but it showing NULL values when I load the data to SQL server. I have tried all the possible date option in SSIS but still showing Null value.
Check the Error in SQL server:
A: The format you show you want cannot use smalldatetime because that is not the format of the data type you selected on your destination table. The destination date format would be like 2016-03-07 09:27:00, but if you want it as 2016-03-07-09-27:01 then you will have to store that as a string in your table.
As well the input value is returning a NULL because SSIS cannot convert that format into a date. You would have to use an expression or Script Task of some sort in order to parse that value out to the end format you want it, before sending it to your destination.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35979176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add Msctf.dll as reference path to c# project? I need to write a COM object in c# inorder to utilize i need to add Msctf.dll as reference to C# project .
A: Right click on Add Reference of your project and browse to your path of Msctf.dll
link (Register COM) : http://msdn.microsoft.com/en-us/library/ms859484.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12176702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Sharing web application for different clients Our framework is Grails. Say domain.com contains an application and currently used by some client. If we want to allow another client with the same functionality but providing a separation for the data of two clients, so that they can't mix both, how to do this? And whenever we want to add n clients to this application, what is the best method to be followed, so that with less / no configuration we can share the common war file for these clients by separating the db.
How the real time web development handle these type of situations?
And, one more point is how to provide client1.domain.com works for client1 and client2.domain.com works for client2. How to make the war file (in Java / Grails) to work like this? Otherwise we have to programmatically control the clients with in the project for every feature to be allowed or unnecessarily maintain separate war file for each client, which will be a waste of resources.
A: You're describing multitenancy - create one table for N 'tenants' instead of N identical (or nearly) tables, but partition it with a tenant_id column, and use that to filter results in SQL WHERE clauses.
For example the generated code for findByUsername would be something like select * from person where username='foo' and tenant_id=3' - the same code as a regular call but with the tenant_id column to restrict within that tenant's data.
Note that previously simple things like unique constraints are now harder because you would want to restrict uniqueness within a tenant, but allow a value to be reused across tenants. In this case changing the unique constraint to be on the combo of username and tenant_id works and does the heavy lifting in the database.
For a while there were several related plugins, but they relied on tweaking internal APIs and some features broke in newer Hibernate versions. But I believe that http://grails.org/plugin/multi-tenant-single-db is active; it was updated over a year ago, but it is being used. Contact the authors if it looks like it'll be what you need to be sure it's active. Note that this can only work with Hibernate 3.x.
Hibernate 4 added support for multitenancy, but I haven't heard much about its use in Grails (which is expected, since it's not that common a requirement). It's not well documented, but this bug report highlights some of the potential pitfalls and should still be a working example (the test app is still on GitHub): https://jira.grails.org/browse/GPHIB-6.
I'd like to ensure that this is working and continues to work, so please let me know via email if you have issues later. It's a great feature and having it in Hibernate core makes things a lot easier for us. But we need to make it easy to use and well-documented, and that will happen a lot faster when it's being used in a real project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26327941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: KineticJS not working in FF and IE My program works perfectly in Chrome, but with FF and IE my canvasses are gone.
The error I got with Firefox is:
SyntaxError: An invalid or illegal string was specified:
...][c].apply(this[b],args)}})(c)}}(),function(){Kinetic.Filters.Grayscale=function...
On kineticJS.js (line 28) (KineticJS JavaScript Framework v4.4.0)
The error I got with IE is:
SCRIPT5022: SyntaxError
h.addColorStop(g[i],g[i+1])
on kineticJS.js, line 28 character 7356
Does somebody know whats going on?
EDIT 3:
When I use fill: 'white' instead of
background = new Kinetic.Rect({
x: 0,
y: 0,
fillRadialGradientStartPoint: 0,
fillRadialGradientStartRadius: 0,
fillRadialGradientEndPoint: 0,
fillRadialGradientEndRadius: 800,
fillRadialGradientColorStops: [0, '#262834', 1, '0f1114'],
width: browserwidth,
height: browserheight,
name: 'background'
});
That is placed in 'background' Rect that scales with the browserheight I got no erros in IE 10, 9 and FF.
But why is it happen only with fillRadialGradient and only in IE and FF? It has a connection with the error I mentioned before:
h.addColorStop(g[i],g[i+1])
on kineticJS.js, line 28 character 7356
What it makes more strange is that I have another object with radialgradientfill which works fine in FF and IE.
var lichtrondje = new Kinetic.Circle({
x: 0,
y: 0,
radius: 90,
fillRadialGradientStartPoint: 0,
fillRadialGradientStartRadius: 0,
fillRadialGradientEndPoint: 0,
fillRadialGradientEndRadius: 90,
fillRadialGradientColorStops: [0, '#DDD', 1, 'rgba(0,0,0, 0.0)'],
opacity: 1,
id: 'lichtrondje' + x,
name: 'lichtrondje'
});
I have found out that the result looks different between the Chrome version and the FF and IE version. The right one is what its intended.
A: I believe you are missing a # in the fillRadialGradientColorStops array
0f1114 --> #0f1114
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16101641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JVM crashing when using any other Hibernate inheritance strategy besides SINGLE_TABLE Ok, this is probably a longshot but here goes.
In Java (JRE 1.6.0_26-b03) I have two classes, SuperControl and its subclass SubControl. They both need to be persistent objects and I'm using Hibernate Annotations to achieve this. I have approximately 210 classes that are being persisted correctly. Except one isn't.
My problem is that SubControl refuses to inherit in any way besides SINGLE_TABLE. When I say "refuses", I mean that the entire JRE crashes.
This is a bit problematic because I'd really prefer SuperControl to be a mapped superclass of SubControl. SuperControl can also be a persistent entity in its own right. The strange thing is that I have an exactly parallel hierarchy in my code elsewhere that works correctly.
This is what I want:
@Entity
@MappedSuperclass
public class SuperControl extends ItsSuperClass {
// ...
}
@Entity
public class SubControl extends SuperControl {
// ...
}
but it bombs out with the error
#
# A fatal error has been detected by the Java Runtime Environment:
#
# Internal Error (c1_Optimizer.cpp:271), pid=5456, tid=1260
# guarantee(x_compare_res != Constant::not_comparable) failed: incomparable constants in IfOp
#
# JRE version: 6.0_26-b03
# Java VM: Java HotSpot(TM) Client VM (20.1-b02 mixed mode, sharing windows-x86 )
# An error report file with more information is saved as:
# C:\eclipse\hs_err_pid5456.log
Without supplying any inheritance hint, Hibernate defaults to SINGLE_TABLE (which I can tell thanks to the creation of a DTYPE column). I can explicitly specify this without the JVM crashing.
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class SuperControl extends ItsSuperClass {
// ...
}
@Entity
public class SubControl extends SuperControl {
// ...
}
The worst part is that if I remove the SubControl class ENTIRELY, or even just its mapping in the hibernate.cfg.xml file, the JVM still crashes. This leads me to believe that there's some kind of hidden linkage between SuperControl and SubControl. Maybe something cached in Eclipse or the like. I've restarted Eclipse, done several clean-and-builds, and even restarted my machine, and the problem's still there.
Any ideas? I've been working on this for hours and have gotten nowhere.
Thanks!
A: This looks like a bug 7042153, aka 2210012 reported in early May.
Note the workaround offered by one user: using the "-server" JVM option fixed it for them.
A: Try Java 1.6.0_20, and check if that works. You have found a JVM bug, and going back 6 minor versions might be enought to get this running.
You are lucky in the way that this bug is reproducable, so create a minimal testcase and post it to the Oracle bug database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6553428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I make a python API to ping an ip address? So I have a discord bot and I want to add a feature where it pings an IP and tells you if it's online or not. I wanted to use an API in flask in case I use it for other projects.
A: In order to ping using python, you can use the pythonping package.
You can also easily use it in flask.
A sample of the package at play is shown below.
import flask
from pythonping import ping
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return ping('127.0.0.1', verbose=True)
app.run()
A: You can use the requests package to perform this operation as follows:
import requests
url = 'https://stackoverflow.com/'
is_up = requests.get(url).status_code == 200
print(f'{url}, up_status={is_up}')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68064613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Sitecore: How to get the class entered in General Link field In the General Link field content author will set some class.
I want to change the class while rendering, so I used the reflector and got the code of Link.cs and trying to extend the PopulateParameters method and looks like this.CssStyle and this.CssClass are always blank. Is there any way to get the value of class entered in the General Link field?
A: Cast your field to LinkField class and use Class property:
LinkField field = Sitecore.Context.Item.Fields["Link"];
string cssClass = field.Class;
**EDIT: **
If you want to change behaviour of Sitecore sc:link to change css class of every link, you need to add your own processor to the renderField pipeline:
public class UpdateLinkClass
{
public void Process(Sitecore.Pipelines.RenderField.RenderFieldArgs args)
{
if (args != null && (args.FieldTypeKey == "link" || args.FieldTypeKey == "general link"))
{
Sitecore.Data.Fields.LinkField linkField = args.Item.Fields[args.FieldName];
if (!string.IsNullOrEmpty(linkField.Class))
{
args.Parameters["class"] = linkField.Class + "-custom";
}
}
}
}
and register it before GetLinkFieldValue processor:
<processor type="My.Assembly.Namespace.UpdateLinkClass, My.Assembly" />
<processor type="Sitecore.Pipelines.RenderField.GetLinkFieldValue, Sitecore.Kernel" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27136867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Read system Call I am trying my hands with unix socket programming in C. But while reading I am getting Err No as 4. I am unable to find out the description of this error code. Does anybody have any idea?
A: If you would start with looking at ultimate source of Unix error code names (/usr/include/errno.h) you'll arrive at the file which contains your error code as
#define EINTR 4 /* Interrupted system call */
(Which is this file is left for you to find out, as an exercise ;))
A: The errno values can be different for different systems (even different Unix-like systems), so the symbolic constants should be used in code.
The perror function will print out (to stderr ) a descriptive string of the last errno value along with a string you provide.
man 3 perror
The strerror function simply returns a const char * to the string that perror prints.
If 4 is EINTR on your system then you received a signal during your call to read. There are ways to keep this from interrupting your system calls, but often you just need to:
while (1) {
ssize_t x = read(file, buf, len);
if (x < 0) {
if (errno == EINTR) {
errno = 0;
continue;
} else {
// it's a real error
A: If you're getting EINTR, it probably means you've installed a signal handler improperly. Good unices will default to restartable system calls when you simply call signal, but for safety, you should either use the bsd_signal function if it's available, or call sigaction with the restartable flag to avoid the headaches of EINTR.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3602384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: add custom class to wysihtml5 text editor I'd like to be able to add a button that adds my own custom class. I don't see this in the documentation anywhere but seems like a common request.
For example.
Highlighting "Some Text" and pressing the button "Custom Class" will add
<p class="wysiwyg-custom-class">Some Text</p>
A: Define new command, my example is based on ForeColor:
(function(wysihtml5) {
wysihtml5.commands.setClass = {
exec: function(composer, command, element_class) {
element_class=element_class.split(/:/);
element=element_class[0];
newclass=element_class[1];
var REG_EXP = new RegExp(newclass,'g');
//register custom class
wysihtml5ParserRules['classes'][newclass]=1;
return wysihtml5.commands.formatInline.exec(composer, command, element, newclass, REG_EXP);
},
state: function(composer, command, element_class) {
element_class=element_class.split(/:/);
element=element_class[0];
newclass=element_class[1];
var REG_EXP = new RegExp(newclass,'g');
return wysihtml5.commands.formatInline.state(composer, command, element, newclass, REG_EXP);
}
};
})(wysihtml5);
usage:
HTML:
<div id="uxToolbar">
<button data-wysihtml5-command="setClass" data-wysihtml5-command-value="span:my-wysihtml5-custom-class" type="button" title="View HTML" tabindex="-1" class="btn btn-mini">
My class
</button>
</div>
so as you can see value is from two parts: element:class
DEMO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13869587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Download URL text file directly to csv file python I have a link to a text file from US Census and I would like to download it into a directory on my computer.
I was thinking about downloading the URL into a text file and then converting the text file into a csv later on. However, I was wondering if it were possible to download directly to a csv file? If it's possible, would appreciate an example.
This is the link to the data:
https://www.census.gov/construction/bps/txt/tb2u2010.txt
A: I may be wrong here, but saving that as a .csv file would not be easy. I don't know Python very much but I'll leave my two cents here:
import urllib.request # lib that handles URLs
target_url = "https://www.census.gov/construction/bps/txt/tb2u2010.txt"
data = urllib.request.urlopen(target_url)
with open('output.txt', 'w') as f: # change this to .csv
for line in data:
f.write(str(data.read()))
This will create a .txt with everything from the website on a single line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53144967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sprint boot: POST an entity with a foreign key I am playing around with Spring boot and I am trying to post an entity that has foreign keys
Example: product (id,code, description, category) and category(id, category)
To post a product i would post {"code":"123","description":"bananas"}
How would I specify the category?
{"code":"123","description":"bananas","category":1} doesn't seem to work
I saw a post here relating to Spring Data that sugested using the URI of the primary table https://stackoverflow.com/questions/44497114/post-an-entity-with-spring-data-rest-which-has-relations
is there a simpler way ?
A: One option is to specify category as json object like below
{"code":"123","description":"bananas","category": { "id" : 1}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59389617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Uncaught Reference Error: draw is not defined I am trying to complete This tutorial on making a tic tac toe game using JavaScript and HTML5.
I've followed each step in the video multiple times. While my code seems to match the code in video I keep encountering an error: Uncaught Reference Error: draw is not defined. The error occurs in line 12.
I must be overlooking something. Can anyone point it out?
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe!</title>
<script type="text/javascript">
var c, canvas;
var turn = 1;
window.onload = function() {
canvas = document.getElementById("canvas");
c = canvas.getContext("2d");
draw();
}
var moves = [];
window.onclick = function(e) {
if(e.pageX < 500 && e.pageY < 500) {
var cX = Math.floor(e.pageX / (500 / 3));
var cY = Math.floor(e.pageY / (500 / 3));
var alreadyClicked = false;
for(i in moves) {
if(moves[i][0] == cX && moves[i][1] == cY) {
alreadyClicked = true;
}
}
if(alreadyClicked == false) {
moves[(moves.length)] = [cX, cY, turn];
turn = turn * -1;
draw();
}
}
var bg = new Image();
var x = new Image();
var o = new Image();
bg.src = "ttt_board.png";
x.src = "ttt_x.png";
o.src = "ttt_o.png";
function draw() {
c.clearRect(0, 0, 500, 500);
c.drawImage(bg, 0, 0);
for(i in moves) {
if(moves[i][2] == 1) {
c.drawImage(x, Math.floor(moves[i][0] * (500 / 3) + 10), Math.floor(moves[i][1](500 / 3) + 10))
} else {
c.drawImage(o, Math.floor(moves[i][0] * (500 / 3) + 10), Math.floor(moves[i][1] * (500 / 3) + 10));
}
}
}
};
</script>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
</body>
</html>
A: The problem is that draw is defined in window.onclick, but you are trying to call it from window.onload. Are you sure you do not have a closing bracket missing before the definition of draw?
A: Try moving the draw() function out of the window.click function.
window.onclick = function(e) {
// ...
};
function draw() {
// ...
}
One of the major benefits of being strict with your indentation is that you can pick up these bugs very quickly.
window.click = function(e) {
// ...
function draw() {
// ...
}
};
Is the code you had.
A: As a result of draw being located inside of the window.onclick anonymous function, it is scoped there. Since window.onload does not share the scope of that anonymous function, you cannot access draw from window.onload. You should removed the draw function from your window.onclick event so that it may be called from other scopes.
function draw(){}
window.onload = function(){ /*code*/ };
window.onclick = function(){ /* code */ };
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18983963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Heroku ActionView::Template::Error (undefined method `name' for nil:NilClass) First time posting on here. I've got a problem with my web-app when trying to open it through heroku. The app is successfully built by Heroku but when I try to open the app I get the following error:
2017-03-13T06:15:35.778714+00:00 app[web.1]: I, [2017-03-13T06:15:35.778662 #4] INFO -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] Completed 500 Internal Server Error in 232ms (ActiveRecord: 18.7ms)
2017-03-13T06:15:35.779870+00:00 app[web.1]: F, [2017-03-13T06:15:35.779817 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964]
2017-03-13T06:15:35.780386+00:00 app[web.1]: F, [2017-03-13T06:15:35.779874 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] ActionView::Template::Error (undefined method `name' for nil:NilClass):
2017-03-13T06:15:35.780553+00:00 app[web.1]: F, [2017-03-13T06:15:35.780501 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] 7: <tr>
2017-03-13T06:15:35.780554+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 8: <% row_cities.each do |city| %>
2017-03-13T06:15:35.780555+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 9: <td>
2017-03-13T06:15:35.780556+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 10: <h3><%= city.name if city.name %></h3>
2017-03-13T06:15:35.780557+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 11: <p><%= city.country %></p>
2017-03-13T06:15:35.780558+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 12: <%= link_to "See More", city_path(city) %>
2017-03-13T06:15:35.780559+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964] 13: </td>
2017-03-13T06:15:35.780602+00:00 app[web.1]: F, [2017-03-13T06:15:35.780550 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964]
2017-03-13T06:15:35.780655+00:00 app[web.1]: F, [2017-03-13T06:15:35.780610 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] app/views/home_page/home.html.erb:10:in `block (2 levels) in _app_views_home_page_home_html_erb__1188228438750051727_70102451451540'
Here is the problematic code (views: home.html.erb):
<div class="container-fluid text-center">
<table>
<% @cities.in_groups_of(3) do |row_cities| %>
<tr>
<% row_cities.each do |city| %>
<td>
<h3><%= city.name %></h3>
<p><%= city.country %></p>
<%= link_to "See More", city_path(city) %>
</td>
<% end %>
</tr>
<% end %>
</table>
</div>
And the controller this belongs to just in case (home_page_controller.rb):
class HomePageController < ApplicationController
def home
@cities = City.all
end
end
I've been at this problems for two weeks now and have looked at other questions similar to this. I've tried all answers to no success.
Any help is appreciated.
Regards,
Llausa
P.S Here is how it looks on my localhost server and how I'd like it to look on heroku
How I'd like it to look - image here
A: This is because you are using in_group_of with no option. Replace your code with this:
<div class="container-fluid text-center">
<table>
<% @cities.in_groups_of(3,false) do |row_cities| %>
<tr>
<% row_cities.each_with_index do |city,index| %>
<td>
<h3><%= city.name %></h3>
<p><%= city.country %></p>
<%= link_to "See More", city_path(city) %>
</td>
<% end %>
</tr>
<% end %>
</table>
</div>
More info here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42757847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make images snap to any "outline" image (using "animals on the beach" demo) I'm new to Konvasjs and new to canvas and I've been try to make a game similar to the demo "animals on the beach" I wanna keep the part where if it in the right outline the score increases but instead of the animals in the demo snapping to their specific outline I want the animal to be able to snap to any outline so the player can get a wrong answer, or get less score.
Sorry if what I'm asking is actually a lot of stuff.
A: I found an alternative solution this may not automatically allow drag objects to snap to every snap zone but it does allow you to control it with less code.
I created a function to get the object(code) and the zone(outline):
function snapTo(code, outlineSnap) {
var outline = outlines[outlineSnap + '_black'];
if(isNearOutline(code, outline)) {
code.position({
x : outline.x,
y : outline.y
});
console.log("privKey:"+ privKey);
console.log("Key:"+ key);
console.log(code.id());
codeLayer.draw();
var testKey = privKey+ "_black";
if(code.id() == outlineSnap) {
setTimeout(function() {
code.draggable(false);
}, 50);
}
}
}
This function has to be in created the for(var key in codes) {} and outside the drag events. I then called the function inside the dragend event.
code.on('dragend', function() {
snapTo(code, "pstart");
snapTo(code, "pend");
}
There's a bit of an issue with adding the score, I have found a solution that just yet other than keeping the if statement to change draggable to false for the right object outline combination, as if this it taken out the user could 'farm' the drag feature for points...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36745500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you sort the output of a python command? Python beginner here. Let's say that I have something at the end of my script that queries info from a system and dumps it into this format:
print my_list_of_food(blah)
and it outputs a list like:
('Apples', 4, 4792320)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Pumpkins', 1, 5074944)
('more stuff', 4545, 345345)
How do I then sort that output based on the 2nd field so that it would look like this:
('Pumpkins', 1, 5074944)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Apples', 4, 4792320)
Other than importing a bash command to cut -d "," -f 2 | head 4 I'd rather use python. I know I can use sorted or sort to sort an existing tuple or dictionary but I'm not sure of how to sort the output of a print. I've done some research and everything points to implementing sort into my script instead of sorting a print output but who knows, maybe someone has a solution. Thanks.
UPDATE:
Thanks everyone. I've tried to make all of the solutions work but I keep getting this error:
File "test.py", line 18, in <lambda>
print sorted(my_list_of_food(blah), key=lambda x: x[1])
TypeError: 'int' object is unsubscriptable
File "test.py", line 18, in <lambda>
print(sorted(my_list_of_food(blah), key=lambda k: k[1]))
TypeError: 'int' object is unsubscriptable
I tried to include this at the beginning of the script:
from __future__ import print_function
but no luck.
A: You can use the key argument to the sort. In your case,
print(sorted(list_of_food, key=lambda k:k[1]))
will do the trick. The key function should return an integer, usually.
A: You can't sort after outputting to stdout. Well, you shouldn't, since it's heavily complicating a simple task. Instead, you sort the value and print the result:
print sorted(my_list_of_food(blah), key=lambda x: x[1])
The part where you were having difficulties is sorting by the second field; that's why that key argument is there - to override the default ordering (which would be the first item of the tuple). To learn more about key functions, check this section on the python Sorting HOW TO
If you're still wondering, technically, you could sort the stdout output if you replaced sys.stdout with a wrapper object that buffered the output then sorted and printed it (to the real stdout) periodically, but it's pointless and hard to get right, IMHO.
A: If it prints out that way, than either my_list_of_food(blah) returns a string, or it returns a class instance that has a __repr__ method that returns that string... Your best bet is to get data in the actual list format before it becomes a string.
If it returns a class instance, get the list and sort on it using key... Otherwise you need to parse the text, so I'll address that part only:
# this is assuming the structure is consistent
# function to parse a line of the form "('{text}', {int}, {int})" into tuple members using regex
import re
re_line = re.compile(r"\('(?P<name>\w*)',\s?(?P<int1>\d+)\s?,\s?(?P<int2>\d+)\)")
def ParseLine(line):
m = re_line.match(line)
if m:
return (m.group('name'), int(m.group('int1')), int(m.group('int2')))
# otherwise return a tuple of None objects
else:
return (None, None, None)
# final sorted output (as tuples of (str, int, int) )
sorted(
[ParseLine(line) for line in my_list_of_food(blah).splitlines()],
key = lambda tup: tup[1]
)
A: OK: If you really have to do it that way: capture the output of the function in
a StringIO object and sort the lines read back from that object.
import sys
try:
from StringIO import StringIO
except:
from io import StringIO
a = [ ('Apples', 4, 4792320),
('Oranges', 2, 2777088),
('Pickles', 3, 4485120),
('Pumpkins', 1, 5074944),
('more stuff', 4545, 345345) ]
[Step 1]
out = StringIO() # create a StringIO object
sys.stdout = out # and redirect stdout to it
for item in a : print (item) # print output
sys.stdout = sys.__stdout__ # redirect stdout back to normal stdout
out.seek(0) # rewind StringIO object
s = out.readlines() # and read the lines.
[Step 2: define a key function to split the strings at comma,
and compare the 2nd field numerically. ]
def sortkey(a):
return int(a.split(',')[1].strip())
[Step 3: sort and print]
s.sort(key=sortkey)
for line in s: print (line)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14613099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: git: recover local file overwritten by a checkout Consider a local file in a git repo called foo/bar.js. The file has been changed locally, and was accidentally overwritten by a previous commit:
$ git log foo/bar.js
commit 052b65bdf19ee4c977ce4d07e9d6fda60a793e0c
Author: Adam Matan ([email protected])
Date: Sun May 21 16:47:22 2017 +0300
...
$ git checkout 052b65bdf19ee4c977ce4d07e9d6fda60a793e0c foo/bar.js
Local changes seem to be lost, as the local file is overwritten by the checkout, and has no track in the git repo. Am I missing a way to recover the file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44494099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: fpdf error and view table error
$sqlinsert="SELECT * FROM imagetable ";
$result = mysqli_query($con, $sqlinsert);
echo "<table border='1'>";
echo "<tr>
<th>ID</th>
<th>School Code</th>
<th>Category</th>
<th> School name </th>
<th> School Address </th>
<th> School name </th>
</tr>";
while($row = mysqli_fetch_assoc($result)){
$id= $row['ID'];
echo "<tr>
<td>";
echo $row['ID'];
echo "<td>";
echo $row['category'];
echo "<td>";
echo $row['sname'];
echo "<td>";
echo $row['sadd'];
echo "<td>";
echo $row['filename'];
echo "<td>";
?>
<form name="form" method="POST" action="parentssubmit.php">
<input type="hidden" value="<?php echo $id;?>" name="search">
<input type="submit" value="View" name="View">
</form>
<?php }
echo "</td></tr>";
echo "</table>";
========================================================================
if (isset($_POST['View']) ){
$pdf=new fpdf();
$pdf->ADDPage();
$pdf->setfont('Arial','B', 16);
$pdf->Cell(40,10, 'sname',1,0,'c');
$pdf->Cell(40,10, 'sadd',1,0,'c');
$pdf->Cell(40,10, 'category',1,0,'c');
$pdf->Cell(40,10, 'scode',1,0,'c');
$con = mysqli_connect("localhost","root","","school");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$file_filename=$_FILES['file']['name'];
$target_path = "Newfolder1";
$image_path = $target_path . DIRECTORY_SEPARATOR . "filename";
$image_format = strtolower(pathinfo('filename', PATHINFO_EXTENSION));
$sql="SELECT * FROM imagetable WHERE ID= '$_POST[search]'";
$result = mysqli_query($con, $sql);
if(!mysqli_query($con, $sql)){
die( "Could not execute sql: $sql");
}
// build the data array from the database records.
While($row = mysqli_fetch_array($result)) {
$pdf->Cell(40,10, $row['sname'],1,0,'c');
$pdf->Cell(40,10, $row['sadd'],1,0,'c');
$pdf->Cell(40,10, $row['category'],1,0,'c');
$pdf->Image($image_path,50,100,50,20,$image_format);
$pdf->ln();}
}
$pdf->output();
this is two pages and error is coming out Undefined index:
file Undefined index: file so please try to point out the mistake because main error is showing when i added the image field then the error is started popping out.
*
*I am trying to fetch the image from the database and trying to show it in PDF format.
A: First, you should close all your <tr> and <td> tags. Second, you're not sending any file with your form, and hence you're getting this Undefined index: file error, so remove these lines,
$file_filename=$_FILES['file']['name'];
$target_path = "Newfolder1";
$image_path = $target_path . DIRECTORY_SEPARATOR . "filename";
$image_format = strtolower(pathinfo('filename', PATHINFO_EXTENSION));
So after user hits view button, you should process your form and display image like this,
// your code
if (isset($_POST['View']) ){
$pdf=new fpdf();
$pdf->ADDPage();
$pdf->setfont('Arial','B', 16);
$pdf->Cell(40,10, 'sname',1,0,'c');
$pdf->Cell(40,10, 'sadd',1,0,'c');
$pdf->Cell(40,10, 'category',1,0,'c');
$pdf->Cell(40,10, 'scode',1,0,'c');
$con = mysqli_connect("localhost","root","","school");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM imagetable WHERE ID= '$_POST[search]'";
$result = mysqli_query($con, $sql);
if(!mysqli_query($con, $sql)){
die( "Could not execute sql: $sql");
}
$row = mysqli_fetch_array($result);
$image_path = $row['file'] . DIRECTORY_SEPARATOR . $row['filename']; // path should be like this, process/upload/8/cdv_photo_001.jpg
$image_format = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));
$pdf->Cell(40,10, $row['sname'],1,0,'c');
$pdf->Cell(40,10, $row['sadd'],1,0,'c');
$pdf->Cell(40,10, $row['category'],1,0,'c');
$pdf->Image($image_path,50,100,50,20,$image_format);
$pdf->ln();
$pdf->output();
}
// your code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34475345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mediarecorder addEventListener is not working in Chrome/Safari I am using mediarecorder in a vue.js app. The code snippet is below. The inline function for ondataavailable executes. However, neither of the two options to specify a function handler for onstop get invoked.
Is there a workaround to this issue?
const options = { mimeType: "audio/webm" };
mediaRecorder = new MediaRecorder(stream, options);
mediaRecorder.ondataavailable = function (e) {
console.log("in dataAvailable", e.data.size);
if (e.data.size > 0) recordedChunks.push(e.data);
};
mediaRecorder.onstop = this.stopRecordingEvent;
mediaRecorder.addEventListener("stop", this.stopRecordingEvent);
Using an inline function for the stop event like dataavailable works, however that gives error in the highlighted line:
mediaRecorder.onstop = function () {
console.log("recording stopped event");
// save the recording bytes in an array
const blob = new Blob(recordedChunks);
const audioURL = URL.createObjectURL(blob);
var recording = {
blob: blob,
url: audioURL,
id: arrRecordings.length + 1,
};
console.log(recording.id, recording.url);
//this line gives an error
this.recordings.push(recording);
console.log(arrRecordings);
recordedChunks.length = 0;
};
A: event ondataavailable works after mediaRecorder stop() function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70995492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Item-by-item list comparison, updating each item with its result (no third list) The solutions I have found so far in my research on comparing lists of objects have usually generated a new list of objects, say of those items existing in one list, but not in the other. In my case, I want to compare two lists to discover the items whose key exists in one list and not the other (comparing both ways), and for those keys found in both lists, checking whether the value is the same or different.
The object being compared has multiple properites that constitute the key, plus a property that constitutes the value, and finally, an enum property that describes the result of the comparison, e.g., {Equal, NotEqual, NoMatch, NotYetCompared}. So my object might look like:
class MyObject
{
//Key combination
string columnA;
string columnB;
decimal columnC;
//The Value
decimal columnD;
//Enum for comparison, used for styling the item (value hidden from UI)
//Alternatively...this could be a string type, holding the enum.ToString()
MyComparisonEnum result;
}
These objects are collected into two ObservableCollection<MyObject> to be compared. When bound to the UI, the grid rows are being styled based on the caomparison result enum, so the user can easily see what keys are in the new dataset but not in the old, vice-versa, along with those keys in both datasets with a different value. Both lists are presented in the UI in data grids, with the rows styled based on the comparison result.
Would LINQ be suitable as a tool to solve this efficiently, or should I use loops to scan the lists and break out when the key is found, etc (a solution like this comes naturally to be from my procedural programming background)... or some other method?
Thank you!
A: You can use Except and Intersect:
var list1 = new List<MyObject>();
var list2 = new List<MyObject>();
// initialization code
var notIn2 = list1.Except(list2);
var notIn1 = list2.Except(list1);
var both = list1.Intersect(list2);
To find objects with different values (ColumnD) you can use this (quite efficient) Linq query:
var diffValue = from o1 in list1
join o2 in list2
on new { o1.columnA, o1.columnB, o1.columnC } equals new { o2.columnA, o2.columnB, o2.columnC }
where o1.columnD != o2.columnD
select new { Object1 = o1, Object2 = o2 };
foreach (var diff in diffValue)
{
MyObject obj1 = diff.Object1;
MyObject obj2 = diff.Object2;
Console.WriteLine("Obj1-Value:{0} Obj2-Value:{1}", obj1.columnD, obj2.columnD);
}
when you override Equals and GetHashCode appropriately:
class MyObject
{
//Key combination
string columnA;
string columnB;
decimal columnC;
//The Value
decimal columnD;
//Enum for comparison, used for styling the item (value hidden from UI)
//Alternatively...this could be a string type, holding the enum.ToString()
MyComparisonEnum result;
public override bool Equals(object obj)
{
if (obj == null || !(obj is MyObject)) return false;
MyObject other = (MyObject)obj;
return columnA.Equals(other.columnA) && columnB.Equals(other.columnB) && columnC.Equals(other.columnC);
}
public override int GetHashCode()
{
int hash = 19;
hash = hash + (columnA ?? "").GetHashCode();
hash = hash + (columnB ?? "").GetHashCode();
hash = hash + columnC.GetHashCode();
return hash;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14564810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.