text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Value is returned as None from function
I am trying to get the value of an user input defined key from nested dictionary.
While I am able to print out the value from the function itself. Return statement sends value as None.
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: 'James',
4: 'lance',
'change1': {5: 'place'},
'country': {'Waterloo': 'Waterloo', 'Australia': 'Australia'},
6: {'Position': 'GM'}
}
def getfromdict(mydict, mykey):
for i in mydict.keys():
if type(mydict[i])==dict:
newdict = mydict[i]
getfromdict(newdict, mykey)
elif i == mykey:
print(mydict[i])
valuefound = mydict[i]
return valuefound
else:
continue
result = getfromdict(people,5)
print(result)
This is the output of code execution: --> place
None
Process finished with exit code 0
have you tried my answer
You can try this to search the keys in the nested JSON
def getfromdict(mydict, mykey):
if type(mydict) == type({}):
for k1 in mydict:
if k1 == mykey:
return mydict[k1]
fromdict = getfromdict(mydict[k1], mykey)
if fromdict is not None:
return fromdict
can you mark this solution as answered, because the other solution is misleading is misleading
Line three of your code snippet should read
return getfromdict(newdict, mykey)
To find a leaf in a tree, well, you can, for istance,
def leaf(tree, key):
if key in tree: return tree[key]
for subtree in filter(lambda s: isinstance(s, dict), tree.values()):
ret_val = leaf(subtree, key)
if ret_val is not None: return ret_val
This implementation has the property that if a key is found at some level, whatever it points to is returned, either a leaf or a subtree (in undesired, a fix is quite straightforward).
have you tried running the code, it won't work as it will get excited in the first nested loop itself
| common-pile/stackexchange_filtered |
How to get the list of csv files in a directory sorted by creation date in Python
I need to get the list of ".csv" files in a directory, sorted by creation date.
I use this function:
from os import listdir
from os.path import isfile, join, getctime
def get_sort_files(path, file_extension):
list_of_files = filter(lambda x: isfile(join(path, x)),listdir(path))
list_of_files = sorted(list_of_files, key=lambda x: getctime(join(path, x)))
list_of_files = [file for file in list_of_files if file.endswith(file_extension)] # keep only csv files
return list_of_files
It works fine when I use it in directories that contain a small number of csv files (e.g. 500), but it's very slow when I use it in directories that contain 50000 csv files: it takes about 50 seconds to return.
How can I modify it? Or can I use a better alternative function?
EDIT1:
The bottleneck is the sorted function, so I must find an alternative to sort the files by creation date without using it
EDIT2:
I only need the oldest file (the first if sorted by creation date), so maybe I don't need to sort all the files. Can I just pick the oldest one?
Might this question be a duplicate of this
The bottleneck isn't really the sorted function but the time spent executing getctime which we now know (from a comment to an answer) is probably due to the fact that the directory in question is on a network drive. A good test would be to run a timer on getting all the files and running getctime on each of them.
You could try using os.scandir:
from os import scandir
def get_sort_files(path, file_extension):
"""Return the oldest file in path with correct file extension"""
list_of_files = [(d.stat().st_ctime, d.path) for d in scandir(path) if d.is_file() and d.path.endswith(file_extension)]
return min(list_of_files)
os.scandir seems to used less calls to stat. See this post for details.
I could see much better performance on a sample folder with 5000 csv files.
Awesome! In my case it works in 0.3 seconds
Using min(list_of_files, key=lambda x: x[0]) will get the oldest timestamp, and will be faster than .sort() by a tiny amount
Is it the same if I use min(list_of_files), without key=lambda x: x[0]?
In this case, basically yes. Seet this post on tuple comparision. Might be even more performant.
You should start by only examining the creation time on relevant files. You can do this by using glob() to return the files of interest.
Build a list of 2-tuples - i.e., (creation time, file name)
A sort of that list will implicitly be performed on the first item in each tuple (the creation date).
Then you can return a list of files in the required order.
from glob import glob
from os.path import join, getctime
def get_sort_files(path, extension):
list_of_files = []
for file in glob(join(path,f'*{extension}')):
list_of_files.append((getctime(file), file))
return [file for _, file in sorted(list_of_files)]
print(get_sort_files('some directory', 'csv'))
Edit:
I created a directory with 50,000 dummy CSV files and timed the code shown in this answer. It took 0.24s
Edit 2:
OP only wants oldest file. In which case:
def get_oldest_file(path, extension):
ctime = float('inf')
old_file = None
for file in glob(join(path,f'*{extension}')):
if (ctime_ := getctime(file)) < ctime:
ctime = ctime_
old_file = file
return old_file
Thanks! But in my case it takes about 25 seconds (half of my function), that is still too much time
@nicc96 In that case it's not your code that's slow - it's your hardware. Ask yourself how/why it could possibly run in under 1 second on my machine but not on yours. Are your CSVs on a network drive perhaps?
Yes, they are! and a file has a size of about 100 KB
@nicc96 The size of the file should be irrelevant as you're not opening them let alone reading them. See my latest edit.
You can try this method:
def get_sort_files(path, extention):
# Relative path generator
sort_paths = (join(path, i)
for i in listdir(path) if i.endswith(extention))
sort_paths = sorted(sort_paths, key=getctime)
return sort_paths
# Include the . char to be explicit
>>> get_sort_files("dir", ".csv")
['dir/new.csv', 'dir/test.csv']
However, all file names are in a relative path; folder/file.csv. A slightly less efficient work-around would be to use a lambda key again:
def get_sort_files(path, extention):
# File name generator
sort_paths = (i for i in listdir(path) if i.endswith(extention))
sort_paths = sorted(sort_paths, key=lambda x: getctime(join(path, x)))
return sort_paths
>>> get_sort_files("dir", ".csv")
['new.csv', 'test.csv']
Edit for avoiding sorted():
Using min():
This is the fastest method of all listed in this answer
def get_sort_files(path, extention):
# Relative path generator
sort_paths = (join(path, i) for i in listdir(path) if i.endswith(extention))
return min(sort_paths, key=getctime)
Manually:
def get_sort_files(path, extention):
# Relative path generator
sort_paths = [join(path, i) for i in listdir(path) if i.endswith(extention)]
oldest = (getctime(sort_paths[0]), sort_paths[0])
for i in sort_paths[1:]:
t = getctime(i)
if t < oldest[0]:
oldest = (t, i)
return oldest[1]
Thanks! But check my EDIT, I can't use the sorted() function
No worries @nicc96. Using sorted or not, you still need to rank the values, avoiding sorted will not fix your bottleneck. Nevertheless, I'll add an alternative to sorting.
@nicc96, see my example with min(), should be slightly faster. But as the other answer pointed out. The speed is lost from the files being on a network drive. Not from the code. Try downloading them and running this again
You could try the following code:
def get_sort_files(path, file_extension):
list_of_files = [file for file in listdir(path) if isfile(join(path, file)) and file.endswith(file_extension)]
list_of_files.sort(key=lambda x: getctime(join(path, x)))
return list_of_files
This version could have better performance especially on big folders. It uses a list comprehension directly at the beginning to ignore irrelevant files right from the beginning. It uses in-place sorting.
This way, this code uses only one list. In your code, you create multiple lists in memory and the data has to be copied each time:
listdir(path) returns the initial list of filenames
sorted(...) returns a filtered and sorted copy of the initial list
The list comprehension before the return statement creates another new list
Thanks but it still takes about 50 seconds
| common-pile/stackexchange_filtered |
What is the maximum SCSI LUN size?
What is the maximum size of single (i)SCSI LUN from perspective of SCSI protocol, what is the limit?
The answer would appear to be heavily dependent on the generation of the SCSI protocol, as it has gone through a handful of revisions through its days of glory.
First, 512 bytes = 2^9 bytes.
The earliest SCSI protocols used 21-bit LBA. Using 512-byte blocks, this gives 2^21 * 2^9 bytes or 1 GiB addressable space. (2^21 * 2^9 = 2^30.) (source)
Newer SCSI variants allow for 32-bit LBA addresses, which gives you 2^41 bytes (2 TiB) addressable. (source) But also see below.
Current in ATA is LBA48, or 48-bit LBA, although I cannot find any definitive statement on whether any current variant of SCSI uses 48-bit LBA. (It makes sense, though, and some Googling provides some fairly strong indications that such is the case. If anyone has a definitive source either way, please comment.) This gives you 2^57 bytes (128 PiB) addressable over the protocol itself, assuming 512 byte blocks. If we are allowed to raise this to 4096 (2^12) byte blocks, that becomes 2^60 bytes = 1 EiB.
According to a comment left by JdeBP, in SCSI, 64-bit LBA support has been mandatory since the turn of the century. With 512 byte sectors and 64-bit addresses, that gives us 2^73 bytes addressable, or 8 ZiB. A ZiB is 1024^3 TiB.
So the realistic answer with current generation hardware is probably either 8 ZiB or 128 PiB maximum LUN size addressable over (i)SCSI, with the former being more likely.
While a total storage capacity of 128 PiB is possible to approach in really large setups, 8 ZiB seems to me to be well out of pretty much anyone's reach for now. Using these newfangled 8 TB drives, that would require approximately 1000^3 = 10^9 drives, for a power requirement for just keeping them spinning of approaching 10 MW.
48 bits are for toys. ☺ SCSI's 16-byte CDBs use 64-bit logical block addresses. This has been the case since the 1990s, and implementing the read(16) and write(16) commands has been mandatory for DASD targets since the turn of the century. As I wrote a decade ago this puts the maximum size supported by the SCSI protocol in the ZiBs.
@JdeBP I updated the answer. Does it feel less like talking about toys, now? (Note that this is Super User, not Server Fault...)
Thanks for answer. @JdeBP I've placed this question here, cause no meaningful I got off the google (at least not in 1st result page) and even not here.
It's a lot easier to find if one knows the answer ahead of time, and searches for "8.0ZiB". ☺ "8ZB" gets one Microsoft on the subject. The proper way to approach this, though, is not random phrase match by Google Web. I learned it by buying books on SCSI — several in fact (I read both Schmidt and Sawert on the subject, for starters.) — then reading the actual SCSI standards documents (including the SBC documents) which laid out the newer CDB fomats and command sets that postdated the books, and then writing a SCSI DASD class device driver.
This is depended on vendor, EMC2 has a limit of 1.999TB in their VNXe3300. It will be a mixture of vendor presenting the LUN, the application layer using the LUN and any OS layer mounting the LUN.
OP specifically asked about the SCSI protocol itself.
Yes, so there is no limit. You can use any size LUN that the device can present. There is no limit on the protocol at all. The only limiting factor is the vendor.
"No limit at all" is misleading, even if the limit is very large. There is always a limit somewhere. It might be so large that it does not matter in practice but that doesn't mean there is no limit, it only means that the limit does not matter in practice.
| common-pile/stackexchange_filtered |
What is this game with Knights and Ogres and wolf riders I played when I was a kid?
I grew up in the 80s, so the game should of come out in the late 80s or early 90s. I believe that the game was made by the same makers that made Hero Quest, but I might be wrong.
The game was an War based game, that had 2 sides a good side and a dark side. The light side had knights and the dark side had a giant Ogre, wolf riders, and other stuff. I really liked it because there was different strategies based on the side you were on.
As a kid, I felt like the map was an 8' x 8' map.
Hopefully this is enough info that someone can answer me... I've done a bunch of googling, but have had no success...
Is this an RPG or board game?
As @SuicideClyde answered, this game is Battle Masters. I still have my original copy, though the box isn't in great shape. The mechanics revolve around a deck of cards which have pictures of specific units for each player - such as the Empire's archers or Chaos's wolf riders. The two most badass pieces are the Empire's cannon (which has a deck of tiles to fire huge distances and possibly take out several units in one shot) and Chaos's Ogre, which can move and attack several times in one turn, and takes several damage to kill.
The deck mechanic is interesting, though it can lead to situations where one player takes several turns in a row before the other player ever getting a turn - such is the nature of a child-shuffled deck, especially - but it's great fun. Damaged units actually lose figures from their bases, reducing the effectiveness of the unit in future combat. It's a relatively elegant system for a kid-friendly game, and it's great fun to look down over the mat at your massive armies, especially if - like me - you were never able to afford/were never exposed to Warhammer figures growing up!
| common-pile/stackexchange_filtered |
How to create ZF3 console application
In Zend Framework 2 it's very simple to add the initial module banner to the console applications.
All we need to is to implement the getConsoleBanner and getConsoleUsage methods and implement the Zend\ModuleManager\Feature\ConsoleUsageProviderInterface or ConsoleBannerProviderInterface interfaces.
This is good enough to dump those messages in the console when public/index.php is started via CLI.
In Zend Framework 3 it's not the same.
Doing the same setup does not provide the same result. Actually in the console we see the default html page for the skeleton app the same way as we visit it via the browser.
That page is being seen before we install the custom module:
Here are the docs for the zend-mvc-console module
https://zendframework.github.io/zend-mvc-console/intro/
Even after module is installed as suggested ('Zend\Mvc\Console' added in module definitions) the console banners are not shown. I've tested with var dumping inside the methods and I'm able to view the data, so the framework executes those methods but shows no result in the console.
I've tested with console routes and controllers. Route is found, controller action is executed but nothing is shown in the cli again.
I've digged in the code of the framework and it seems the Zend\Mvc\Console\ResponseSender\ConsoleResponseSender class is never executed.
Do I have to register some view_manager strategies in order to get something displayed in the CLI?
Here are the sources on top of the zf3 skeleton application:
https://gist.github.com/kachar/06f0c9096bcc1cc0b00f4612aed1b68b
Running the app:
$ php -v
PHP 7.0.6 (cli) (built: Apr 27 2016 14:00:40) ( ZTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
$ php public/index.php
Application\Module::getConsoleBanner
Application\Module::getConsoleUsage
$ php public/index.php user
Application\Controller\IndexController::indexAction
It might be a bug in zend-mvc-console: https://github.com/zendframework/zend-mvc-console/issues/12
@kachar: did you succeed in implementing zf-console as suggested by @weierophinney? If you did, would you share how with us?
Per our own documentation, MVC <-> Console integration is deprecated. We recommend using zf-console or symfony console for building console functionality for your application.
We are aware of issues with zend-mvc-console, and we'll be issuing a patch release soon to address them, which will fix your short-term problems. However, we recommend migrating to another solution in the long-term.
what is the reason zend-mvc-console is deprecated ?
I tried zf-console, it's simple but it's difficult to integrate. I cannot create handler using Factory, which mean I have to inject the whole service manager. I think zf-console is more focus on simple single app, but if we want to merge multiple console I don't think it's a good solution, it's very dirty.
If you need more features than zf-console offers, symfony/console is an excellent solution. We are, in fact, rewriting existing tooling or creating new tooling using symfony/console. As to why zend-mvc-console being deprecated: it's because zend-mvc and console tooling are simply a bad fit, and integrating them adds far too much complexity and edge cases for us to feel comfortable maintaining.
Yeah I migrate to zf-console after further study, but not sure whether zend event ( not mvc event ) can work inside service.
Yes, of course zend-eventmanager works fine; it can be used standalone in any PHP application.
For anyone who have decided to use zend framework 3 (or laminas) and symfony/console together (as @weierophinney mentioned) I recommend to use this answer from zend framework official forum https://discourse.laminas.dev/t/how-to-launch-a-basic-php-cli/1473/11 (author rieschl ). I will copy the code to here from there:
I’ve written different “single file” scripts, but in the end
symfony/console is the best if your cli scripts evolve. And it’s
amazingly easy to setup. What I’ve done is to let the ServiceManager
create the Symfony console app, so my CLI entry point (at bin/console)
looks like this:
#!/usr/bin/env php
<?php
declare(strict_types=1);
use Laminas\Mvc\Application as ZfApp;
use Symfony\Component\Console\Application as ConsoleApp;
chdir(dirname(__DIR__));
require dirname(__DIR__) . '/vendor/autoload.php';
$zfApp = ZfApp::init(require dirname(__DIR__) . '/config/application.config.php');
/** @var ConsoleApp $consoleApp */
$consoleApp = $zfApp->getServiceManager()->get(ConsoleApp::class);
return $consoleApp->run();
As you can see, I build the Laminas App (called ZfApp here, it’s
pre-Laminas), get the ServiceManager from there and the Symfony
console from the ServiceManager. The Service Factory looks like this
<?php
declare(strict_types=1);
namespace Eventjet\Factory;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
final class ConsoleApplicationFactory
{
public function __invoke(ContainerInterface $container): Application
{
$app = new Application(
'Eventjet Console Legacy System',
'1.0'
);
foreach ($this->createCommands($container) as $command) {
$app->add($command);
}
return $app;
}
/**
* @return Command[]
*/
private function createCommands(ContainerInterface $container): array
{
$commandNames = $this->config($container)['ej-console']['commands'];
return array_map(
static function (string $commandName) use ($container) {
return $container->get($commandName);
},
$commandNames
);
}
/**
* @return mixed[]
*/
private function config(ContainerInterface $container): array
{
return $container->get('config');
}
}
That way, I can just create a new Console Class, register as
class-string in the config under the [‘ej-console’][‘commands’] config
key and have it availabe right away :slight_smile: The config would
look something like that:
return [
'ej-console' => [
'commands' => [
SomeCommand::class,
],
],
];
That answer help me to start using zf3 and symfony/console in one day.
| common-pile/stackexchange_filtered |
how to createWriteStream() to GCS?
I'm trying to write an Express route that takes an image URI in the POST body and then saves the image into a Google Cloud Storage Bucket.
I'm not able to persist this image to local disk and need to stream the buffer straight to the GCS bucket.
My route creates a 4KB "stub" in the GCS bucket but there's no image payload. My nodejs then proceeds to crash...
Q: What is the correct way to .pipe() the results of the https.request() to blob.createWriteStream()? Is this the right approach?
I've spent a few days trying to find the right solution with different stream handlers but with precious little progress to show for it. Can someone help?
message: 'The rate of change requests to the object my-projectID/testimage.jpg exceeds the rate limit. Please reduce the rate of create, update, and delete requests.'
const streamifier = require('streamifier');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
projectId: 'my-projectID',
keyFile: '../config/my-projectID.json'
});
const bucket = storage.bucket('my-projectID');
const blob = bucket.file('testimg.jpg');
app.post('/bam', passport.authenticate('basic', {session: false }), (req, res) => {
return new Promise((resolve, reject) => {
https.request(req.body.pic, (response) => {
response.on('data', (d) => {
streamifier.createReadStream(d)
.pipe(blob.createWriteStream({
resumable:false,
public:true,
metadata:{ contentType: 'image/jpeg' }
}));
});
response.on('finish', (done) => {
console.log(done);
});
response.on('error', (err) => {
console.log(err);
});
}).end();
});
});
** Apologies for my ugly JS, I'm still at the bottom of ES6 learning curve.
I haven't tried with https.request(), but I was able to upload an image directly to GCS without storing it locally by following the Cloud Storage Node.js Client:
const fs = require('fs')
const request = require('request')
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');
const blob = myBucket.file('image.jpg');
const uploadblob = (url, callback) => {
request.head(url, (err, res, body) => {
request(url)
.pipe(blob.createWriteStream())
.on('close', callback)
})
}
const url = 'https://www.example/image.jpg'
uploadblob(url, () => {console.log('Done!')})
I like how simple this is but couldn't get it to work with https.request(). It just errored saying the response wasn't pipeable.
I accepted this as the answer as it does actually work, just not with native https.request(). Thanks for your help.
If your goal is to save an image to GCS you have to create a Promise and then resolve it. According to the Google Cloud Storage documentation you have to instantiate a new Storage object, then pointing at the bucket you want, then create a promise that upload the file to the bucket via "createWriteStream" and then resolve the promise you want. I.E. here I'm uploading a file to the bucket and then returning the public url. If you take a look to this code, this is the right way to create a WriteStream to GCS. It's a little bit more complex and different function than yours just cause here you can upload multiple files with a foreach loop but the process to create a stream to GCS basically remains the same.
This is my function in the controller:
controllers/postControllers.js:
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);
//Func to upload files to GCS
const uploadFileTGcs = async (file) => {
let promises = [];
_.forEach(file, (value, key) => {
const {originalname, buffer} = value;
const blob = bucket.file(originalname.replace(/ /g, '_'));
const promise = new Promise((resolve, reject) => {
const blobStream = blob.createWriteStream({
resumable: false,
public: true,
});
blobStream.on('error', () => {
reject(`Unable to upload image, something went wrong`);
}).on('finish', async () => {
const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`;
resolve(publicUrl);
}).end(buffer);
});
promises.push(promise);
});
return Promise.all(promises).then(promises => {
return promises;
});
};
Then in the route I can use that function as a middleware:
router.post('/create', async (req, res, next) => {
try {
if (!req.files) {
res.status(400).json({
messages: 'No file uploaded',
});
return;
}
const promiseReturned = await postsController.uploadFileTGcs(req.files);
....
res.status(promiseReturned ? 200 : 404).json({
result: promiseReturned, //here I'm returning the url of the files stored in gcs
message: 'Post created',
});
} catch (e) {
res.status(500).json({
result: e.toString(),
});
}
});
I edited the OP with my attempt to implement a Promise. The memory leak error has been replaced by one from CGS. I know I'm still missing something here, probably I don't really understand your code. Does my edited OP look closer to what's needed?
are you still getting the GCS error? that seems to be related to a quota limit
Will it be resumable if we change "resumable: false" to "resumable: true"? I'm currently in need of a resumable upload process.
| common-pile/stackexchange_filtered |
.Net Compact Framework development on Windows Embedded CE 6.0
I am busy developing a .Net compact Framework 3.5 application for Windows CE 6.0 and am really struggling to figure out how to get a development environment up and running to debug my code.
Creating the Visual Studio project and writing the code is not the problem. But now to press F5 and run this puppy in an actual Win CE 6.0 Emulator (or similar?!) is where I am getting stuck and I have Googled this subject to death and just not finding any good tutorials/documents/help on how to get it from 'n Visual Studio project to debugging the project (or even running a simple hello world) in Win CE 6.0.
So my question is this. Can anybody please point me in the direction of a good tutorial (or provide one your selves) to get a Win CE 6.0 dev environment up and running.
Perhaps I am missing something and it just is not possible to connect and debugging to Win CE? If that is the case, how do you recommend debugging Compact Framework code in general?
The closest that I have gotten to a CE tutorial is this: http://tech-stuff-home.blogspot.com/2011/03/building-workspace-for-device-emulator.html
And I have done all the steps in this tutorial to get Win CE build running, but the problem is that this does not connect Compact Framework development to the device created above.
Edit: Even though I get CE running in a device emulator (using tutorial above), I cannot get this as a deploy option in the Device Emulator Manager when deploying a CF project.
what version of VS are you using?
You should make a connection using CoreCon. Th3e steps involved are
Copy all of the CoreCon bits from your dev PC to the device (emulator is just a device)
Verify/note the IP address of the device
Modify the connection in your PC to use that address for connecting
Run conmanclient2.exe (on the device)
Run cmaccept.exe (on the device)
Verify the target device is set to the device you conmfigured
Test the connection from Studio
Debug
It is not completely clear for me, but I understand you have no problems running in an emulator but you can't run nor debug the application on an actual device?
I cannot say what is actually causing it, but things I always check:
Device is not connected (can you see it in My Computer?)
Make sure you select the device option instead of the emulator (in VS2008 in
the toolbar, you should have the 'Device' panel visible. In this
panel you can switch devices and there you should have 'Windows
Mobile 6 ... Device' selected. Try connecting from there without
actually running the app.
Check the Configuration Manager, set it to
Debug (Release sometimes gives problems)
In the Project options, check the Devices tab. Select the appropriate Target for and
optionally check 'Deploy latest version of .NET' to be sure all the
files are there.
Depending on your system OS, it might be needed to install ActiveSync (XP) or Windows Mobile Device Center (Vista and above). When it is installed, connect the device and let Windows install all the drivers needed. Then reboot and try connecting again. In both cases connecting the device should invoke a response from Windows for connecting to your device.
Try using the Visual Studio Remote Tools, for example the Remote File Viewer. Does it work?
Do you get any kind of error message when trying to connect? Unfortunately I never found a good tutorial on this subject. I learned all this the hard way when I started CF development a couple of years ago.
This is for Windows CE 6 and not Windows Mobile 6. Although I also thought it's about the same thing there is quite a vast difference. Also I'd add that the problem is not connection to an actual device. The problem is to debug directly on a Win CE 6 Emulator.
I have less experience using the Emulator and even less using the Emulator for CE. I do not agree there is that vast a difference between CE and Mobile though, but perhaps this is more pronunciated when using an emulator.
Can you boot the emu? Can you connect to it from VS after it has started? If not, what error are you getting? Is the correct CF framework installed on the emu?
I thought Windows Mobile 6 was based on CE 5.2.
Here's the best description that I have read about how CE and Win Mobile are different: http://blogs.msdn.com/b/fzandona/archive/2006/05/16/599485.aspx
| common-pile/stackexchange_filtered |
Average Price per column within different tables
I'm stumped in trying to complete a problem I was tasked in getting solved.
I'm tasked with doing the following: Calculate the average cost for different products and group them by the category of the product.
How can I do this against different tables?
If I wrote a really nice but long solution query, took a screenshot of it, and added that image as an answer, would you be annoyed about the unnecessary transcription effort? Please don't use images of data, just copy/paste some data into the question and format it using the {} button in the toolbar. ps: You can use https://ozh.github.io/ascii-tables/ to create ascii tables.
@TheCuriousProgrammer . . . From what I calculate, Postgres is right. Please elaborate on how you calculate your "ideal" solution.
@Used_By_Already Sorry about that, StackOverflow noob here. I'll definitely use this going forward.
You don't need your where clause. You have joined the entire supply table, so every selling_price is already part of the query.
@GordonLinoff So my "ideal" solution is produced by adding the 'selling_price' of each product that is related to a category.
For example: Category 1 has product(1), product(2), product(3). Therefore, I'm doing (($4) + ($10 + $5) + ($5 + $12) / 3) = $12
I see. You want the "average" per "product", not over all the products. So, you need to calculate this yourself using COUNT(DISTINCT):
SELECT p.category AS category_id,
SUM(s.selling_price::numeric) / COUNT(DISTINCT p.product_id)
FROM product p JOIN
supply s
ON p.product_id = s.product_id
GROUP BY p.category;
Ahhhhh! That works perfectly. Thank you so much for your quick assistance.
| common-pile/stackexchange_filtered |
How do I find recurring pattern lines in a large file
I have a large file that contains many lines of strings in a format of:
A
B
D
B
C
D
C
D
C
D
As you can see C and D appears recurrently 3 times next to each other , so I want to parse the file to find the recurring pattern of them to output:
A
B
D
B
repeat C D 3 times
C
D
in actual case, it the recurring pattern of lines that next to each other may goes up to 3 lines but no more than that, e.g
A
B
D
B
C
D
E
C
D
E
So the output would be:
A
B
D
B
Repeat C D E 2 times
C
D
E
Here is the runnable code, but how could I find the longest repeat patterns if there are other repeated pattern ahead of it?
def is_list_equal(left, right):
if len(left) != len(right):
return False
for i in xrange(len(left)):
if left[i] != right[i]:
return False
return True
def find_dup_from_end(l, min_pattern_len, min_repeats):
assert min_pattern_len * min_repeats <= len(l)
max_pattern_len = len(l) / min_repeats
l = l[::-1]
for i in xrange(max_pattern_len, min_pattern_len-1, -1):
s1 = l[:i]
for j in range(1, min_repeats):
s2 = l[len(s1)*j:len(s1)*(j+1)]
if not is_list_equal(s1, s2):
break
else:
return (len(l)-len(s1)*min_repeats, len(s1))
return None, None
def find_dup(file, min_pattern_len=2, max_pattern_len=10, min_repeats=2):
assert min_pattern_len > 0
assert min_repeats > 1
assert min_pattern_len <= max_pattern_len
feed = []
min_feed_length = min_pattern_len*min_repeats
max_feed_length = max_pattern_len*min_repeats
start = None
length = None
with open(file) as f:
mylist = f.read().splitlines()
for line in mylist:
line = line.strip()
api = line
fn = 'a'
feed.append((fn, api))
if len(feed) < min_feed_length:
continue
if len(feed) > max_feed_length:
fn2, api2 = feed[0]
print fn2, api2
feed = feed[1:]
feed1 = [api for _, api in feed]
start, length = find_dup_from_end(feed1, min_pattern_len, min_repeats)
if length:
print(feed[start:start+length], min_repeats)
break
# print "length", length
feed = feed[:(start - length*(min_repeats-1))]
for fn2, api2 in feed:
print fn2, api2
if __name__ == '__main__':
find_dup('./apiLoopTest.text', 1, 2, 5)
a string1
a string2
([('a', 'string3'), ('a', 'string4')], 5)
a string3
a string4
Can you demonstrate any effort at solving this yourself?
I am very new to python and I thought about use map to store the string as key, number of appearance as value, however, I am not sure how to handle the case such that 2 or 3 lines as a pattern.
If you are very new, my best advice is to try things yourself. You actually learn much better that way.
@ScottHunter, thanks for suggestions and I totally agree. Any insight and comments on this implementation would be appreciated. Thanks!
This is a classical problem in CS called longest repeated substring.
The following code using the re module should give you a good starting point. Stick the example text from above and the regexp into site regex101.com for a description of the regexp and to test matches on other sample input.
import re
regex = r"(?P<_REP>(?P<GRP>(?:^[A-Z]$\n?){2,3})(?P=GRP)+)"
test_str = ("""\
A
B
D
B
C
D
E
C
D
E
""")
for match in re.finditer(regex, test_str, re.MULTILINE | re.DOTALL):
groupdict = match.groupdict()
GRP, _REP = groupdict['GRP'], groupdict['_REP']
print('The folloing group was repeated %i times from location %i\n%s'
% ((len(_REP) + 1) / len(GRP), match.start(), GRP))
Output:
The following group was repeated 2 times from location 8
C
D
E
| common-pile/stackexchange_filtered |
Star pyramid program in c
I have output in image, but code is not proper
i want code for the given output
#include <stdio.h>
int main() {
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
Are you saying that the image is what you want, or what you currently get?
Above code is code print star pyramid
Why did you write it down on a piece of paper and then take a picture? Please post this as text so people can help you more easily.
Okay, from next time I will not do like that
The question was a little difficult to understand, I'm assuming you're asking how to get the output as described in the image. This code does that:
#include <stdio.h>
int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (int i=0; i<rows; ++i) {
for(int j=0; j<rows*2-1; ++j) {
if (j <= i || j >= rows*2-2-i) {
printf("* ");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
I have the output that is in the photo, but i don't have the code for it, the above code is print star pyramid.
| common-pile/stackexchange_filtered |
Can I set up Hornetq Core-Bridges between two different Hornetq Server Versions?
I have to set up a Hornetq Core-Bridge to a Hornetq 2.1.X Server, but I would like to use a more updated version on my side of the architecture (2.2.X). Is it compatible?
I haven't found info about it on documentation (as always btw, regarding to hornetq).
Obs: The 2.1.X Server is running on a JBoss AS, and mine is on stand-alone mode.
Until hornetq 2.2.2, hornetq didn't have version compatibility support. That means that you would need all your servers on the same version. (same as you would need for your clients).
After hornetQ 2.2.2 we offer version compatibility, however the client has to be older than the server. We don't test a 2.2.5 talking to a 2.2.2 server.
So, if the core-bridge is installed in a 2.2.2 talking to a 2.2.5, you would be fine.
a 2.2.5 talking to a 2.2.2.. probably not
A 2.1.X talking to 2.2.x.. definitely not.
Thank you very much for the explanation. I'll use the same version on my side of the communication. And just to know, what about JMS Bridges? Is there any issue regarding to versions?
JMS Bridges are talking JMS. You should be fine as long as you have the proper version being by the connection factory. In theory you could have multiple versions installed on the same application server with some class loading isolation, but this is a bit complex to manage. In practice you will need the same versions between different hornetq versions
| common-pile/stackexchange_filtered |
Caffe Import error: libopencv_highgui.so.3.3: cannot open shared object file: No such file or directory
I created a virtual environment for python2.7 and I installed caffe using the command conda install -c conda-forge caffe. But when I try to import caffe, its throwing the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/data/home/eex608/.conda/envs/MyPython2.7Caffe/lib/python2.7/site-packages/caffe/__init__.py", line 1, in <module>
from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver, NCCL, Timer
File "/data/home/eex608/.conda/envs/MyPython2.7Caffe/lib/python2.7/site-packages/caffe/pycaffe.py", line 13, in <module>
from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \
ImportError: libopencv_highgui.so.3.3: cannot open shared object file: No such file or directory
Can anyone tell me how to resolve this error?
The package info after I installed caffe (if this info is useful to debug)
2018-10-08 23:07:03 (rev 1)
anaconda {5.3.0 -> custom}
blas {1.0 -> 1.1 (conda-forge)}
ca-certificates {2018.03.07 -> 2018.8.24 (conda-forge)}
certifi {2018.8.24 -> 2018.8.24 (conda-forge)}
h5py {2.8.0 -> 2.8.0 (conda-forge)}
harfbuzz {1.8.8 -> 1.7.6}
hdf5 {1.10.2 -> 1.10.1 (conda-forge)}
matplotlib {2.2.3 -> 2.2.3 (conda-forge)}
mkl-service {1.1.2 -> 1.1.2}
mkl_fft {1.0.4 -> 1.0.6 (conda-forge)}
mkl_random {1.0.1 -> 1.0.1 (conda-forge)}
numexpr {2.6.8 -> 2.6.6 (conda-forge)}
numpy {1.15.1 -> 1.15.2 (conda-forge)}
numpy-base {1.15.1 -> 1.15.2}
openssl {1.0.2p -> 1.0.2p (conda-forge)}
pyqt {5.9.2 -> 5.6.0}
pytables {3.4.4 -> 3.4.4 (conda-forge)}
qt {5.9.6 -> 5.6.3}
qtconsole {4.4.1 -> 4.4.1 (conda-forge)}
scikit-learn {0.19.2 -> 0.20.0 (conda-forge)}
scipy {1.1.0 -> 1.1.0 (conda-forge)}
+boost-1.66.0 (conda-forge)
+boost-cpp-1.66.0 (conda-forge)
+caffe-1.0 (conda-forge)
+ffmpeg-3.2.4 (conda-forge)
+gflags-2.2.1 (conda-forge)
+giflib-5.1.4 (conda-forge)
+glog-0.3.5 (conda-forge)
+jasper-1.900.1 (conda-forge)
+leveldb-1.18 (conda-forge)
+libgcc-7.2.0 (conda-forge)
+libgfortran-3.0.0 (conda-forge)
+libiconv-1.15 (conda-forge)
+libopenblas-0.3.3
+libprotobuf-3.5.2 (conda-forge)
+libwebp-0.5.2 (conda-forge)
+lmdb-0.9.22 (conda-forge)
+openblas-0.2.20 (conda-forge)
+opencv-3.4.1 (conda-forge)
+protobuf-3.5.2 (conda-forge)
+python-gflags-3.1.2 (conda-forge)
+python-leveldb-0.193 (conda-forge)
+x264-1!152.20180717 (conda-forge)
Looks like even though conda installs opencv version of 3.4 as part of caffe installation, at the time of import, caffe expects opencv version of 3.3. You could actually find libopencv_highgui.so.3.4 at the path <path_to_conda>/envs/env_name/lib. Hence it looks more like a bug. Why don't you try caffe installation from a different channel?
same error. other caffe installtions from anaconda doesnt work too
@Khan Did you face issue with conda install -c defaults caffe and conda install -c intel caffe. Both works fine for me.
@AnjuPaul-Intel that worked for me, thanks
In my scenario, it looks like the current conda-forge version of opencv does not install libopencv_*.so files in env_name/lib. Probably a recent bug, since I have an older installation without this problem.
| common-pile/stackexchange_filtered |
elisp , passing functions as arguments and call it, an Eval error happend, why?
my elisp program is:
(defun test (f x) (f x))
(test (lambda (x) (* x x)) 10)
run it, an error happened:
* Eval error * Symbol's function definition is void: f
Emacs is a lisp-2, so has a different namespace for functions and variables. So, in test, the f in the second (f x) is not the same as the (f) in the parameter list.
Try
(defun test (f x) (funcall f x))
All is good.
Here's the correction:
(defun test (f x)
(funcall f x))
(test (lambda (x) (* x x)) 10)
| common-pile/stackexchange_filtered |
how to re-run method when you re-visit screen in react-native?
I have wrote a method and tried calling that method in componentDidMount() ,componentWillMount(), render() methods but no methods runs again in react-native. I want to re-run that method every time screen is visited.
If you use react-navigation, you can use import { NavigationEvents } from 'react-navigation';, then in your render method:
return (
<View>
<NavigationEvents
// onWillFocus={payload => console.log('will focus',payload)}
// onDidFocus={payload => console.log('did focus',payload)}
// onWillBlur={payload => console.log('will blur',payload)}
// onDidBlur={payload => console.log('did blur',payload)}
/>
<View></View>
</View>
Reference: https://reactnavigation.org/docs/en/navigation-events.html
Glad can help, accepting the correct answer would be appreciated
| common-pile/stackexchange_filtered |
How to setup datastructure so to make pandas and numpy co-operate?
Having troubles compiling code that is based on pandas and numpy. I will try to explaining the issues by providing a downscaled working examples of where the problem lies.
What I'm basically trying to do is Markowitz portfolio optimization, in the following way.
First I have a pandas.Dataframe that has closing prices for given ticker in the following way.
df = pd.DataFrame()
df['AAPL'] = [1.2,1.4,1.5]
df['GOOGL'] = [2.1,2.4,2.6]
df['DATE'] = ['2017-01-01', '2017-01-02','2017-01-03']
df = df.set_index('DATE')
Next I want to create some basic statistics to pass the in some functions, which I do in the following way:
returns = df.pct_change()
mean_returns = returns.mean()
cov_matrix = returns.cov()
num_portfolios = 10
risk_free_rate = 0.0178
The type of these statistics is of:
pandas.core.series.Series
pandas.core.frame.DataFrame
The following functions are where the problems start to arise:
def portfolio_annualised_performance(weights, mean_returns, cov_matrix):
returns = np.sum(mean_returns*weights ) *252
std = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)
return std, returns
def random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate):
results = np.zeros((3,num_portfolios))
print('results:',type(results))
weights_record = []
for i in range(num_portfolios):
weights = np.random.random(12)
weights /= np.sum(weights)
weights_record.append(weights)
portfolio_std_dev, portfolio_return = portfolio_annualised_performance(weights, mean_returns, cov_matrix)
results[0,i] = portfolio_std_dev
results[1,i] = portfolio_return
results[2,i] = (portfolio_return - risk_free_rate) / portfolio_std_dev
#print('results[2,0]:',type(results[2,0]))
#print('std', type(portfolio_std_dev))
#print(portfolio_return)
return results, weights_record
def display_simulated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate):
results, weights = random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate)
max_sharpe_idx = np.argmax(np.array(results[2]))
sdp, rp = results[0,max_sharpe_idx], results[1,max_sharpe_idx]
max_sharpe_allocation = pd.DataFrame(weights[max_sharpe_idx],index=df.columns,columns=['allocation'])
max_sharpe_allocation.allocation = [round(i*100,2)for i in max_sharpe_allocation.allocation]
max_sharpe_allocation = max_sharpe_allocation.T
min_vol_idx = np.argmin(results[0])
sdp_min, rp_min = results[0,min_vol_idx], results[1,min_vol_idx]
min_vol_allocation = pd.DataFrame(weights[min_vol_idx],index=df.columns,columns=['allocation'])
min_vol_allocation.allocation = [round(i*100,2)for i in min_vol_allocation.allocation]
min_vol_allocation = min_vol_allocation.T
When trying to run:
display_simulated_ef_with_random(cov_matrix, mean_returns, num_portfolios, risk_free_rate)
The following error appears
----> 2 results, weights = random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate)
---> 15 results[0,i] = portfolio_std_dev
ValueError: setting an array element with a sequence.
What am I doing wrong and how can I fix this?
What version of python, pandas, numpy are you using? This works with no errors for me (after changing size of weights to weights = np.random.random(2), since you only provide 2 assets)
I'm using numpy 1.14.3 and pandas 0.23.0. Oh sorry about that, I have 12 assets in my full example, posted link to full code if interested.
@KenSyme I see that it worked for me also, the issue comes in a lates stage I realised, will post.
Instead of telling us "where the problems start to arise" give us a specific line of code that doesn't work, and what you think the result should be.
I have posted the whole error, since I believe it's deeply in the data-structure and believe that it can't be fixed only be changing one line of code. But I could be completly wrong as I often am.
You are calling your function with the parameters in the wrong order. Swap the first two and it works fine:
display_simulated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate)
I didn't even come to think of that, feel ashamed but you just solved a problem I have had for 2 days. Thank you for lending me your attention to detail and time!
| common-pile/stackexchange_filtered |
MKOverlayPathRenderer color dependent by property
I would like to draw a line on my mapview with a gradient, but the gradient color on a specific position should be dependent on a property from the line (e.g speed or altitude)
I found several MKOverlayPathRenderer which can draw a gradient, but the color moves from the first in the array to the last, but in my case the color can repeat. They should not go from green to orange to red from start to end. Either they can be green to orange to green to orange to red to orange and so on...
My current implementation is to go through the location points and check the property, which is color dependent and then draw different polylines depending on the property. So the result is a big number of polylines, which is not good I think in terms of performance and it looks not smooth either.
Is this the correct way or is there one to draw one line and create a MKOverlayPathRenderer which can handle these colouring requirements?
thank you for any tips
| common-pile/stackexchange_filtered |
Can I bulk upgrade deployed SPFx web parts?
I created a SharePoint Framework web part and deployed the package to the App Catalog on my client's O365 tenancy. My client has added the web part to around 150 sites.
I've since deployed a new version of the package, which contains some important updates to the web part, to the App Catalog. I can upgrade the web part manually on each site from the Site Contents page (i.e. exactly the same as the add-in model). However, I don't really want to do this manually 150 times. As far as I can see, there aren't any hooks for automating or scripting this (CSOM, PnP PowerShell ,etc) - any ideas?
Edit - to clarify the behaviour I'm seeing, here's a couple of screenshots. On the Site Contents page:
And on clicking through:
If you only updated the code, you should be able to simply redeploy your assets to your CDN location.
did you change the version number, or have you added any new properties? these seem to cause isues .
Thanks guys. I did change the version number of the package. Redeploying the assets to the CDN won't solve the problem alone, as the SPFx tooling generates different unique names for various assets every time you bundle - so we do also need to deploy a new sppkg to the App Catalog (either that or hack around with the build process).
If you do don't change the version number you wont need to do the upgrade.
Thanks @russellg - that did the trick. I rebuilt the package using the original version number and redeployed to the App Catalog. All instances of the SPFx web part are now using the updated code.
You shouldn't need to "upgrade" anything. As soon as you update the package in the app catalog, all running webparts will use the updated manifest, which should point to the updated code.
Thanks, but that's not the behaviour I'm seeing. On each site that includes the web part, on the Site Contents page, I see the message An update for this app is available (i.e. the behaviour is exactly the same as the add-in model). I can either leave the site running the old version of the web part, or I can click GET IT and get the new version. I did change the package version number before I re-deployed to the app catalog - if I left this unchanged (not a great software development practice), would the web parts automatically use the updated manifest?
Yes - they should use the updated manifest. If there was additional upgrade actions in your feature XML you would need to explicitly update them. This is good feedback though - ideally we shouldn't say "upgrade this" if upgrading isn't going to do anything material.
Here is something I recently did to bulk upgrade the solution in a scenario where I added new webparts to a project and had to increment the version number. This meant I had to upgrade the solution in each site collection that it was deployed to : http://vipulkelkar.blogspot.com/2018/08/bulk-upgrade-spfx-solution-in-multiple.html
I had something similar
First I didn't use the skipFeatureDeployment then I tried setting it to TRUE to have the webpart available to all subsites (my AppCatalog is Site collection scoped)
"skipFeatureDeployment":true,
then I had to use the Update commande with powershell
Connect-PnPOnline -URL $site -Credentials $credentials
Add-PnPApp -Path $appPath -Scope Site -Publish -Overwrite -SkipFeatureDeployment
$addedApp = Get-PnPApp -Scope Site -Identity bcaff853-6bfb-4391-af92-8f387f36e843
Update-PnPApp -Identity $addedApp.Id -Scope Site
Get-PnPApp -Identity $addedApp.Id -Scope Site
| common-pile/stackexchange_filtered |
Postgres: How to insert row with autoincrement id
There is a Table "context".
There is an autoincrement id "context_id".
I am using sequence to retrieve the next value.
SELECT nextval('context_context_id_seq')
The result is: 1, 2, 3,...20....
But there are 24780 rows in the "context" table
How can I get the next value (24781)?
I need to use it in the INSERT statement
In my case that sql worked: ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH 111;, see https://stackoverflow.com/questions/8745051/postgres-manually-alter-sequence/8750984#8750984
INSERT INTO public.tablename (id, operator, text) values((SELECT MAX(id)+1 FROM public.tablename), 'OPERATOR','');
why is this the correct answer?
This is bad practice
| common-pile/stackexchange_filtered |
How to post JSON data to Action Method ?
I am POSTing to the server (.Net) and I am having trouble passing arrays to the controller action. I've tried just about every possible combination without any luck. However, one of them is puzzling me.
If I perform this request :
var dataArray = [ { /* some plain object */ }, { /* another plain object */ ], ... ];
$.ajax(url, {
type: "post",
data: { models: dataArray }
});
Resulting a request data sent like
models[0][property1]:value1
models[0][property2]:value2
...
models[1][property1]:value3
models[0][property2]:value4
...
Unfortunately, the request is just not understood by .Net MVC4. Following a related SO question I've tried traditional: truebut the request sent to the server looks like this:
models:[object Object]
Which, obviously, sends not an object, but the string "[object Object]". ...What's wrong with this? Am I doomed to send serialized strings (and have to manually deserialize them on the server side) for every request involving non primitive parameters?
Note : this is my action method. As for now, everything I try results in
the parameter is an array of the correct size, but each item is a new unmodified (empty) object or
the parameter is null
[HttpPost]
public ActionResult UpdateModels(Models.SimpleModel[] models)
Try using JSON.stringify for array like JSON.stringify(dataArray)
UPDATE
MVC3 converts the string data to the .NET object automatically, if we use stringify while using ajax calls. I think same should be the case with MVC4.
Update 2
set contentType attribute to application/json; charset=utf-8
I tried, it doesn't work unless I deserialize the string manually (so instead of having an IEnumerable<> or an array of my objects, I need to receive a string). I'd like to find how .Net MVC4 can accept what I'm sending without being such a jerk
Yes, however MVC4 does not understand JSON data if the contentType is not explicitly set.
| common-pile/stackexchange_filtered |
VB.Net - Create JObject from subset of properties in existing JObject
I'm working in UIPath and trying to put together a single JSON configuration file for a library. My hands are sort of tied as far what functionality in VB.Net I can use but I'd like to filter my properties by environment. I'm able to successfully filter out the environment I'm not concerned with but I'm stuck with the existing environment property at the highest level of the JSON structure. I want to get rid of that one too after I know which one I want to keep.
Starting Point
{
"Development": {
"Database": {
"DB 1": {
"Server": "Foo",
"Application Name": "App1"
},
"DB 2": {
"Server": "Boo",
"Application Name": "App2"
}
}
},
"Production": {
"Database": {
"DB 1": {
"Server": "FooFoo",
"Application Name": "App1"
},
"DB 2": {
"Server": "BarBar",
"Application Name": "App2"
}
}
}
What I want to get to based on Environment (Development or Production)
{
"Database": {
"DB 1": {
"Server": "Foo",
"Application Name": "App1"
},
"DB 2": {
"Server": "Boo",
"Application Name": "App2"
}
}
Here is what I've tried so far:
Read JSON File to String
Deserialize to Newtonsoft JObject
Filter by environment
configData.Descendants
.OfType(Of JProperty)
.Where(Function(attr) attr.Name.ToUpper = "PRODUCTION" Or attr.Name.ToUpper = "DEVELOPMENT" And attr.Name.ToUpper <> environment.ToUpper)
.ToList()
.ForEach(Sub(attr) attr.Remove())
Result
{
"Development": {
"Database": {
"DB 1": {
"Server": "Foo",
"Application Name": "App1"
},
"DB 2": {
"Server": "Boo",
"Application Name": "App2"
}
}
}
From here is where I'm stuck and can't seem to get anything to work. I want to be able to access my configuration properties without the caller knowing what environment its in.
Something like
configuration("Database")("DB 1")
Versus
configuration(environment)("Database")("DB 1")
If I'm taking a stupid approach to this altogether I'd also accept that as an answer as well. I've never really played with VB or .Net before so its all fairly new to me. I'm understanding some things but am far from really understanding anything powerful.
Does JsonExtensions.RemoveAllExcept<TJToken>(this TJToken obj, IEnumerable<string> paths) from this answer to How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET meet your needs?
Dim environment = "Development"
Dim filteredJson = JObject.Parse(yourJson)(environment).ToString
will give you
{
"Database": {
"DB 1": {
"Server": "Foo",
"Application Name": "App1"
},
"DB 2": {
"Server": "Boo",
"Application Name": "App2"
}
}
}
Substitute "Production" for "Development" when appropriate, of course.
Note that you have a missing closing brace in your json samples
| common-pile/stackexchange_filtered |
Filter out some records on particular periods
I have below tables structures,
Trans Table:
Trans_Id(PK) User_Id(FK) Arroved_Date
________________________________________________
1 101 05-06-2016
2 101 20-06-2016
3 102 06-06-2016
4 103 10-06-2016
5 103 25-06-2016
Table2:
Id(Pk) User_Id(Fk) Start_Date End_Date
__________________________________________________________________
1 101 01-06-2016 15-06-2016
2 103 05-06-2016 20-06-2016
I want to filter out the transaction, if the Approved_Date is not between the users Start_Date and End_Date of table2.
Expected Result:
Trans_Id
________
2
3
5
The expected result is not in line with the explanation of the expected result. Transaction ID #3 in trans table has no corresponding User's entry in table2
Yes. It might have in second table or not. if not, it should not be filtered out.
This query should give you the expected results:
select t1.trans_id from t1
left join t2
on t1.user_id=t2.user_id
where t2.id is null OR t1.Arroved_Date not between t2.Start_Date and t2.End_Date
Try
SELECT Trans_ID
FROM Table1
JOIN Table2 ON Table1.User_Id=Table2.User_Id
where Approved_date Between Start_Date And End_Date
Based on your explanation (not on the expected result) you need to just JOIN the two tables on the FK you pointed out, in order to get the relationship between the rows in the two tables.
Then just apply a WHERE clause to filter the row based on your condition:
select t.trans_id
from trans t
inner join table2 t2 on t.user_id = t2.user_id
where t.approved_date between t2.start_date and t2.end_date
SELECT t.trans_id
FROM Trans tr
LEFT JOIN Table2 t2 ON tr.User_id = t2.User_id
WHERE t2.id IS NULL
OR t.Approved_Date IS NULL
OR t2.Start_Date IS NULL
OR t2.End_Date IS NULL
OR tr.Approved_Date <= t2.Start_Date
OR tr.Approved_Date >= t2.End_Date
The null-checks are only needed if the columns are nullable. The left join can be changed to an inner join if every transaction has a corresponding row in table 2. The answer assumes that there is not more than one row in table 2 for each transaction.
i'm not sure but from you expected output..
SELECT distinct t1.Trans_ID
FROM Table1 t1
LEFT JOIN Table2 t2 on 1=1
where t1.Approved_date Between t2.Start_Date And t2.End_Date
Try this one.
SELECT A.Trans_ID
FROM TEMP A
JOIN TEMP B ON A.User_Id = B.User_Id
WHERE A.Approved_date BETWEEN Start_Date AND End_Date
| common-pile/stackexchange_filtered |
how to store data in same key in dictionary using JavaScript
This is my output, in place of [object,object], it should give value but I am unable to get value.
[ 'CME,ES,201703': '0[object Object][object Object][object Object]',
'CME,ZB,201703': '0[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]',
'LME,ZB,201703': '0[object Object][object Object]',
'LME,ES,201703': '0[object Object]',
'CME,ES,201706': '0[object Object]' ]
For this I m writing the pc of code
var response = result['s:Envelope']['s:Body'][0].OrderReportResponse[0].obj[0];
var marketOrder = response['a:MarketOrder'];
// Storing values in Dictionary
var dict1 = [];
var dict2 = [];
for (var i = 0; i < marketOrder.length; i++) {
var keys1 = []; // Storing multiple keys in 1 object
var keys = [];
// if (dict1.length === 0) {
keys.push({
k1: marketOrder[i]['a:SecurityExchange'],
k2: marketOrder[i]['a:Symbol'],
k3: marketOrder[i]['a:MaturityMonthYear']
});
if (keys1.indexOf(keys[0].k1) && keys1.indexOf(keys[0].k2) && keys1.indexOf(keys[0].k3)) {
keys1.push(keys[0].k1, keys[0].k2, keys[0].k3);
}
for (var k1 in keys1[0]) {
var dict = {};
dict[keys1] = marketOrder[i];
if (dict1.indexOf(dict)) {
dict1.push(dict);
}
}
}
var targetObj = [];
var targetObj1 = [];
for (var i = 0; i < dict1.length; i++) {
for (var key in dict1[i]) {
if (!targetObj.hasOwnProperty(key)) {
targetObj[key]= 0;
//targetObj1.push(targetObj);
}
targetObj[key] += (dict1[i][key]);
}}
console.log(targetObj);
Where I am doing mistake because of that I am unable to fetch data in same key.
Your first snippet is syntactically invalid. Is that an array or an object?
For one thing, your use of array.indexOf() is not correct. It returns the index if found, or -1 if the passed item is not found. So currently all of your conditionals will fail if the item specified is found at position 0, but will pass if either the item is not found or has an index > 0.
Secondly, if you want to store multiple items, just use an array for the value and just push items to it when you find that the key exists. If the key doesn't exist, then set it to an array containing the first item. For example:
if (!Array.isArray(targetObj[key]))
targetObj[key] = [ dict1[i][key] ];
else
targetObj[key].push(dict1[i][key]);
bt i want that in dictionary, and how to use Array for that.
var targetObj = [];
var targetObj1 = [];
for (var i = 0; i < dict1.length; i++) {
for (var key in dict1[i]) {
if (!targetObj.hasOwnProperty(key)) {
targetObj[key]= 0;
//targetObj1.push(targetObj);
}
targetObj[key] += (dict1[i][key]);
}}
I am getting problem in this part only, If I will remove this "+" from targetObj[key] += (dict1[i][key]);
then it will store only 1 value for 1 key combination and If I am Adding "+" sign, then it is giving like [object, object]
Right, that is why I suggested the solution in my answer. Set and append to proper arrays instead and you won't have that problem of your objects being converted to strings and then appended to the existing string value.
Yes Now I am gettiong what I want but How to print the values, If i am Printing it to my console, it is giving the values for column but not giving the value of that row
'LME,ZB,201703':
[ { 'a:Account': [Object],
'a:AlgoName': [Object],
'a:AvgPrice': [Object],
'a:BeginString': [Object],
'a:BodyLength': [Object],
'a:ChildAccount': [Object],
'a:ClOrdId': [Object],
'a:ContractName': [Object],
'a:CurrentUser': [Object],
'a:CustomerOrFirm': [Object],
Now I am gettiong the output like above,
| common-pile/stackexchange_filtered |
How is "signed or unsigned type" meant in this C90 undefined behaviour definition?
In the ANSI C90 standard, section 6.3 has this to say about expressions:
An object shall have its stored value accessed only by an lvalue that has one of the following types: [...] a type that is the signed or unsigned type corresponding to a qualified version of the declared type of the object
And there is this instance of undefined behaviour in Annex G.2:
The behavior in the following circumstances is undefined: [...] An object has its stored value accessed by an lvalue that does not have one of the following types: the declared type of the object, a qualified version of the declared type of the object, the signed or unsigned type corresponding to the declared type of the object, the signed or unsigned type corresponding to a qualified version of the declared type of the object, an aggregate or union type that (recursively) includes one of the aforementioned types among its members, or a character type (6.3).
I find the wording of the emphasised parts ambiguous and am struggling to interpret it.
Does it mean "the signed type corresponding to the original type if it was signed, or the unsigned type corresponding to the original type if it was unsigned"; or "the type (whether signed or unsigned doesn't matter) corresponding to the original type"? That is, is:
signed int a = -10;
unsigned int b = *((unsigned int *) a);
...undefined?
If signed/unsigned doesn't matter, given that the standard makes the distinction between the three types char, signed char, and unsigned char, would accessing a char via signed char * or unsigned char * be defined?
It's saying that it's not undefined behavior to cast the value to a different signedness. If the object is declared signed int, you can access it using an unsigned int lvalue, and vice versa.
The case where the signedness is the same is already covered when it says "the declared type of the object", although this case could also be considered to say that.
In the case of char, both signed char and unsigned char are "the signed or unsigned type corresponding to" that type.
All together it's just saying that the signedness of the lvalue doesn't affect whether the access is well-defined.
My comment about char being a distinct type was a little vague. I understand that for any given implementation, char will either be the signed or unsigned version; but the standard does go to some lengths to make the distinction in way it doesn't do for the other integral types eg. in <IP_ADDRESS> there's "The three types char, signed char, and unsigned char are collectively called the character types." I don't know whether this has any real significance though; it sounds like it doesn't.
char is a distinct type. C 2018 6.7.2 5 specifies the elements in each line in the list in paragraph 2 designates the same type, except it is implementation defined whether, for bit-fields, int is the same type as signed int or unsigned int. That list puts char, signed char, and unsigned char in separate lines. Note 45 informs us, in part, “char is a separate type from the other two and is not compatible with either.” Apple clang-1<IP_ADDRESS> reports, when attempting to return either a signed char * or an unsigned char * for a char *, that they are incompatible (both).
@EricPostpischil Thanks, I've edited the answer to say that in this case they both fall into the criteria.
Please note that Annex G is informative and the relevant part to quote is normative C90 6.3.
This refers to the precursor to the "strict aliasing rule" later introduced in C99. In C90, it was ambiguous what to do with objects that had no type, such as the data pointed at by the return from malloc.
It means that if the type of the object is either signed int or unsigned int, you can do a lvalue access either with signed int* or unsigned int*. These two pointer types are allowed to alias. So for example if you have a function like this:
void func (signed int* a, unsigned int* b)
then the compiler cannot assume that a and b point to different objects.
(Note that wildly exotic systems can in theory have padding bits and trap representations for signed types, so accessing an unsigned int through a signed int* could be UB for other reasons, in theory.)
The character types are a special case compared to other integer types indeed. But it doesn't matter here, since the rule have a special case too: "or a character type". char, unsigned char and signed char are all character types. This means that all pointer access to an lvalue using any of these 3 types are well-defined.
The lvalue type doesn't even need to be a character type! You can for example lvalue access an int through signed char* and it is well-defined, but not the other way around.
In C89/C90, every object had a type. Under C89/C90 rules, given void *vp=calloc(4,128); float *fp = vp; int32_t *ip=vp;, assuming the malloc succeeds, fp[0], f[]1], etc. will be an objects of type float and ip[0], ip[1], etc. will be objects of type int, while vp wouldn't identify any object at all. The primary problems with C89 were that said "accessed by" rather than "aliased by". With that change, even though fp[0] and ip[0] exist simultaneously, and an access to fp[0] would access the stored value of ip[0], that wouldn't matter unless code used both...
...ip[0] and fp[0] to access the object, and at least one of those accesses was a write.
Good point about 6.3, I've made that the primary source in my Q.
@supercat I'd read it a bit stricter, unless there's another section that informs this? ie. code could have both fp and ip declared, but only code that does at most one of fp[n] or ip[n] is valid (write or not). Is that interpretation wrong?
@detly: The C89 Committee was chartered to describe a pre-existing language; the behavior of accessing fp[1] and ip[2] was unambiguously defined in that language when int32_t was defined as a type that was the same size as float; nothing in the published Rationale indicates any intention to change it. Committees have generally taken the view that in cases where an action was unanimously supported and obviously useful, they didn't need to worry about whether the Standard's rules actually defined the behavior or left it as one of the "popular extensions" alluded to in the Rationale.
@detly: If one interprets the phrase "object" used in the Effective Type Rule as being applicable to the blob of memory returned by malloc, even though the definition of malloc() does not refer to that blob as an "object", and even though that would be inconsistent with the use of the term elsewhere in the Standard, then writing fp[1] and ip[2] in that order might leave the "object" returned from malloc() with an effective type of int, and I think some compiler writers think that's what the Standard intends, but...
...that would gut the semantics of the language, be totally contrary to pre-existing practices, and require using the word "object" in a sense that is contrary to its meaning everywhere else. While the footnote to the Effective Type rule would suggest that "object" should have a novel meaning, nothing in the standard really indicates what that meaning is.
When C89 was written, unsigned types were a sufficiently new addition to the language that a lot of code used int in places where unsigned--once it existed--would have made more sense. The authors of the Standard wanted to ensure that functions that used the newer unsigned type would be able to exchange data with those that had been written to use int because unsigned hadn't existed yet.
The Standard is a bit ambiguous as to whether a type like unsigned* has a "corresponding signed type" int*, or unsigned** has a "corresponding unsigned type" int**, etc. Given the purpose of allowing interaction between code that predates unsigned types with code that uses them, making a function that's written to operate on sequences of int* unusable by clients that have sequence of unsigned* would be contrary to that purpose and also to the Committee's charter. Upholding the stated purpose wouldn't require that int** be universally usable to access objects of type unsigned*, but would require that compilers given constructs like:
unsigned *foo[10];
actOnIntPtrs((int**)foo, 10);
recognize that the called function might affect objects of type unsigned* stored in foo.
| common-pile/stackexchange_filtered |
How to Change the language of my JDateChooser?
I would like to change the language of my JDateChooser to Chinese.
I have tried this method:
//change jdatelanguage
Locale locale = new Locale("zh", "CN");
But it didn't work. Maybe I put it in the wrong place.
Can someone please help?
I also tried this method:
java -Duser.language=fr -Duser.country=FR -cp build/classes DateDemo
Did you try calling JDateChooser#setLocale? - It would also help to know which JDateChooser you're using :P
How do I call JDateChooser#setLocale? I am usingJcalendar 1.4. Thank you!
From JCalendar Tutorial - "The JCalendar components take advantage of the internationalization and localization work done by the Calendar class. In order to fully localize JCalendar to other than US English, you will need to obtain the source code for JCalendar and create a org.freixas.jcalendar.Bundle_.properties file which translates the text in org.freixas.jcalendar.Bundle.properties, where is a two-letter country code."
Have you tried JLocaleChooser?
| common-pile/stackexchange_filtered |
printer_open () php support, printing from web app possible solutions
Is printer_open() still supported in the latest php version? I am trying to figure out if its possible to print directly from PHP but I am not having any luck. I have found some useful questions and articles but they all use the "printer_open()" and when I try using it (even after adding the dll ext. and adding the ext to my php.ini then restarting my xampp) I get error :
Fatal error: Uncaught Error: Call to undefined function printer_open()
in C:\xampp\htdocs\PHP-Printer-master\test_dll.php:6 Stack trace: #0
{main} thrown in C:\xampp\htdocs\PHP-Printer-master\test_dll.php on
line 6
I also have gone into the PHP manual and can't find any refrences on this:
https://www.php.net/manual-lookup.php?pattern=printer_open&scope=quickref
I get: **
"printer_open doesn't exist. Closest matches:"
**
so my best guess is that is no longer supported? but I would like to see if there is a more concrete answer/documentation proof that is been deprecated... To make sure I am not basing my decision/research on assumptions
My ultimate goal:
I have a web application form and after all the values are input I want to be able to print a receipt with no printer dialog from mobile devices, and pc . I understand there is a browser restriction so this is technically not possible. Are there any other solutions I could use? Do I have to build an app and have the users allow it in order to accomplish something like this?
I have done some research but so far the only "viable" options are: build an app, use a windows print service.
I also found this: https://github.com/mike42/escpos-php/tree/master/example
and I am still unable to get this to work (printer issues) but in the mean time I wanted to get maybe some extra feedback or opinions.
I apologize I am not an expert in this subject and I am just learning about all this as I go. Any feedback will be greatly appreciated!
Thanks!
printer_open would want the printer to be attached to the web server. You won't find a php based solution for printing on the client, because client-side is not handled at all by php. Look for a html/javascript/css solution.
I've encountered this use case in my own business.
You have to :
- buy a Google Cloud Print enabled printer
- register the printer with Google Cloud Print
- create a document (receipt, invoice, etc.) in a common format, such as PDF (through some third-party PHP lib like TCPDF)
- send the document to the printer through Google Cloud Print
There's no official and easy to use PHP API available for Google Cloud Print, you will have to deal with raw json POST requests or use a third-party api lib (I wrote one, available on my github).
| common-pile/stackexchange_filtered |
Python loop keeps stopping in Window's interpreter
I'm using the default Python 3.8 interpreter in Windows.
Whenever I run a long loop in it, it'll stop and I have to press or hold down the Enter key for it to keep going. This was never a problem in Linux.
How do I fix this behavior?
# this loop will eventually stop/hang/pause forever, until I press the Enter key
for i in range(5000):
time.sleep(1)
print(i)
If I run the code through any IDE, it doesn't pause. But I want to run this particular code directly in the interpreter for my own reasons.
I took this screenshot after waiting more than 1 minute for it to continue. This isn't a once off problem. ANY loop I run, no matter how small or big or complex, will permanently stop after a few iterations until I press the ENTER key on my keyboard.
How do you know if it has stopped/paused? This will take 5000 seconds to run.
What is your evidence of "forever"? This is a loop that simply sleeps for over 80 minutes, one second at a time. There is no output, no input, ...
@HarshalParekh This isn't what's happening, I fixed my silly example
@Prune I fixed my example
@Jase this is still not a good example. It’ll keep on pruning 5000 “1”s. Replace it with print(i) and you’ll see that there is no problem with the code.
@HarshalParekh The code stops as I said. Whether I print 1, i, or do any other operation. The problem isn't with the code, as I said it works in any IDE (I've tried Wind, Pycharm). The problem is when I run it inside the Windows interpreter. If I run it on my Ubuntu box in the terminal, it works fine.
@HarshalParekh I just attached a screenshot
@Jase - strange, I am unable to replicate this on my windows machine, maybe someone who can replicate this can help you.
Voting to close that it’s not actually a problem as stated in the accepted answer.
The console will pause the script if you click on the output, it will try to stop the code to "select" a part of the output. give it a try without clicking it. ENTER will remove focus from the select bar on the console, so you will see that the it's not there anymore.
This simply means that there’s no error in the interpreter. If it’s true then the question has wrong information. It nowhere mentions that it stops after the first keyboard input. I am voting to close the question as not reproducible or caused by typo.
The program you have shown will literally do nothing. It won't print anything to console and doesn't wait for input.
So it will literally run for 83 minutes not showing that it is doing anything and then it will exit with a exit code of 0.
This isn't what's happening, I fixed my silly example
Ok I see what you mean. So I had this issue before as well. It had to do with how windows command line works since that is what python uses when you run it directly. If you click your mouse on any line above where the cursor is it will freeze the program. When you hit enter you tell the command line you want to go to cursor and it resumes. Give this a try. If you want to bring the window to the fore ground of your desktop click the taskbar of the window rather than on the window itself. Let me know if this works for you.
If it just pauses without you clicking it then I'm unable to reproduce your error with python 3.8.3 Windows 10 64-bit
If quick-edit mode is enabled in the console, then clicking anywhere on the console screen switches to select mode. You'll see the title bar updated to start with "Select" (localized, of course). When print writes to sys.stdout, if it's a console screen-buffer file, then internally it calls WriteConsoleW. In select mode, the latter blocks until the user exits select mode by pressing a key such as escape to end the selection or enter to copy the selection to the clipboard. This is a convenience for the user in select mode, but how easy it is to enable it with a single click is bad design.
I have a guess at what you are running into.
Of course, the program continues to run, but you just did not see the output, because the output is buffered and you don't flush it.
So, after each print(i), call the function flush_output_streams():
def flush_output_streams() -> None:
"""
flushes the output streams.
flush calls are wrapped in try ... except, because
standard streams might be replaced with other streams which
dont have the flush method.
"""
try:
sys.stdout.flush()
except Exception:
pass
try:
sys.stderr.flush()
except Exception:
pass
The print function also accepts a flush parameter, which can be set to True so "that the stream is forcibly flushed".
@Gino Mempin: thanks for the edit - I prefer to flush explicitly at certain stages of the program, because I also need to flush the streams for logging (StreamHandler).
On Linux there is usually no problem, but on some windows machines it can take a long time until the output streams are getting flushed by itself.
| common-pile/stackexchange_filtered |
My code is reading the textbox just once
The problem is that my code is just reading the Textboxes just the very first time, wheneaver I do any change to the Textboxes it doesn`t read the new ones.
This is the code of the form with 2 textBoxes.
public partial class Form1 : Form
{
double tb1, tb2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 forming = new Form1();
Reading objR = new Reading(forming);
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
}
And the class where I´m trying to read the textboxes is this:
class Reading
{
double _tb1, _tb2;
public Reading(Form1 form)
{
this._tb1 = double.Parse(form.textBox1.Text);
this._tb2 = double.Parse(form.textBox2.Text);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
I think that Reading objR = new Reading(forming);reads the TextBoxes but they are read just once, When I Click my Button again it is just giving me the same info, I added the method mAdd to make sure the textboxes are being used correctly.
What can I do to actualy read the newest data in the Textboxes?
public partial class Form1 : Form
{
double tb1, tb2;
private void button1_Click(object sender, EventArgs e)
{
Reading objR = new Reading();
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
public class Reading
{
public double Reading(double a,double b)
{
_tb1= a;
_tb2 = b;
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
First, it's overkill to pass the entire form in to your Reading class' constructor. Why not just have a constructor with two double arguments?
Second, if you have to pass the form, then remove the Form1 forming = new Form1(); and replace the next line with Reading objR = new Reading(this);
It´s just a test I did, I need to use more types of variables. Thank You very much
The main reason is you are passing a NEW instance of Form1 to your reading class and not the instance where the textboxes you are changing.
Just to add to ffa's answer.
With this, the return value of reading class' mAdd and mAdd2 will be the same.
private void button1_Click(object sender, EventArgs e)
{
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
Reading objR = new Reading(tb1, tb2);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
class Reading
{
double _tb1, _tb2;
public Reading(string tb1, string tb2)
{
this._tb1 = double.Parse(tb1);
this._tb2 = double.Parse(tb2);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
| common-pile/stackexchange_filtered |
The screen size overwrites the other ones :S
Ive been trying to make a change of my category images depending on screen size. But right now only the first screen width size are being used. It seems as though the other ones are being overridden by the first row of code (max-width: 769px). (on this site: http://origami.directory/)
What can I do so it changes 3 times as it should do?
.category-list-item {
float: left;
padding: 1em;
}
@media screen and (max-width: 769px) {
.category-list-item { width: 20%; }
};
@media screen and (min-width: 480px) {
.category-list-item { width: 25%; }
};
@media screen and (max-width: 480px) {
.category-list-item { width: 33.33%; }
};
If someone could help me fix this I would be super grateful!
/ Martin
Hm that looks familiar. I wrote that sample CSS for another question. However I don't really understand your question. Can you add a image where we can see what you are trying to do?
Remove the extra semi-colon ; from the end of your queries.
Your queries should be like this:
@media screen and (max-width: 769px) {
.category-list-item { width: 20%; }
}
@media screen and (min-width: 480px) {
.category-list-item { width: 25%; }
}
@media screen and (max-width: 480px) {
.category-list-item { width: 33.33%; }
}
Your queries are conflicting with each other making the second query obsolete. Specify a range for each like this:
@media (max-width: 480px) {
.category-list-item{width: 33.33%;}
}
@media (min-width: 481px) and (max-width: 768px) {
.category-list-item { width: 25%; }
}
@media (min-width: 769px) {
.category-list-item { width: 20%; }
}
I'm not very sure with the min-width:769px part so just let me know what exactly are you trying to do and I'll fix that accordingly. The above is just to show you how queries work basically.
Thanks! :) could you check this one out as well?
http://stackoverflow.com/questions/32039534/cant-get-get-queried-object-id-to-work-on-a-image-category-based-website
Please mark this as the right answer if it helped you in fixing your issue Martin. And checking the other question now.
Hi again. Do you mean you are checking this out: http://stackoverflow.com/questions/32039534/cant-get-get-queried-object-id-to-work-on-a-image-category-based-website?
And also. How do I mark this as the right answer? / Martin
Just click on the tick mark on the left side of the answer Martin. And regarding the other question, I think that is wordpress related so you should post that in http://wordpress.stackexchange.com/ instead.
| common-pile/stackexchange_filtered |
Extjs4 save all grid data in a table
I know how to get a value from a selected row of a grid, just like this:
var records = Ext.getCmp('My_Grid').getSelectionModel().getSelection();
var record = records.length === 1 ? records[0] : null;
alert(record.get('name'));
But what I want is to get the name of all rows of the grid. To do it, I have used the method above, to write this functional function:
var MonTableau = new Array();
for (var j=0; j<=Ext.getCmp('My_Grid').getStore().getCount()-1; j++) {
Ext.getCmp('My_Grid').getView().select(j);
var records = Ext.getCmp('My_Grid').getSelectionModel().getSelection();
var record = records.length === 1 ? records[0] : null;
MonTableau[j+1]=record.get('name');
}
But it's not professional, I want more simple and professional method.
The ExtJS store provides an each function which applies a passed fn for each record cached (already loaded) in the store:
var myStore = Ext.getCmp('My_Grid').getStore();
myStore.each(function(rec) {
console.log(rec.get('name'));
});
P.S. I'm using console.log(); rather than alert(); as I think it's easier to read everything from the browser log.
| common-pile/stackexchange_filtered |
Scanner doesn't recognize a number on the first try?
If I input 1 or 3, my game will start on the first try but if I input 2, I'll get invalid input. Try again :. When I input 2 again, my game will start.
public static void Difficulty() {
System.out.println("*********************************");
System.out.println("* Welcome to Crypto's MathGame! *");
System.out.println("*********************************");
System.out.println("");
System.out.println("[1] Easy Difficulty");
System.out.println("[2] Medium Difficulty");
System.out.println("[3] Hard Difficulty");
System.out.print("Please choose an option : ");
String option = input.nextLine();
if((!("1".equals(option) || !("2".equals(option) || !("3".equals(option)))))){
System.out.print("Invalid input. Try again : ");
option = input.nextLine();
}
}
}
Why does my Scanner not recognize '2' on the first try?
Because your if condition logically says nothing is valid. "2" is not "1" (or "3").
As a side note, you could consider using input.nextInt() and use numeric comparisons if(option <= 0 || option > 3) { ... }
Also, you brackets look wonky. Note what the first ! is negating compared to the other !s.
@ElliottFrisch so what's the solution? I still don't understand why '1' and '3' get recognized right away but '2' needs to be inputted twice
This should work
if(!("1".equals(option) || "2".equals(option) || "3".equals(option)))
{
System.out.print("Invalid input. Try again : ");
option = input.nextLine();
}
But more importantly @Crypto do you understand why your way didn't work?
Hmm. Not really. Is it because I had 3 !'s which made '2' reverse? could explain? :)
@Crypto It is because 1. you have used nested conditions 2. Wrong logic.
I would recommend you to draw the logic circuit (using logic gates) of your if statement and draw mine as well. Then you can easily find the difference.
@Crypto I suggest you read about De Morgan's laws. if (!"1".equals(option) && !"2".equals(option) && !"3".equals(option))
| common-pile/stackexchange_filtered |
FrameLayout onClick for overlapping images on Android
First I thought that the problem will be very easy to solve, but it proved to be a challenge.
Scenario
One FrameLayout and two ImageViews, one over the other. The first images has a Translate animation and a onClick event. Let's translate this in something practical: the Framelayout has one Rabbit image and a Bush image. The Rabbit has a translate animation so it moves out of the bush. As soon as the rabbit becomes visible, the user can tap on it. Unfortunately this does not work as intended. Even if the rabbit is not visible (being behind the bush) if the user taps on the bush, the click event of the rabbit fires. I tried to add onClick event (that doesn't do anything) for the bush image, but now only this one fires, and the rabbit ones doesn't.
Code
Animation
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%"
android:toXDelta="100%"
android:fromYDelta="0%"
android:toYDelta="0%"
android:duration="25000"
android:zAdjustment="top" />
Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layBackground"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@drawable/someimage">
<ImageView android:id="@+id/imgAfterBush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:layout_marginLeft="50dip"
android:onClick="imgAfterBushOnClick"/>
<ImageView android:id="@+id/imgBush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bush"
android:layout_gravity="bottom|left"
/>
</FrameLayout>
I want the onClick event of the Rabbit image to fire only when it is visible. Any solutions ? Thank you.
It is not too difficult, however you need first to learn:
creating custom views
drawing on canvas
animating images on canvas
detecting on touch events
Here is a simple one for the start, which I did for a similar question: How can I use the animation framework inside the canvas?
Your example is very good. Thank you for that. I need to have more animations in different places of my layout, so I'll have more active custom views. In order to create them and show them properly I need to take care of their width/height. This is starting to get way too complicate. I will try to test your example and try to see if I can adapt it.
Also, I have posted a new question regarding what I need to do and probably both questions will have the same type of solution. Here it is http://stackoverflow.com/questions/5087926/animating-a-imageview-on-a-random-path-in-android But I've started to study SurfaceView as you said in your previous link and seems to fit my needs better.
Animations on Android < 3.0 only affect the rendering of a View: the view you animate is still at its original position. You need to move the View (by changing its layout parameters for instance) yourself when the animation is over.
Thank you for your answer but I don't understand it. What's the point of having a Translation animation if the user can't interact with it while running? The user needs to be able to tap on the imageview while it animates, not when it's over.Hmm... this means I need to implement my own animation system with View parameter changing on a timer? For such a basic thing ? What other solution there is for my situation ?
It seems worth noting that if you go with that approach (moving the View after the animation is done,) the bunny ImageView would not be clickable while it's animating. If the bunny ImageView is slowly creeping out from under the bush ImageView and the user should be able to click on it at any time, this won't suit your needs.
| common-pile/stackexchange_filtered |
Converting String to Interger
I want to change the color of text by applying a condition. I'm getting the text from Json. Code is working fine without that "check for the color change" part present at the end of the code. Otherwise, It isn't returning anything. app crashes. What's the problem??
Here is the code :
ArrayList<HashMap<String, String>> list = new ArrayList<>();
try {
JSONObject jobj = new JSONObject(jsonResposnce);
JSONArray jarray = jobj.getJSONArray("items");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jo = jarray.getJSONObject(i);
String itemName = jo.getString("itemName");
String Power = jo.getString("Power");
String RH = jo.getString("RH");
String DAILYDATE = jo.getString("DAILYDATE");
String TPH = jo.getString("TPH");
String Production = jo.getString("Production");
HashMap<String, String> item = new HashMap<>();
item.put("itemName", itemName);
item.put("Power", Power);
item.put("RH", RH);
item.put("TPH", TPH);
item.put("DAILYDATE", DAILYDATE);
item.put("Production", Production);
list.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(new ArrayAdapter<HashMap<String, String>>(this, R.layout.listdaily_row,
R.id.yx_item_name, list) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = super.getView(position, convertView, parent);
final HashMap<String, String> item = getItem(position);
TextView itemName = rowView.findViewById(R.id.yx_item_name);
itemName.setText(item.get("itemName"));
TextView Power = rowView.findViewById(R.id.yx_power);
Power.setText(item.get("Power"));
TextView RH = rowView.findViewById(R.id.yx_rh);
TextView TPH = rowView.findViewById(R.id.yx_tph);
TPH.setText(item.get("TPH"));
TextView DAILYDATE = rowView.findViewById(R.id.yx_date);
DAILYDATE.setText(item.get("DAILYDATE"));
TextView Production = rowView.findViewById(R.id.yx_prod);
Production.setText(item.get("Production"));
// check for the color change
String check = item.get("RH");
if (check != null && Integer.parseInt(check) >= 10) {
RH.setTextColor(Color.GREEN);
} else {
RH.setTextColor(Color.RED);
}
RH.setText(item.get("RH"));
return rowView;
}
});
What is the error that you get?
paste the exception message too... please
It shows loading dialog for few seconds and then screen goes blank. Later, shows app stopped working
No error in building the app. Problem after running the activity
Please have a look at Unfortunately MyApp has stopped. How can I solve this? to get the crash log that people are asking for.
Try printing the value of check, most probably it's not a numeric string. It's better to add a vlidation of this string before using it in the if statement.
In locat it shows the error : java.lang.NumberFormatException: For input string: "" Problem lies in the If condition line. I don't know why?? what's wrong here
If you were given a string "" which number would you make of it? Integer.parseInt() can't parse an empty string.
Thanks @Markus. There was some null values and decimal values which was causing the error. Somehow I can't remove null and decimal values from my item list(accessing it from gsheet). Is there any other method other than 'Integer.parseInt' to deal with it while having null and decimal values.?? I can use float for decimal values. But what should be used for handling null ??
What about a simple if (check != null && !check.isEmpty() && Integer.parseInt(check) >= 10) {...}?
The Problem was the null string. So I modified the check part to handle null value issue, as shown below and now it's working.
// check price
String checkPrice = item.get("RH");
int check = 0;
try
{
if(checkPrice != null)
check = Integer.parseInt(checkPrice);
}
catch (NumberFormatException e)
{
check = 0;
}
if (check>= 10) {
RH.setTextColor(Color.GREEN);
} else {
RH.setTextColor(Color.RED);
}
RH.setText(item.get("RH"));
return rowView;
}
});
| common-pile/stackexchange_filtered |
Why is $\bar x(1-\bar x) + \frac{s^2}{n}$ an unbiased estimator of $\mu (1-\mu)$?
Let's consider a population of boolean values [0,1]. In the population, the mean (or frequency of 1) is $\mu$. We take a sample of size $n$, which mean $\bar x$ is
$$\bar x = \frac{\sum_i^n x_i}{n}$$
and sample variance
$$s^2 = \frac{\sum_i^n (x_i - \bar x)^2}{n-1}$$
I would like to estimate the parameter $D=\mu (1-\mu)$. It appears from the below small simulations (coded in R) that the unbiased estimator of $D$ is
$$\hat D = \bar x(1-\bar x) + \frac{s^2}{n}$$
Can you help me to figure out why this is true?
nbtrials = 5000
popSize = 200
pop = 0:1
sampleSize = 10
out = numeric(nbtrials)
for (trial in 1:nbtrials)
{
s = sample(pop,size=sampleSize, replace=TRUE)
xbar = sum(s) / sampleSize
out[trial] = xbar * (1-xbar) + var(s) / sampleSize
}
xbar=sum(pop) / length(pop)
print(paste("True value of D = ",xbar *(1-xbar)))
print(paste("Average estimated value of D = ",mean(out)))
There seems to be a problem with the expression of sample variance. Kindly fix that.
@MathLover Thanks! fixed
Several facts you need to use:
$$ E[X_1] = \mu, Var[X_1] = \mu(1 - \mu), E[\bar{X}] = E[X_1], Var[\bar{X}] = \frac {1} {n} Var[X_1], E[S^2] = Var[X_1]$$
Then we have
$$ \begin{align}
E[\hat{D}]
&= E[\bar{X}] - E[\bar{X}^2]+\frac {1} {n} E[S^2] \\
&= \mu - Var[\bar{X}]-E[\bar{X}]^2 + \frac {1} {n}\mu(1 - \mu) \\
&= \mu - \frac {1} {n} \mu(1-\mu)-\mu^2+\frac {1} {n}\mu(1 - \mu) \\
& = \mu - \mu^2 \\
& = \mu(1 - \mu)
\end{align}$$
Therefore this is an unbiased estimator of $\mu(1 - \mu)$
Note that $$E[\bar{x}]=\mu,$$ $$var(\bar{x})=\frac{\mu}{n}\left(1-\mu\right),$$ and $$E[\bar{x}^2]=var(\bar{x})+E[\bar{x}]^2 = \mu^2 + \frac{\mu}{n}\left(1-\mu\right).$$
Also, $$E[s^2]=var{(x_i)}=\mu\left(1-\mu\right).$$
Therfore,
$$E[\hat{D}]=E[\bar{x}]-E[\bar{x}^2]+\frac{E[s^2]}{n}=\mu-\mu^2-\frac{\mu(1-\mu)}{n}+\frac{\mu\left(1-\mu\right)}{n} = \mu(1-\mu).$$
So $\hat{D}$ is an unbiased estimator of $\mu(1-\mu)$.
Incidentally, $s^2$ is also an unbiased estimator of $\mu(1-\mu)$.
| common-pile/stackexchange_filtered |
Provide different guidance text to suggested edit reviewers and to rejected editors
Some guidance is associated to suggested edit rejection reasons.
This guidance is shown to reviewers and to the original author alike. But reviewers and editors don't need the same kind of input: reviewers need guidance to make the determination as to whether an edit falls under a rejection reason, while editors need guidance to explain why the edit is wrong.
For some rejection reasons, the same guidance text is fine, but others would benefit from different guidance. For example:
Title: attempt to reply
Guidance to reviewers: This edit an attempt to reply to or comment on the existing post.
Guidance to the editor (for a question): To request some clarification or improvement from the author of the question, leave a comment under the question. If you want to provide a solution, use the answer box at the bottom of the page.
Guidance to the editor (for an answer): To request some clarification from the author or provide constructive criticism, leave a comment under the answer. If you want to provide an alternative solution, use the answer box at the bottom of the page.
Guidance to the editor (for an answer, if the editor is the asker): To request some clarification from the author or provide constructive criticism, leave a comment under the answer. To add additional information about your problem, edit your question.
In this case, reviewers don't need to be given hyper-detailed guidance as to when to edit vs when to answer vs when to comment. On the other hand, editors who fall afoul of this reason are often new to Stack Exchange and need guidance that's as tailored as possible.
See also Provide more in-line guidance to suggested edit reviewers for a discussion of additional guidance for reviewers.
The same may apply to close reasons: everyone needs to know what the close reason means, but beyond that close voters need additional guidance to indicate whether the close reason apply, while authors need guidance as to how they might improve their question to make it reopenable.
| common-pile/stackexchange_filtered |
Function wrapper in C++
Very simply, I’m using an optimization library in C++ that takes in a function of a single variable. I would like to be able to pass in multiple parameters though (which this library does not support). What I would like to do is create a lambda function of the sort (kind of like in Python) that lets me represent the cost function as a function of a single variable that passes in two parameters.
Here’s a simplified version of what I’m going for in pseudocode. Any help would be much appreciated. I can’t seem to get this to work with lambda in C++.
Optimize comes from a library (asa047). The version I wrote here isn’t at all realistic, but is just meant to demonstrate what this function takes in.
double cost(double x, double param1, double param2){
return x*param1 + param2;
}
double optimize(double fn( double x), double initial_value){
return optimal_x;
}
int main(){
double param1 = 2;
double param2 = 3;
function_object f; //What I would like to create
f(double x){
return cost(x,param1,param2);
}
optimize(f,2);
}
Where do param1 and param2 come from in the "real thing" ? (I'm sure they aren't just local variables as you have in the samples)
Unless the optimization library (which one?) allows you to pass user-defined data to your callback function (do you have any documentation for it?), what you are asking for is simply not possible (without resorting to creating a low-level thunk). The syntax you propose can be done easily using a lambda, however a capturing lambda (which yours would have to be) can't be used with a C-style function pointer, only a non-capturing lambda can do that.
@JerryJeremiah that won't work if optimize() expects a C-style function pointer, ie because it itself is in a C library (which I suspect it is), or otherwise does not support std::function or templated Callable parameters.
Is optimize your own function? Or is this from a library?
If it's this asa047, the function is declared to take an array of values as an argument, not a single value.
If you only want GCC, you can do it with local functions: https://stackoverflow.com/questions/1023261/is-there-a-way-to-do-currying-in-c
You can fake it sorta, by abusing static template members http://coliru.stacked-crooked.com/a/f66a402941b535ee
Another really bad idea is to static_assert(sizeof(double)>=sizeof(void*)), and then play reinterpret_cast games on the x parameter...
What I could see under the link to the asa47 library is that the function comes with source code. That means you can modify its parameters to pass any additional stuff as you need. I think that's the easiest and most correct way to achieve what you need. I.e. if fir example you want to additional int parameter, double fn ( double x[] ) can be replaces with something like double fn ( double x[], int p), then add int p to the "nelmin" function itself, and then modify call to fn() in the nelmin() to pass that additional p.
| common-pile/stackexchange_filtered |
Redirection url provoc a lost of information in my url
I'm trying to do a redirection from my host : http://www.carthera.com to http://www.carthera.eu,
Everything looks fine, but when i try to go on another page with carthera.eu I have this :
http://carthera.eu/index.php?page=carthera&ssmenu=0
But with carthera.com I just have the
http://carthera.com
Does anyone know where it comes from and how can i fix this ?
Thanks a lot!
For information, the problem was that the host used an Iframe to display carthera.com. So basically when I went on carthera.com, I would have an iframe with carthera.eu. So the information for the get are not displayed in carthera.com but in the iframe carthera.eu ...
| common-pile/stackexchange_filtered |
Upload File as a parameter to job in Azure DevOps
I have a Azure DevOps pipeline that automates user creation in salesforce. I am expecting the user details in an excel file, which is to be fed to the Azure DevOps pipeline as a pre-build parameter. However, I am not able to find a solution to it in Azure DevOps.
I had implemented this in Jenkins already using File parameter plugin in my previous projects. Does Azure DevOps has this capability?
After searching through various blogs and posts, I realized that there is no way to get this done directly in VSTS. However, I was able to get a work around for the same.
I created a VSTS User story and uploaded my attachment there
Using the Work Item ID, I used the work Item api to get the attachment ID.
Using the attachment API I was able to write a python script to download this attachment as a part of a pre-step in the Pipeline. Then this was available to use through out my automation script.
I don't think you can load a file before the build start and read the variables, but, you can add a task that read the variables from a file and put him in the beginning (the first step in your pipeline).
There are few extensions to read variable from a JSON file, for example: Json to Variable.
If you want to read from excel I think you should write a script that does it.
Thanks! I do have a script in place that converts excel to Json and then I use it for th further automation. However, these are self service CI/CD pipelines for non technical folks. My user will not know how to commit the excel into git or load it artifactory. Hence I wanted them to upload a file before the build like jenkins: (https://stackoverflow.com/questions/42224691/how-to-use-file-parameter-in-jenkins/42242113)
@B.TAnand According to your scenario, if you want to upload a file before build, I am afraid that this is currently not possible in azure devops.You could add your request for this feature on our UserVoice site.
@B.T Anand If Shayki's answer is helpful to you, would you please mark it as the answer.Or if you have any concern, feel free to share it here.
Using local hosted agent, you can publish artifact from local share, then move to i.e. ms-hosted agent and use it normally.
- task: DownloadFileshareArtifacts@1
inputs:
filesharePath: '\\myhost\myshare\myfolder'
artifactName: 'my-artifact'
downloadPath: '$(System.ArtifactsDirectory)'
parallelizationLimit: '8'
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/download-fileshare-artifacts?view=azure-devops
| common-pile/stackexchange_filtered |
change color of a row without refreshing page
I am working on a project at the moment. In iI am using ajax to update and calculate scores, which works fine. However, I have a color scheme that changes according to the score. The color does change, but only after the page is refreshed. Is there anyway I can get the color to change with refreshing the page? In my previous versions I used a button to refresh the page, but is there any way I can accomplish this without refreshing the page?
Here is the code that I am using to assign colors:
<?php $row_class = "";
while($row = mysql_fetch_assoc($dbResult1))
{
if($row['total_mai'] <= 2)
$row_class = "success";
else if($row['total_mai'] >= 5)
$row_class = "danger";
else if($row['total_mai'] >= 3 and $row['total_mai'] < 5)
$row_class = "warning";
// echo $row_class;
?>
In another page, here is an example of one question, it has three answers and depending on the answer a color is assigned based on the score
<tr>
<td class="form-group col-md-6">Is the duration of therapy acceptable?</td>
<td class="form-group col-md-6">
<p class="radio-inline">
<input type="radio" name="therapydur" id="j1" value="0" <?php echo $j1; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','0','<?php echo $row['p_id']; ?>')">
<a href="#" data-toggle="tooltip" data-placement="top" title="acceptable">A</a>
</input></p>
<p class="radio-inline">
<input type="radio" name="therapydur" id="j2" value="0" <?php echo $j2; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','0','<?php echo $row['p_id']; ?>')">
<a href="#" data-toggle="tooltip" data-placement="top" title="marginally acceptable">B</a>
</input></p>
<p class="radio-inline">
<input type="radio" name="therapydur" id="j3" value="1" <?php echo $j3; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','1','<?php echo $row['p_id']; ?>')">
<a href="#" data-toggle="tooltip" data-placement="top" title="unacceptable">C</a>
</input></p>
</td>
</tr>
Here is the ajax from the same page:
<script language="javascript" type="text/javascript">
function ajaxFunction(title,id,val,p_id)
{
//alert("test");
//alert(id);
//alert(val);
//alert(title);
//alert(p_id);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
var resp = xmlhttp.responseText;
var split_v = resp.split("__");
//alert(split_v.length);
//alert(split_v[1]);
document.getElementById("ajaxDiv_"+id).innerHTML=split_v[0];
document.getElementById("ajaxTotal").innerHTML=split_v[1];
}
}
xmlhttp.open("GET","ajax_mai.php?pdr_id="+id+"&value="+val+"&title="+title+"&p_id="+p_id,true);
xmlhttp.send();
return true;
}
</script>
You'll want to use css set on the element via js to change the colours
ok, does it make any difference if I am using bootstrap? Would you have an samples I could look at?
Are you setting colours via classes? If so list them. Are you returning just html in the ajax request or json?
No, the colors are being set according to a score e.g. if total > 5 ="success"
can you show the data that is returned from your ajax call? Is it json? Does the $row_class get returned in the response?
basically the data is returned is a score from 10 question, as in the example above.
@BarryMcDaid1982 I think you misunderstand. What is returned via the ajax request? Is it html/json/some other format?
you need to load script to ajax as well as you load dom via ajax because script in yoyr static page can not run to your ajax data
how exactly would I do that? I have only started using ajax last week, so this is pretty new to me, thanks
you can load a seprate script file with your data that you get from ajax like echo this or reurn it
could you give an example or adapt my code to show me please?
| common-pile/stackexchange_filtered |
Synchronising data between differently sized, and intermittently connected, devices
I am trying to find a solution to sharing my /home directories between my home computers. I have one desktop, with a 1TB disk, and a laptop with a 500GB disk. I also have a home server, which has a 1TB disk. The server's disk is completely usable for the solution.
I'd like a solution that would be able to run on my home network - so Ubuntu One is out of the question, and it's prohibitively expensive for the amount of data - and would allow my laptop, with a smaller total hard drive space than my desktop, to access all my files - I believe this removes an rsync based solution.
I would also like to be able to access files that have been "synchronised", for lack of a better word, to my laptop when I am not connected to my home network. This would also be useful for my desktop, in the case of the server being powered down.
I am quite competent with Linux, as well as networking, so I am not afraid of any technical issues.
Thanks in advance,
Joe.
I think you would like to make your own personal "Dropbox" at your home server.
There is a project called lipsync:
"A lightweight service that provides automated file synchronization between multiple hosts
lipsync is an open source, lightweight service that provides automated two-way, Dropbox file synchronization in Linux by utilizing OpenSSH, rsync, and lsyncd. lipsync is a the realization of a popular blog post of mine named HOWTO build your own open source Dropbox clone Since I made the posting I’ve received a great deal of interest, and had time to test and architect a workable solution. Thanks to everyone that read, commented and encouraged the further development of this idea!"
Here is the idea:
While a cool project, that requires all computers to have the same sized discs - my laptop has a smaller hard-drive than my desktop, and I would still like access to all my files, so I don't believe an rsync based method would work.
I think I misunderstood you before :-( Do you have more than 500 GB and want to access these files (at your server for example) from your laptop? Can't you just make a shared folder then?
There are more than 500GB of data, and I'd like to be able to access it all on my laptop. WHile a shared folder would work, I'd like to be able to access as many files as possible on my laptop while it's disconnected.
Now I got it :-) May be something with file compression would be good for the laptop? Or maybe have some folders priority?
Joe, I'm not sure how all your requirements can be satisfied - on the one hand, you want the files to be synchronized (i.e. physically copied) between the laptop and the other machines so you can access them offline, on the other - you state that you don't have enough space on the laptop for all your files, which kinda implies you want to access the files remotely without copying them to the laptop (via a SMB share, for example) - but in this case you're loosing the offline capability, of course.
The only solution I see is to sync some of your files using lipsync as suggested by desgua or even using Ubuntu One (it's quite possible that your really important files take less than a few gigabytes) and access the rest (videos?) via a share.
I was wondering if there's a possibility of synchronising file metadata, and then caching the file's data when it's accessed, when the network is available?
| common-pile/stackexchange_filtered |
Oracle forms Multiple rows modification issue
I m using forms 11g
I have one master-detail form.
I want to restrict the user from saving the non detail block record, If record entered in the corresponding master block has been rollbacked.
To be clear when i query or move out of that field i see a message 'do you want to save changes made?'
when i say 'NO', my master block values rolled back , but non detail block records are saving
I tried to use issue_rollback(null); but not working
Please add a Minimal Reproducible Example in order to describe your problem well.
I m using forms 11g
I have one master-detail form.
I want to restrict the user from saving the non detail block record, If record entered in the corresponding master block has been rollbacked.
to be clear when i query or move out of that field i see a message 'do you want to save changes made?'
when i say 'NO', my master block bvalues rolled back , but non detail block records are saving
I tried to use issue_rollback(null); but not working
| common-pile/stackexchange_filtered |
How to organize apps into folders in Android Programming?
I'm developing a launcher application. I want to auto organize apps into folders with subjects as Game, Social Network, Entertainment, Tool... But I do not know based on the information of the application to know what type it.
Sample : http://dantri4.vcmedia.vn/tI0YUx18mEaF5kMsGHJ/Image/2014/07/APUS-Launcher-3-feb4a.jpg
Is this question related to programming?
Yes, Android programming
As far as I know there is no straightforward way to achieve that.
The only thing that I could think about is to try to find some key words in the labels name of the apps.
Something like that:
private ArrayList<PackageInfo> searchPackageForString(PackageManager pm, String find){
List<PackageInfo> packs = pm.getInstalledPackages(0);
ArrayList<PackageInfo> results = new ArrayList<>();
for (PackageInfo pi : packs) {
if(pi.applicationInfo.loadLabel(pm).toString().toLowerCase().contains(find)){
results.add(pi);
}
}
return results;
}
Then you could try something like That:
searchPackageForString(getPackageManager(), "game");
I didn't try it but I thing that this is the only possibly direction.
Of course I can be wrong...
Edit:
Now that I looked in the pic you attached, I think that they check by find apps respond to Intents for action.
here some example:
https://stackoverflow.com/a/28404480/3332634
i used intent for find apps. but classify applications into folders by topic, then there is no good solution
Of course there is no perfect solution because there is no API to what you asking. I think that my answer + the link I gave you is the closest you can get.
OK. thank you so muck. i will try to find a bettter solution then share it with you.
| common-pile/stackexchange_filtered |
FCU: DeviceError:serial:open: No such file or directory
I am try to simulate UAV in gazebo using px4 and mavros roslaunch mavros px4.launch
got the following error
... logging to /home/mubashir/.ros/log/595548e6-bb3f-11ee-bab8-f3b849e8f78c/roslaunch-pc-8488.log
Checking log directory for disk usage. This may take a while.
Press Ctrl-C to interrupt
Done checking log file disk usage. Usage is <1GB.
started roslaunch server http://pc:39963/
SUMMARY
========
CLEAR PARAMETERS
* /mavros/
PARAMETERS
* /mavros/camera/frame_id: base_link
* /mavros/cmd/use_comp_id_system_control: False
* /mavros/conn/heartbeat_rate: 1.0
* /mavros/conn/system_time_rate: 1.0
* /mavros/conn/timeout: 10.0
* /mavros/conn/timesync_rate: 10.0
* /mavros/distance_sensor/hrlv_ez4_pub/field_of_view: 0.0
* /mavros/distance_sensor/hrlv_ez4_pub/frame_id: hrlv_ez4_sonar
* /mavros/distance_sensor/hrlv_ez4_pub/id: 0
* /mavros/distance_sensor/hrlv_ez4_pub/orientation: PITCH_270
* /mavros/distance_sensor/hrlv_ez4_pub/send_tf: True
* /mavros/distance_sensor/hrlv_ez4_pub/sensor_position/x: 0.0
* /mavros/distance_sensor/hrlv_ez4_pub/sensor_position/y: 0.0
* /mavros/distance_sensor/hrlv_ez4_pub/sensor_position/z: -0.1
* /mavros/distance_sensor/laser_1_sub/id: 3
* /mavros/distance_sensor/laser_1_sub/orientation: PITCH_270
* /mavros/distance_sensor/laser_1_sub/subscriber: True
* /mavros/distance_sensor/lidarlite_pub/field_of_view: 0.0
* /mavros/distance_sensor/lidarlite_pub/frame_id: lidarlite_laser
* /mavros/distance_sensor/lidarlite_pub/id: 1
* /mavros/distance_sensor/lidarlite_pub/orientation: PITCH_270
* /mavros/distance_sensor/lidarlite_pub/send_tf: True
* /mavros/distance_sensor/lidarlite_pub/sensor_position/x: 0.0
* /mavros/distance_sensor/lidarlite_pub/sensor_position/y: 0.0
* /mavros/distance_sensor/lidarlite_pub/sensor_position/z: -0.1
* /mavros/distance_sensor/sonar_1_sub/horizontal_fov_ratio: 1.0
* /mavros/distance_sensor/sonar_1_sub/id: 2
* /mavros/distance_sensor/sonar_1_sub/orientation: PITCH_270
* /mavros/distance_sensor/sonar_1_sub/subscriber: True
* /mavros/distance_sensor/sonar_1_sub/vertical_fov_ratio: 1.0
* /mavros/fake_gps/eph: 2.0
* /mavros/fake_gps/epv: 2.0
* /mavros/fake_gps/fix_type: 3
* /mavros/fake_gps/geo_origin/alt: 408.0
* /mavros/fake_gps/geo_origin/lat: 47.3667
* /mavros/fake_gps/geo_origin/lon: 8.55
* /mavros/fake_gps/gps_rate: 5.0
* /mavros/fake_gps/mocap_transform: True
* /mavros/fake_gps/satellites_visible: 5
* /mavros/fake_gps/tf/child_frame_id: fix
* /mavros/fake_gps/tf/frame_id: map
* /mavros/fake_gps/tf/listen: False
* /mavros/fake_gps/tf/rate_limit: 10.0
* /mavros/fake_gps/tf/send: False
* /mavros/fake_gps/use_mocap: True
* /mavros/fake_gps/use_vision: False
* /mavros/fcu_protocol: v2.0
* /mavros/fcu_url: /dev/ttyACM0:57600
* /mavros/gcs_url:
* /mavros/global_position/child_frame_id: base_link
* /mavros/global_position/frame_id: map
* /mavros/global_position/gps_uere: 1.0
* /mavros/global_position/rot_covariance: 99999.0
* /mavros/global_position/tf/child_frame_id: base_link
* /mavros/global_position/tf/frame_id: map
* /mavros/global_position/tf/global_frame_id: earth
* /mavros/global_position/tf/send: False
* /mavros/global_position/use_relative_alt: True
* /mavros/image/frame_id: px4flow
* /mavros/imu/angular_velocity_stdev: 0.0003490659 // 0...
* /mavros/imu/frame_id: base_link
* /mavros/imu/linear_acceleration_stdev: 0.0003
* /mavros/imu/magnetic_stdev: 0.0
* /mavros/imu/orientation_stdev: 1.0
* /mavros/landing_target/camera/fov_x: 2.0071286398
* /mavros/landing_target/camera/fov_y: 2.0071286398
* /mavros/landing_target/image/height: 480
* /mavros/landing_target/image/width: 640
* /mavros/landing_target/land_target_type: VISION_FIDUCIAL
* /mavros/landing_target/listen_lt: False
* /mavros/landing_target/mav_frame: LOCAL_NED
* /mavros/landing_target/target_size/x: 0.3
* /mavros/landing_target/target_size/y: 0.3
* /mavros/landing_target/tf/child_frame_id: camera_center
* /mavros/landing_target/tf/frame_id: landing_target
* /mavros/landing_target/tf/listen: False
* /mavros/landing_target/tf/rate_limit: 10.0
* /mavros/landing_target/tf/send: True
* /mavros/local_position/frame_id: map
* /mavros/local_position/tf/child_frame_id: base_link
* /mavros/local_position/tf/frame_id: map
* /mavros/local_position/tf/send: False
* /mavros/local_position/tf/send_fcu: False
* /mavros/mission/pull_after_gcs: True
* /mavros/mission/use_mission_item_int: True
* /mavros/mocap/use_pose: True
* /mavros/mocap/use_tf: False
* /mavros/mount/debounce_s: 4.0
* /mavros/mount/err_threshold_deg: 10.0
* /mavros/mount/negate_measured_pitch: False
* /mavros/mount/negate_measured_roll: False
* /mavros/mount/negate_measured_yaw: False
* /mavros/odometry/fcu/odom_child_id_des: base_link
* /mavros/odometry/fcu/odom_parent_id_des: map
* /mavros/plugin_blacklist: ['safety_area', '...
* /mavros/plugin_whitelist: []
* /mavros/px4flow/frame_id: px4flow
* /mavros/px4flow/ranger_fov: 0.118682
* /mavros/px4flow/ranger_max_range: 5.0
* /mavros/px4flow/ranger_min_range: 0.3
* /mavros/safety_area/p1/x: 1.0
* /mavros/safety_area/p1/y: 1.0
* /mavros/safety_area/p1/z: 1.0
* /mavros/safety_area/p2/x: -1.0
* /mavros/safety_area/p2/y: -1.0
* /mavros/safety_area/p2/z: -1.0
* /mavros/setpoint_accel/send_force: False
* /mavros/setpoint_attitude/reverse_thrust: False
* /mavros/setpoint_attitude/tf/child_frame_id: target_attitude
* /mavros/setpoint_attitude/tf/frame_id: map
* /mavros/setpoint_attitude/tf/listen: False
* /mavros/setpoint_attitude/tf/rate_limit: 50.0
* /mavros/setpoint_attitude/use_quaternion: False
* /mavros/setpoint_position/mav_frame: LOCAL_NED
* /mavros/setpoint_position/tf/child_frame_id: target_position
* /mavros/setpoint_position/tf/frame_id: map
* /mavros/setpoint_position/tf/listen: False
* /mavros/setpoint_position/tf/rate_limit: 50.0
* /mavros/setpoint_raw/thrust_scaling: 1.0
* /mavros/setpoint_velocity/mav_frame: LOCAL_NED
* /mavros/startup_px4_usb_quirk: False
* /mavros/sys/disable_diag: False
* /mavros/sys/min_voltage: 10.0
* /mavros/target_component_id: 1
* /mavros/target_system_id: 1
* /mavros/tdr_radio/low_rssi: 40
* /mavros/time/time_ref_source: fcu
* /mavros/time/timesync_avg_alpha: 0.6
* /mavros/time/timesync_mode: MAVLINK
* /mavros/vibration/frame_id: base_link
* /mavros/vision_pose/tf/child_frame_id: vision_estimate
* /mavros/vision_pose/tf/frame_id: odom
* /mavros/vision_pose/tf/listen: False
* /mavros/vision_pose/tf/rate_limit: 10.0
* /mavros/vision_speed/listen_twist: True
* /mavros/vision_speed/twist_cov: True
* /mavros/wheel_odometry/child_frame_id: base_link
* /mavros/wheel_odometry/count: 2
* /mavros/wheel_odometry/frame_id: odom
* /mavros/wheel_odometry/send_raw: True
* /mavros/wheel_odometry/send_twist: False
* /mavros/wheel_odometry/tf/child_frame_id: base_link
* /mavros/wheel_odometry/tf/frame_id: odom
* /mavros/wheel_odometry/tf/send: False
* /mavros/wheel_odometry/use_rpm: False
* /mavros/wheel_odometry/vel_error: 0.1
* /mavros/wheel_odometry/wheel0/radius: 0.05
* /mavros/wheel_odometry/wheel0/x: 0.0
* /mavros/wheel_odometry/wheel0/y: -0.15
* /mavros/wheel_odometry/wheel1/radius: 0.05
* /mavros/wheel_odometry/wheel1/x: 0.0
* /mavros/wheel_odometry/wheel1/y: 0.15
* /rosdistro: noetic
* /rosversion: 1.16.0
NODES
/
mavros (mavros/mavros_node)
auto-starting new master
process[master]: started with pid [8503]
ROS_MASTER_URI=http://localhost:11311
setting /run_id to 595548e6-bb3f-11ee-bab8-f3b849e8f78c
process[rosout-1]: started with pid [8520]
started core service [/rosout]
process[mavros-2]: started with pid [8528]
[ INFO] [1706159125.586876777]: FCU URL: /dev/ttyACM0:57600
[ INFO] [1706159125.588129257]: serial0: device: /dev/ttyACM0 @ 57600 bps
[FATAL] [1706159125.588247399]: FCU: DeviceError:serial:open: No such file or directory
================================================================================REQUIRED process [mavros-2] has died!
process has finished cleanly
log file: /home/mubashir/.ros/log/595548e6-bb3f-11ee-bab8-f3b849e8f78c/mavros-2*.log
Initiating shutdown!
================================================================================
[mavros-2] killing on exit
[rosout-1] killing on exit
[master] killing on exit
shutting down processing monitor...
... shutting down processing monitor complete
done
I am using ros noetic with gazebo11
Welcome to Robotics Stack Exchange! Please make sure the device is connected. What does ls /dev/ttyACM0 command say?
Thank you. following command ls /dev/ show me following /dev/tty, I think I do not need a device connected at `/dev' I want to do gazebo similation sitl
You should be checking ls /dev/ttyACM0 instead. On the other hand, please check the documentation carefully. Currently, your command roslaunch mavros px4.launch is looking for a device connected at /dev/ttyACM0.
the problem solves by giving the following argument fcu_url:="udp://:14540@<IP_ADDRESS>:14557 just make sure dependant packages are installed and run roslaunch mavros px4.launch fcu_url:="udp://:14540@<IP_ADDRESS>:14557". so by default the is /dev/ttyACM0 which mean the launch file expect an flight controller is connected to it. but we are taking the data from the simulation, not the physical hardware.
| common-pile/stackexchange_filtered |
How to parse stock data from objects into an array
I am using the Recharts library to plot some stock market data. However, the simple line chart requires a very strict data structure like so
{name: 'Page A', uv: 4000, pv: 2400, amt: 2400}
I have data that looks like this
Object
AAPL:Array[4]
0:Object
adjClose:53.509768
close:411.23
date:"2012-01-02T18:30:00.000Z"
high:412.499989
low:408.999989
open:409.399998
symbol:"AAPL"
volume:75555200
__proto__:Object
1:Object
2:Object
3:Object
length:4
__proto__:Array[0]
GOOGL:Array[4]
TSLA:Array[4]
where each object for a specific ticker represents one day for that ticker. It seems like I need to go from that to a data structure like this
data=[
{date: 'Jan 12, 2012', AAPL: {open: 12, close: 15}, TSLA: {open: 15, close: 21}, GOOGL: {open: 125, close: 21}},
{date: 'Jan 13, 2012', AAPL: {open: 15, close: 12}, TSLA: {open: 21, close: 155}, GOOGL: {open: 21, close: 25}}
...
...
...
];
I am still not entirely sure that Recharts will plot the data the way I want even this way, but it seems the most likely option.
Just to clarify, the way I want it plotted is a separate line chart for each ticker on the same chart element
You can iterate through each symbol and then build the data object using a simple loop, with a sub loop into each symbol. This will assume each symbol contains identical arrays for the same dates.
// result object
let result = [];
// get the ticker list from the object keys
const tickers = Object.keys(yourDataObject);
// get number of days for first ticker by looking at it's array length
const days = yourDataObject[tickers[0]].length;
// iterate through the days to parse the data
for (let i = 0; i < days; i++) {
// initiate row data with date of the first symbol
let rowData = {
date: new Date(yourDataObject[tickers[0]][i]).toLocaleDateString(),
}
// iterate through the tickers for that day
symbols.forEach(symbol => {
const tickerDayData = yourDataObject[symbol][i];
rowData[ticker] = {
open: ~~tickerDayData.open, // using ~~ to get the int value, you could round if you'd prefer
close: ~~tickerDayData.close,
};
});
// add to main result array
result.push(rowData);
}
If you provided actual data we could run this in the console for testing.
Hey, that worked a charm. Thanks!
Yeah, sorry about not providing actual data. I just pulled that data from an api for an app I'm writing, so I wasn't sure how to put up the original data on here.
Great, glad to hear. Hope this helps broaden your understanding of JS.
| common-pile/stackexchange_filtered |
How to use a main column value on the sub-query of a join
I have a table "links". Links belong to "campaigns".
Links have many "clicks", "social_clicks" and "impressions"
For each active link belonging to an active campaign I want to calculate the following rate per day: (clicks + social_clicks) / impressions
The following query works correctly. But I think querying the links table again 3 times is not optimal. I'm not able to use the link-ids from the main query, I tried to replace the sub queries with "l.id" and "t1.link_id" but it returns "Unknown column"
How can I access a column of the main query in the sub-query of a join, and is there a better way to get the result I need?
Tables:
links: id int, campaign_id int, status int
campaigns: id int, is_active int
clicks: id int, link_id int, created datetime
social_clicks: id int, link_id int, time datetime
impressions: id int, link_id int, created datetime
Query:
select l.id,
sum(case when t1.col = 'clicks' then ct else 0 end) as total_clicks,
sum(case when t1.col = 'impressions' then ct else 0 end) as total_impressions,
coalesce(sum(case when t1.col = 'clicks' then ct else 0 end) / nullif(sum(case when t1.col = 'impressions' then ct else 0 end),0), 1000) as ctr,
t1.dt
from links l
inner join campaigns c
on c.id = l.campaign_id
and c.is_active = 1
left join
(
select count(1) as ct, link_id, date(created) dt, 'clicks' as col
from clicks
where created >= '2020-11-10 00:00:00'
and link_id IN (SELECT l2.id from links l2 INNER JOIN campaigns c2 on c2.id = l2.campaign_id AND c2.is_active = 1 WHERE l2.status = 1)
group by date(created), link_id
union all
select count(1) as ct, link_id, date(time) dt, 'clicks'
from social_clicks
where time >= '2020-11-10 00:00:00'
and link_id IN (SELECT l2.id from links l2 INNER JOIN campaigns c2 on c2.id = l2.campaign_id AND c2.is_active = 1 WHERE l2.status = 1)
group by date(time), link_id
union all
select count(1) as ct, link_id, date(created) dt, 'impressions'
from impressions
where created > '2020-11-10 00:00:00'
and link_id IN (SELECT l2.id from links l2 INNER JOIN campaigns c2 on c2.id = l2.campaign_id AND c2.is_active = 1 WHERE l2.status = 1)
group by date(created), link_id
) t1 on t1.link_id = l.id
where l.status = 1
group by l.id, t1.dt
having total_clicks > 0
You should at least provide some sample data.. a fiddle maybe?
I think you can make the inner join and left joins in the outer loop into the union all statements. Whether the below change will be helpful for your case?
select res2.id, res2.dt, sum(res2.clicks_count), sum(res2.impressions_count),
coalesce(sum(res2.clicks_count) / nullif(res2.impressions_count), 1000) as ctr,
from (
select res.id, res.dt,
case when res.col = 'clicks' then 1 else 0 end clicks_count,
case when res.col = 'impressions' then 1 else 0 end impressions_count
from
(
select li.id, cl.link_id, date(cl.created) dt, 'clicks' as col
from clicks cl inner join links li on cl.link_id = li.id
inner join campaigns ca on li.campaign_id = cl.id
where cl.created >= '2020-11-10 00:00:00'
and ca.is_active = 1
and li.status = 1
union all
select li.id, cl.link_id, date(cl.created) dt, 'clicks' as col
from social_clicks cl inner join links li on cl.link_id = li.id
inner join campaigns ca on li.campaign_id = cl.id
where cl.time >= '2020-11-10 00:00:00'
and ca.is_active = 1
and li.status = 1
union all
select li.id, im.link_id, date(im.created) dt, 'impressions' as col
from impressions im inner join links li on im.link_id = li.id
inner join campaigns ca on li.campaign_id = im.id
where im.created >= '2020-11-10 00:00:00'
and ca.is_active = 1
and li.status = 1
) res) res2
group by res2.id, res2.dt
having sum(res2.clicks_count) > 0;
| common-pile/stackexchange_filtered |
GitLab: You are not allowed to access master! After moving gitlab to another server
I'm moving my gitlab instance to another server and I run to problem.
clone is working fine, but push is throwing error, and I can't figure out where is problem.
In gitlab logs is nothing usefull.
git push
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 351 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: GitLab: You are not allowed to access master!
remote: error: hook declined to update refs/heads/master
To git@server:user/repo.git
! [remote rejected] master -> master (hook declined)
error: failed to push some refs to 'git@server:user/repo.git'
I don't know where is problem, I change little bit configuration. Repos and satelites where on previous server symlinks to /media/data/git/repositories now is /home/git symlink to /media/disk/git But i don't think that is the problem.
EDIT://
gitlab:check is everything OK also gitlab-shell check is OK
you need to import ssh keys again
I've add new ssh key and use it. When I do git clone, I'm asked for ssh password and clone is fine.
Open the project page, go to "Commits", choose "Branches" tab, and check the Protected-section - maybe someone has restricted the access for master branch.
That is not problem i have only master branch in most projects. I now have two separate gits on one domain, one is on another port, and when I try push on old working domain everything works, but new one wont.(of course I made clone from them separately)
howdy, got similar problem, the https-protocol is ok but the git-protocol keep denying the push. did you find any solution on this?
[TL:DR]
After loads of frustrated hours and lots of trial and error, I found a solution to this problem (for me anyway).
cd /home/git/repositories
rm -rf */*/hooks/update
[Explanation]
I upgraded from 6.3 -> 6.9 sequentially with no problems on the front end, but (silly me) didn't check push & pulls each time so I don't know exactly where this started happening. I suspect after the 6.7 upgrade. Both SSH and HTTP push & pulls stopped working but with slightly different errors. I searched for symlinks on the repositories directory like some threads said, I also ran chmod's and chown's to ensure git had access to all the repositories. I also checked NGINX config's to ensure it was pointing to the right IP/FQHN. No dice, same errors. I finally found this issue which lead me check a few things and finally to the solution above.
I'm not sure if this fix is because the 'update' files in each repo's hooks folder were symlinks, or because of something in the files themselves, but now I can push & pull as normal.
I use the Bitnami version and the previously configured config.yml file pointed to a symlink rather than the actual directory.
I Fixed this changing the gitlab-shell config.yml to point to the real repository directory.
# repos_path: "/opt/gitlab-6.3.0-1/apps/gitlab/repositories"
to
repos_path: "/home/git"
On a fresh install for me, I had serious issues when /home was a symlink to /usr/home.
gitlab-shell/config.yml contained repos_path: "/home/git/repositories which caused the same error output you referenced above. Putting the canonical path in it's place corrected the issue. If you watch the http traffic you'll see two GET's, one to //api/v3/internal/allow/allowed with arguments key_id, action, ref, and project
In my case project was rpaisley/asdf on the first call, and usr/rpaisley/asdf on the second which failed.
I'm going to drill into this a bit and see if I can at least get Gitlab to detect that it's not a canonical path and warn the user before simply not functioning.
I had the same problem and thought @Kythrin 's answer solved it but stumbled upon another related problem and this might be a fitting place to post the solution:
Yes indeed, now 'push' to the master repository works, however the update hooks are needed to automatically close issues via commit & push (for example, git commit -m "closes #1" should close Issue #1 of that specific repository). This didn't work when the update hooks were deleted. And if the update hooks were not deleted, the push didn't work again. After hours of troubleshooting, the problem was that the remote repository could not be cloned using the standard way via
ssh://git@git.[myserver].com:[portNr]/[git-project]/[git-repository].git
, instead a directory prefix was needed (note: only on OS X 10.8+, Windows 8 worked fine) to clone the correct repository.
As far as I understood the reason for this behaviour was that an already existing public ssh authorization key for the git user didn't have the commands to retrieve infos about the remote rempository, it's relative path inside of the parent directory etc.. instead of getting that info from the correct, remote gitlab user who already had the necessary commands. So instead of using the key with the gitlab commands the previously created one was used.
I suspect because git installs with OS X/XCode and when we setup Gitlab on our server later and connected, the public key of the git user was not updated?
Now cloning with only specifying the relative address of the remote repository works as well as using the update hooks to close issues conveniently via commit.
(Should a technically more experienced user or one with english as first language be able to explain that problem and the reason why better, please feel free to edit or suggest edits to my post)
The solution is written in the Trouble Shooting Guide:
Could not read from remote repository
Error: clone from ssh doesn't work
The SSH path for my project doesn't work because it is missing the repositories directory.
git@git.myserver.com:mygroup/proj1.git
should be
git@git.myserver.com:repositories/mygroup/proj1.git
Problem: Described in https://github.com/gitlabhq/gitlabhq/issues/3686. The public key for the git user already existed in ~/.ssh/authorized_keys before you setup gitlab, the key for gitlab should begin with:
command="/home/git/gitlab/apps/gitlab/gitlab-shell/bin/gitlab-shell
key-2",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty
Solution: Remove the keys which do not start with the above command from ~/.ssh/authorized_keys
I also did an upgrade over more than one step to 6.9. and run into this problem. It seems connected with the following issue in the GitLab Community Edition:
https://gitlab.com/gitlab-org/gitlab-ce/issues/333
The update hook in the repositories is a symlink, so I comment the security check in /home/git/gitlab-shell/lib/gitlab_update.rb (what is the source of the symlink):
10:27:34me@hogwarts:/home/git/gitlab-shell$ git diff lib/gitlab_update.rb
diff --git a/lib/gitlab_update.rb b/lib/gitlab_update.rb
index 4b0673f..174bbad 100644
--- a/lib/gitlab_update.rb
+++ b/lib/gitlab_update.rb
@@ -36,13 +36,14 @@ class GitlabUpdate
# get value from it
ENV['GL_ID'] = nil
- if api.allowed?('git-receive-pack', @repo_name, @actor, @ref_name, @oldrev, @newrev, forced_push?)
- update_redis
- exit 0
- else
- puts "GitLab: You are not allowed to access #{@ref_name}!"
- exit 1
- end
+ #if api.allowed?('git-receive-pack', @repo_name, @actor, @ref_name, @oldrev, @newrev, forced_push?)
+ # update_redis
+ # exit 0
+ #else
+ # puts "GitLab: You are not allowed to access #{@ref_name}!"
+ # exit 1
+ update_redis
+ exit 0
end
It's a hack, but works for me now. Hopefully somebody or me finds some spare time to dig deeper into this issue.
| common-pile/stackexchange_filtered |
How to save GLSurfaceView rendering to file?
I'm using VideoSurfaceView extends GLSurfaceView to render filtered video. I'm doing it buy changing the fragment shader according to my needs. Now I would like to save/render the video after the changes to a file of the same format(Ex. mp4 - h264) but couldn't find how to do it.
I am using this library - https://github.com/krazykira/VidEffects.
Any experts here?
I would try and use the MediaProjection API. Here is an Google sample for this api. Notice: this might not work on the new emulators.
This is not permanent solutions. I want to keep both original and filter video and need to save in memory.
| common-pile/stackexchange_filtered |
iOS11 - Realm Framework not building
I've downloaded Xcode 9 Beta 4 to fix a problem I have on my app in iOS 11.
However now Xcode won't let my build my app because Realm (and RealmSwift) are in Swift 3.1 and not 3.2.
Here is the message :
Module compiled with Swift 3.1 cannot be imported in Swift 3.2
I don't use CocoaPods or Carthage. Do you know how can I solve this issue ?
Did you download the precompiled framework from the official site? You will need to build it yourself (either from binary of by using Carthage/CocoaPods) using Swift 3.2
How can I build it myself ? It's already in my project as a framework.
See Building Realm
The instructions I shared at https://stackoverflow.com/a/44641478/1991710 should produce a framework that can be used with Swift 3.2 and Swift 4.
Possible duplicate of How can I use Realm with Swift 4?
Make you selected command line tools for Xcode 9. You can find it Preferences -> Locations -> Command Line Tools.
Then clean your project and build again. Should work.
| common-pile/stackexchange_filtered |
Accessing Citrix MDX in Ionic for getting user details
I have created a Hybrid Ionic3 app. It has been wrapped with MDX toolkit and is made available through Citrix SecureHub. The app can be downloaded and it works fine as intended. Now we want to build some role based features. As per the MDX toolkit documentation, there are methods available for iOS and Android to get user name - which we can then use to tie to roles and other user details.
I could not find any plugin for Ionic, wanted to check if someone has done something similar and is writing a custom Cordova Plugin the only option?
| common-pile/stackexchange_filtered |
TO make Grant I have error 1064 (42000)
I am making a simple Grant in mysql, but wondering what is wrong with the below code.
GRANT ALL PRIVILEGES
ON name_database.*
TO 'root'@'localhost'
IDENTIFIED BY PASSWORD 'password';
Why I constantly get the error message like:
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right
syntax to use near
Try :
GRANT ALL PRIVILEGES
ON name_database.*
TO 'root'@'localhost'
IDENTIFIED BY 'password'; /*<--- no PASSWORD KEYWORD*/
| common-pile/stackexchange_filtered |
Hosting a hotspot without signaling metered connection
Currently, I am running a hotspot from an Android phone as my home network. The cellular plan for this phone has unlimited data.
When I host the hotspot, connected devices detect that this hotspot has a cellular connection behind it, and treats it as a cellular connection. This, for example, limits connected Android phones to not back up photos via Google Photos if the "back up over cellular data" option isn't enabled.
Can I somehow edit the way the hotspot is being run, so that it doesn't signal to connected devices that there is a cellular connection in the background?
The hosting phone is rooted, and I have no trouble using a terminal-based setup (with hostapd or similar)
EDIT:
Additional information:
raphael:/ # netstat -lntup | grep -E ':53|:67'
tcp 0 0 <IP_ADDRESS>:53 <IP_ADDRESS>:* LISTEN 22525/dnsmasq
tcp 0 0 <IP_ADDRESS>:53 <IP_ADDRESS>:* LISTEN 22525/dnsmasq
tcp6 0 0 2a00:801:237:80f8::c:53 :::* LISTEN 22525/dnsmasq
tcp6 0 0 ::1:53 :::* LISTEN 22525/dnsmasq
udp 0 0 <IP_ADDRESS>:5353 <IP_ADDRESS>:* 17668/mdnsd
udp 0 0 <IP_ADDRESS>:53 <IP_ADDRESS>:* 22525/dnsmasq
udp 0 0 <IP_ADDRESS>:53 <IP_ADDRESS>:* 22525/dnsmasq
udp 0 0 <IP_ADDRESS>:67 <IP_ADDRESS>:* 2243/com.android.networkstack.process
udp6 0 0 :::5353 :::* 17668/mdnsd
udp6 0 0 :::5353 :::* 17668/mdnsd
udp6 0 0 2a00:801:237:80f8::c:53 :::* 22525/dnsmasq
udp6 0 0 ::1:53 :::* 22525/dnsmasq
raphael:/ # cat /proc/22525/cmdline
/system/bin/dnsmasq--keep-in-foreground--no-resolv--no-poll--dhcp-authoritative--dhcp-option-force=43,ANDROID_METERED--pid
It's because Android's DHCP server sends ANDROID_METERED DHCP option to connected clients. You can set connection unmetered on connected hosts, see screenshot in this answer: https://android.stackexchange.com/a/215528/218526
Thank you! I was looking to implement it from the hotspot side (to avoid having to change every connected device), but this is a step along the way!
Which Androis version your hotspot device is running? If it's Android 9 or earlier you can edit dnsmasq commandline arguments. I can write a bit detailed answer. What does netstat -lntup | grep -E ':53|:67' and pgrep -a dmsmasq return when hotspot is on?
The hotspot phone is running Android 11, so that might be a problem. I edited my original post with output of the commands you wrote.
Unfortunately both commands you have run don't provide the info I'm looking for. Run netstat with root so that last column is not empty. pgrep was supposed to show the running dnsmasq process. Instead you can try cat /proc/$(pgrep dnsmasq)/cmdline. // You can use https://pastebin.com to share command output.
I thought that was the case. I've updated it with more reasonable outputs now. Thanks!
Hmm. dnsmasq is listening on port 53, as DNS server. But on port 67 Android's Java stack is listening as DHCP server, as expected. So it's not a straightforward option to remove ANDROID_METERED option, as we can do with dnsmasq on Android 9 and earlier versions. Still there is a possibility to manipulate DHCP options using third party software like dhcpoptinj. However I've never tried this.
I see. Thanks for the tip about injecting dhcp options, I'll check it out!
Another option is not to use Android's hotspot feature at all. Instead create hotspot from commandline. This answer may help: https://android.stackexchange.com/a/217896/218526
Thanks, I actually saw that post, but my device (running an AOSP-based ROM) didn't have iw and some of the other commands mentioned in the guide.
I've all of the 4 statically built binaries. But I don't think they are missing in any Android release. Android framework itself rely on these binaries under the hood. Check your /system and /vendor in depth.
I did a 'find / -name "iw"' and nothing came up, but maybe its hidden somewhere...
Might be. Exceptions may exist.
| common-pile/stackexchange_filtered |
Jquery store values from array
success: function (response) {
for (var i in response)
{
var serialized_data = '['+response[i].position+']';
alert(serialized_data);
}
}
Result of serialized_data = [{"x": 0, "y": 0, "width": 2, "height": 2}]
Data is getting from table via jquery ajax and stored in a variable.
How can I get data of x,y,width and height in jquery? Could you please help me to find a solution?
data[0].x, data[0].y, data[0].width, data[0].height
@Viral Thanks for your quick reply. I have updated my response code and results could you please check.
Use Following process to get values
$.each(eval(response),function(i,item)
{
var x=item.x;
var y=item.y;
var width=item.width;
var height=item.height;
}
Thanks for you support. I got the result.
success: function (response) {
for (var i in response)
{
var obj = jQuery.parseJSON( response[i].position );
var x = obj.x;
var y = obj.y;
var width = obj.width;
var height = obj.height;
}
}
| common-pile/stackexchange_filtered |
Getting around async issue in node.js application command line
My application is a simple mysql client used from command line - it connects to database and makes few queries to get information from database. Mysql functionality is encapsulated in a class and problem is since calls to mysql server is async (understandably) - the code flow reaches end of application.
And I am unable to refer to 'this'(Mysql) inside a method of Mysql class.
How do I get around this problem ?
Below is my code.
//CLASS
function Mysql(config) {
//...
}
//METHOD
Mysql.prototype.getDbInfo = function (cbk) {
this.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(this.configVar);
});
}
module.exports = Mysql;
//CLASS OBJECT
var test = new Mysql(config);
//METHOD INVOKE
test.getDbInfo(function (err,results) {
//...
});
Every time that you jump into a callback function you are loosing the scope of the this object. There are different ways to work around it.
Assign this to another variable
The first solution is to assign the this object to another variable (e.g.: that, self). When you assign one variable to another and the first variable is an object then you keep the reference to the original object and you can use it within the callback. Something like that:
Mysql.prototype.getDbInfo = function (cbk) {
var self = this;
self.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(self.configVar);
});
}
Bind the this object to the function
You can bind the this object to the function and like that you set the this keyword set to the provided value (in your case the scope outside of showTables function). You can read the documentation of this and you will be able to understand more:
Mysql.prototype.getDbInfo = function (cbk) {
this.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(self.configVar);
}.bind(this));
}
Use es6 arrow functions
It is more or less the same solution like the first one. If you use a transpiler you will find out that it is translated like the first solution:
Mysql.prototype.getDbInfo = function (cbk) {
self.showTables((e,r) => {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(this.configVar);
});
}
| common-pile/stackexchange_filtered |
Public action method "actionMethod" not found in Controller "controller"
I have an admin area in my ASP.NET MVC 4 project.
After add Authorize attribute in Index action of Home controller in admin area (localhost/admin/), when I redirected to /Account/Login I get an error saying that ObjetivosSubMenu was not found in AccountController, the problem is that action is in my _Layout.cshtml file (@Html.Action("ObjetivosSubMenu")) and Login.cshtml file do not point to this layout.
Index action in HomeController in admin area:
// GET: /Admin/Home/
[Authorize(Users = "admin")]
public ActionResult Index()
{
return View();
}
What I'm doing wrong?
Specify the area in @Html.Action() e.g. @Html.Action("ObjetivosSubMenu", "MyController", new { area = "admin" })
@StephenMuecke This action is not in admin area. When I get redirected to Account/Login, the error says that this action dont exist in Account controller, and in fact, not exist, this action is in HomeController of base URL. The strange thing is _Login.cshtml (Account/Login) does not point to _Layout.cshtml wich is pointed by Index action of HomeController (not the same of admin area)
Then @Html.Action("ObjetivosSubMenu", "MyController", new { area = "" })
Seems that just adding the controller is sufficient: @Html.Action("ObjetivosSubMenu", "Home"), now is working, and I figured out that Login.cshtml was using the layout defined in the _ViewStart.cshtml.
No problem - you didn't say which (if any) area the ObjetivosSubMenu was in which is why I made the comment
| common-pile/stackexchange_filtered |
Build Query From List Box In PHP
I have a page where I am wanting to allow a user to select fields from a select that exist in a table, then display the contents of those fields on screen. I have set-up the select like so
<select name="queryfields" size="12" multiple="multiple" tabindex="1">
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="address">address</option>
<option value="phone">phone</option>
And I know to discover what options were selected I can use this:
<?php
header("Content-Type: text/plain");
foreach ($_GET['queryfields'] as $selectedOption)
echo $selectedOption."\n";
?>
And that gives me an array of the fields selected. However, how do I then parse the array to generate my full query? For example, let's say that firstname, lastname were selected. I would then want to build my query like this:
Select firstname, lastname from employeedata
Unknown to me, is how to get the data from the array into a select statent like my above code snippet.
Try This:
$sql = '';
$selected_fields = array();
foreach ($_GET['queryfields'] as $selectedOption){
//echo $selectedOption."\n";
$selected_fields[] = $selectedOption;
}
if(!empty($selected_fields)){
$fields = implode(',', $selected_fields);
$sql = 'SELECT '.$fields.' from employeedata';
}
//print query if it is not empty
if(!empty($sql)){
echo $sql;
}
Can this be achieved on the same page w/o a redirect? Possibly with some JS?
This is php code, if you want to access this code, you have to use Ajax. But I don't understand your requirement now!!
You're code worked as I requested. I did not realize it was seperate methodology (AJAX) to do on same page. I will google ajax.
You can use PHP implode() function.
<?php
header("Content-Type: text/plain");
$q = "SELECT ".implode(', ', $_GET['queryfields'])." FROM employeedata";
?>
But there are some possibilities for SQL injection. You should read the about that before proceeding. How can I prevent SQL injection in PHP?
You can create a design like the below
<?php
header("Content-Type: text/plain");
$filter = array_filter($_GET['queryfields'], function($val) {
$allowedFields = array(
'firstname',
'lastname',
'address',
'phone',
);
return in_array($val, $allowedFields);
}
$q = "SELECT ".implode(', ', $filter)." FROM employeedata";
?>
Would you place this in the same page as the select or is this on the page that I would be using $_GET
| common-pile/stackexchange_filtered |
Nagios set the host state to CRITICAL only after 2 check
I have a nagios server, that is a backup server as well. This server receives auto backup files from over 30 network devices in my network. The network gears send backup files hourly, but not at the same time.
I have a simple script to check if backup file has been created for the last 30 minutes:
#! /bin/bash
PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
. $PROGPATH/utils.sh
if [ "$1" = "" ]
then
echo -e " Use : $PROGNAME -- Ex : $PROGNAME /etc/hosts \n "
exit $STATE_UNKNOWN
fi
if [[ -z `find /backupdir/ -name "$1*" -mmin -30 -type f` ]]
then
echo "CRITICAL - $1 : backup not working for the last hour"
exit $STATE_CRITICAL
else
echo "OK : $1 config backup is working "
exit $STATE_OK
fi
as in 30 minutes there might be some devices that has been backed up timely, is there anyway to set the check service to set to CRITICAL state only after 2 checks in an hour?
I have tried this but seems to not work:
# 'check backup'
define service {
hostgroup_name ciscos
service_description auto backup config check
check_command check_cisco_backup
use generic-service
normal_check_interval 30
max_check_attempts 4
retry_check_interval 4
notification_interval 60
}
I haven't got enough reputation to add a comment to your reply. Below example is to clarify my question:
- router R1 backing up config file to nagios server N1 at the first minute of every hour
- R2 -> N1 at 31st minute of every hour
- I want N1 to run 'auto backup config check' service every 30 minute,
- so at the first time the service run, apparently one of the two routers will be checked as CRITICAL and the other is OK, and the second the service run, the former OK one will be CRITICAL and vice versa
Please see if you can help to define the service or modify the script in the most optimal way.
Please clarify your question. Do you want the check to return green if it has been backed up in the past half hour, yellow if it has not been longer then a half hour and red if it has been longer then an hour?
normal_check_interval and retry_check_interval are version 2 syntax, btw
Which version of nagios do you use ?
I presume that if you exit with critical state on every check there won't be any escalation. You might exit via an STATE_WARNING and use check escalation
cf : Nagios check service frequency based on service status
| common-pile/stackexchange_filtered |
Need help understanding how Ninject is getting a Nhibernate SessionFactory instance into a UnitOfWork?
So using some assistance from tutorials I have managed to wire up a Nhibernate session to my repositories and my repositories to my controllers using Ninject. However, there is one peice of the setup that I am not grasping the "automagic" of what Ninject is doing and was hoping someone could explain.
Below is my Ninject ModuleRepository that inherits from NinjectModule that does all the binding.
public class ModuleRepository : NinjectModule
{
public override void Load()
{
var helper = new NHibernateHelper(ConfigurationManager.ConnectionStrings[Environment.MachineName].ConnectionString);
Bind<ISessionFactory>().ToConstant(helper.SessionFactory)
.InSingletonScope();
Bind<IUnitOfWork>().To<UnitOfWork>()
.InRequestScope();
Bind<ISession>().ToProvider<SessionProvider>()
.InRequestScope();
Bind<IRepository<Product>>().To<ProductRepository>();
Bind<IRepository<Category>>().To<CategoryRepository>();
}
}
Here is the UnitOfWork class:
public class UnitOfWork : IUnitOfWork
{
private readonly ISessionFactory _sessionFactory;
private readonly ITransaction _transaction;
public ISession Session { get; private set; }
public UnitOfWork(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
//Open Session
Session = _sessionFactory.OpenSession();
Session.FlushMode = FlushMode.Auto;
_transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
}
public void Commit()
{
if (!_transaction.IsActive)
throw new InvalidOperationException("There is no active Transaction");
_transaction.Commit();
}
public void Rollback()
{
if (_transaction.IsActive)
_transaction.Rollback();
}
//Close open session
public void Dispose()
{
Session.Close();
}
}
So I understand that we are creating a single instance constant instance of the object that creates a Nhibernate SessionFactory. Below is the SessionProvider class which returns the session from the UnitOfWork object that wraps each unit of work in a transaction.
SessionProvider
public class SessionProvider : Provider<ISession>
{
protected override ISession CreateInstance(IContext context)
{
var unitOfWork = (UnitOfWork)context.Kernel.Get<IUnitOfWork>();
return unitOfWork.Session;
}
}
The Repositories take a ISession in their constructor. But what I am not seeing is how the UnitOfWork.Session is the "session" that gets passed to my repositories?
Any help in understanding this would be great. Thanks.
The binding using:
Bind<ISession>().ToProvider<SessionProvider>().InRequestScope();
states that it should maintain Request Scope. That means that Ninject will cache all requests for ISession during the entire HttpRequest - so all classes being injected (or explicitly getting an instance) will be using the same instance of the ISession. In your configuration the same goes for the IUnitOfWork.
See this post by Nate Kohari for descriptions of the different scope objects in Ninject.
| common-pile/stackexchange_filtered |
C# export grid to word using template
I have created a word template with some number and text fields and I export my data from my application like this:
Object oMissing = System.Reflection.Missing.Value;
Object oTemplatePath = "C:\\MyTemplate.dotx";
Application wordApp = new Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
{
Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
if (fieldName == "Name")
{
myMergeField.Select();
wordApp.Selection.TypeText(txtSponsorResp.Text.ToString());
}
//other fields .....
}
}
wordDoc.SaveAs("myFile.doc");
wordApp.Documents.Open("myFile.doc");
wordApp.Application.Quit();
And here is my code to export a grid to another word document:
System.Web.UI.WebControls.GridView GridView1 = new System.Web.UI.WebControls.GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = bud; //where bud contains the datasource
GridView1.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Export-Grid.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
How can I use both of them and export all the fields and the grids in one document using a word template?
why word? why not excel?
I wonder if I may be easier to write the whole file in c# instead of trying to fill out a template. you could make one class that is, in effect, the template, and it gets called by your function that has all the data fields
Are you doing the word template on the server?
@JeremyThompson yes
Kb257757 @aggicd. Instead use ClosedXML or Record a macro of word inserting the data, translate that to.net
@JeremyThompson ok thank you
You will have to iterate over the field of the grid and insert them into the document using the aspose fields:
Document wordDoc = new Document(myDoc);
foreach (GridViewRow row in GridView1.Rows)
{
foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
{
//iterate over fields and save to apose:
doc.MyField = row.MyRow;
}
}
//save To Aspose
Aspose must know which of the fields you are going to populate, if any.
Else, it won't export anything.
furthermore, word doesn't act kindly with grids. It won't let you export a table because it cannot create one, unlike excel.
instead of inserting an entire grid, just populate each and every field.
| common-pile/stackexchange_filtered |
K3b fails to burn Windows ISO to DVD-R at 98% (Brasero also fails)
I'm trying to create a bootable Windows 8.1 ISO on a blank DVD after my system repeatedly failed to boot from a USB, only showing a flashing dash. I tried using Brasero, but I always get an error that it failed, so I tried K3b and it seems to work until it reaches 98% and than stops for about 30 seconds before displaying an error message. I tried Windows 7 ISO and the exact same thing happens. In Disks the device says: /dev/sr0 (Read-Only) I don't know if that could be the issue. The error Brasero displays is: Error while burning. SCSI error on write(0,16): See MMC specs: Sense Key 5 "Illegal request", ASC 21 ASCQ 04.
Burned media
DVD-R Sequential
Devices
HL-DT-ST DVDRAM GH22NS50 TN02 (/dev/sr0, CD-R, CD-RW, CD-ROM, DVD-ROM, DVD-R, DVD-RW, DVD-R DL, DVD+R, DVD+RW, DVD+R DL) [DVD-ROM, DVD-R Sequential, DVD-R Dual Layer Sequential, DVD-R Dual Layer Jump, DVD-RAM, DVD-RW Restricted Overwrite, DVD-RW Sequential, DVD+RW, DVD+R, DVD+R Dual Layer, CD-ROM, CD-R, CD-RW] [SAO, TAO, RAW, SAO/R96P, SAO/R96R, RAW/R16, RAW/R96P, RAW/R96R, Restricted Overwrite, Layer Jump] [%7]
System
K3b Version: 21.12.3
KDE Version: 5.91.0
Qt Version: 5.15.3
Kernel: 5.15.0-50-generic
Used versions
growisofs: 7.1
growisofs
Executing 'builtin_dd if=/dev/fd/0 of=/dev/sr0 obs=32k seek=0'
/dev/sr0: engaging DVD-R DAO upon user request...
/dev/sr0: reserving 2111287 blocks
/dev/sr0: "Current Write Speed" is 4.1x1352KBps.
0/4323915776 ( 0.0%) @0x, remaining ??:?? RBU 100.0% UBU 0.0%
=== last message repeated 6 times. ===
1540096/4323915776 ( 0.0%) @0.3x, remaining 1122:37 RBU 100.0% UBU 87.5%
:-( write failed: Invalid argument
/dev/sr0: flushing cache
growisofs command:
/usr/bin/growisofs -Z /dev/sr0=/dev/fd/0 -use-the-force-luke=notray -use-the-force-luke=tty -use-the-force-luke=4gms -use-the-force-luke=tracksize:2111287 -use-the-force-luke=dao:2111287 -dvd-compat -speed=3 -use-the-force-luke=bufsize:32m
Please include OS & release details; you provide some package details but not your OS/release.
Commands like growisofs do not make bootable disks. Look at the description of it, it is for adding data to a data disk.
Update:
I tried xfburn and it managed to burn the ISO successfully. So it seems the problem was with the software.
Problem solved
| common-pile/stackexchange_filtered |
Implementing multiple builds with AWS codebuild, with dependant artifacts
I currently work on a project that makes use of AWS CodeBuild for our CI workflow. There is currently one big build, that takes up quite a bit of time as it includes an e2e test suite that takes some time to run, and can sometimes be flaky, causing the whole build to fail and need to be restarted.
I would like it if we could split our build down into smaller, modular builds, that could run independently (and also provide independent status feedback to the associated PR on GitHub).
I was looking at using CodePipeline to achieve this, however it would seem CodePipeline is only configurable to run against master (or a specified branch), rather than on a per PR basis. We would like our tests to run against PRs and prevent erroneous code from being merged into master in the first place.
I was thinking, would it be possible just to use codebuild to achieve this, with multiple builders responsible for different build tasks (for example linting/unit testing could happen in one builder, separate to compiling the application, and running the e2e tests).
I would love something like:
|----------| |---------|
| Compiler | | Linter |
| Builder | | Builder |
|----------| |---------|
| \
| \
|-----------| |----------|
| Unit Test | | E2E Test |
| Builder | | Builder |
|-----------| |----------|
Where each box represents a CodeBuild builder/buildspec and the line represents an artefact dependency.
Here, the 'Compiler Builder' and 'Linter Builder' are kicked off on push to the PR. When the 'Compiler Builder' completes, it transfers the build artefacts of the compiled code to the 'Unit Test Builder', and the 'e2e Builder' for each of these test suites to run, which both report back independent status's to the PR.
It seems like CodePipeline is the ideal tool for this sort of thing, only it does not work using a compatible workflow for our team.
It isn't clear to me how to go about setting something like this up for CodeBuild, though I have seen people allude to it on other posts/SO questions that you can use other AWS services to orchestrate this sort of thing (AWS Lambda/AWS Step Functions). I am not particularly clued up on AWS services, and what is and isn't possible which is why I am asking here. I just want confirmation that what I describe above is possible, and which services will need to be used to achieve this.
I think one of the key hurdles I am struggling with is how to make the output from one codebuild build become the input for another, I have looked at using S3 for storing build artifacts, though I'm not sure how to use that in another build, which is also then connected to GitHub, and able to report a status back to a PR.
Did you ever found a solution? I have the same requirement, wanting to have several builds that depend on each other. I tried doing this using the Batch build build-graph feature of CodeBuild and it kinda works, I'm just not able to export variables for the following deployment actions.
In CodePipeline, each action (within each stage) has an input artifact and output artifact.
This can be use to solve your specific hurdle.
As you described, some jobs (actions) should run in parallel (i.e. on same stage) and should output their artifacts to the output-artifact.
Other jobs should run in serial, so they should occur on another stage (e.g. afterwards) and those jobs (actions) may make use of the previous output artifacts as their input-artifact.
| common-pile/stackexchange_filtered |
X is the major conference in our domain next to / beside / alongside Y
X is the name of a conference. Y is the name of a conference.
I wonder which form(s) are correct amongst the following:
X is the major conference in our domain next to Y.
X is the major conference in our domain beside Y.
X is the major conference in our domain alongside Y.
I would also be interested in alternative formulations (if possible, without significantly altering the sentence structure).
The intended meaning is as follows: there exist many conferences in our domain, X and Y are the two major conferences, and X is on a par with Y.
If X and Y really are equal, why not say so?
X and Y are the major conferences in our domain
If they are not equal and X is the more imoortant, it would be better to say
X is the major conference in our domain, followed by Y
If the difference between X and Y is small, yiu could say "closely followed by"
Thanks, X and Y are the major conferences in our domain is nice but I would prefer to have Y mentioned somewhere around the end of the sentence.
| common-pile/stackexchange_filtered |
Indexing PostGIS table by tile boundaries
I have a PostGIS table with 2M rows, all Points. I'm creating tiles from the data, but it's quite slow.
Although I have the normal geometry indexes enabled on the table, I wonder if it's possible to index better according to tile boundaries (which are alwayws the same).
Or is the normal geom_idx taking care of this already?
did you cluster on the geom_idx?
No, I don't know what that means.
It is in fact possible. And it may even cluster a little better (especially for polygons). I recommend using a quadtile key/quadkey/quadtree system to refer to the item's tile. See http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/ for some visualization, well documented code, and explanation of different ways to refer to and calculate a tile.
| common-pile/stackexchange_filtered |
tikz connection label and node distance
Is it possible to have tikz automatically determining the distance between two nodes based on a third node used to connect them?
For instance, in the following picture the arrow used to connect the nodes are too short. Can tikz calculate its length automatically so that its label fits it better?
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node [rectangle,draw] (b) [right=of a] {token list};
\draw [->] (a.east) -- (b.west) node[above] {lexical analysis};
\end{tikzpicture}
\end{document}
... and after posting my answer, I've found the similar question I was thinking of: http://tex.stackexchange.com/q/20693/86
@AndrewStacey I would even say that it is a duplicate.
(I feel certain that I've answered a similar question before, but I can't find it now.)
One solution is simply to change the order in which you draw things. Since the token list node's position should depend on the length of the lexical analysis node, draw the lexical analysis one first.
\documentclass{article}
%\url{http://tex.stackexchange.com/q/46842/86}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node[above right] at (a.east) (l) {lexical analysis};
\draw[->] (l.south west) -- (l.south east);
\node [rectangle,draw,right] at (l.south east) (b) {token list};
\end{tikzpicture}
\end{document}
To put the lexical analysis and the node commands in the same command, you could write
\draw[->] node [
above right,
append after command={
(\tikzlastnode.south west) -- (\tikzlastnode.south east)
}
] at (a.east) (l) {lexical analysis};
Result:
You can also get the length of the argument using \pgfmathwidth or width with the use of \pgfmathparse
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\pgfmathwidth{"Lexical Analysis"}
\node [rectangle,draw] (b) [right= \pgfmathresult pt of a] {token list};
\draw [->] (a.east) -- (b.west) node[midway,above] {lexical analysis};
\end{tikzpicture}
\end{document}
If the positioning is too tight you can further add some additional space.
you can use an intermediate node with \ phantom as shown below to calculate the width
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node[right =0em of a](ph){\phantom{lexical analysis}};
\node [rectangle,draw] (b) [right=0em of ph] {token list};
\draw [->] (a.east) -- (b.west) node[midway,above] {lexical analysis};
\end{tikzpicture}
\end{document}
| common-pile/stackexchange_filtered |
How to download a PDF file from Google Sheet with specific margins and page breaks?
I see some ways to generate PDF from google sheets. But can not find how to set page settings like hiding gridlines, set margins, page breaks etc.
When I choice download as PDF from file menu I can do this.
So is there some method to get access to page settings with script?
My sheet contains charts and picture. I'm looking for method which not ignoring media content
The easiest way to convert an Google Spreadsheet to pdf specifying different parameters is with UrlFetchApp
It allows you to specify different printing options by adding them to the url,among others the margins and gridlines.
Sample:
function myFunction() {
var token = ScriptApp.getOAuthToken();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
var url = "https://docs.google.com/spreadsheets/d/"+id+"/export?";
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+'&top_margin=0.50'
+'&bottom_margin=0.50'
+'&left_margin=0.50'
+'&right_margin=0.50'
+ '&gridlines=false'
// other parameters if you need
/*
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false' // hide page numbers
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
*/
var response = UrlFetchApp.fetch(url + url_ext,
{
headers: {
'Authorization': 'Bearer ' + token
},
muteHttpExceptions:true
});
DriveApp.createFile(response.getBlob().setName("myPdf"));
}
Unfortunately, I am not aware of a way to set page breaks, but people are using workarounds.
| common-pile/stackexchange_filtered |
Placing image buttons over a background image
I have a new project that requires me to create a webform with c# that contains a background image of a map and I have to make hotspots in specific cities. Clicking on a spot I need to open a pop-up messagebox with some info.
I am thinking on putting image buttons above the background image in specific positions.
Is there a way to do that? The design mode of webforms does not help in putting images in specific places.
Please post any code that you have tried. I would also recommend adding the 'CSS' tag as this could probably be accomplished with classes and styling. Add specific classes to each button, and then you can target the background-image attribute.
Of course it will happen with ccs. The problem is how to find the exact settings for the place of the images without doing it manually. I have more than 500 images that I have to place in the background. Is there a tool that I can use to find the position css settings?
Still no code.... without any it's just speculation. "Of course it will happen with CSS" -- without minimal reproducible code, what else do you expect? Please read: https://stackoverflow.com/help/how-to-ask
You should try Stack Exchange (https://stackexchange.com/), as you've missed the point of Stack Overflow (reviewing CODE to solve problems).
you can use Image map as bellow
<img src="workplace.jpg" alt="Workplace" usemap="#workmap">
<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>
Ref= https://www.w3schools.com/html/html_images_imagemap.asp
That is not what I need. I need specific image buttons that I will create in specific spots above the background image.
i need to put images of people in specific spots, the color of the people will change based on a condition from code (so I need 2 images for one) and all of these will go above the background image.
| common-pile/stackexchange_filtered |
Windows Update is downloading updates when it is supposed to notify me first
I have Windows XP SP2, and Windows Update is set to notify me that updates are available and not download any updates.
However, recently, the yellow shield in the system tray has appeared indicating that updates are downloading.
I have gone into the Windows Security centre and confirmed updates are set to notify only, and not download.
How do I fix this?
Move first to SP3, ASAP!
You may be getting pushed emergency out of band updates...these typically disregard policy.
True and SP2 is at the end of it's support cycle.
| common-pile/stackexchange_filtered |
How can I create a menu in python and use functions as my options?
I hope you're doing great! I would really appreciate if you help me with this problem of mine. I wrote this code that creates dictionary based on user's input, then updates it, sorts by keys and values, finds if the item is in the dictionary, counts the number of unique values and, finally, saves the original dictionary to the .txt file. The code itself works fine, but I wanted to present it as a menu so that user could choose what he/she would want to do next, but when I tried to just call the functions from the menu it didn't work and now I have no idea how to do it properly. Could you explain how I can do that? Thanks in advance!
Have you tried printing the names of functions (hard coded as string in print) and get the input from user. You can also use a while loop on top of it to keep it moving.
If you're trying to create a user-friendly interface, you might want to look into Tkinter.
What sort of menu are you looking for? What's not working? If the overall business logic of managing the dictionary is not critical to the problem please try to remove or stub them. See [mcve].
@RaoSahab That was my second thought, but it would not work either... Maybe I coded it wrong??
1) Add a menu function, I only did the first three so that you can get the idea (you can do the rest of them), for example.
def menu():
print '1) Create a dictionary'
print '2) Update the dictionary'
print '3) Sort the dictionary'
task = raw_input('Enter the number to perform the corresponding task: ')
if task == '1':
user_dict = creating_dictionary()
elif task == '2':
try:
updating_dictionary(user_dict)
except UnboundLocalError:
print "A dictionary doesn't exist, you'll have to create one\n"
creating_dictionary()
elif task == '3':
try:
sorting_dictionary(user_dict)
except UnboundLocalError:
print "A dictionary doesn't exist, you'll have to create one\n"
creating_dictionary()
2) add menu() as your first statement in main()
3) at the end of every function add a call to menu()
4) If you set it up correctly then the only call you'll need in main() is menu(). You'll be able to delete all of the other function calls since at the end of every function you'll be calling menu().
@Vero Weller --- Start your program by requiring the user to make a dictionary such as you did here: user_dict = creating_dictionary() and then give them menu options for the other tasks and pass the dictionary around as required.
| common-pile/stackexchange_filtered |
I want to Remove the addition symbol from in-between the numbers using python and please find the below my code
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
This is my output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
I want the + symbol only in between the numbers.Not to be in the last or the first.
When I run your code, I enter 9 for limit and then I get the output as 1 2 3 4. There are no + symbols, so I don't understand what your question is.
My Bad. I have edited the code. Now try to run again and you will find the issue
So you don't want the + after the 9, right? Then you should stop your loop one number sooner and treat the last one specially after the loop.
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
if count != limit:
allvalue += str(number) + " + "
else:
allvalue += str(number)
print(allvalue)
Hope this help.
I would like to share with you a sure shot mathematical solution to this problem.
This problem is a typical variation of Sum of n numbers problem, where the sum depicting limit here is already given as input, instead of n.
import math
limit = int(input("Limit: ")) # n * (n + 1) / 2 >= limit
n = math.ceil( ((1 + 4*2*limit)**0.5 - 1) / 2 ) # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit
allValue = " + ".join([str(i) for i in range(1, n+1)])
print(allValue)
A likely solution is using " + ".join(), which uses the string method on the " + " to collect the values together
>>> values = "1 2 3 4 5".split()
>>> " + ".join(values)
'1 + 2 + 3 + 4 + 5'
You don't need both the number and count variables, and by starting from initial value you can add the + before the number.
limit = int(input("Limit: "))
count = 1
allvalue = str(count)
while count < limit:
count += 1
allvalue += " + " + str(count)
print(allvalue)
Here is simple and easy approach, you can try slice in the result string
print(allvalue[:-2])
code:
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
print(allvalue[:-2])
output:
result shared : https://onlinegdb.com/HFC2Hv4wq
Limit: 9
1 + 2 + 3 + 4 +
1 + 2 + 3 + 4
You could also try using a for loop.
limit = int(input("Limit: "))
allvalue = ""
for i in range(0, limit):
if i+1 == limit:
allvalue += str(i+1)
else:
allvalue += str(i+1) + "+"
print(allvalue)
| common-pile/stackexchange_filtered |
How to remove all newlines from a file?
I have the command cat file.txt | gawk '{print $2}' > test which displays:
1
1
0
0
1
1
Afterwards:
vi test
:%s/\n//
Which outputs: 110011
My question is I don't know how I could incorporate this last step with pipes.
Update: Might be with sed. I tried to use sed 's/\n//' but still doesn't work (it changes nothing).
To delete bytes in the file test just use tr. This will save the output in test2
<test tr -d '\n' >test2
Instead of cat and piping like that you should redirect directly
You can use awk but it also receives a file name so no need to pipe the output to it like in your answer, and you also don't actually need 2 steps like that. Just set the output record separator which is a new line by default to an empty string. This will print the second field from the original file directly into the output file
awk -v ORS='' '{ print $2 }' file.txt >test
# or
awk -v ORS='' '{ print $2 }' <file.txt >test
Alternative the variable can be set like this
awk 'BEGIN { ORS="" } { print $2 }' file.txt >test
You might want to add END { print "\n" } to print a newline at the end
Demo on online bash
The command <test tr -d '\n' >test2 works just fine, thanks for that :) But I don't know why the awk commands don't work for me. When I do a cat test after the awk commands, I get no output.
remember that command runs with the original file.txt, not the test. That's why I said you need only 1 step, no need to go through the intermediate test file
@phyclv You're right! Thank you very much for the demo as well :]
You would need another gawk that substitute newlines to "":
cat file.txt | gawk '{print $2}' | gawk '{printf "%s",$0} END {print ""}'
Source: 1 (serverfault.com)
Even simpler:
cat test | awk '{printf $2} END {print ""}'
And finally:
cat test | gawk '{printf $2}'
(Using cygwin64 terminal)
And now really final: gawk '{printf $2}' test
Another way is:
gawk '{print $2}' file.txt | paste -d'\0' -s
-s does a serial paste
-d '\0' pastes without a delimiter.
Using Raku (formerly known as Perl_6)
Raku is a programming language in the Perl-family of programming languages. In particular, Raku offers high-level Unicode support built-in, no external libraries required:
~$ cat test | raku -e 'lines.join.put;'
#OR
~$ cat test | raku -ne '.print;'
Sample Input:
1
1
0
0
1
1
Sample Output:
110011
https://raku.org
| common-pile/stackexchange_filtered |
Container privileges
I want to deploy an an app in cloudfoundry that needs to have access to a file system for storage purposes. As the appcloud only provides S3 support I wanted to use the https://github.com/s3fs-fuse/s3fs-fuse in order to make the conversion. However, this image needs to be run as "privileged" and this is not possible in a standard Cloudfoundry instance.
According to the documentation, https://docs.developer.swisscom.com/concepts/container-security.html, there is a way to tune the privileges of a container via the diego manifest.
Is this a possibility? is this accessible for the cloudfoundry users? Any other way I can run this container?
You cannot configure the usage of privileged/unprivileged containers as a CF user. You would need to have operator level access to do that. Additionally, the operator would need to enable usage of privileged container for all app. You can't turn it on for individual apps.
See docs here:
https://docs.cloudfoundry.org/concepts/container-security.html#types
| common-pile/stackexchange_filtered |
Python decorator eats function results
Running python 3.9 on MacOS 13.4.1 on 2020 iMac 27".
While trying to use a decorator to time the execution time of a function, I have found that the value returned by the function being timed is reduced to 'None'. The timing_decorator is copied from a forgotten source. It works fine with functions that return no value.
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:7.3f} seconds to run.")
return
return wrapper
@timing_decorator
def funky(p1,p2):
return p1 * p2
print(funky(6,7))
Running this code as is prints 'None'.
Commenting out the line '@timing_decorator' prints the expected result '42'
I have found quite a few references for passing parameters to the decorated function but nothing about the return values.
Note how you don't do anything with result. That's the return value.
Thank you @Carcigenicate for taking the time to state the obvious!!
All you have to do is simply return 'result' inside of function 'wrapper'.
Like this:
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:7.3f} seconds to run.")
return result # Return the actual result of the normal function instead of nothing
return wrapper
@timing_decorator
def funky(p1,p2):
return p1 * p2
print(funky(6,7))
This returns what your decorator is expected to do, and 42, the result of your function 'funky'
| common-pile/stackexchange_filtered |
Phalcon form sanitize
Is there a way in which one can filter data that is auto-completed in a form generated by VOLT.
Consider the login form: Email/password.
When I edit the HTML (in the broser) and send the email as an array ('name="email[]") I can sanitize it in PHP and 'cast' as en email:
$loginEmail = $this->request->getPost("email",'string');
$loginEmail = $this->filter->sanitize($loginEmail, "email");
in order to prevent other attacks.
But when making the email field an array VOLT generates an error:
"Notice: Array to string conversion in ..."
VOLT form values are populated automatically...
I know I should disable NOTICES in production but still...
How can I treat this by using VOLT?
EDIT
Template sample:
{{ text_field('id':"email","class":"form-control", "size": 32,"placeholder":'Email address') }}
After a var_dump and setting the email string through validation I get at a certain point:
protected '_viewParams' =>
array (size=5)
'title' => string 'Test' (length=5)
'showSlider' => boolean true
'hideUnlogged' => boolean true
'user' => null
'email' => boolean false
BUT the variables are sent to VOLT in an upper layer because it is still set as an ARRAY.
The only viable solution is to make an object or something and get from a config what validation rules to apply to forms (by name) and rewrite the post variable in public/index.php something like this:
if(isset($_POST['email']))
{
$_POST['email'] = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
}
If anyone has a better solution in which this can be done in a controller rather that this or in a service with event handlers...
I'm lost a little. The error occurs in the Volt template when you pass it the form data that contains array instead of the string, correct? You need to validate that form data and sanitise it before passing to the template, correct?
Another thing that I'm unclear about is when you send email as an array the name of the input changes from email to email[]. So, if email is specified as the form element name, the form should be getting that value, not email[]. In other words unless there is an bug somewhere, there should be no way of getting an array instead of the string unless you are expecting it…
I ran a vulnerability scan, and this came up and am a bit frustrated by this because it should be easy to bypass this. This shouldn`t happen but there is the saying: NEVER TRUST USER SUBMITTED DATA (Cross-site scripting, injections etc).
I agree on that, I just don't get the picture of what's happening on the server. Does it happen in the template when you are rendering it? Does the template take values from the form? If so, can you include form code? If not, can you describe what's going on in the action which handles the request (before you get to the template rendering)?
It happens when I submit the form with wrong credentials (before submitting I altered the name of the email and pass as an Array), volt tries to prefill the submitted data ($_POST vars into the form) then the notice occurs. He tries to echo $_POST['email']...
Yes, but before Volt fills the submitted data many things happen: your router finds out and tells dispatcher what controller / action to run, then inside your controller / action POST data (can be and should be) processed, usually a Form component can be used for that, and then if it's valid some logic is performed and THEN the values are passed to the view, which is ONLY THEN gets rendered using Volt engine.
I have the LoginController and index.volt, a fix I found is to register a VOLT filter : return '@Validation::string_cast(' . $resolvedArgs . ')';//suppress when $_POST is empty, and changing in index.volt : {{ text_field('value':email|string_cast,'id'...
Let us continue this discussion in chat.
You can do anything you wish by implementing a custom filter and doing a proper conversion from array to string.
$filter = new \Phalcon\Filter();
//Using an anonymous function
$filter->add('superSanitisedString', function($value) {
if (is_array($value)) {
$value = empty($value) ? '' : reset($value);
}
return (string) $value;
});
//Sanitize with the "superSanitisedString" filter
$filtered = $filter->sanitize($possibleArray, "superSanitisedString");
But… don't bend the stick too much – this is a clear validation job and then sanitisation. Check that the value is a string, if not – ask to provide one. It's easier and smarter to protect your app from invalid inputs than from idiots who provide that input :)
Edit:
You can use a custom volt filter which can be added as a service, implement a class with a static method to return the sanitized value and use it in the template.
I found out than if I detect that if the request is $_POST I can overwrite the value (I can use your example of custom filter) sent to the template by using $this->view->email = (string)$sanitizedString (as example)
I was intrigued that the framework doesnt do it or they didnt prevent this
Yep. To make things more fluent you can extend the Request class with your own logic and to add setPost($name, $value) – Phalcon doesn't give it out of the box. And if you have some general rules for request values you can also add them directly into the Request component.
Unfortunately I have the same issue even if I set $this->view->email = $sanitizedString, I think the prepopulation is done on an upper layer
| common-pile/stackexchange_filtered |
Results are different between python and mysql for similar command
I was using python to create a dictionary but as my data got larger I started to get memory errors so I thought I would save memory and just write the data to a database instead, but the results are not the same. I think this has to do with defaultdict's behavior(but I'm not sure).
Here's the working python code(it basically builds a table of values):
from collections import defaultdict
data = [2,5,10]
target_sum = 100
# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool) # all values are False by default
T[0, 0] = True # base case
for i, x in enumerate(data): # i is index, x is data[i]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s / x + 1):
if T[s - c * x, i]:
T[s, i+1] = True
#check the python dict results
count = 0
for x in T:
if T[x] == True:
print x, ':', T[x]
count = count +1
print 'total count is ', count
#False is 152 and True is 250. Total is: 402
The result is a large table of values(you can see the breakdown in the comment. This is the correct result I want), but when I change the last line of the first for statement to add to a database and not to a local dict, the results differ.
Here's my modified code that is problematic:
cursor = conn.cursor ()
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS data_table")
cursor.execute ("""
CREATE TABLE data_table
(
value CHAR(80),
state BOOL
)
""")
#with database
for i, x in enumerate(data): # i is index, x is data[i]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s / x + 1):
cursor.execute(""" SELECT value, state FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
if cursor.rowcount == 0:
#print 'nothing found, adding'
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', False)""" % ([s - c * x, i]))
elif cursor.rowcount == 1:
cursor.execute (""" UPDATE data_table SET state=True WHERE value = '%s'""" % ([s - c * x, i]))
#print 'record updated'
conn.commit()
#False is 17 and True is 286. Total is: 303
Just to sum it up(in case you don't want to run the code), defaultdict creates an false entry when something is queried( in this case if T[s - c * x, i]:) so to replicate this feature I do a mysql lookup for the value and if it doesn't exist then I create it, if it does exist then I set it to true. I highly suspect I'm failing to replicate the functionality correctly
The only other thing I was thinking is python displays the results as (222, 0) : False but mysql is doing [222,0] not sure if that makes a difference.
Your two examples are not updating the same key:
# First example
if T[s - c * x, i]:
T[s, i+1] = True
# Key is (s, i+1)
# Second example
elif cursor.rowcount == 1:
cursor.execute (""" UPDATE data_table SET state=True WHERE value = '%s'""" % ([s - c * x, i]))
# Key is (s - c * x, i)
IMO it would make more sense to just store the True cases in the database, that might make your program simpler. Otherwise, you'll also need to check if (s, i+1) exists in the database, update it to True if it does, create a new row if it doesn't.
P.S. I also missed the command where you set (0, 0) to True. Shouldn't that be in an insert, just after you created your database?
Update: also found another problem in your code: the select command just checks whether or not a row exists, not what its value is. To correctly replicate your first example, your code should be:
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', True)""" % ([0, 0]))
conn.commit()
# Inserted the (0,0) case
for i, x in enumerate(data):
for s in range(target_sum + 1):
for c in range(s / x + 1):
cursor.execute(""" SELECT value, state FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
if cursor.rowcount == 0:
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', False)""" % ([s - c * x, i]))
elif cursor.rowcount == 1:
(value, state) = cursor.fetchone() # Gets the state
if state: # equivalent to your if in the first example
insertOrUpdate(conn, [s, i+1])
conn.commit()
Changed lines commented.
Update 2: that was not enough... (as I said, it'd be much simpler if you just stored the True values). Moved the part inside the if here, for readability:
def insertOrUpdate(conn, key):
cursor.execute(""" SELECT value, state FROM data_table WHERE value='%s' """ % key)
if cursor.rowcount == 0:
# Insert as True if not exists
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', True)""" % key)
elif cursor.rowcount == 1:
(value, state) = cursor.fetchone()
if !state:
# Update as True, if it was False
cursor.execute (""" UPDATE data_table SET state=True WHERE value = '%s'""" % key)
Update 3: Just to contrast, look how the program would be simpler by just storing the True values. It also uses less disk space, takes less time and behaves more like the defaultdict.
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS data_table")
cursor.execute ("""
CREATE TABLE data_table(
value CHAR(80)
)
""")
cursor.execute (""" INSERT INTO data_table (value) VALUES ('%s')""" % [0, 0])
conn.commit()
for i, x in enumerate(data): # i is index, x is data[i]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s / x + 1):
cursor.execute(""" SELECT value FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
if cursor.rowcount == 1:
cursor.execute(""" SELECT value FROM data_table WHERE value='%s' """ % [s, i+1])
if cursor.rowcount == 0:
cursor.execute (""" INSERT INTO data_table (value) VALUES ('%s')""" % [s, i+1])
conn.commit()
Thank you for pointing that out..I just fixed that. Everything is false now. But the algo works by seeing past requests and then changing the value if it was made before.
@Lostsoul check my updated answer, that error was not the only one.
@Lostsoul I also posted an alternative solution, storing only the True values
omg! You did so much work, thank you. I thought I had a small bug but you put in so much effort to actually correct the structure of the design. I'm going to play around with the code and get back to you, but thank you very very much, you really didn't have to(but I do appreciate it). P.s you also saved me work, my plan was to get the entire dict into the database then run a stored procedure to remove all the false records
| common-pile/stackexchange_filtered |
Linux mint partition problem
When i started working with linux mint this partition was working well then mounting error began to appear and i solved it doing:
sudo ntfsfix dev/sda
mounting error came many times, but this time after solving mounting error using this code another error came says:
(Sorry, could not display all the contents of "partition name": Error when getting information for file '(partition location)/found.000': Input/output error)
Note:
I have windows os too, in the same computer, and I don't use a virtual machine. And I checked that partition in windows and it works well.
Use only the NTFS partition for reading. The writing functionality from Linux is not entirely stable.
If you're using Windows 10, it has a Fast Startup feature that essentially hibernates the OS instead of really shutting down. As a result, NTFS filesystems are left in open state, which makes them unmountable in Linux, unless you first use ntfsfix.
On dual-boot systems, it is probably best to disable Windows Fast Startup if you want to access the NTFS filesystems from the Linux side.
sudo ntfsfix dev/sda
I'm guessing this is not an exact representation of the command you used.
Running ntfsfix on the whole /dev/sda disk instead of just the NTFS partition (e.g. /dev/sdaN where N is a number) is not advisable and might cause filesystem corruption issues.
i disabled Windows Fast Startup but nothing change
| common-pile/stackexchange_filtered |
Debugging ExceptionInInitializerError
After a Java 10 migration, I am encountering an error java.lang.ExceptionInInitializerError
With no other info. Error occurs when I try to run/debug the project. Where should I begin looking to diagnose this?
Here is the full output in the console:
Information:java: Errors occurred while compiling module 'pw-support-server_main'
Information:javac 10.0.2 was used to compile java sources
Information:11/27/2018 6:06 PM - Compilation completed with 1 error and 0 warnings in 2 s 173 ms
Error:java: java.lang.ExceptionInInitializerError
Seems like you're either using an incompatible version of IntelliJ OR the error shared by you is incomplete still.
Seems issue is related to Lombok plugin: https://github.com/rzwitserloot/lombok/issues/1572
You can try to set breakpoints in the constructors of ExceptionInInitializerError.
Resolved using the following steps, which are probably very specific to my situation:
Changes to build.gradle:
buildscript {
dependencies {
classpath "io.franzbecker:gradle-lombok:1.10"
}
}
Changed to classpath "io.franzbecker:gradle-lombok:1.14" (update to latest version)
Added inside of the block allprojects {
lombok {
version = "1.18.4"
sha256 = ""
}
The Franzbecker-lombok thing defaults to installing lombok 1.16.20, which has this issue. Telling gradle to use lombok's latest version solved this. Getting the right syntax among all the gradle version changes, Java version changes, etc, was just a little confusing.
Side note: The issue also occurred on Java 11.
| common-pile/stackexchange_filtered |
Method not being called
I have a fairly simple method in a class in a separate file, which takes in an integer, looks it up in a case select, and returns an NSURL pointer that corresponds to it. It has this method:
#import <Foundation/Foundation.h>
@interface ChangeCurrentScene : NSObject
{
NSString *filePath;
NSURL *url;
int currentScene;
}
- (NSURL *)changeSceneURL:(int)toDesiredScene;
@end
I'm not 100% sure how I'm supposed to call it from outside, but I have a button hooked up in my storyboard, which definitely works, and I'm using this line to call it:
nextURL = [sceneChanger changeSceneURL:1];
From this header file:
@interface MSViewController : UIViewController <AVAudioPlayerDelegate> {
BOOL userInputAvailable;
int currentScene;
NSURL *nextURL;
ChangeCurrentScene *sceneChanger;
}
@property (strong) AVAudioPlayer *menuPlayer;
@property (strong, nonatomic) IBOutlet UILabel *userChoiceLabel;
@property (strong, nonatomic) IBOutlet UIImageView *nowPlayingIcon;
- (BOOL) playScene : (NSURL *)fileToBePlayed;
@end
I've put a breakpoint on the first line of the changeSceneURL:toDesiredScene class, but it is not called at all. No crashes, but no calls either. First off, is this the correct way to use the return from a called method? nextURL is an NSURL object, and I want the returned value to be stored in it. Secondly, what reason would there be for the method not being called at all? I'm really stumped here, but I'm sure it's something blindingly simple.
Thanks, in advance!
Can you show the header file for the object with the name sceneChanger ? That object should be where the method changeSceneURL:is located. But something else could be happening, so add the entire header file to your original question.
Put a breakpoint on the nextURL= line, and check the value of sceneChanger. It is probably nil.
Chech that sceneChanger is not nil. You can send messages to nil, but the method doesn't get called.
Edit You should initialize sceneChanger somewhere like this:
sceneChanger = [[ChangeCurrentScene alloc] init];
Yes, it is nil. I tested in gdb with "po sceneChanger". How do I assign a value to it? Do I need to assign an NSURL to it, or an int? It's a method, I wasn't aware a method had a value.
@lukech - No, sceneChanger is an object, it is an instance of ChangeCurrentScene.
| common-pile/stackexchange_filtered |
Implement a correct scope in an Angular library
I have a question about how to implement a correct API exposure in Angular libraries.
So basically I have a Service, and a component inside my library that consumes some methods of the Service. Those methods thus cannot be private, since my component has to get access to them. But I don't want to expose those methods to the user publicly. In other words: those methods should be consumed internally (thus not private), but should not be consumed externally.
I know that there is the possibility to expose the API through public-api.ts but this is not giving me enough control on it.
How do you achieve this?
Maybe you need to define the service class in the same file as the component is defined? But without exportint the service and having it provided in the compinent providers.
| common-pile/stackexchange_filtered |
Find all natural $n$ numbers.
Find all natural $n$ numbers such that
$15(n!)^2+1$ is divisible by $2n-3$.
My try: First I assumed $2n-3$ is not prime number. Let $a$ be divisor of $2n-3$. It's clear that $a<n-1$, so $15(n!)^2$ is divisible by $a$. Which means $15(n!)^2+1$ is not divisble by $a$. But it is given that $15(n!)^2+1$is divisble by $n$ which means it is divisible by $a$ too. But we have already proved it is not. Contradiction!
So $2n-3$ must be prime number. Now if we change $2n-3$ as $p$. We can say $((p+3)/2)!*((p+3)/2)!$ is congruent to $-1$ by $p$ module. By Wilson's theorem $((p+3)/2)!*((p+3)/2)!$ is congruent to $(p-1)!$ by $p$ module
That's an interesting question. Show some work and/or tell us what you think so the question won't close.
it has been checked by a computer up to n = 40000. the set now contains the numbers {1,2,10,77}. I do not have a proof that there are no new numbers that satisfy the conditions for the set above n = 40000. I can see why people thought this question was impossible. it may actually be a nice problem that is solvable if you can prove that the statement is false for n > 77. the rest are checked by computer.
| common-pile/stackexchange_filtered |
Deploying ASP.NET MVC 4 Application to private staging / preview
I'm building an MVC4 application that is starting to take shape and I want to deploy it privately for staging and preview purposes. I would like only a select few people to be able to access the full application. Most of the application is public, but there is a private area as well that requires the user to login.
I'm looking for the most unintrusive way to privately deploy this application to staging/preview. By unintrusive I mean that I don't want to toggle more than a few lines of code, preferably just a flag in the web.config, to deploy it normally vs privately.
I also want this authorization to overlap the site's existing authorization functionality. In other words, when the person goes to the preview URL I give them, they are brought to a landing page where they must log in using the username/password I also gave them. Once they login, they should be brought to what will be the actual landing page if the application was in production. However, they should NOT be logged in to the application itself (this is what I mean by overlap). This way, they can use the application as normal (registering, then logging in a second time to get to the application's private areas.)
I'd like to have something along the lines of this in my web.config:
<StagingAccess deployPrivately ="true">
<StagingUsers>
<StagingUser>
<UserName>JoeShmoe</UserName>
<Password>Staging123</Password>
</StagingUser>
</StagingUsers>
</StagingAccess>
Such that I can simply toggle deployPrivately, add a StagingUser node for a select user, then deploy to my host using Web Deploy.
Some steps would be perfect as I've never actually deployed an MVC app before, let alone like this. But I really need to start being able to show the application to people without exposing any of my code and without a remote desktop to my machine, which makes the app seems laggy.
where do you intend to deploy production? will it be a cloud?
No it won't be to a cloud, Thanks.
consider using azure as your staging environment. You can lock it off and getting a limited usage account shouldnt cost more than $80/month
Do I have to write additional code to make my application a "cloud application" or is this simply a matter of choosing Azure as my hosting provider? Can you provide a link, guide, or full answer to help me understand the steps needed to take? Thanks
Ok I found what I needed. For converting an existing MVC app to Azure: http://blogs.msdn.com/b/bursteg/archive/2009/05/23/asp-net-mvc-on-windows-azure-asp-net-mvc-web-role.aspx
And for deploying that solution to the cloud: http://dotnetslackers.com/articles/aspnet/Developing-ASP-NET-MVC-4-Application-and-Deploying-to-Windows-Azure-Cloud.aspx
Thanks for your help.
sorry didnt notice the posts. good luck.
How about a combination of Authorization Rules: http://weblogs.asp.net/gurusarkar/archive/2008/09/29/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config.aspx
and Web.Config Transformations? http://msdn.microsoft.com/en-us/library/dd465326.aspx
Then you would Publish the application using VS with a specific configuration chosen - I believe this could help you accomplish your goals.
I believe the Authorization Rules link you posted does not apply to MVC architecture that uses virtual directories not phsyical folders/files locations. The resources I need to protect are my controllers. +1 for Web.Config transformations, selecting a specific web.config transformation will make it more convenient however doesnt address the root problem. Thanks
You're correct that they are essentially "virtual" resources - however Authorization Rules do work (though not generally accepted as "good practice" but should work for your limited use case. I'm confident there is another solution, however I don't believe it will be as simple as doing some xyz.config changes.
| common-pile/stackexchange_filtered |
Is instantiating a GUID in Entity Framework Core bad practice?
If I have a model with a key of type Guid, is it bad practise to set the ID explicitly in the constructor?
I know it will be set implicitly by Entity Framework, but will anything bad happen (perhaps performance wise) from setting it explicitly?
Example:
class MyModel
{
public MyModel()
{
Id = Guid.NewGuid();
}
[Key]
public Guid Id { get; set; }
}
I'm thinking a Guid is backed up by a sequential ID in SQL server, and if I set a value explicitly, I suppose I will decrease indexing performance because it will no longer be sequential?
I have not been able to find an answer on this and I am highly curious about it.
Test it yourself. Create 100000 entities and let EF assign the GUID. Profile a few queries against it. Wipe the table, then create 100000 entities with a GUID you new up yourself and profile that. I will assume (and it is only an assumption), that there'll be no difference.
guids aren't sequential though. They tend to be if generated by the same system, but that seems foolish to rely on.
The SQL datatype for a .Net Guid is a uniqueidentifier
I see a design flaw rather than a performance problem: models shouldn't generate their id. It's out of their responsibility. Repositories do so in the Add method.
Guid can be generated in many ways: for example, it can be random or sequential. There're different algorithms to generate them either way. Therefore, you're closing your choices to just one.
And you're forcing the moment on which the model id is assigned: you mighn't want this in order to delay its assignment until the model may need to be persisted. For example, a zero Guid may be useful to know that some model isn't persistent yet.
| common-pile/stackexchange_filtered |
Hypothesis testing - Newbie blockers - Update and more
Brief : I'm from manufacturing industry, a processing machine in our production line used to do pressing, polishing and QA one after the other. Now we have a new machine that will perform these at the same time. Ideally the new machine will produce units in less time than the old machine. I want to prove that time taken by new machine is significantly less than old machine.
Null hypothesis - There is no significance difference in time taken by both machines to produce one unit.
Alternate hypothesis - Time taken by new machine is less than old machine.
Initial Plan : I initially planned on performing bootstrapping to identify the population distribution. Assuming the data was normally distributed from bootstrap, I planned on Two sample t-test, else Mann Whitney U-test. There is also some extreme outliers ~2% in a data of 50K or more records. I thought of removing these outliers completely as they are less than 5%.
Questions : My problems are, (1) during research I came across normality test (Shapiro-Wilk) which I though might help to statistically confirm the normality. (2) Then I ran into proportion tests for sample size, which is also being recommended. (3) Then came across (winsorized mean), for replacing outliers with non-outliers.
With just a regular (trust me, am not over researching) research, I'm flooded with over information, which is quite confusing. What should be the ideal framework for my use case. What would you all recommend that I do, correct or refer???
I planned on performing all the steps I as per my plan. But, now having second thoughts if that will be correct. Any advice, feedback, corrections will be really helpful.
Update:
Thank you all so much for inputs. I was able to research and decide the trade-offs.
Let me summarize what I've done and require your suggestions and input again for a particular blocker in sample size.
Data 1 size = 10 million records
Data 2 size = 1 million records
population distribution (for both) = log normal distribution: right skewed. It almost looks like needle and a reallllyyyyyy long tail.
S.D and variance for both populations are different.
Outlier - used IQR method (Q1 - 1.35 * IQR and Q3 + 1.35 * IQR) to trim outliers.
Converted data to log 10 and achieved normal distribution
performed two sample t-test with n=30 and 5% alpha, rejected the null hypothesis.
New blocker:
I read two books (Practical statistics for Data scientists by Peter Bruce and Andrew Bruce and Statistics by Robert S Witte and John S Witte) and Data camp course to learn hypothesis test. In all of them, they had always assumed sample size, likewise I just assumed a sample size of 30 and performed the test. Now I ran into (Power analysis) and other tools to calculate the sample size. My doubt is
Is it necessary to calculate the sample size?
What other essentials like these am I missing out on (I've included every step of my test process above)?
Any recommended steps/procedures/tests that you would suggest before I start the hypothesis test?
(1) How many data points do you have? (2) Note that Mann-Whitney does not test equality of means, but something quite different. If you do want to test equality of means and are concerned about any lack of normality (and with large enough sample sizes, this is much less of an issue), a bootstrap or permutation test would be more appropriate. (Sorry for proposing yet another method...)
(3) Can you edit your post to include a sample or all of your data?
Words like "significance" or "significant" do not belong in hypotheses. Those are words that would go in a conclusion, if you use them at all (the ASA suggested not).
You can't prove anything with statistics (which about quantifying uncertainty). What about an alternative framework where you estimate the time to produce units, with the first machine and with the second, with sufficient precision?
Failure to reject H0 in a goodness of fit test like the Shapiro-Wilk does not demonstrate that the null is true, only that your sample size was too small to reject. The relevant consideration is not really whether you can detect non-normality, but its impact on your inference. The probability of the former increases with sample size, but important parts of the latter reduce with sample size, so you're more likely to reject normality in cases where it matters less, and to fail to reject where undetected large deviations from normality matter more. Many answers on site address this issue.
The answer is, as always, it depends. Statistics is a lot less about 'when X do Y' and a lot more about making trade-offs between assumptions that may or may not even be verifiable or come back to bite you.
The Mann-Whitney U will give you a test for your hypothesis, i.e. a sufficiently extreme test statistic is evidence that one of the two samples "stochastically dominates" the other. Specifically, you reject the hypothesis that if you pick a given rank from each of your samples, it's equally likely that one value is bigger than the other or vice versa. The great thing about this is that it's relatively free from assumptions, a trade-off is that you don't get any information about how big the difference really is because everything happens in the rank scale.
A t-test directly compares the mean of two samples and thereby comes with a few additional assumptions, an important one being that the mean is an appropriate summary statistic (through homogeneity of variance and normally distributed [symmetric] residuals). The big element in your favor is that you have a sample size of 50,000 if I understand well, which is very likely enough that you can rely on the central limit theorem. There's no fixed number of samples where this is or isn't appropriate, but the idea is that your sample mean will always be normally distributed even if your sample isn't, and it will commonly be relied upon in much smaller samples than yours.
Actively testing for normality is not useful because such tests have very low power for small samples (where the CLT may not hold), and have very high power for large samples in that they will reject even the smallest deviation from the theoretical normal distribution (whereas you can rely on the CLT at that point). I'm also not sure why you would bootstrap your sample to check its distribution, can you not just plot a histogram or some other empirical (cumulative) distribution curve?
To summarize the choice of test: the parametric t-test comes with advantages (more power, actual parameters that describe your samples) at the cost of additional assumptions, but I wouldn't worry too much about the latter for the reasons above. At these sample sizes I would expect the MWU test to have very high power as well, so more likely than not they will be consistent. A trade-off of this high power is that you may end up calling very small differences statistically significant, so always keep an eye on the real-world impact of the numbers you get (e.g. is it worth replacing all machines to save 5 seconds on a 3 hour production time?).
Finally, let's address outliers. It's not clear how you established that 2% of your data consists of 'extreme outliers', very often this means that they are outside some sort of distributional assumption which may or may not even be appropriate. As a counterexample, what if both machines are equally fast when they work, but one of them is less reliable and when they break down the production time is much longer? What if it is exactly these data points that you're calling outliers? You throw them out, see no difference in the remaining data, and declare both machines equal - a conclusion that is only true when the machines are not breaking down. It's always a good idea to investigate extreme values and check if there is perhaps a technical explanation (for example, production time should be in minutes but this one was entered in years by accident). In absence of one I would not throw them out mindlessly. The same applies to winsorization, this will force additional distributional assumptions onto your data (are these correct?) and will hurt the generalizability of your findings.
Update, Thank you all very much for the detailed answer. I did a lot of research referred few books and was able decide trade-offs in terms of test selection, outlier handling, normality test and others. On surface it didn't seem too vast. But. man it is too vast.
| common-pile/stackexchange_filtered |
mongodb query and return specific collections
I'm trying to return all collections where field grade: 'Grade Two', I've tried a number of queries but getting either error or nothing being returned. I want my query only return documents from the collection with 'Grade Two', that should return only two docs.
I've tried the below queries:
db.users.find({grade: "Grade Two"})
db.users.find({}, {grade: "Grade Two"})
db.users.find({}, {profile: {grade: "Grade Two"}})
I'm getting error with message: "errmsg" : "Unsupported projection option: profile: { grade: \"Grade Two\" }",
{
{
"_id": "4YH8hDjNhN39CTtZh",
"username": "philcee.philips",
"emails": [
{
"address"<EMAIL_ADDRESS> "verified": false
}
],
"profile": {
"name": {
"firstname": "Philcee",
"lastname": "Philips"
},
"gender": "Female",
"nationality": "foo",
"grade": "Grade Two"
},
"roles": {
"__global_roles__": [
"student"
]
},
{
"_id": "8UH8hDjNhN39CTtm6",
"username": "gibson.wilson",
"emails": [
{
"address"<EMAIL_ADDRESS> "verified": false
}
],
"profile": {
"name": {
"firstname": "Gibson",
"lastname": "Wilson"
},
"gender": "Male",
"nationality": "bar",
"grade": "Grade Two"
},
"roles": {
"__global_roles__": [
"student"
]
},
{
"_id": "i7G8hDjKhN39CTYt9",
"username": "daniel.jones",
"emails": [
{
"address"<EMAIL_ADDRESS> "verified": false
}
],
"profile": {
"name": {
"firstname": "Daniel",
"lastname": "Jones"
},
"gender": "Male",
"nationality": "bar",
"grade": "Grade One"
},
"roles": {
"__global_roles__": [
"student"
]
}
}
Is there another way to query for specific docs from the collection mentioned?
Use .dot notation db.users.find({ "profile.grade": "Grade Two" }) and for projection db.users.find({ "profile.grade": "Grade Two" }, { "profile.grade": 1 })
Great, thanks. This was really helpful. All good now.
You can use .dot notation to find inside an object
db.users.find({ "profile.grade": "Grade Two" })
And to return specific field you can use projection in the second argument of the find query
db.users.find({ "profile.grade": "Grade Two" }, { "profile.grade": 1 })
| common-pile/stackexchange_filtered |
Beginner React query(How to remove a element and append another element)
I've just started learning React and after going through some guides, I tried making a Markdown Previewer. I successfully build it. But I wanted something else, I wanted to make a <textarea> then after the user has written on it then when they click on a button, it renders the HTML on itself(which isn't possible). So, is there a way to remove the <textarea> and append a div with the rendered HTML.
I mean, how can I remove the <textarea> and then append a new <div> with when the user clicks on the button?
If the question isn't clear, just comment what is missing, I'll edit it.
JSX for the Markdown
const example = `Heading
=======
Sub-heading
-----------
### Another deeper heading
Paragraphs are separated
by a blank line.
Leave 2 spaces at the end of a line to do a
line break
Text attributes *italic*, **bold**, ` +
' `monospace`' + `, ~~strikethrough~~ .
Shopping list:
* apples
* oranges
* pears
Numbered list:
1. apples
2. oranges
3. pears
The rain---not the reign---in
Spain.
*[Lavios](kdsbjhsdbhjfbdjbs)*`
const App = React.createClass({
getInitialState() {
return {
data: example
}
},
updateVal(e) {
this.setState({
data: e.target.value
});
},
render() {
return (
<div id="app">
<div id="app-inside-first">
<textarea rows='35' cols='20' value={this.state.data} onChange={this.updateVal}/>
</div>
<div id="app-inside-second">
<Markdown stats={this.state.data} />
</div>
</div>
)
}
});
const Markdown = React.createClass({
render() {
let render_content = markdown.toHTML(this.props.stats);
return (
<div dangerouslySetInnerHTML={{__html: render_content}} />
)
}
});
ReactDOM.render(<App />, document.getElementById("container"));
Here's the jsfiddle
You can use if-else condition https://facebook.github.io/react/tips/if-else-in-JSX.html
You'll need to use a ternary statement to switch between rendering the textarea and the HTML based on the app's state. I've updated the <App /> component to show this: the key part is the { this.state.showHtml ? this.renderHtml() : this.renderTextarea() } line. This checks whether showHtml is set; if so, it renders the HTML version, and if not, renders the textarea instead.
I also added a button which toggles the showHtml state, and moved the textarea and HTML components to separate functions - you'll need to do a bit of tidying up but this should give you the gist.
const App = React.createClass({
getInitialState() {
return {
data: example
}
},
updateVal(e) {
this.setState({
data: e.target.value
});
},
// render the output
renderHtml() {
return (
<div dangerouslySetInnerHTML={{__html: render_content}} />
);
},
// render the textarea
renderTextarea() {
return (
<textarea rows='35' cols='20' value={this.state.data} onChange={this.updateVal}/>
);
},
// toggle the showHtml state when the button is clicked
handleClick() {
this.setState({ showHtml: !this.state.showHtml });
},
render() {
return (
<div id="app">
// switch between textarea and output on click
<button onClick={ this.handleClick }>Show HTML</button>
<div id="app-inside-first">
// key bit! if this.state.showHtml is true, render
// output, otherwise render textarea
{ this.state.showHtml ? this.renderHtml() : this.renderTextarea() }
</div>
<div id="app-inside-second">
<Markdown stats={this.state.data} />
</div>
</div>
)
}
});
| common-pile/stackexchange_filtered |
How can i get a Mongoose custom error message?
So I have this mongoose schema that I want to validate
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You Must Include A Name"],
toLowerCase: true,
},
price: {
type: Number,
required: [true, "Price Must Be Included"],
min: 0
},
})
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
In index.js I extended Error class and wrote this middleware
app.use((err, req, res, next) => {
if (err.name == 'CastError') next(new AppError(`This is a CastError${err.message}`, 400))
else if (err.name == 'ValidationError') next(new AppError(err.message, 400))
else {
next(err)
}
})
app.use((err, req, res, next) => {
console.log(err.msg)
const { message = 'Something Went Wrong', status = 500 } = err
res.status(status).send(message)
})
When I make a validation error i get this: Product validation failed: price: Price Must Be Included
or when leave both name and price empty it get:Product validation failed: name: You Must Include A Name, price: Price Must Be Included
I just want: "Price Must Be Included"
or: "Name must be included"
How can I achieve that?
In your else if parse the err.message down to the message you want to emit and use that. Here is one way to parse it using string split on colon
else if (err.name == 'ValidationError') {
const messageParts = err.message.split(':');
next(new AppError(messageParts[2], 400)
} else ...
| common-pile/stackexchange_filtered |
General Error Handler for Restangular
So far I have around 4 calls to my API using Restangular and in each one of them I have been checking for them on the second argument of the then as shown below:
Restangular.all("accounts").getList().then(function() {
console.log("All ok");
}, function(response) {
console.log("Error with status code", response.status);
});
As you can see this is not a maintainable approach since this creates a lot of duplicate error handling code across the application.
I understand that the errorInterceptor exists however I cannot imagine a use for it to create a general error handler.
I hope that maybe some new ideas can help me on this issue.
Thanks :)
Instead of to check do we have a specific error handler in the promise chain or not, I added my general error handler to be cancellable in later of the promise chain:
Restangular.setErrorInterceptor(
function(response, deferred, responseHandler) {
var generalHandlerTimer = $timeout(function(){
generalErrorHanding(response);
},1);
response.cancelGeneralHandler = function(){
$timeout.cancel(generalHandlerTimer);
};
return true; // continue the promise chain
}
);
and a call where error can happen:
restangularizedUser.patch({
user: {
email:newValue
}
}).then(function(res) {
//Success
}, function(response) {
//Error
//Cancel the general error handler due to I want to handle it on my way
response.cancelGeneralHandler();
$log.debug('Handle the ERROR on my specific way');
});
Disadvantage:
If you need to use a specific error handler, then you need to call the response.cancelGeneralHandler();
Advantage:
No hack is required :)
I had similar problem. Problem with errorInterceptor is that it is called before any callbacks so we have an option to do something always not only when we need it. I solved this problem in hacky way so it's up to you whether you'll use it in your code or not. Works fine on:
"angular": "1.3.0",
"restangular": "1.4.0",
First I do use errorInterceptor:
RestangularConfigurer.setErrorInterceptor(function (response, deferred, responseHandler) {
var hasSomeErrback = deferred.promise.$$state.pending.map(function (thenAttachment) {
if (thenAttachment[2]) {
return true
}
else {
return false
}
}).reduce(function (accumulator, value) {
return accumulator || value
}, false)
if (!hasSomeErrback) {
myErrorService.globalError()
}
})
But instead of calling global error handler (myErrorService.globalError()) every time I do it only when there are not error callbacks registered. This is quite hacky, as it uses interal data of promise object but seems to work, see tests:
describe('when server responded with error', function () {
beforeEach(function () {
spyOn(myErrorService, 'globalError')
$httpBackend.whenGET('/api/evil').respond(500, 'pure evil')
})
it('should call global error handler if error callback was NOT attached', function () {
myApiClient.all('evil').getList().then(function () {
})
$httpBackend.flush()
expect(myErrorService.globalError).toHaveBeenCalled()
})
it('shouldnt call global error handler if error callback was attached', function () {
myApiClient.all('evil').getList().then(function () {
}, function () {
console.log('Inside local catch')
})
$httpBackend.flush()
expect(myErrorService.globalError).not.toHaveBeenCalled()
})
it('shouldnt call global error handler if error callback was attached using catch', function () {
myApiClient.all('evil').getList().catch(function () {
})
$httpBackend.flush()
expect(myErrorService.globalError).not.toHaveBeenCalled()
})
})
Copied from http://www.ngroutes.com/questions/AUuADiQ_a5vEqxqlK7FY/general-error-handler-for-restangular.html
| common-pile/stackexchange_filtered |
using paper-datatable-card in a custom-tag
//index.html
<html>
<head>
<link rel="import" href="test-table.html">
</head>
<body>
<template is="dom-bind" id="index">
<test-table data="{{data}}" ></test-table>
</template>
</body>
</html>
Polymer({
is: "test-table",
properties : {
data : {type : Array},
}
/*I dont know where should I put this stuff
"queryForIds:"
"getByIds :"
"set:"
"length:0"
*/
});
<dom-module id="test-table">
<template>
<paper-datatable-card id="datatableCard" header="Users" page-size="10" data-source="{{data}}" id-property="_id" selected-ids="{{selectedIds}}">
<paper-datatable id="datatable" data='{{data}}' selectable multi-selection selected-items="{{selectedItems}}">
<paper-datatable-column header="Id" property="_id" sortable>
<template>
<span>{{value}}</span>
</template>
</paper-datatable-column>
</paper-datatable>
</paper-datatable-card>
</template>
</dom-module>
as part of single page application I am using “paper-datatable-card” in my own custom-tag. I able to display the records but I’m not getting where I have to put the code for pagination. And I don’t want to put all records into dataSource at a time.
Any help is appreciated,
Thank you,
Venkat.
Your question is pretty vague. Can you please add some actual code that demonstrates what you try to accomplish?
You can edit your question. Please add the code to your question. Code in comments is quite cumbersome to read.
please check the code mentioned above
Did you check this example https://github.com/David-Mulder/paper-datatable/blob/master/demo/paper-datatable-card/full-implementation.html#L119?
i'm using the same example but as a custom-element. So I am unable to put the code from lines 117 to 133 in my custom elements as it doesnt support dom-bind
From within your Polymer component, you can set data in the ready method:
ready: function() {
this.data = {
queryForIds: function(sort, page, pageSize){
// implement me
},
getByIds: function(ids){
// implement me
},
set: function(item, property, value){
// implement me
},
length:0
};
}
Your comment question:
So I am unable to put the code from lines 117 to 133 in my custom elements as it doesnt support dom-bind
Answer (in Polymer 2.0) you can do it in your component constructor all the methods and all the data variables:
class YourComponent extends Polymer.Element {
contructor() {
super();
//in case if you use paper-datatable-card
this.data = {
get: function (sort, page, pageSize) {
return new Promise((resolve, reject) => {
const exampleData = [
{ 'name': 'someName1' },
{ 'name': 'someName2' }
];
resolve(exampleData);
});
},
set: function(item, property, value){...},
length: 1
};
//in case if you use paper-datatable only then without get or set properties
this.data = [ { name: 'someName' } ];
}
}
| common-pile/stackexchange_filtered |
When should I use a ellipsis in a Menu Item
When should I put ... at the end of a menu item? I seem to remember reading some rules but can't for the life of me find them.
For context - I'm adding a properties option to a right click menu and am wondering if it is appropriate to add them.
Use the unicode ellipsis when possible.
Seems some one has already had a posting on this. Please check http://stackoverflow.com/questions/278655/when-should-i-use-a-ellipsis-in-a-menu-item
This is such a great question!
http://stackoverflow.com/questions/637683/when-to-use-ellipsis-after-menu-items
Good article, which is consistent with the good answers below:
https://uxdesign.cc/dot-dot-dot-7ce6170bfc7f
One exception to the first two answers: if the whole point of the menu command is to open a window or dialog, then you don't need an ellipsis. For example, a "Get Info" or "Properties" command shouldn't have it, even though it's opening a window which lets you edit things.
It's only when the menu command's purpose is to do something else, but it needs a dialog or confirmation in order to do it.
Thankyou JW - that was the rule I was looking for. I'd remembered reading before but couldn't recall it.
That's good to know. One thing, is that a Mac rule and is it documented somewhere?
Here's a link to the Mcintosh UI guidelines: http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGText/chapter_14_section_3.html
They indicate the use of an ellipsis when the action needs a different window. The doc spells it out well.
In that document, look for "is completed by the opening of a panel." That's what I'm referring to.
sblundy -- I think Windows and other GUIs have generally taken the same approach. It's not always obvious when to apply this guideline, though, so you'll see plenty of exceptions.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa974176.aspx says "Don't use an ellipsis whenever an action displays another window—only when additional information is required."
As I understand it it indicates that the option will ask you something else before actually doing anything. The 3 dots are actually called an ellipsis, and if you check out the English use it kind of makes sense:
http://en.wikipedia.org/wiki/Ellipsis
BTW I've noticed OpenOffice breaks this convention sometimes!
It's important to know the distinction between "... will ask you something else" and "open a dialog". As other answers point out, you only use the ellipsis when the action needs more information before continuing. If the actual action is to display a dialog (for example, "Help About"), no ellipsis should be used since no more information is needed to perform that action.
According to the GUI design guidelines (windows 95 edition!) that was at my last job the Ellipsis signifies that it will want more information from you.
To add some context to this, the ellipsis is supposed to reassure the user that an action isn't going to be completed after choosing the menu. This was especially important for destructive actions. Would you rather choose "Delete…" or "Delete" ?
When the option will send the user to some sort of dialog where the user has to do something before a real change is made. Options without the ellipse take effect immediately.
For example, 'Save' doesn't have an ellipsis, while 'Save As...' does because the user has to input the new name/location of the file.
It means that there will be another dialog box after you select that option, it won't actually 'do' anything. There will be another prompt.
More correctly, I think, it means "more information is needed before this action will be performed". Typically that more information will come from a dialog box but I suppose one could come up with a UI that doesn't use dialog boxes in the traditional sense.
To be exact, the rule is that if more information is required from the user to complete an action, then include an ellipsis. In the MS Vista User Experience Guidelines, getting a confirmation qualifies as "more information" (see http://msdn.microsoft.com/en-us/library/aa511502.aspx). Commands to show Properties, About, Help, Options do not get ellipsis because no further information is needed to execute the command, which is "Show Properties" or "Show Documentation" or "Show Options." The File Open command gets an ellipsis because additional information is needed to open the file, namely the file name.
If the menu is an action that the user will be doing, but the action won't be completed until we get more information from the user, you show an ellipsis, e.g.:
Format Hard Drive… (we need to know which one, and the file system type)
Save As… (we need to know what filename and type to save as)
Print… (we need to know what printer and quality settings)
Find… (we show a text box asking for the text to search for, and where)
Rename… (rename to what)
As opposed to actions that will happen the moment you click the menu item, e.g.:
Save
Undo
Redo
Select All
Ellipses don't just indicate that a dialog will appear. i.e. if it's not an "action", then there's no ellipses, e.g.:
About Gizmo
Page Setup
Print Preview
Options
File Properties
And asking the user if they want to do something does not count as "getting more information from the user", e.g.:
Delete File
Recycle File
New Text Document
Originally, it meant:
An ellipsis (...) after a menu item means that after the item is chosen, the user will be asked for more information before the operation is carried out. Usually, the user must fill in a dialog box and click and OK button or its equivalent. Don't use the ellipsis when the dialog box that will appear is merely a confirmation or warning (for example, 'Save changes before quitting?').
(Apple Human Interface Guidelines, page 69)
Note that it did not mean "show a dialog box", even though that was often the consequence of this. For example, on Mac OS (not X), the "Options" button in the Page Setup window had no ellipsis, even though it showed a modal dialog box. No ellipsis is used because showing the options window is the operation.
(Tog on Interface, pages 46-47)
Of course, these days nobody cares about such things as human interface guidelines, not even Apple, so you can pretty much do what you want and still be more consistent than most any other application out there.
I think the "pretty much do what you want" recommendation is wrong. There are well established cross-platform conventions that should be followed, and the use of the ellipsis in menus falls squarely in that category.
Why "should" they be followed? The most popular and the most usable programs in the world today don't follow anybody's HIGs. By what metric is following them a good idea?
The words you (Alec) chooses mean different things to me. "HIGs" are guidelines specified by a vendor -- 'use this for forward/back buttons, use that for standard menus, use other pixels for a border". I'm talking about conventions such as the use of an elipsis, the traditional menu structure of file/edit/view/help, that sort of thing. Sure, sometimes a program can break the mold and be highly usable (think: the ribbon in newish MS products) but by and large your average programmer should stick to standard conventions.
As for the why... pick up just about any research paper dealing with usability. I think it's an established fact that consistency (first with the system, second within an app) makes for easier to use programs because you leverage what the user has already learned. For every one "most popular and ... usable program" that defies convention, I can show you thousands that are not usable largely because they eschew convention.
I've usually seen it in places where more input is required from the user before completing an operation. If your properties dialog is allowing the user to change properties, I would include the ellipses. If it's just displaying the information, don't include it.
They usually signify that clicking on that entry will open a dialog window.
This IS a programming question, unless UI theory doesn't count as programming, in which case anything related to HTML/CSS/Design isn't relevant, as well as possibly windowing libraries.
There is more to it than that. See the comment I posted on Kyle Rozendo's answer.
This is too simplistic, there are cases when the button is only supposed to open a window to show information, those don't need ellipses. Its more accurate to say when you want to perform an action that requires additional input.
It generally means that a Dialog will be shown when the item is clicked.
This is a common misconception because in the common cases such as File|Open, File|Print, File|Save a dialog is displayed but the actual definition in Microsoft's and others' UI guidelines is that the ellipsis indicates more information is needed before the action will be performed. To illustrate the distinction, it is generally incorrect to put an ellipsis on Help|About because displaying the About dialog is the objective of the command not an intermediate step prompting for more information before the actual command can be completed.
You should add ellipses to the end of text only if you're truncating the text (this applies anywhere). You should truncate the text if it's too long to reasonably fit where you're putting it.
Edit: interesting, I never noticed that menus in Windows use the ellipses to indicate truncated text, but also use the ellipses on short text to indicate that more information will be collected before the action is taken. This is inconsistent interface design, but since menus are under the control of individual programmers it's unavoidable.
I think you're being down-voted because your answer is incorrect. You said you should use ellipses "only if you're truncating the text" and that's simply untrue.
Ellipses have meant "more information is required" on menus on just about all platforms probably since menus were first invented.
I didn't say I didn't deserve any down-votes. :) I totally misunderstood his question as being about when he should abbreviate his own menu items, which made the question seem totally stupid (when it was just me being stupid).
That being said, I have to admit that this is the first time I ever noticed that the ellipses in a menu always (or usually) indicate that more info will be collected before the action is taken. Go ahead and give me another downvote.
It usually means it'll take your focus away from the current window. Like for example, notepad has a "Find..." which means you're going to focus on another window (ie dialog box) to enter something. But in firefox, it has just "Find" which then focuses on a text input on the same window.
| common-pile/stackexchange_filtered |
Temporary method within method?
In the method below, there are three conditionals. I'd like to replace them with a method and pass in the conditional.
Also, the conditional body is nearly repeated. Is it possible to create a method that exist only locally within MyMethod()? So the code below reduces to something like this:
//reduced code
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
return localMethod((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1");
return localMethod((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true);
return localMethod((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");
//...localMethod() defined here...
}
But in the above, only one should return.
//original code
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
if(class1Var.SomeBool && !class2Var.SomeBool)
{
return new ClassZ
{
Property1 = false,
String1 = "This is string1"
};
}
if(class1Var.SomeBool && !class2Var.IsMatch(class2Var))
{
return new ClassZ
{
Property1 = true,
};
}
if(class1Var.SomeProperty.HasValue && !class2Var.SomeBool)
{
return new ClassZ
{
Property1 = false,
String1 = "This is string2"
};
}
}
Basically, I'd like to create a temporary method within a method.
Not sure exactly what you want but surely your local method could just be a private method?
It could. I'd rather try to keep it inside MyMethod() since it doesn't need to exist outside.
I don't think that is possible, if you are really concerned about accidentally calling it, you could make the whole thing into a nested class, but really what is your concern? If it is private, it can't even be called by derived classes so providing it is clearly documented as not for use, what is the problem?
You can use Func notation for this. Funcs encapsulate delegate methods. Read the documentation of Funcs here. For a Func with n generic parameters, the first n-1 are the inputs of the method and the last parameter is the return type. Try something like this:
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
Func<bool, bool, string, ClassZ> myFunc
= (predicate, prop1Value, string1Value) =>
predicate
? new ClassZ { Property1 = prop1Value, String1 = string1Value }
: null;
return myFunc((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1")
?? myFunc((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true)
?? myFunc((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");
}
Here, we instantiate a Func that takes in a bool (the predicate), the parameters to set (the second bool and the string), and returns a ClassZ.
This is also using null coalescing (the ?? notation), which returns the first non-null argument. Read more about null coalescing here.
The other option is to use Actions, which encapsulate void methods. Read about Actions here. You could instantiate a new ClassZ, and then call 3 Actions on it, which conditionally set the variables provided.
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
Action<bool, bool, string, ClassZ> myAction
= (predicate, prop1Value, string1Value, classZInstance) =>
if (predicate)
{
classZIntance.Property1 = prop1Value;
classZInstance.String1 = string1Value;
}
var myClassZ = new ClassZ();
myAction((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1", myClassZ)
myAction((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true, classZ)
myAction((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2", myClassZ);
return myClassZ;
}
| common-pile/stackexchange_filtered |
why would identical mongo query take much longer via aggregation than via find?
so, i have 10M people documents. this query:
db.getCollection('people').find({'address.zip': '87447'}).sort({'name.last': -1}).limit(3)
returns in < 20ms
this query:
db.getCollection('people').aggregate([{$match: {'address.zip': '87447'}},{$sort: {'name.last': -1}}, {$limit: 3}])
returns in > 20s
i have indexes on address.zip and name.last
there are only about 100 or so documents that meet the $match criteria...
baffled...
here are explains:
find
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "people.people",
"indexFilterSet" : false,
"parsedQuery" : {
"address.zip" : {
"$eq" : "87447"
}
},
"winningPlan" : {
"stage" : "SORT",
"sortPattern" : {
"name.last" : -1.0
},
"limitAmount" : 3,
"inputStage" : {
"stage" : "SORT_KEY_GENERATOR",
"inputStage" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"address.zip" : 1
},
"indexName" : "address.zip_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"address.zip" : []
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"address.zip" : [
"[\"87447\", \"87447\"]"
]
}
}
}
}
},
"rejectedPlans" : [
{
"stage" : "LIMIT",
"limitAmount" : 3,
"inputStage" : {
"stage" : "FETCH",
"filter" : {
"address.zip" : {
"$eq" : "87447"
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"name.last" : 1
},
"indexName" : "name.last_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"name.last" : []
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "backward",
"indexBounds" : {
"name.last" : [
"[MaxKey, MinKey]"
]
}
}
}
}
]
},
"serverInfo" : {
"host" : "00caaca2f8e7",
"port" : 27017,
"version" : "3.7.2",
"gitVersion" : "ca0a855dfc0f479d85b76a640b12a259c0547310"
},
"ok" : 1.0
}
aggregate
{
"stages" : [
{
"$cursor" : {
"query" : {
"address.zip" : "87447"
},
"sort" : {
"name.last" : -1
},
"limit" : NumberLong(3),
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "people.people",
"indexFilterSet" : false,
"parsedQuery" : {
"address.zip" : {
"$eq" : "87447"
}
},
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"address.zip" : {
"$eq" : "87447"
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"name.last" : 1
},
"indexName" : "name.last_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"name.last" : []
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "backward",
"indexBounds" : {
"name.last" : [
"[MaxKey, MinKey]"
]
}
}
},
"rejectedPlans" : []
}
}
}
],
"ok" : 1.0
}
any suggestions on where the issue lies or how to troubleshoot?
did you compare the execution times having the compound index suggested by @Asya Kamsky
Aggregate and find use different query plans because currently aggregation explicitly requests that a non-blocking plan (i.e. one that can use an index to provide the sort order) is used.
There is a Jira ticket (https://jira.mongodb.org/browse/SERVER-7568) that's tracking the work to improve this, as the query plan that sorts in memory can be faster if a small number of documents match the query.
However, in all cases having a compound index that satisfies the filter and sort clauses would perform best for both find and aggregate. In your case that would be an index on {"address.zip":1, "name.last":1}
Note that as of 3.6 you can also provide hint to aggregate to specify which index you want used.
thanks @asya, in my case, i was going for an ad-hoc query setup where i would place solo indices on fields available for either filter or sort and let the optimizer do it's thing. compound-indices would lead to an exponential number of combinations if i went for that. the hint thing might help at times, but i wouldn't know as much as the optimizer. i like the suggestions for improvement called out in SERVER-7568 tho, guess i'll keep an eye on that. thx!
| common-pile/stackexchange_filtered |
How to add folders with C++ files to a NetBeans project?
I had copied folder to my project folder with one cpp file and set of headers. It appeared in project view. How I understand this means they was added to project (if I can see they in project view). Right?
But undefined reference to ((
Then I found that they does not exist in logicalFolder of nbproject/configurations.xml. I had added it manualy (found solution for this from stackoverflow: Netbeans-specific C++ error Undefined reference to XXX - (Solution posted)). How I understand this is not normal behaviour. Right?
<logicalFolder name="SourceFiles"
displayName="Source Files"
projectFiles="true">
<itemPath>src/jsoncpp/jsoncpp.cpp</itemPath>
...
Clean and build. As result in output I see that all files compiled except cpp file from my added folder:
src/jsoncpp/jsoncpp.cpp
No any mentions about jsoncpp.cpp in compile output pane. All files compiled (in src folder) except jsoncpp.cpp (in src/jsoncpp folder).
Could you help me how to fix this?
Product Version: NetBeans IDE 8.2 (Build<PHONE_NUMBER>01)
Updates: NetBeans IDE is updated to version NetBeans 8.2 Patch 2
Java: 1.8.0_131; Java HotSpot(TM) 64-Bit Server VM 25.131-b11
Runtime: Java(TM) SE Runtime Environment 1.8.0_131-b11
System: Linux version 3.13.0-119-generic running on amd64; UTF-8; en_US (nb)
User directory: /home/xxx/.netbeans/8.2
Cache directory: /home/xxx/.cache/netbeans/8.2
P.S. Also on the Navigator pane of src/jsoncpp/jsoncpp.cpp I see "Limited assistance (no associated project)"
You aren't supposed to go directly to the nbproject directory and make changes there. Instead:
Open Projects pane
Right click on project name - popup menu will be shown
Click Add Existing Items from Folders... button in this menu - a popup window will appear
Click Add Folder button to choose a folder - a selection popup window will appear
Select the folder you want and click the Select button
Click Add to add the folder to your project
All the files from this folder will be added to your project. If you want to add files one by one you can use the Add Existing Item button in the popup menu.
The added folder will be shown on the Files pane as a logical folder with name, consisting of your project name, dash and the absolute folder path. You can use this logical folder to easily access its files. Logical folders don't have to be in the project directory - they can be anywhere in your filesystem.
Did not help :-(
Create new "C/C++ Application" project with "uncheck create main file" and select folder of project;
"Add existing Items from folders" and select all files in subfolder "src" including jsoncpp. All files/folders was added;
Add libraries and select "C++ 11" compiler;
Add "src/jsoncpp" to "Build/C++ Compiler/Include Directories";
Add "src/jsoncpp" to "General/Source Folders". Result: two entries "src" and "src/jsoncpp";
Clean and build;
Result: same error. "jsoncpp/jsoncpp.cpp" is exist in project view but did not compiled
After add "src/jsoncpp" I found that after closing properties dialog and reopen it I see that "src/jsoncpp" disappired in "General/Source Folders" and only "src" entry remain.
@AlexanderSymonenko - you are right, my answer isn't helpful, I'll edit it. But - I was able to add existing directories and/or files to my test project, and it was compiled OK
Ok. In any case thank you. I had reported issue: https://netbeans.org/bugzilla/show_bug.cgi?id=270895
Yahoo! All is works. I had used "Add existing item" for select all files and my jsoncpp folder instead "Add existing item" for files in "src" folder and "Add existing items from Folders" for "src/jsoncpp" folder. More detailed can be read in my additional comment in bug report. But in any case bug is exist )) You add item to "General/Source folders" and it disappears without any feedback/errors from GUI. Oh my brain. I'm beginning to regret that I had choose NetBeans instead Qt Creator for new project.
@AlexanderSymonenko - a majority of my NetBeans projects are actually with existing sources (with my own Makefile) - this is more flexible and shields me from NetBeans quirks
| common-pile/stackexchange_filtered |
How to achieve the combobox with multiselect capability by typing
I am able to select the combobox with multiselect property as true..and i am able to select a value by typing but only one value..is there any way to select more than value by typing
In ExtJs 6 multiSelect config from Combo box has been deperciated ..This cfg has been DEPRECTED since 5.1.0
Yes it is deprecated but we can still use the multiselect and i am able to select the mouse and i want to select multiple ones by typing the values.And also the tagfield is not fit in my scenario. .thats why i am trying to use combo with multiselect
| common-pile/stackexchange_filtered |
Catalog price rules disappear after 24 hours in Magento <IP_ADDRESS>
We used two suggestions from https://stackoverflow.com/questions/25280095/ to solve this problem.
We applied the "line 121" fix to app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php
We also installed AOE scheduler and used the settings suggested by Lakshin Karunaratne at the end of the post.
Neither of these are working. After manually running all rules, all discount prices are reverted back to full price after 24 hours.
AOE is running successfully. However, catalogrule_apply_all is the only rule not running successfully. I see this has been quite an ongoing issue. Anyone have a fix?
I have no idea how or why this started working. After a couple days, sale prices stopped reverting and the rules remain applied.
| common-pile/stackexchange_filtered |
Burninate the [godaddy] tag
First off, godaddy has 903 questions tagged with it. godaddy-economy-hosting has 15. (no longer true, burninated)
EDIT: we're at under 100 questions with godaddy tagged.
GoDaddy is a platform for hosting, and these askers seem to think that tagging their questions with their service provider, when it doesn't make too much of a difference, will in some way solicit more answers. (well, technically it does apparently, because more baffled people come from Google for oft unrelated questions just because of "godaddy" in the title...)
GoDaddy is quite literally just shared VPS hosting, same as any other hosting, running on an IIS cluster if Windows or apache if Linux. They are often the XY Problem because these users are pretty much assuming their sloppy coding can't be their fault and assume it is the hosting provider's fault.
The majority of these questions* simply casually mention their hosting provider at the start of the question:
I'm [hosting|deploying] a [insert app/technology name] [project|site] on [hosting provider]
While this is fine and dandy to mention, it doesn't really tell us much of anything extra to mention the hosting provider, and it certainly doesn't make sense to tag it as such, unless GoDaddy were wishing to outsource their support or something. We can't magically fix a hosting problem with software solutions just because we know who your plumber is, or anything. We certainly wont be following that plumber's tags on SO to see a wide range of unrelated things they haven't done, either.
There are also a few questions which are effectively just godaddy support, namely:
How to access the php.ini file in godaddy shared hosting linux
https://stackoverflow.com/questions/16118746
Should be retagged php, and maybe(?)file-upload, though that tag is also really broad
My request is this:
Burninate the godaddy-economy-hosting tag completely and immediately. DONE.
Burninate the godaddy tag.
Close questions which are solely tagged with godaddy (I have no idea how to search for this. Anyone know?) as off-topic.
Anyone else agree? If not, why?
* Sample of 80. I also came across this
EDIT 2:
It seems the vast majority of the remaining GoDaddy questions are pretty much GoDaddy tech support (And if you look in the tag top users, there's a godaddy employee, too). There is also a question I just flagged, which is clearly by a novice user, and would have probably been titled by me as "Magento base_url structure" over on Magento.SE. So many of these questions are either purely off-topic (how can i has teh codes on my host?), or have fluff in them about their web hosts.
When we are done with this tag, can we please have it blacklisted along with other web hosting/DNS hosting guys? Because everything that uses these tags is either off topic for SO, or is incorrectly using the tag.
As an addendum, due to Charles' comment, I have yet to find any questions about the godaddy API so far.
I don't think we should kill the tag completely.. it may have value in some cases.
Yes, definitely. If we keep Go Daddy tags, then requests for tags for other hosts would be reasonable, and that would be a huge mess.
@0A0D can you provide an example of an instance where it would be a valid tag?
Devils advocate: does this mean that the [tag:heroku], [tag:azure], [tag:azure-web-sites] and other similar tags should be removed as well? How are those tags different from [tag:godaddy]?
They're different because they provide APIs, platforms, development technology, deployment bits, and other development-relevant things. While godaddy does have some API bits (for resellers, apparently), most of the questions with the tag are not used for that API. The common use is "oh, I'm hosted there," which is irrelevant. Questions about the API bits should be retagged, then the tag nuked from orbit.
@KyleTrauberman: here is an example that is localized to godaddy http://stackoverflow.com/questions/16128213/mysql-connection-issues
@charles so burninate [tag:godaddy] and then create a [tag:godaddy-api] tag for the edge cases?
@Hiroto, bingo. Unfortunately this is going to have to be a manual process, with a queue of 900+ questions...
I'm working on the [tag:godaddy] questions.
working on de-localizing the godaddy tagged questions that have noise in them now.
Solely godaddy questions: http://data.stackexchange.com/stackoverflow/query/113482/select-all-questions-with-only-a-specific-tag?Tag=godaddy (enter godaddy as the parameter)
Godaddy's back: 1004 questions as I type. Almost all are still pretty much tech support issues, or are general and not specific to Godaddy.
@quantas I'll ping a dev later and ask about this
I came here to post the same request. I am on a personal mission to remove godaddy tags from questions where it is clearly irrelevant. There are a lot of GoDaddy tech support questions though, where the tag is relevant even though the question is inappropriate for SO. Many of those can probably be closed as "general software" or "recommending a library or tool". Still, burninating the tag won't stop the questions. Maybe it makes sense to keep the tag, so SO knows what questions to automatically close. ;)
Related http://meta.stackexchange.com/questions/228693/blacklist-godaddy-tag-and-rename-to-godaddy-api?lq=1
| common-pile/stackexchange_filtered |
Saving Images into SQLite database
I have a program that collects some data from the web-site. Text data is appended into "info" DataFrame and photo urls are appended to "photos" DataFrame.
I have already inserted "info" table to my SQL database and works really fine!
data.to_sql('Flat', con=conn, if_exists='replace',index=False)
Now i need to understand how can convert image links to Blob data and insert it into DataBase.
Download the image content at those links, and then store it as BLOBs. Easy-Peasy.
BLOBs are Binary Large OBjects. First you need to convert the image to a binary object.
def convertToBinaryData(imageLocation):
#Convert digital data to binary format
with open(imageLocation, 'rb') as file:
blobData = file.read()
return blobData
The rest is a simple insert, make sure you are connected. Create an insert statement, inject your binaries into this statement.
insert = """ INSERT INTO 'images' ('id', 'image') VALUES (?, ?) """
id = 1
image = convertToBinary(imageLocation)
cursor.execute(insert, (id, image))
connection.commit()
These functions are omitting how to create a connection and get a cursor, however full example can be found at: https://pynative.com/python-sqlite-blob-insert-and-retrieve-digital-data/
That's great, but i have image URLs)
Depending on the size of the images, you can request them and then turn them to blobs. Or even request them as blobs.
https://stackoverflow.com/questions/34077942/python-use-requests-to-read-an-image-url-then-save-as-blob-data-to-mysql
and how can i get them as Blobs ?
Depends on the provider or tools I left a link to another question, where the question contains accurate code.
| common-pile/stackexchange_filtered |
Meteor : Changes in collections are not reflected in rendered HTML
I have been trying to doing some very simple publish/subscribe in Meteor and I cannot get it to work as I expect from reading the sources available such as the Meteor documentation.
I am using a Macbook Pro with OSX Yosemite and running Node.js v0.10.40, Meteor v<IP_ADDRESS> and Chrome Version 43.0.2357.132 (64-bit).
Here is what I am experiencing with two different examples:
First: Simple todos tutorial.
simple-todos.html
<head>
<title>Todo List</title>
</head>
<body>
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</body>
<template name="task">
<li>{{text}}</li>
</template>
simple-todos.js
Tasks = new Meteor.Collection("tasks");
// simple-todos.js
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function(){
Tasks.find({});
}
});
}
Problem description
The tutorial states that when adding items to the Tasks it should be reflected live in the browser. It does not. I have tried adding items as Tasks.insert({text: "todo from server", createdAt: new Date()}) in the JS console in Chrome and in the meteor shell. I have also added items using meteor mongo and still no changes in the rendered client view
The autopublish package is installed and I can insert and query the Tasks collection from the JS console in the browser, but the changes are not reflected in the rendered HTML.
Second: A simple publish/subscribe scenario
Basic.html
<head>
<title>basic</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
<p>text gets pushed</p>
</body>
Basic.js.
MessageColl = new Mongo.Collection("messages");
if(Meteor.isServer){
Meteor.publish("messages",function(){
MessageColl.find({});
})
}
if(Meteor.isClient){
Meteor.subscribe("messages", {
onReady: function () { console.log("onReady And the Items actually Arrive", arguments); },
onError: function () { console.log("onError", arguments); }
});
}
Problem description
When the autopublish package is added to my project everything works as intended. I can insert new items from the JS console in Chrome and I can query the MessageColl collection and retrieve the results as well.
When the autopublish package is removed I can insert items in the MessageColl collection from the JS console in Chrome and verify that they have been added by querying the collection in the meteor shell. However when I try to query either using MessageColl.findOne() or MessageColl.find().fetch() the return value is undefined.
All changes being done in the structure of the HTML-document gets pushed as expected.
Neither the onReady or the onError callback functions gets called, so that points toward an issue related to the subscribe method.
I think both problems are pretty straightforward to solve (but frustrating when you can't work out why - I've been there). Basically, you aren't actually returning anything from your functions so your code doesn't have a result.
In your template helper you need to add return like this:
tasks: function(){
return Tasks.find({});
}
Similarly, in your publication you also need return like this:
Meteor.publish("messages",function(){
return MessageColl.find({});
})
| common-pile/stackexchange_filtered |
How does Scrypt use Salsa?
Bcrypt uses Blowfish to encrypt a derived key from the passphrase, and Blowfish is a cryptographic algorithm, but here it is said that:
Note that
Salsa20/8 Core is not a cryptographic hash function since it is not
collision-resistant.
so how this is useful in Scrypt?
Salsa20/8 is used not to enhance cryptographic strength, but to make random-ordered requests to the RAM (and to slower FPGA/ASIC implementation of scrypt). The scrypt uses PBKDF2-HMAC-SHA-256 (PBKDF2 of HMAC-SHA256) to provide such strength.
There is simple variant of scrypt, with parameters p=1 (Parallelization parameter), N=16384, r=8, taken from linked draft and simplified for p=1:
Algorithm scrypt
Input:
P Passphrase, an octet string.
S Salt, an octet string.
N CPU/Memory cost parameter, must be larger than 1,
a power of 2 and less than 2^(128 * r / 8).
r Block size parameter.
p Parallelization parameter, a positive integer
less than or equal to ((2^32-1) * hLen) / MFLen
where hLen is 32 and MFlen is 128 * r.
dkLen Intended output length in octets of the derived
key; a positive integer less than or equal to
(2^32 - 1) * hLen where hLen is 32.
Output:
DK Derived key, of length dkLen octets.
Steps:
1. B[0] = PBKDF2-HMAC-SHA256 (P, S, 1, 128 * r)
2. B[0] = scryptROMix (r, B[0], N)
3. DK = PBKDF2-HMAC-SHA256 (P, B[0], 1, dkLen)
We can see that there are two PBKDF2 with HMAC SHA256, one before ROMix and one after. They will provide collision resistance for the scrypt.
And here is the scryptROMix, which uses N-sized array, every element of which is equal to scryptBlockMix of previous element (step 2). Salsa is used inside scryptBlockMix and in scryptROMix it defines both transformations of X and the order of read accesses to V array:
Algorithm scryptROMix
Input:
r Block size parameter.
B Input octet vector of length 128 * r octets.
N CPU/Memory cost parameter, must be larger than 1,
a power of 2 and less than 2^(128 * r / 8).
Output:
B' Output octet vector of length 128 * r octets.
Steps:
1. X = B
2. for i = 0 to N - 1 do
V[i] = X
X = scryptBlockMix (X)
end for
3. for i = 0 to N - 1 do
j = Integerify (X) mod N
where Integerify (B[0] ... B[2 * r - 1]) is defined
as the result of interpreting B[2 * r - 1] as a
little-endian integer.
T = X xor V[j]
X = scryptBlockMix (T)
end for
4. B' = X
thank you! but i dont get this: 'The scrypt uses PBKDF2-HMAC-SHA-256' so will i say that Scrypt uses pbkdf2 ?
PBKDF2 is the (KDF) function definition (pbkdf2 algorithm), it can be used with many hashed; and HMAC-SHA256 is actual parameter to the PBKDF2 function. So, when author writes only PBKDF2, we can't implement it; but when the PBKDF2-HMAC-SHA-256 name is used, we can implement PBKDF2 with HMAC-SHA-256 as hash function.
The scrypt draft even says "The PBKDF2-HMAC-SHA-256 function used below denote the PBKDF2 algorithm used with HMAC-SHA-256 as the PRF."
am sorry, here is what i understand: salsa uses pbkdf2, scrypt uses salsa = scrypt uses pbkdf2?
Abdelouahab Pp, wrong. There is scrypt algorithm for crypting passowrds. Scrypt uses PBKDF2, then some function (which uses Salsa20 for some operations), then another iteration of PBKDF2.
ah, so like that i can say that pbkdf2 and scrypt and not separate algorithms but pbkdf2 is used in scrypt?
Abdelouahab Pp, There are lot of algorithms: SHA1, SHA256, HMAC, PBKDF2, Bcrypt, Scrypt (and other listed in wikipedia). And some of them are built based on another, sometimes via usage of original algo, and sometimes by usage of some parts of original algo. E.g. PBKDF2-HMAC-SHA-256 is variant of PBKDF2, which uses HMAC-SHA256 as PRF parameter. HMAC-SHA256 itself uses SHA256 (but there are also HMAC with MD5 and other hashes). Bcrypt uses parts of modified Bluefish cipher. And for scrypt - is uses PBKDF2 (PBKDF2-HMAC-SHA-256 variant) and some parts of Salsa20.
ah! now i get the idea, because i the past i considered the three as separate algo, so now i have SCrypt and BCrypt, and pbkdf2 which is used by SCrypt and not the concurrent of SCrypt itself ;)
Abdelouahab Pp, but bcrypt, scrypt and PBKDF2 are sometimes used as concurrents (for secure storage of hashed passwords in client-server applications)! And PBKDF2 even had some NIST recommendations. But scrypt still uses PBKDF2, and the scrypt's author claims that scrypt is very good for password storage while both bcrypt, PBKDF2, HMAC, FreeBSD MD5 are bad choice for storage because either they are easily attacked using GPU/FPGA/ASIC, or they should be tuned to very long checks of single passwords - minutes per client. Will you wait 2 minutes between entering gmail password and entering site?
yes that is the problem, it seems that if someone will use a powerful algorithm (= slow) he will get a DOS in his server!
thank you again ;)
Abdelouahab Pp, powerful algorithm (scrypt) is so powerful, that it provides good protection even without DDoS. But still good settings of scrypt are to use several megabytes (4-8-16) per instance (less then ~0.1 sec check latency), so limiting the number of users capable of doing simultaneous login. But for very fast checking, like less 1 millisecond per user, bcrypt is stronger than scrypt. And PBKDF2 is usually not strong enough to protect from FPGA attacker.
on python, sadly SCrypt is hard to compile, needs openSSL and it dident work, only works on Linux, pbkdf2 is so easy to implement on python since it dont need C extensions to speed up
Salsa20 core is not a collision resistant hash function, see DJB's own webpage:
http://cr.yp.to/salsa20.html
For example, Salsa20core(x) = Salsa20core(x + c) for c =
"0000000800000008...", thus demonstrating trivial collisions.
To be concrete, try computing Salsa20core for the the following two
inputs:
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
and
00000080000000800000008000000080
00000080000000800000008000000080
00000080000000800000008000000080
00000080000000800000008000000080
the output for both inputs should be all zeros.
In what way do you think this property weakens scrypt?
so that means SCrypt is not collision resistant too? so then BCrypt is better?
Yes, Salsa20 core is not meant to be collision resistant. But that is not relevant to the intended use case of Scrypt: Password hashing.
Password hashing is an unfortunate name, as "hashing" has so many specific meanings depending on the context. Two scenarios where you use password hashing are:
Password storage for online services. Imagine your users log in to your site using passwords and you have to store some information per user to check that the supplied password is correct. On the other hand, if that stored information is stolen (SQL injections etc.) you don't want the passwords to be recoverable.
Key derivation for symmetric encryption. TrueCrypt and other full disc encryption software encrypt your data using a key that is derived from the password you type in at boot time. Usually that password is not as good as a 128 bit random key would be. For example if you use 5 alphanumeric characters you might only have 36^5=60,466,176 possible passwords. If the time it takes to check whether one password is correct or not is small, bruteforcing becomes quite feasible.
What both have in common is that you have low entropy input data and want to have a guaranteed and relatively high time to compute the hash of the password. This makes sure that bruteforcing the small number of likely passwords is difficult.
Out of the classical security criteria (collision resistance, pre-image resistance and second pre-image resistance) of a cryptographic hash function only pre-image resistance is thus of interest for password hashing, as you don't want an attacker to be able to compute valid login data out of the password hash in the password storage scenario.
and SCrypt will use salsa to make the ram full in small amount of time?
It's not about filling the ram, but about needing a lot of memory to be fast. This is meant to hinder extremely parallelized hardware implementations. See http://en.wikipedia.org/wiki/Scrypt#Overview for details.
it's kind of feeling, since that ram is not shared, then it cant be accessible for another resource?
IMHO it's just a warning to the reader that this is not a standard hash-based design like BSD-crypt or PBKDF2, which are traditional choices. They use the Salsa20/8 Core mixing function because its speed improves upon the first mixing function that was used in the defining paper for scrypt (that is referenced in the RFC you linked to): there he uses the SHA-1 compress function (not SHA-1 as a hash) which is function that transforms 20 bytes to 20 bytes (it's really a blockcipher, using the message blocks as a key); In the same paper he then suggests SALSA20/8 as a mixing function.
so salsa is not a cryptographic function? because i dont find it like DES or AES or Blowfish or Twofish?
It is, but it is not a hash in the traditional sense. It's a cryptographic mixing function, normally used as a component in the stream cipher Salsa20. The use in scrypt is different from its use in the stream cipher, and the author in the scrypt paper shortly discusses that too.
ah, so it is a new concept, what they want to say is: it is different than BCrypt and PBKDF2
what did you mean by compress function and not hash?
Study the SHA-1 spec. The work is done mostly in a function that transforms the 20 byte state to another 20 byte state with the message as "key" (this component is the blockcipher SHACAL). So at the core of SHA-1 is a block transform as well, and this is the one used. The whole hash is the function with the fixed input state, and message padding added, plus the iterative application of this transform for successive blocks.
so it is always 20 bytes? i thought it was a typo, because compression should get less characters? am sorry if i ask lot of question, am a beginner
The compression is as seen from the point of view of the message, not of the state. The state stays the same size, and the message bytes are all used, as many as we have. We output the state at the end, which is often a lot shorter than the message, which has been mixed into the state iteratively.
sorry if i dont get the idea, but if we have for example the message "hello, im a simple test" then this is the message, so what is the state? is it what will generate the hash?
| common-pile/stackexchange_filtered |
Displaying all the collapsible content in Accordion using Selenium Webdriver
Suppose I want to simulate a scenario, where a user wants to see all the collapsible content like the Accordion widget, one by one, with some wait, in between two clicks ( at most 2-3 seconds)
The user clicks on Section 1, then waits for 2 seconds and then clicks on Section 2, and so on.
I thought of implementing in this way
package com.rahul.misc;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class accordion {
public WebDriver driver;
private String baseUrl;
public static void main(String[] args) {
accordion acc=new accordion();
acc.checkFirefox();
// TODO Auto-generated method stub
}
public void checkFirefox(){
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
baseUrl="http://jqueryui.com/accordion/";
driver.get(baseUrl);
List<WebElement> allinks= driver.findElements(By.cssSelector(".ui-accordion-header"));
for(WebElement w:allinks){
new Actions(driver).click().build().perform();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This code compiles correctly but it does nothing. I am skeptical about part where I have put all the elements in list. Is this the correct way to catch all the web elements for the widget. If no how do I do it.
Also is the action performed correct? Because in the scenario, user won't be doing in, he'll be just clicking on the collapsible header.
The reason why your code isn't doing anything is because the elements are contained in an iframe. findElements() does not throw an exception if no elements are found, thus your code runs to completion.
You can fix that part like so:
baseUrl="http://jqueryui.com/accordion/";
driver.get(baseUrl);
driver.switchTo().frame(driver.findElement(By.cssSelector(".demo-frame")));
Once you're done in the iframe, you'll need to switch back out like so:
driver.switchTo().defaultContent();
I believe you'll encounter another issue on this line:
new Actions(driver).click().build().perform();
click() in an Actions context clicks where the mouse currently is. As you haven't told the mouse where to point, it's clicking somewhere, but not on the element you wish. You can fix this a couple of different ways.
I would recommend this:
w.click();
If you want to stay with the Actions chain, you can fix it like this:
new Actions(driver).click(w).build().perform();
Thank you very much. It perfect. Forgot about the iframe thing.
| common-pile/stackexchange_filtered |
Classify, up to similarity, the $3$ by $3$ matrices with coefficients in $\mathbb{Q}$ that satisfy $A^6=I$.
I am working on the following question in review for my algebra final:
Classify, up to similarity, the $3$ by $3$ matrices with coefficients in $\mathbb{Q}$ that satisfy $A^6=I$.
My work:
As $A^6 - I = 0$, we know that the minimal polynomial of $A$, $m_A(x)$ divides $x^6 - 1$. We factor
$$x^6 - 1 = (x^3 - 1)(x^3 + 1) = (x - 1)(x^2 + x + 1)(x + 1)(x^2 - x + 1).$$
Thus, the possible minimal polynomial must have degree of the matrix (which is $3$), so $m_A(x)=$
$1$. $(x-1)(x^2 + x + 1)$
$2$. $(x-1)(x^2 - x + 1)$
$3$. $(x+1)(x^2 - x + 1)$
$4$. $(x+1)(x^2 + x + 1)$
These have rational canonical forms
$$\begin{pmatrix}
1 & 0 & 0 \\
0 & 0 & -1 \\
0 & 1 & -1
\end{pmatrix} \quad \begin{pmatrix}
1 & 0 & 0 \\
0 & 0 & -1 \\
0 & 1 & 1
\end{pmatrix} \quad \begin{pmatrix}
-1 & 0 & 0 \\
0 & 0 & -1 \\
0 & 1 & 1
\end{pmatrix} \quad \begin{pmatrix}
-1 & 0 & 0 \\
0 & 0 & -1 \\
0 & 1 & -1
\end{pmatrix}$$
Is this correct? Edit: I forgot $I$.
I am also trying to find the number of classes if the matrices are over $\mathbb{C}$. My idea is that is is $6$ choose $3$ because over $\mathbb{C}$ there are 6 total roots, but the correct answer is apparently $56$??
Why don’t you include $I$?
Hmm... what minimal polynomial gives $I$?
That would be $X-I$
Plus $\begin{pmatrix}1&0&0\0&0&1\0&1&0\end{pmatrix}$. Its minimal polynomial is $X^2-1$. Degree of candidate of minimal polynomial wolud be less than 4, not equal to 3.
The characteristic polynomial always has degree equal to the dimension of the space, and the minimal polynomial always divides the characteristic polynomial
The minimal polynomial has degree at most the degree of characteristic polynomial, so even $x-1$ or $x^2-1$ or $x^2-x+1$ are candidates.
If $m_A(x) = x -1$, what is the list of invariant factors? It doesn't seem possible to me
$m_A(x) = x -1\iff A=I.$
Eigenvalues can be repeated
As $\deg m(x) \leq 3$, the following are your candidates for the minimal polynomial:
Degree 1: $x-1$, $x + 1$.
Degree 2: $x^2 + x + 1$, $x^2 - x + 1$, $x^2 - 1$.
Degree 3: $(x-1)(x^2 + x + 1)$, $(x-1)(x^2 - x + 1)$, $(x + 1)(x^2 - x + 1)$, $(x+1)(x^2 + x + 1)$.
$x^2 + x + 1$ is impossible because there is no polynomial in $\mathbb{Q}[x]$ of degree $1$ dividing it. (Recall that in your Smith Normal Form, your invariant factors $f_1 \mid f_2 \mid \dots \mid f_{k} $ satisfy $f_1 f_2 \dots f_k = c(x)$ and $f_k = m(x)$.) Similar for $x^2 - x + 1$.
This gives rise to the following eight invariant factors:
Degree $1$: $\{ x - 1, x -1 , x-1\} , \{ x+1, x+1, x+1\}$,
Degree $2$: $\{x - 1, x^2 - 1\}, \{ x +1, x^2 - 1\}$,
Degree $3$: $\{1 , (x-1)(x^2 + x + 1)\}$, and I'll let you list the other three yourself.
Since the number of conjugacy classes is in bijection with the number of invariant factors, there are eight such conjugacy classes.
For the case over $\mathbb{C}$, since $c(x)$ has distinct roots, your minimal polynomial always splits, and hence $A$ is diagonalizable. Then split by cases based on the number of distinct entries on the diagonal. You should get:
One distinct entry: 6 ways.
Two distinct entries: 30 ways.
Three distinct entries: 20 ways.
This looks nice. How come for three distinct entries there aren’t $6\times5\times4=\color{blue}120$ ways?
Ordering of the roots along the diagonal doesn't matter, so 20 comes from 6 choose 3.
As mentioned in the comment, the minimal polynomial of a $3\times 3$ matrix may have degree less than $3$. And even if the minimal polynomials are the same, the matrices might still not be similar. For example, $\operatorname{diag}(1, 1, -1), \operatorname{diag}(1, -1, -1)$ both have $(x+1)(x-1)$ as their minimal polynomials.
Two rational matrices are similar over $\mathbb Q$ iff they are similar over $\mathbb C$ (cf. Similar matrices and field extensions).
Since $x^6-1$ has no repeated roots, $A$ can be diagonalized (over $\mathbb C$), hence its class up to similarity (over $\mathbb C$ hence $\mathbb Q$) only depends on its eigenvalues. And since $3$ is odd, $A$ has at least one real eigenvalue which can only be $\pm 1$. Also if $\zeta$ is an eigenvalue of $A$, so is $\bar\zeta$. Therefore either all eigenvalues of $A$ are in $\{\pm 1\}$, or $A$ has one eigenvalue in $\{\pm 1\}$ and a pair of imaginary eigenvalues.
If $A$ has only possibly $\pm 1$ as eigenvalues, it's a matter of distributing the multiplicity $3$ and there are ${3+1\choose 1}=4$ possibilies according the stars and bars. (The representatives are $I_3, -I_3, \operatorname{diag}(1, 1, -1), \operatorname{diag}(1, -1, -1)$)
If $A$ has a pair of imaginary eigenvalues, there are two pairs that can be chosen. Also the real eigenvalue has two choices as well, hence in total there are $2\times 2=4$ choices.
So in total there are $8$ possibilities.
If the matrix is allowed to be over $\mathbb C$, the problem is simply to distribute the multiplicity $3$ to $6$ possible eigenvalues, and by the stars and bars again, the answer is ${3+5 \choose 3}=56$.
Another perspective on this question, this is asking for the number of isomorphism classes of representations of the cyclic group of order $6$ of dimension $3$. By general theory, all such representations are semi simple, and (by computation, or general cyclic group theory) we have two one dimensional irreps, and two irreps of dimension $2$. By semi simplicity, we can compute the isomorphism class in the Grothendieck ring, with this basis of simples. So it's the number of solutions to $(a,b,c,d)$ for nonnegative integers $a,b,c,d$ with $a+b+2c+2d=3$, which gives the same answer of $8$.
| common-pile/stackexchange_filtered |
In C#, how to delete "Explorer file associate" overriding the "Registry Classes" File Association?
How to programatically delete all "file association" created by Explorer so that the file associations under HKCR work correctly?
For Example, I want to delete the registry key corresponding a user clicking "open with..." in explorer. Example:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt
or other file extension such as .py or .pl.
I wrote some c# code to do this... however it throws an exception. Here's What I'm trying to do:
ExplorerOverrideDelete(".txt");
// Throws Exception:
// System.UnauthorizedAccessException: Cannot write to the registry key.
Here's the Functions:
public static void ExplorerOverrideDelete (string ext)
{
if (!ext.StartsWith(".")) {
ext = "." + ext;
}
var hivereg = GetHive("HKCU");
var key = hivereg.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\"
+ ext);
if (key == null)
return;
var keyroot = hivereg.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts");
if (keyroot == null)
return;
keyroot.DeleteSubKeyTree(ext);
key.Dispose();
keyroot.Dispose();
hivereg.Dispose();
}
private static RegistryKey GetHive(string hive) {
switch(hive.ToUpper()) {
case "HKCU": return Registry.CurrentUser;
case "HKLM": return Registry.LocalMachine;
case "HKCR": return Microsoft.Win32.Registry.ClassesRoot;
}
return null;
}
Some more Information:
PS C:\Users\john\Documents> get-acl HKCU:Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts | fl
Path : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileE
xts
Owner : DESKTOP-D3USQOT\john
Group : DESKTOP-D3USQOT\None
Access : DESKTOP-D3USQOT\john Allow FullControl
NT AUTHORITY\SYSTEM Allow FullControl
BUILTIN\Administrators Allow FullControl
NT AUTHORITY\RESTRICTED Allow ReadKey
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES Allow R
PS C:\Users\john\Documents> get-acl HKCU:Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt | fl
Path : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileE
xts\.txt
Owner : DESKTOP-D3USQOT\john
Group : DESKTOP-D3USQOT\None
Access : DESKTOP-D3USQOT\john Allow FullControl
NT AUTHORITY\SYSTEM Allow FullControl
BUILTIN\Administrators Allow FullControl
NT AUTHORITY\RESTRICTED Allow ReadKey
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES
"UnauthorizedAccessException" is pretty clear. Try running your program as administrator.
My understanding is that you don't need administrator to modify HKCU. HKLM is the hive that requires Admin privilege. Also, I tried it already.
Below is the code that works for me. I still don't entirely understand why I need to run this as Admin since the ACL for current user has full-control. If anybody has any idea about that, give me a shout below. Thanks.
public static void ExplorerOverrideDelete (string ext)
{
if (!IsAdministrator()) {
MessageBox.Show(
"ExplorerOverrideDelete(): Rerun program as Admin",
"Access Denied"
}
if (!ext.StartsWith(".")) {
ext = "." + ext;
}
var keyroot = Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts",
RegistryKeyPermissionCheck.ReadWriteSubTree);
if (keyroot == null)
return;
keyroot.GetAccessControl(System.Security.AccessControl.AccessControlSections.All);
// /keyroot.GetAccessControl(
// System.Security.AccessControl.AccessControlSections.All
// & ~System.Security.AccessControl.AccessControlSections.Audit);
try {
keyroot.DeleteSubKeyTree(ext);
}
catch(Exception e) {
keyroot.Close();
hivereg.Close();
MessageBox.Show(e.Message);
}
keyroot.Close();
hivereg.Close();
}
public static bool IsAdministrator()
{
System.Security.Principal.WindowsIdentity identity
= System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal
= new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(
System.Security.Principal.WindowsBuiltInRole.Administrator
);
}
| common-pile/stackexchange_filtered |
Factorization systems on tensor product of presentable categories
This question is motivated by the following particular problem.
I have two presentable categories $\cal A,B$ with orthogonal factorization systems $({\cal E}, {\cal M})$ (on A) and $({\cal U},{\cal V})$ (on B). I want to produce a factorization system on the tensor product ${\cal A}\otimes{\cal B}$ out of these data.
This is the standard way, I think:
Consider the product of factorization systems on ${\cal A}\times{\cal B}$; this is precisely what you think.
Consider the image of the left class ${\cal E}\times{\cal U}$ under $\otimes$, call it $\Sigma = {\cal E}\otimes{\cal U}$
The (=a strongly orthogonal variant of the) small object argument used in ${\cal A}\otimes{\cal B}$ gives that the pair
$$
({\cal L},{\cal R}) = (\text{Sat }\Sigma, \Sigma^\perp)
$$
(on the left, saturation: closure under retracts, transfinite compositions and pushout; on the right, the right orthogonal to $\Sigma$) is a orthogonal factorization system on ${\cal A}\otimes{\cal B}$.
Now, I'm interested in having some nice properties of $({\cal E}, {\cal M})$ and $({\cal U}, {\cal V})$ preserved by this construction; like for example if both $({\cal E}, {\cal M})$ and $({\cal U}, {\cal V})$ are proper, generated by small classes of small objects, reflective/coreflective (i.e. all the classes have the 2-out-of-3 property), semi-exact, simple, normal... then also $(\cal L,R)$ has these properties.
| common-pile/stackexchange_filtered |
Converting byte[] property to Bitmap in android using ksoap2
I have this code to get an array of byte. The client is built in ksoap2.
All properties I am getting fine but when I try to get the property which has an image it returns null when BitmapFactory.decodeByteArray is executed. And really I get information when I am debugging.
The code I am using is:
String result = ((SoapObject)poSoap).getProperty("MyImage").toString();
byte[] bytes = result.getBytes();
Bitmap png = BitmapFactory.decodeByteArray(bytes, 0, <<<png file size>>>);
MyImage property is a png file.
As server I am using WCF in C# and i get the file using:
var bytes = File.ReadAllBytes(@file);
@file is the path to the file, it is working fine.
I think problem is not in server side it is in client side.
Do I have another way to get that property (type byte[]) and convert it to Bitmap?
I got the solution, as I said it was client side, only I needed to decode in base64, my new code is:
String result = ((SoapObject)poSoap).getProperty("MyImage").toString();
byte[] bloc = Base64.decode(result, Base64.DEFAULT);
Bitmap png = BitmapFactory.decodeByteArray(bloc,0,bloc.length);
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.