text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to perform a double click using phpunit_selenium2 extension? The question is specifically to the phpunit_selenium2.
A: So the true opensource way: there is no such a feature? Clone a repo, implement a feature, create pull request, ?????, PROFIT!!!!1
https://github.com/sebastianbergmann/phpunit-selenium/pull/212
Now phpunit_selenium2 supports double click. You can use it like:
$this->moveto($element);
$this->doubleclick();
Correspondent example from the tests
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14189639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implement universal, lightweight, and unobtrusive tagging of arbitrary objects? NB: The material in the subsection titled Background is not essential. The full description of the question is fully contained in the preceding paragraphs.
I'd like to implement a universal, lightweight, and "unobtrusive" way to "tag" arbitrary objects.
More specifically, I want to define the equivalent of the (abstract) functions tag, isTagged, and getTagged, such that:
*
*isTagged(t) is true if and only if t was the value returned by tag(o), for some object o;
*getTagged(tag(o)) is identical to o, for every object o;
*if t = tag(o), then tag(t) should be identical to t;
*with the exception of the behaviors described in (1), (2), and (3) above, and strict identity tests involving ===, tag(o) and o should behave the same way.
[EDIT: One further requirement is that the implementation should not modify the Object class, nor any other standard class, in any way.]
For example:
>>> isTagged(o = "foo")
false
>>> isTagged(t = tag(o))
true
>>> getTagged(t) === o
true
>>> tag(t) === t
true
>>> t.length
3
>>> t.toUpperCase()
"FOO"
Below I give my best shot at solving this problem. It is (almost) universal, but, as it will soon be clear, it is anything but lightweight!!! (Also, it falls rather short of fully satisfying requirement 4 above, so it is not as "unobtrusive" as I'd like. Moreover, I have serious doubts as to its "semantic correctness".)
This solution consists of wrapping the object o to be tagged with a "proxy object" p, and copying all the properties of o (whether "owned" or "inherited") to p.
My question is:
is it possible to achieve the specifications given above without having to copy all the properties of the tagged object?
Background
Here's the implementation alluded to above. It relies on the utility function getProperties, whose definition (FWIW) is given at the very end.
function Proxy (o) { this.__obj = o }
function isTagged(t) {
return t instanceof Proxy;
}
function getTagged(t) {
return t.__obj;
}
var tag = (function () {
function _proxy_property(o, pr) {
return (typeof pr === "function")
? function () { return pr.apply(o, arguments) }
: pr;
}
return function (o) {
if (isTagged(o)) return o;
if (typeof o.__obj !== "undefined") {
throw TypeError('object cannot be proxied ' +
'(already has an "__obj" property)');
}
var proxy = new Proxy(o);
var props = getProperties(o); // definition of getProperties given below
for (var i = 0; i < props.length; ++i) {
proxy[props[i]] = _proxy_property(o, o[props[i]]);
}
return proxy;
}
})();
This approach, ham-fisted though it is, at least seems to work:
// requirement 1
>>> isTagged(o = "foo")
false
>>> isTagged(p = tag(o))
true
// requirement 2
>>> getTagged(p) === o
true
// requirement 3
>>> tag(p) === p
true
// requirement 4
>>> p.length
3
>>> p.toUpperCase()
"FOO"
...well, almost; requirement (4) is not always satisfied:
>>> o == "foo"
true
>>> p == "foo"
false
>>> o == o
true
>>> p == o
false
FWIW, here's the definition of the function getProperties, which is used by the tag function. Criticisms welcome. (WARNING: I'm a completely clueless JS noob who doesn't know what he's doing! Use this function at your own risk!)
function getProperties(o) {
var seen = {};
function _properties(obj) {
var ret = [];
if (obj === null) {
return ret;
}
try {
var ps = Object.getOwnPropertyNames(obj);
}
catch (e if e instanceof TypeError &&
e.message === "obj is not an object") {
return _properties(obj.constructor);
}
for (var i = 0; i < ps.length; ++i) {
if (typeof seen[ps[i]] === "undefined") {
ret.push(ps[i]);
seen[ps[i]] = true;
}
}
return ret.concat(_properties(Object.getPrototypeOf(obj)));
}
return _properties(o);
}
A: You're over complicating it :
var tag = function(o) {
Object.defineProperty(o, '__tagged', {
enumerable: false,
configurable: false,
writable: false,
value: "static"
});
return o;
}
var isTagged = function(o) {
return Object.getOwnPropertyNames(o).indexOf('__tagged') > -1;
}
A: I think you're overcomplicating all of this. There's no reason you need to store the tag on the object itself. If you create a separate object that uses the object's pointer as a key, not only will you conserve space, but you'll prevent any unintentional collisions should the arbitrary object happen to have a property named "_tagged".
var __tagged = {};
function tag(obj){
__tagged[obj] = true;
return obj;
}
function isTagged(obj){
return __tagged.hasOwnProperty(obj);
}
function getTagged(obj){
if(isTagged(obj)) return obj;
}
== EDIT ==
So I decided to take a minute to create a more robust tagging system. This is what I've created.
var tag = {
_tagged: {},
add: function(obj, tag){
var tags = this._tagged[obj] || (this._tagged[obj] = []);
if(tag) tags.push(tag);
return obj;
},
remove: function(obj, tag){
if(this.isTagged(obj)){
if(tag === undefined) delete this._tagged[obj];
else{
var idx = this._tagged[obj].indexOf(tag);
if(idx != -1) this._tagged[obj].splice(idx, 1);
}
}
},
isTagged: function(obj){
return this._tagged.hasOwnProperty(obj);
},
get: function(tag){
var objects = this._tagged
, list = []
;//var
for(var o in objects){
if(objects.hasOwnProperty(o)){
if(objects[o].indexOf(tag) != -1) list.push(o);
}
}
return list;
}
}
Not only can you tag an object, but you can actually specify different types of tags and retrieve objects with specific tags in the form of a list. Let me give you an example.
var a = 'foo'
, b = 'bar'
, c = 'baz'
;//var
tag.add(a);
tag.add(b, 'tag1');
tag.add(c, 'tag1');
tag.add(c, 'tag2');
tag.isTagged(a); // true
tag.isTagged(b); // true
tag.isTagged(c); // true
tag.remove(a);
tag.isTagged(a); // false
tag.get('tag1'); // [b, c]
tag.get('tag2'); // [c]
tag.get('blah'); // []
tag.remove(c, 'tag1');
tag.get('tag1'); // [b]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18554287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: activate opcache load comments in php 7 I want to migrate a symfony website from php 5.6 to php 7.1.4
I got this error :
AnnotationException in AnnotationException.php line 193:
You have to enable opcache.load_comments=1 or zend_optimizerplus.load_comments=1.
I my php.ini I already had opcache.save_comments set to '1' so I've added opcache.load_comments=1 in the php.ini but when I see my phpinfo() the opcache.load_comments parameter didn't appear ... and if I try :
ini_set('opcache.load_comments', 1);
echo "VALUE : " . ini_get('opcache.load_comments');
It doesn't work neither ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43759855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: variable byte in assembly set to 48 I am new to assembly and I am trying to write a program that computes C + A. C is a 32-bit variable, while A is an 8-bit variable.
This is the code I have: (variables are global so they can be changed in main.c)
# prologue
pushl %ebp # save previous stack frame pointer
movl %esp, %ebp # the stack frame pointer for sum function
#body of the function
movl $0, %edx
movl $0, %eax
movsbl A, %eax
addl C, %eax #eax = eax + C
#epilogue
movl %ebp, %esp # restore the previous stack pointer ("clear" the stack)
popl %ebp # restore the previous stack frame pointer
ret
For some reason, when A = 0, and C = 1, I get the value 49. If A is 1 and C is 1, I get the value 50. I have done a debug, and I can see that when it reaches the command "movsbl A, %eax" the register eax always gets the value 48 + whatever value I give A. Don't know why this is happening. In main.c the variable A is set to 0, but even if I change to, let's say 5, it still gives me 48 in eax. I've tried numerous solutions.
#include <stdio.h>
#include "asm.h"
char A=0;
int C=0;
int main(void) {
printf("Valor A:");
scanf("%s",&A);
printf("Valor C:");
scanf("%d",&C);
long long num = sum_and_subtract();
printf("sum_and_subtract = %lld:0x%x\n", num, num);
return 0;
}
Any suggestions would by highly appreciated!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64806197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GSON getting arrays I'm fairly new to GSON and I was wondering how to store an array from a json page, for example if I have:
{capitals:[{"alabama":"montgomery"},{"alaska":"juneau"},{"arizona":"phoenix"}]}
I'm unsure of how to do this, previously I've had pages a name and information inside of them (like so),
"name":{"var1":"aaa", "var2":"bbb"}
and I've been able to create a class for that, just a bit confused of how to process arrays.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24222676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Insert Data into table with select query in Databricks using spark sql I have tried to insert data into a table with select query using sparksql in Databricks. But I'm getting the error as the mismatched column, but i have checked the column exists. Can someone help me on this issue?
%sql
insert into db.tab1(Ab) select distinct B from db.tab2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54648212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Access all Struts project files in cPanel Technologies: Java, Struts, MySQL, goDaddy VPS.
all servers have one common DB.
Downloaded database from there. But somehow in cPanel file system, I can not see any project files. I found WEB-INF/ with empty class folder and empty lib folder inside.
So, How do I get all Struts project files and setup in local computer?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44852483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: From a local branch pull master it's hang In Git I am working in a local branch.
I need to take a pull from origin's master branch. So from local branch run a pull command.
git pull origin master
Password for 'xxx':
From xxxx
* branch master -> FETCH_HEAD
Auto-merging "file name"
Auto-merging "file name"
After auto-merging it's hung. nothing happens. After that I click CTRL+C, it stopped.
A: Keep it simple from your local branch:
git fetch origin && git merge origin/master
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57832565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: D3 JS - Why d3 is not appending a string? I have this json file:
[
{
"id": "1",
"name": "Hello world",
"shape": "rect",
"fill": "pink"
}
]
And I also have this javascript file:
const svg = d3.select('svg')
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
d3.json("tree.json").then(data => {
const elements = svg.selectAll('*')
.data(data);
elements.enter()
.append("rect")
.attr("x", 20)
.attr("y", 20)
.attr("width", 100)
.attr("height", 100)
.attr("fill", d => d.fill)
elements.enter()
.append('text')
.attr("x", 50)
.attr("y", 60)
.html("text", d => {d.name})
})
and this html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<svg width="600" height="600">
</svg>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="index.js"></script>
</body>
</html>
Now the output is:
1st output
but when I switch "rect" with d => d.shape it doesn't behave as before.
d3.json("tree.json").then(data => {
const elements = svg.selectAll('*')
.data(data);
elements.enter()
.append(d => d.)
.attr("x", 20)
.attr("y", 20)
.attr("width", 100)
.attr("height", 100)
.attr("fill", d => d.fill)
But how is it different than the previous one? I also tried outputting d.shape, and it prints string. Then how can I make something that will create a shape according to the shape data?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71220920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Wordpress 6 click excerpt to show full post I'm trying to learn the new Wordpress 6 from scratch.
In the custom theme index.php I can get the post title and the excerpt.
while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ?></h2>
<?php the_excerpt(); ?>
<?php endwhile;
In the functions.php I followed online tutorial and created a new_excerpt_more() function, which will get the permalink of the post
function new_excerpt_more() {
return '<a href="'. get_permalink() . '"> Read More...</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
My issue is when I click the Read More... hyperlink, it doesn't show the full post content as I wanted. What is the simplest way to make the_excerpt() clikable and to show the full post content?
Rererence url:
http://ulike.vip/a/w
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72429736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load test against Android native application? I have created one android app. I would like to make load testing to android app. But I don't have any idea about how to perform load testing.
My requirement is 3 devices testing my app simultaneously.
Thanks in advance!
A: If your application communicates with backend server you can simulate network traffic coming from hundreds of applications using i.e. Apache JMeter by following next simple steps:
*
*Record your application traffic (one or several scenarios) using JMeter's built-in proxy server
*
*disable cellular data on device and enable WiFi
*make sure that host running JMeter and mobile device are on same network/subnet
*start JMeter's proxy server
*configure your mobile device to use JMeter as a proxy
*click all buttons, touch actions, etc.
*Add virtual users
*Run the test
If your application connects with the backend over HTTPS you may use 3rd-party tool like ProxyDroid to set up SSL proxy. You will also need to install JMeter's self-signed certificate ApacheJMeterTemporaryRootCA.crt which is being generated in JMeter's /bin folder when you start proxy server. The easiest way to install it on the device is to send it by email.
See Load Testing Mobile Apps. But Made Easy guide for more detailed instructions.
If you application doesn't use backend - it doesn't make sense to load test it at all.
A: I can achieve this using JUnit Parallel test with selendroid
download ParallelTest folder from github https://github.com/gworksmobi/Grace
Reference : https://testingbot.com/support/getting-started/parallel-junit.html (this link is for selenium I am just modified to selendroid)
Steps:
*
*Download folder from github
*Add supporting selendroid jar to eclipse (http://selendroid.io/setup.html)
*Create project.
*Create the exact ditto class into your project as per github download folder
*Now make the changes as per your application in JUnitParallel.java
Description of class :
JUnitParallel.java -> have business logic of testing
Parallelized.java -> provide multi thread support
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33829120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: select2 Tagging with JSON I just started using [select2][1] and I'm working on a project that needs a list of tags (like on StackOverflow) that is populated from a JSON data source. I'm using an example found on this question: [Tagging With Ajax In Select2][2] but I'm having some trouble getting it to work.
// Testing JSON load
$("#testJsonLoad").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: 'data.json',
dataType: "json",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
Just for testing purposes the data.json page has this data in it:
{
"data": [
{ "id" : 1, "text" : "Alabama" },
{ "id" : 2, "text" : "Alaska" },
{ "id" : 3, "text" : "Arizona" },
{ "id" : 4, "text" : "Arkansas" },
{ "id" : 5, "text" : "California" },
{ "id" : 6, "text" : "Colorado" },
{ "id" : 7, "text" : "Connecticut" },
{ "id" : 8, "text" : "Delaware" },
{ "id" : 9, "text" : "District of Columbia" },
{ "id" : 10, "text" : "Florida" },
{ "id" : 11, "text" : "Georgia" },
{ "id" : 12, "text" : "Hawaii" },
{ "id" : 13, "text" : "Idaho" } ]
}
My problem is that I'm getting this error:
this.text is undefined - Line 78
return this.text.localeCompare(term) === 0;
I am thinking it may have something to do with the way my JSON is formatted. I've tried a few different formats out and most of my research online hasn't yielded positive results.
A: Results is expecting id and text nodes in the json, you can either tell your JSON to ouput the results using these node names or specify which to use in the JS:
Example from site:
query: function (query) {
var data = {results: []}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {s = s + query.term;}
data.results.push({id: query.term + i, text: s});
}
query.callback(data);
}
A: Put debugger before if ($(data).filter(function () and check what you have got in $(data)
A: I found the issue. I needed to call the data.data (in my example) in the results ajax function.
Example:
results: function (data, page) {
return {
results: data.data
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15852071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot align Text within Column Jetpack I am practicing JetPack compose, but my text won't align in the center for some reason within the 2 surfaces. Any tips why?
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SimpleLayoutsTheme {
// A surface container using the 'background' color from the theme
MainScreen("Hello World!")
}
}
}
}
@Composable
fun MainScreen(message: String) {
Surface {
Column {
Surface(modifier = Modifier
.width(500.dp)
.height(250.dp)) {
Text(text = message, Modifier.align(Alignment.CenterHorizontally))
}
Surface(modifier = Modifier
.width(500.dp)
.height(250.dp)) {
Text(text = message, Modifier.align(Alignment.CenterHorizontally))
}
}
}
}
I tried adding .FillMaxWidth() as a modifier to text, but it didn't help.
A: You can not align directly on a surface. You have to wrap your content with Column, Row, Box, etc.
You can change your code like the following
@Composable
fun MainScreen(message: String) {
Surface {
Column {
Surface(
modifier = Modifier
.width(500.dp)
.height(250.dp),
color = Color.Green
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = message)
}
}
Surface(
modifier = Modifier
.width(500.dp)
.height(250.dp),
color = Color.Blue
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = message
)
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69592746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Free Linux Cluster Build for Small Scale Reseach I need to build a small cluster for my research. It's pretty humble and I'd like to build a cluster just with my other 3 laptops at home.
I'm writing in C++. My codes in MPI framework are ready. I can simulate them using visual studio 2010 and they're fine. Now I want to see the real thing.
I want to do it free (I'm a student). I have ubuntu installed and I wonder:
*
*if I could build a cluster using ubuntu. I couldn't find a clear answer to that on the net.
*if not, is there a free linux distro that I can use at building cluster?
*I also wonder if I have to install ubuntu, or the linux distro on the host machine to all other laptops. Will any other linux distribution (like openSUSE) work with the one at the host machine? Or do all of them have to be same linux distro?
Thank you all.
A: In principle, any linux distro will work with the cluster, and also in principle, they can all be different distros. In practice, it'll be a enormously easier with everything the same, and if you get a distribution which already has a lot of your tools set up for you, it'll go much more quickly.
To get started, something like the Bootable Cluster CD should be fairly easy -- I've not used it myself yet, but know some who have. It'll let you boot up a small cluster without overwriting anything on the host computer, which lets you get started very easily. Other distributions of software for clusters include Rocks and Oscar. A technical discussion on building a cluster can be found here.
A: I also liked PelicanHPC when I used it a few years back. I was more successful getting it to work that with Rocks, but it is much less popular.
http://pareto.uab.es/mcreel/PelicanHPC/
Just to get a cluster up and running is actually not very difficult for the situation you're describing. Getting everything installed and configured just how you want it though can be quite challenging. Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5818866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get the number of contributors of Github repositories using Github API and PyGithub package I am using following code to get the number of contributors of a repository
from github import Github
g = Github("*****github Access token****")
repo = g.get_repo('mui-org/material-ui')
contributors_count = repo.get_contributors().totalCount
It is giving number of contributors as 443, however, the correct number of contributors on the github website is 1077.
Can some one tell why am I getting different values?
Also, is there any other function in PyGithub to get correct number of contributors?
A: I'm bumping up against this too. I'm pretty sure the difference in the the counts is including or excluding "anonymous contributors". The GitHub endpoint accepts an anon param that can be set to True.
Looking at its source, PyGithub doesn't accept any arguments for its get_contributors method, so it doesn't currently surface anon contributors. It could be forked or patched to take it.
For my needs, I'm going to write my own method that makes a request for a repo, parses the "last" relation from the Link header and calculates based on the number of results on the last page. Still writing it, so I don't have a code sample for now.
Sorry I don't have anything more actionable for the moment.
A: This has been added since to PyGitHub. Now you just simply have to do:
repo.get_contributors(anon="true")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54134023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SSL Certificate Errors With BrowserMob-Proxy on Firefox 50 I am having trouble getting https requests to pass through BrowserMob-Proxy with Firefox 50. However with Firefox ESR45.4 there is no such issue.
As a simple test I started BrowserMob-Proxy and created an instance on port 8088.
I then launched Firefox (This was done manually to verify it wasn't some with the automation scripts) and in settings set both the HTTP Proxy and SSL Proxy to localhost and port 8088.
Then goto https://www.google.com
Firefox ESR45.4 opens google without issue.
Firefox 50.x opens a "Your connection is not secure" page, and because of HSTS you cannot add an exception.
Am I overlooking something obvious, or has Mozilla finally broken Firefox to the point where you can't test with it anymore?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41814611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 100% width pseudo elements don't match the width of parent when in a justified text line As you can see in the example, when setting the width of an absolute positioned pseudo element works find normally, but if it's within an element with text-align: justify set, the pseudo element seems to be the width that the parent element would be if justify were not set.
This is evident by it not happening on links outside the paragraph, or on the last line where the text is not justified.
Anyone know how to avoid this?
It appears to only happen in Firefox, not Chrome. Any ideas for a workaround?
I found this bug report on Bugzilla.
.test {
position: relative;
background: #ccc
}
.test::before {
content: '';
position: absolute;
background: red;
height: 2px;
width: 100%;
}
p {
width: 300px; margin: auto;
text-align: justify;
}
<a href="#" class="test">how it should look</a>
<p>
Lorem ipsum dolor sit amet, <a href="#" class="test">i am text</a> consectetur adipiscing elit. Maecenas tristique tristique sem at molestie. Maecenas eget lacus est. <a href="#" class="test">i am text</a> Aenean leo eros, eleifend id blandit sit amet, feugiat sit amet velit. Quisque <a href="#" class="test">i am text</a> mattis at diam et vulputate. Pellentesque vitae nisi lacinia, tempus lorem in, dapibus sem. Phasellus auctor urna risus, eu tempus enim scelerisque at. Proin at nunc quis tellus <a href="#" class="test">i am text</a> ultricies faucibus quis eu risus. Donec hendrerit venenatis orci vitae aliquet. Praesent pretium sodales nisl, id commodo nisl accumsan ac. <a href="#" class="test">i am text</a> </p>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50881023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why doesn't this work? ORA-00979: not a GROUP BY expression Why doesn't this work
SELECT FIRST_NAME,
MIDDLE_NAME,
LAST_NAME,
EMP_MOBILE_NO,
NEW_EMPNO ,
SECTION_NAME,
EMP_TYPE,
JOINING_DATE
FROM EMP_OFFICIAL,EMP_PERSONAL
where EMP_PERSONAL.STATUS='Active'
and EMP_OFFICIAL.WORK_ENT='Worker'
AND EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO
GROUP BY EMP_OFFICIAL.SECTION_NAMEORDER BY EMP_PERSONAL.NEW_EMPNO DESC
When I am Query this show group By the expression
I will tried but no solution found
A: lFirst does not have any aggregate function (MAX, MIN, SUM, COUNT...) so there is no need to have a GROUP BY clause. Do not confuse between DISTINCT row operator and GROUP BY clause.
Second, "BY EMP_PERSONAL.NEW_EMPNO DESC" Does not mean anything ! Is it a compement to GROUP BY or a part of ORDER BY ?
To solve the first part, rewrite your query as :
SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE
FROM EMP_OFFICIAL,EMP_PERSONAL
WHERE EMP_PERSONAL.STATUS='Active'
AND EMP_OFFICIAL.WORK_ENT='Worker'
AND EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO
Also a JOIN must be write with the JOIN operator not as a cartesian product followed by a restriction. So rewrite your query as :
SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE
FROM EMP_OFFICIAL
JOIN EMP_PERSONAL
ON EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO
WHERE EMP_PERSONAL.STATUS='Active'
AND EMP_OFFICIAL.WORK_ENT='Worker'
This will be most optimized by the optimizer because it not spread time and operations to do the translation between false JOIN and real joins...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68998121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C parse comments from textfile So I am trying to implement a very trivial parser for reading a file and executing some commands. I guess very similar to bash scripts, but much simpler. I am having trouble figuring out how to tokenise the contents of a file given you are able to have comments denoted by #. To give you an example of how a source file might look
# Script to move my files across
# Author: Person Name
# First delete files
"rm -rf ~/code/bin/debug";
"rm -rf ~/.bin/tmp"; #deleting temp to prevent data corruption
# Dump file contents
"cat ~/code/rel.php > log.txt";
So far here is my code. Note that I am essentially using this little project as a means of become more comfortable and familiar with C. So pardon any obvious flaws in the code. Would appreciate the feedback.
// New line.
#define NL '\n'
// Quotes.
#define QT '"'
// Ignore comment.
#define IGN '#'
int main() {
if (argc != 2) {
show_help();
return 0;
}
FILE *fptr = fopen(argv[1], "r");
char *buff;
size_t n = 0;
int readlock = 0;
int qread = 0;
char c;
if (fptr == NULL){
printf("Error: invalid file provided %s for reading", argv[1]);
exit(1);
}
fseek(fptr, 0, SEEK_END);
long f_size = ftell(fptr);
fseek(fptr, 0, SEEK_SET);
buff = calloc(1, f_size);
// Read file contents.
// Stripping naked whitespace and comments.
// qread is when in quotation mode. Everything is stored even '#' until EOL or EOF.
while ((c = fgetc(fptr)) != EOF) {
switch(c) {
case IGN :
if (qread == 0) {
readlock = 1;
}
else {
buff[n++] = c;
}
break;
case NL :
readlock = 0;
qread = 0;
break;
case QT :
if ((readlock == 0 && qread == 0) || (readlock == 0 && qread == 1)) {
// Activate quote mode.
qread = 1;
buff[n++] = c;
}
else {
qread = 0;
}
break;
default :
if ((qread == 1 && readlock == 0) || (readlock == 0 && !isspace(c))) {
buff[n++] = c;
}
break;
}
}
fclose(fptr);
printf("Buffer contains %s \n", buff);
free(buff);
return 0;
}
So the above solution works but my question is...is there a better way to achieve the desired outcome ? At the moment i don't actually "tokenize" anything. Does the current implementation lack logic to be able create tokens based on the characters ?
A: It is way easier to read your file by whole lines:
char line[1024];
while(!feof(fptr))
{
if(!fgets (line , 1024 , fptr))
continue;
if(line[0] == '#') // comment
continue; // skip it
//... handle command in line here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49091785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: server functionality when user is not on the web app node express Excuse me if this questions seems under par, everything I've learned was on my own and in communities like this.
So I have a web application and what I would like is for the user to give me information and then based on that information I search through my database (MySQL) for a matching user and connect the two of them. After the user gives me information they will clearly no longer be on the site but I still wanted to mediate the matching.
What I have right now is to come up with a list of possible matches based on the user's input and then use automated email to contact the match, let them know they have been requested, and have them click a link in the email saying they approve.
Will I have to direct the email to my site in some way so that I can know if they have confirmed or denied the request? Is it possible to do that in an automated email? Is there a better way to approach this?
I am using node, mysql, and express. Any and all help is appreciated
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40388888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Move divs on a html page via CSS\JQuery i want to recreate a simple one page web site.
This is a good example of what i want to have in the end:
http://onepagelove.com/demo/?theme=EastJava
I basically have too main divs one is the sidebar and the main container.
By default i want that only the main container is visible. By clicking on the button i want that the sideBar moves in the screen like in the example above.
<html>
<head>
<title>One Page</title>
<meta name="author" content="Me">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="clearfix">
<div class ="sideBar">
</div>
<div class ="mainCon">
<div class ="moreB">
<div class="buttonText">
Learn More
</div>
</div>
</div>
</div>
</body>
</html>
the important css so far:
.sideBar{
width: 20%;
height: 100%;
background-color: #FF0040;
float: left;
}
.mainCon{
height: 100%;
width: 80%;
float: left;
background-color: #F3F781;
}
.moreB{
color: #ffffff;
width: 100px;
height: 50px;
margin-top: 50%;
margin-right: 50%;
margin-left: 50%;
border-radius: 60px 60px 60px 60px;
-moz-border-radius: 60px 60px 60px 60px;
-webkit-border-radius: 60px 60px 60px 60px;
border: 2px solid #ffffff;
}
I guess i need Jquery or something like this to solve the problem but sadly i have no idea how. Any suggestions? I think it shouldnt be that hard. But i have no idea how i can place a div outside of the screen and then move it in the screen after pressing a button.
MC
A: You're gonna need to change up your CSS a little so the clearfix can be moved in the first place.
.clearfix{
position: absolute;
left: -20%;
top: 0px;
height: 100%;
width: 100%;
}
As for jQuery, it's pretty simple to use.
function toggleSidebar(){
$('.in').animate({left: '0%'}, function(){
$(this).addClass('out').removeClass('in');
});
$('.out').animate({left: '-20%'}, function(){
$(this).addClass('in').removeClass('out');
});
}
$('.moreB').on('click', toggleSidebar);
One more thing to do is to add a semantic class to clearfix named in
<div class="clearfix in">
A: You can do this primarily with CSS, and use jQuery to toggle a class on the wrapping element to expand/collapse the sidebar.
http://jsfiddle.net/G7K6J/
HTML
<div class="wrapper clearfix">
<div class ="sideBar">
</div>
<div class="mainCon">
<div class="moreB">
<div class="buttonText">
Learn More
</div>
</div>
</div>
</div>
CSS
.clearfix {
clear:both;
overflow:hidden;
}
.sideBar{
width: 0%;
height: 200px;
background-color: #FF0040;
float: left;
-webkit-transition: width 300ms;
-moz-transition: width 300ms;
-o-transition: width 300ms;
transition: width 300ms;
}
.mainCon{
height: 200px;
width: 100%;
float: left;
background-color: #F3F781;
-webkit-transition: width 300ms;
-moz-transition: width 300ms;
-o-transition: width 300ms;
transition: width 300ms;
}
.wrapper.expanded .sideBar {
width:20%;
}
.wrapper.expanded .mainCon {
width:80%;
}
.moreB{
color: #ffffff;
width: 100px;
height: 50px;
margin:0 auto;
border-radius: 60px 60px 60px 60px;
-moz-border-radius: 60px 60px 60px 60px;
-webkit-border-radius: 60px 60px 60px 60px;
border: 2px solid #ffffff;
}
jQuery
$(".moreB").click(function(){
$(".wrapper").toggleClass("expanded");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23893734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pass Django variables between view functions I'm asking a question about variables handling in my Django application view.
I have 2 functions :
*
*The first one lets me to display query result in an array with GET filter parameter (in my case, user writes year and Django returns all objects according to this year. We will call query_naissance this variable).
*The second one lets me to create a PDF. I have lots of variables but I want to take one more time query_naissance in my PDF.
This is my first function :
@login_required
def Table_annuelle_BirthCertificate(request) :
query_naissance = request.GET.get('q1')
...
return render(request, 'annuel.html', context)
And my second function looks like :
@login_required
def Table_Naissance_PDF(request) :
data = {"BirthCertificate" : BirthCertificate}
template = get_template('Table_raw.html')
html = template.render(Context(data))
filename = str('Table annuelle Naissance.pdf')
path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename
file = open(path, "w+b")
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8')
file.close()
context = {
"BirthCertificate":BirthCertificate,
"query_naissance":query_naissance,
}
return render(request, 'Table.html', context) # Template page générée après PDF
So How I can add query_naissance given by user in my first function to my second one without write one more time a field ?
Then, I have to call this variable like {{ query_naissance }} in my HTML template.
Thank you
A: In order to persist information across requests, you would use sessions. Django has very good session support:
# view1: store value
request.session['query_naissance'] = query_naissance
# view2: retrieve vlaue
query_naissance = request.session['query_naissance']
# or more robust
query_naissance = request.session.get('query_naissance', None)
You need 'django.contrib.sessions.middleware.SessionMiddleware' in your MIDDLEWARE_CLASSES.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42111303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: is.na(x)` is a matrix, it must have the same dimensions as the input-error in R I tried
x[is.na(x)] <- 0
to replace NA with 0. But the above error occurs. x is a data.frame.I can´t recreate the error in an example,sorry. What can I do about that in general?
Error in `[<-.data.frame`(`*tmp*`, is.na(x), value = 0) : unsupported matrix index in replacement
3.
stop("unsupported matrix index in replacement")
2.
`[<-.data.frame`(`*tmp*`, is.na(x), value = 0)
1.
`[<-`(`*tmp*`, is.na(x), value = 0)
EDIT
x is also a list
str(x)
data.frame': 21448 obs. of 4 variables:
$ item : chr "v" "v" "a" "a" ...
$ E : num 126.4 126.4 51.7 51.7 51.7 ...
$ E: num 419 417.6 49 49.3 49 ...
$ c : num [1:21448, 1:3] 331.4 330.3 94.8 95.4 94.8 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : NULL
.. ..$ : chr [1:3] "item" "E" "E"
- attr(*, "problems")= tibble [5,624 x 5] (S3: tbl_df/tbl/data.frame)
..$ row : int [1:5624] 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 ...
..$ col : chr [1:5624] "Sex" "Sex" "Sex" "Sex" ...
..$ expected: chr [1:5624] "1/0/T/F/TRUE/FALSE" "1/0/T/F/TRUE/FALSE" "1/0/T/F/TRUE/FALSE" "1/0/T/F/TRUE/FALSE" ...
..$ actual : chr [1:5624] "m" "m" "m" "m" ...
..$ file : chr [1:5624] "'../data/tables/k.tsv'" "'../data/tables/k.tsv'" "'../data/tables/k_13_08.tsv'" "'../data/tables/k.13_08.tsv'" ...
- attr(*, "spec")=List of 3
..$ cols :List of 26
.. ..$ diet_item_id : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ file_name : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ sample : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ time_point.label : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ time_point : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ day : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ date :List of 1
.. .. ..$ format: chr ""
.. .. ..- attr(*, "class")= chr [1:2] "collector_date" "collector"
.. ..$ St_complet : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ Time : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ Sex : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_logical" "collector"
.. ..$ P : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ item : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ item_id : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ cat : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ subcat : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ descr : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ E : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ database : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
.. ..$ E : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ K : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ F : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ B : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ G : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ E: list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ A : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
.. ..$ E : list()
.. .. ..- attr(*, "class")= chr [1:2] "collector_double" "collector"
..$ default: list()
.. ..- attr(*, "class")= chr [1:2] "collector_guess" "collector"
..$ skip : num 1
..- attr(*, "class")= chr "col_spec"
A: If x is a data.frame object, it should work:
df <- data.frame(a = c(1,2,3), b = c(4,NA,6), c = c(NA, 8, NA))
df[is.na(df)] <- 0
> df
a b c
1 1 4 0
2 2 0 8
3 3 6 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63469253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: efficient power exponent method in java(JDK 1.7) I want to create an optimum method for power(base,exponent) in java required for my project,where the types of both base and exponent is int,and exponent <= 10^9.However this has to be done in java?I know that bitshift can be used ,but it itself involves the usage of bitset in java.Kindly suggest an implementation
A: Just use the java.lang.BigInteger class. It has a pow() method that does exactly what you want in a rather efficient way.
A: Since the exponent is in int, you already have the binary representation of the number (well the computer does). So you should have three integers, the base, the exponent and a temporary integer that you will use for computation and one more for solution. You start with this:
unsigned int base;//you manage input for this and exponent like you wish, probably passed in as parameters
unsigned int exponent;
unsigned int temp = base;
unsigned int answer = 1;
while (exponent!=0){
if (exponent%2 == 1){
answer *= temp;
}
exponent>>1;
temp<<1;
}
Please try this algorithm and let me know how it works. The while look runs at max the bit length of the exponent (i.e. 32 times). This code doesn't handle large numbers or negative numbers, but I'm not sure if you require this or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12919461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I need a good tool to style my code - i.e. spacing , brackets, etc I have about 4000 lines of code that I need to re-style.
I'm not doing this by hand.
Are there any tools available that will help change style?
A: Try jEdit - they have auto-indentation, and works on most OSes.
http://www.jedit.org/
A: "Any" IDE will do it for you. So which one are you using ?
Vim : gg , = , G
Netbeans : "Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted."
Notepad++ : Check out this link posted here
A: Eclipse has a configurable source code formatter that can be triggered automatically on Save and manually with Ctrl+Shift+F (customizable shortcut) for most if not all editor plugins (i.e., most if not all languages). Of those that I use, only PHP Development Tools has configuration limits there.
You really should name the programming/markup language(s) that you are using.
A: AStyle (C/C++/Java/C#) command line tool. I use it within any IDE by invoking external command with shortcut.
http://astyle.sourceforge.net/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8109467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pinging first available host in network subnets I've written a small script in Python that pings all subnets of my school's wireless network and prints out the IP addresses and hostnames of computers that are connected to each subnet of the network. My current setup is that I'm relying on creating threads to handle each of the ping requests.
from threading import Thread
import subprocess
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
ip = q.get()
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0])
except:
print "%s: alive"%ip
q.task_done()
num_threads = 100
queue = Queue()
addresses=[]
#Append all possible IP addresses from all subnets on wireless network
for i in range(1,255):
for j in range(1,254):
addresses.append('128.119.%s.%s'%(str(i),str(j)))
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in addresses:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
However, I want to modify my script so that it only seeks out the first available host in the subnet. What that means is that suppose I have the following subnet (128.119.177.0/24) and the first available host is 128.119.177.20. I want my script to stop pinging the remaining hosts in the 128.119.177.0/24 after I successfully contact 128.119.177.20. I want to repeat that for every subnet on my network (128.119.0.1 - 128.119.255.254). Given my current setup, what would be the best course of action to make this change? I was thinking of doing something like a list of Queues (where each Queue holds 255 IP addresses for one of the subnets) and having one thread process each queue (unless there is a limitation on how many threads I can spawn in Python on Windows).
EDIT: I have played around with nmap (and Angry IP scanner) for this task, but I was interested in pursuing writing my own script.
A: Simplest thing would be to have a thread work through a whole subnet and exit when it finds a host.
UNTESTED
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
subnet = q.get()
# each IP addresse in subnet
for ip in (subnet=str(x) for x in range(1,254)):
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0]
except:
print "%s: alive"%ip
break
q.task_done()
num_threads = 100
queue = Queue()
#Put all possible subnets on wireless network into a queue
for i in range(1,255):
queue.put('128.119.%s.'%i)
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Wait until worker threads are done to exit
queue.join()
A: Since you know how many threads you got in the beginning of the run, you could periodically check the current number of threads running to see if nowThreadCount < startThreadCount. If it's true terminate the current thread.
PS: Easiest way would be to just clear the queue object too, but I can't find that in the docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1883136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: React app renders blank page when introducing Material UI component I am using create-react-app and Material UI to develop a web app. I am trying to use MUI's Basic App Bar as a header/nav element but when I create it as a component in my app and try to use it in my App.js file it breaks the page, rendering either a blank page or the background color and nothing else. I have other MUI components rendering appropriately but when I try to add this custom component from the MUI example code it breaks the page. I can add standard HTML code into the same component file and it will render appropriately, so it's clearly an issue with how I'm using the MUI component.
Relevant directory structure:
-- src/
-- Components/
-- App/
-- App.css
-- App.js
-- App.test.js
-- ButtonAppBar.js
-- index.css
-- index.js
-- theme.js
App.js
import React from 'react';
import logo from './../../logo.svg';
import './App.css';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
import { Button, Paper } from '@material-ui/core';
import ButtonAppBar from '../ButtonAppBar'
function App() {
return (
<Container maxWidth="xl" className="App">
<Paper>
<ButtonAppBar />
<img src={logo} className="App-logo" alt="logo" />
<Typography variant="h4" component="h1" gutterBottom>
Energy Infrastructure API
</Typography>
<Typography variant='subtitle2' component='subtitle2' gutterBottom>
Documentation for the Energy Infrastructure API, from the Center for Research-based Decision Making on Climate and Energy Policy
</Typography>
<br></br>
<Button variant="contained" color="secondary">
Twitter
</Button>
<Button variant="contained" color="secondary">
Github
</Button>
<Button variant="contained" color="primary">
Get Started
</Button>
</Paper>
</Container>
);
}
export default App;
ButtonAppBar.js
import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
export default function ButtonAppBar() {
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</Box>
);
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/core/styles';
import App from './Components/App/App';
import theme from './theme';
// import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<App />
</ThemeProvider>,
document.getElementById('root'),
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71975291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: apache camel cxf https not working I am trying to publish a webservice using apache camel cxf. I am able to access the published webservice using http. However I am trying to configure the same using https. But I am not able to get it to work.
below are parts of spring context and wsdl files
<camel-cxf:cxfEndpoint id="myEndoint"
address="http://localhost:9000/PostXml/" serviceClass="com.XXXXXXXXXX.techquest.ServicesPortType"
xmlns:ssp="http://techquest.interswitchng.com/" endpointName="ssp:PostXml"
serviceName="ssp:PostXml" />
<http:conduit name="*.http-conduit">
<http:tlsClientParameters
secureSocketProtocol="SSL">
<sec:keyManagers keyPassword="password">
<sec:keyStore type="JKS" password="password"
file="A:/apache-sermfino_conf/cherry.jks" />
</sec:keyManagers>
<sec:trustManagers>
<sec:keyStore type="JKS" password="password"
file="A:/apache-ser/truststore.jks" />
</sec:trustManagers>
<sec:cipherSuitesFilter>
<!-- these filters ensure that a ciphersuite with export-suitable or
null encryption is used, but exclude anonymous Diffie-Hellman key change
as this is vulnerable to man-in-the-middle attacks -->
<sec:include>.*_EXPORT_.*</sec:include>
<sec:include>.*_EXPORT1024_.*</sec:include>
<sec:include>.*_WITH_DES_.*</sec:include>
<sec:include>.*_WITH_AES_.*</sec:include>
<sec:include>.*_WITH_NULL_.*</sec:include>
<sec:exclude>.*_DH_anon_.*</sec:exclude>
</sec:cipherSuitesFilter>
</http:tlsClientParameters>
<http:client AutoRedirect="true" Connection="Keep-Alive" />
</http:conduit>
===============================================================================
<wsdl:portType name="ServicesPortType">
<wsdl:operation name="PostXml">
<wsdl:input message="tns:PostXml" />
<wsdl:output message="tns:PostXml" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="ServicesSoap12Binding" type="tns:ServicesPortType">
<soap12:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="PostXml">
<soap12:operation soapAction="PostXml" style="document" />
<wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ServicesPortTypeService">
<wsdl:port binding="tns:ServicesSoap12Binding" name="ServicesSoap12Endpoint">
<soap12:address location="http://localhost:9000/PostXml" />
</wsdl:port>
</wsdl:service>
A: The first one configuration is for the http client not for the server side.
You can find the configuration example here[1]
[1]http://cxf.apache.org/docs/jetty-configuration.html
A: I was able to configure apache-camel-2.19.4 with camel-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:context="http://www.springframework.org/schema/context"
xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:cxfcore="http://cxf.apache.org/core"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
">
<cxf:cxfEndpoint id="my-endpoint-http"
address="http://localhost:8080/test"
endpointName="tns:endpointName1" serviceName="tns:endpointServiceName1"
wsdlURL="myService.wsdl" xmlns:tns="myServiceWsdlNamespace">
<cxf:properties>
<entry key="allowStreaming" value="true" />
<entry key="autoRewriteSoapAddressForAllServices" value="true" />
</cxf:properties>
</cxf:cxfEndpoint>
<cxf:cxfEndpoint id="my-endpoint-https"
address="https://localhost:8443/test"
endpointName="tns:endpointName1" serviceName="tns:endpointServiceName1"
wsdlURL="myService.wsdl" xmlns:tns="myServiceWsdlNamespace">
<cxf:properties>
<entry key="allowStreaming" value="true" />
<entry key="autoRewriteSoapAddressForAllServices" value="true" />
</cxf:properties>
</cxf:cxfEndpoint>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route id="my-endpoint-http-route" streamCache="true">
<from uri="cxf:bean:my-endpoint-http?dataFormat=MESSAGE" />
<to uri="direct:myServiceDirect" />
</route>
<route id="my-endpoint-https-route" streamCache="true">
<from uri="cxf:bean:my-endpoint-https?dataFormat=MESSAGE" />
<to uri="direct:myServiceDirect" />
</route>
<route id="all" streamCache="true">
<from uri="direct:myServiceDirect" />
<log message="headers1=${headers}" />
</route>
</camelContext>
<cxfcore:bus/>
<httpj:engine-factory bus="cxf">
<httpj:engine port="8443">
<httpj:tlsServerParameters secureSocketProtocol="TLSv1">
<sec:keyManagers keyPassword="skpass">
<sec:keyStore password="changeit" file="src/test/resources/certificate-stores/localhost-keystore.jks" />
</sec:keyManagers>
<!--
<sec:trustManagers>
- <sec:keyStore resource="certs/serviceKeystore.jks" password="sspass" type="JKS"/> -
<sec:keyStore password="changeit" file="src/main/resources/certificate-stores/cacerts" />
</sec:trustManagers>
-->
<sec:cipherSuitesFilter>
<sec:include>.*_WITH_3DES_.*</sec:include>
<sec:include>.*_WITH_DES_.*</sec:include>
<sec:exclude>.*_WITH_NULL_.*</sec:exclude>
<sec:exclude>.*_DH_anon_.*</sec:exclude>
</sec:cipherSuitesFilter>
<!-- <sec:clientAuthentication want="true" required="false"/> -->
</httpj:tlsServerParameters>
</httpj:engine>
</httpj:engine-factory>
</beans>
With this you should be able to access:
*
*http://localhost:8080/test?wsdl
*https://localhost:8443/test?wsdl
The file src/test/resources/certificate-stores/localhost-keystore.jks should contain a generated key pair (use KeyStoreExplorer) and the pair saved with keyPassword(skpass) key password and password(changeit) for the keystore file password.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11340092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: MYSQL Count all rows and pagination of data using range/limit I dont know if this is a duplicate
but here's my question..
I was trying to implement a pagination of data taken from database
My dilemma is:
*
*Should i go about pagination, querying data in groups, ie. 5 (doing a Select with limits/ range), then displaying them in a table with pagination. It will have page numbers so it would require counting all the table entries thus that would be 2 database queries for the initial display.or
*query all the row entries and then count the result set and apply pagination. This would remove the query count on the database but would also mean that i would download the whole data everytime a single view on any page is made (but i could also apply caching)
and other suggestions are highly accepted and thank you in advance
A: SQL_CALC_FOUND_ROWS .
This will allow you to use LIMIT and have the amount of rows as no limit was used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6173139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating an add-on for an existing plugin I'd like to create a Geofire plugin which extends the current firebase_database plugin.
I added the firebase_database plugin to the example project in my plugin project and it all works fine. But now I'm trying to actually use the native firebase database library in my plugin project but I can't seem to import it.
So do I have to natively import the firebase database project in my plugin project? Because if so, wouldn't that interfere with the firebase_database plugin?
So as an example of what I'd like to import:
I'd like to import https://github.com/flutter/plugins/blob/master/packages/firebase_database/android/src/main/java/io/flutter/plugins/firebase/database/FirebaseDatabasePlugin.java. This is imported in the source code of the firebase_database plugin as you can see here: https://github.com/flutter/plugins/blob/master/packages/firebase_database/android/src/main/java/io/flutter/plugins/firebase/database/FirebaseDatabasePlugin.java
This plugin is added to the example project of my plugin project and works fine in the Dart code. Shouldn't I now be able to access that import in my plugin project (so not the example project)?
A: You should not need to import FirebaseDatabasePlugin in your plugin. There are no public APIs of the Java FirebaseDatabasePlugin class for you to call. Instead, you can import the Firebase native classes directly, and add a dependency on the Firebase libraries in the build.gradle of your plugin. Just use the same build.gradle values that the firebase_database plugin does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46216449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which version of Com.javaeatmoi.core compatible with spring 5.3 Which version of com.javaeatmoi.core:javaeatmoi-spring4-vfs2-support compatible with spring version 5.3.14
Current i have eatmoi as 1.4.1 but in the Vfs2PathMatchingResourcePatternResolver doFindPathMatching jar it has 2 parameter.
But spring PathMatchingResourcePatternResolver::doFindPathMatching has 3. This was working fine in spring version 4.2.5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72655421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UTF-8 encoding not used although it is set in source() I don't understand what is going on here (working with RStudio on Windows platform):
Save script test_abc.R
a <- "ä"
b <- "ü"
c <- "ö"
Then, run the following script Test.R:
compare_text <- function() {
l <- list()
if (a != a2) {
l[[1]] <- c(a, a2)
}
if (b != b2) {
l[[1]] <- c(b, b2)
}
if (c != c2) {
l[[1]] <- c(c, c2)
}
}
a <- "ä"
b <- "ü"
c <- "ö"
a2 <- "ä"
b2 <- "ü"
c2 <- "ö"
out_text <- compare_text()
# The next active "source-line" overwrites a, b and c!
source("path2/test2_abc.R") # called "V1" OR
# source("path2/test2_abc.R", encoding = "UTF-8") # called "V2"
out_text2 <- compare_text()
print(out_text)
print(out_text2)
If you run the script test.R in version V1 you get
source('~/Desktop/test1.R', encoding = 'UTF-8')
# NULL
# [1] "ö" "ö"
although it states that it is run using UTF-8 encoding.
If you run the script test.R in version "V2" you get
source('~/Desktop/test1.R', encoding = 'UTF-8')
# NULL
# NULL
I don't know whether that related post is helpful.
A: In V1 you source a file without specifying the encoding of that file (test_abc.R). The "encoding"-section of source help says:
By default the input is read and parsed in the current encoding of the R session. This is usually what it required, but occasionally re-encoding is needed, e.g. if a file from a UTF-8-using system is to be read on Windows (or vice versa).
The "Umlaute" can't be read correctly and function compare_text returns c(c, c2) because c != c2 is TRUE.
In V2 the "Umlaute" are read correctly and compare_text function returns null (no difference is found).
It's R itself that reads the file within the source function. R uses the default encoding of the OS. On Windows, this is (mostly?) "Windows code page 1252", which differs from UTF-8. You can test it on your machine with Sys.getlocale(). That's why you have to tell R that the file you want to source is encoded UTF-8
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41743949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c++ , pthread and static callbacks. "this" returns a pointer to the base class inctead of the derived one I am using as basis this cpp thread class. This I use as a base class for threads. Note that in my case Thread::main() is a virtual function (unlike in the link). So I basically use:
class Thread {
public:
virtual void main()
{
cout << "This should not be run once derived and redefined." << endl;
}
void run()
{
pthread_create(&thread, 0, &callback, this);
}
pthread_t thread;
}; // class Thread
void* callback(void* obj)
{
static_cast<Thread*>(obj)->main();
return(0);
} // callback
Then I create a derived class and re-define the myThreadedClass::main() member to actually do something meaningful.
Finally, I instantiate the myThreadedClass object from other classes or my main function call as follows:
main(int argc, char** argv){
myThreadedClass thr;
thr.run();
//do other stuff
}
This works fine; The callback function gets a pointer to the derived class instantiation, so the myThreadedClass::main() gets executed.
However, I now try to create a different derived class class otherThreadClass : public Thread. Again I re-define my otherThreadClass::main() , but now I have a member function in the derived class which (unlike before) calls Thread::run().
class otherThreadClass : public Thread{
public:
writeToDiskAsync(string& str){
prepareString(str);
//spawn a thread to carry the write without blocking execution
run();
}
};
in this case from my main function I do
main(int argc, char** argv){
otherThreadClass thr;
thr.writeToDiskAsync(aString);
//do other stuff
}
The problem in this case is that the callback function gets a pointer to the Thread class and the Thread::main() ends up being executed instead of the otherThreadClass::main().
I tried passing a pointer to the instantiated myThreadedClass object during instantiation (using initialisation lists and an altered call to Thread::run(void* instance)) as follows
//in main function
otherThreadClass thr(&thr);
//in class
otherThreadClass::otherThreadClass(otherThreadClass* ptr):instancePtr(ptr)
{}
otherThreadClass::writeToDiskAsync(string& str)
{
//do stuff
run(instancePtr);
}
//and finally
Thread::run(void* parentObj)
{
pthread_create(&thread, 0, &callback, parentObj);
}
but it does not work. And I think this is probably not a nice way to do it anyway. So what can I do to let the callback function get apointer to the derived class instance instead of the base class ?
thank you
A: If you will try to call a function using base class ptr , everytime base class version gets called as long as function is not virtual .
so simpler solution to your problem would be to make main virtual as below :
#include <iostream>
#include<pthread.h>
#include<unistd.h?
using namespace std;
void* callback(void* obj);
class Thread {
public:
virtual int main()
{
cout << "Hi there Base class" << endl;
return(0);
}
void run()
{
pthread_create(&thread, 0, &callback, this);
}
pthread_t thread;
};
class otherThreadClass : public Thread{
public:
virtual int main()
{
cout << "Hi there other class" << endl;
return(0);
}
void writeToDiskAsync(string str){
//spawn a thread to carry the write without blocking execution
run();
}
};
class Thread;
void* callback(void* obj)
{
static_cast<Thread*>(obj)->main();
return(0);
} // callback
int main() {
// your code goes here
otherThreadClass thr;
thr.writeToDiskAsync(string("aS"));
sleep(10);//it is neccessary as main thread can exit before .
return 0;
}
output : Hi there other class
Whereas if main is not virtual , it will always call base class version of main as you are calling through a base class ptr (static binding will happen )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34438946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delay all ajax requests
Uncaught TypeError: Illegal invocation
I'm having this error when trying delay all ajax requests in my application.
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
setTimeout( function () {
send.call(this, data); //Error here
},3000);
};
})(XMLHttpRequest.prototype.send);
Could you give me some hints? Thanks in advance.
A: It seems you are calling .call passing in the current scope which would be window.
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
var self = this;
setTimeout( function () {
send.call(self, data); //Updated `this` context
},3000);
};
})(XMLHttpRequest.prototype.send);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43874455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to edit the configuration file of boost in slave using buildbot ShellCommand? So I am trying to build and test boost in the remote slave( mac ). I want to edit tools/build/v2/user-config.jam file so that I could use the toolset=clang.
How can I add
//in user-config.jam
// toolset will use clang
using clang
: ...etc
in the user-config.jam file?
A: It turns out that unix has a nice little command called
echo
so what I can do is use this command to edit that file.
ShellCommand(
name = "append config instruction"
command=['echo','I am adding this configuration cause it was missing','>','~/user-config.jam']
)
This command will add that line in the configuration file.
if you want to make it look like
"I am adding this configuration cause it was missing" I meant to add "" then
echo "\"xyz\"" > text.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17414997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Promtail Targets Failed
*
*What Grafana version and what operating system are you using?
Promtail:latest & Loki:2.2.0, Kubernetes (GitVersion:"v1.18.8") and Helm (Version:"v3.6.2")
*
*What are you trying to achieve?
To can scrape my active targets and push them to Loki.
*
*What happened?
All targets are marked as "not ready". If I am going to the /targets page, all my active_targets are marked as "false".
In Loki I have no logs.
As well the /var/logs/ folder is empty in Promtail. The logs I am receiving from the promtail pod are like this:
level=info ts=2021-08-06T05:30:09.076046169Z caller=filetargetmanager.go:254 msg="Adding target" key="{app=\"<app_name>\", container=\"<container_name>", job=\"<job_name>", namespace=\"<namesapce_name>", node_name=\"<nodeName_name>", pod=\"<pod_name>"}"
level=info ts=2021-08-06T05:30:09.076046169Z caller=filetargetmanager.go:254 msg="Removing target" key="{app=\"<app_name>\", container=\"<container_name>", job=\"<job_name>", namespace=\"<namesapce_name>", node_name=\"<nodeName_name>", pod=\"<pod_name>"}"
level=info ts=2021-08-06T05:30:14.095615824Z caller=filetarget.go:150 msg="filetarget: watcher closed, tailer stopped, positions saved" path=/var/log/pods/*<some_path>/<container_name>/*.log
Promtail/metrics:
HELP promtail_targets_failed_total Number of failed targets.
TYPE promtail_targets_failed_total counter
promtail_targets_failed_total{reason="empty_labels"} 2280
promtail_targets_failed_total{reason="exists"} 470
HELP request_duration_seconds Time (in seconds) spent serving HTTP requests.
*
*What did you expect to happen?
That my targets getting scraped and pushed to Loki.
*
*Can you copy/paste the configuration(s) that you are having problems with?
file: |
server:
log_level: {{ .Values.config.logLevel }}
http_listen_port: {{ .Values.config.serverPort }}
health_check_target: false
client:
url: {{ tpl .Values.config.lokiAddress . }}
{{- tpl .Values.config.snippets.extraClientConfigs . | nindent 2 }}
positions:
filename: /run/promtail/positions.yaml
scrape_configs:
{{- tpl .Values.config.snippets.scrapeConfigs . | nindent 2 }}
{{- tpl .Values.config.snippets.extraScrapeConfigs . | nindent 2 }}
scrapeConfigs: |
# See also https://github.com/grafana/loki/blob/master/production/ksonnet/promtail/scrape_config.libsonnet for reference
# Pods with a label 'app.kubernetes.io/name'
- job_name: kubernetes-pods-app-kubernetes-io-name
pipeline_stages:
{{- toYaml .Values.config.snippets.pipelineStages | nindent 4 }}
kubernetes_sd_configs:
- role: pod
relabel_configs:
- action: replace
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_name
target_label: app
- action: drop
regex: ''
source_labels:
- app
- action: replace
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_component
target_label: component
{{- if .Values.config.snippets.addScrapeJobLabel }}
- action: replace
replacement: kubernetes-pods-app-kubernetes-io-name
target_label: scrape_job
{{- end }}
{{- toYaml .Values.config.snippets.common | nindent 4 }}
# Pods with a label 'app'
- job_name: kubernetes-pods-app
pipeline_stages:
{{- toYaml .Values.config.snippets.pipelineStages | nindent 4 }}
kubernetes_sd_configs:
- role: pod
relabel_configs:
# Drop pods with label 'app.kubernetes.io/name'. They are already considered above
- action: drop
regex: .+
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_name
- action: replace
source_labels:
- __meta_kubernetes_pod_label_app
target_label: app
- action: drop
regex: ''
source_labels:
- app
- action: replace
source_labels:
- __meta_kubernetes_pod_label_component
target_label: component
{{- if .Values.config.snippets.addScrapeJobLabel }}
- action: replace
replacement: kubernetes-pods-app
target_label: scrape_job
{{- end }}
{{- toYaml .Values.config.snippets.common | nindent 4 }}
# Pods with direct controllers, such as StatefulSet
- job_name: kubernetes-pods-direct-controllers
pipeline_stages:
{{- toYaml .Values.config.snippets.pipelineStages | nindent 4 }}
kubernetes_sd_configs:
- role: pod
relabel_configs:
# Drop pods with label 'app.kubernetes.io/name' or 'app'. They are already considered above
- action: drop
regex: .+
separator: ''
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_name
- __meta_kubernetes_pod_label_app
- action: drop
regex: '[0-9a-z-.]+-[0-9a-f]{8,10}'
source_labels:
- __meta_kubernetes_pod_controller_name
- action: replace
source_labels:
- __meta_kubernetes_pod_controller_name
target_label: app
{{- if .Values.config.snippets.addScrapeJobLabel }}
- action: replace
replacement: kubernetes-pods-direct-controllers
target_label: scrape_job
{{- end }}
{{- toYaml .Values.config.snippets.common | nindent 4 }}
# Pods with indirect controllers, such as Deployment
- job_name: kubernetes-pods-indirect-controller
pipeline_stages:
{{- toYaml .Values.config.snippets.pipelineStages | nindent 4 }}
kubernetes_sd_configs:
- role: pod
relabel_configs:
# Drop pods with label 'app.kubernetes.io/name' or 'app'. They are already considered above
- action: drop
regex: .+
separator: ''
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_name
- __meta_kubernetes_pod_label_app
- action: keep
regex: '[0-9a-z-.]+-[0-9a-f]{8,10}'
source_labels:
- __meta_kubernetes_pod_controller_name
- action: replace
regex: '([0-9a-z-.]+)-[0-9a-f]{8,10}'
source_labels:
- __meta_kubernetes_pod_controller_name
target_label: app
{{- if .Values.config.snippets.addScrapeJobLabel }}
- action: replace
replacement: kubernetes-pods-indirect-controller
target_label: scrape_job
{{- end }}
{{- toYaml .Values.config.snippets.common | nindent 4 }}
# All remaining pods not yet covered
- job_name: kubernetes-other
pipeline_stages:
{{- toYaml .Values.config.snippets.pipelineStages | nindent 4 }}
kubernetes_sd_configs:
- role: pod
relabel_configs:
# Drop what has already been covered
- action: drop
regex: .+
separator: ''
source_labels:
- __meta_kubernetes_pod_label_app_kubernetes_io_name
- __meta_kubernetes_pod_label_app
- action: drop
regex: .+
source_labels:
- __meta_kubernetes_pod_controller_name
- action: replace
source_labels:
- __meta_kubernetes_pod_name
target_label: app
- action: replace
source_labels:
- __meta_kubernetes_pod_label_component
target_label: component
{{- if .Values.config.snippets.addScrapeJobLabel }}
- action: replace
replacement: kubernetes-other
target_label: scrape_job
{{- end }}
{{- toYaml .Values.config.snippets.common | nindent 4 }}
*
*Did you receive any errors in the Grafana UI or in related logs? If so, please tell us exactly what they were.
*Did you follow any online instructions? If so, what is the URL?
I followed mostly the instructions of the offical repo.
https://github.com/grafana/helm-charts/tree/main/charts
I have created the following recourses:
For Loki:
I have a Secret (with the configs), Service and Statefulset.
Promtail:
I have a DaemonSet, Secret, powerful ClusterRole and CluserRoleBinding.
A: Well I'm not sure this will help you, but I had the same promtail logs of adding target and immediately removing them.
My config was a bit different, I was running promtail locally and scraping some files. The problem was that promtail didn't have access rights to read those files.
So I'd suggest double checking that your promtail pod has read access to the files you're trying to scrape and then restarting the service.
I also didn't see any errors in grafana or Loki, as the logs were never pushed to Loki.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68707813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to completely change a string passed into a function in Python? I want to pass a variable to a function for changing, like this:
def change(x):
x="changed!"
y="hello"
change(y)
print(y) # hello
This is because you can only mutate variables when passing, but how can I completely change the variable?
A: You could potentially add a global variable in the function like this:
def change():
global y
y="changed!"
y="hello"
change()
print(y)
However, I wouldn't really recommend this as it could lead to minor bugs later on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65707388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How to handle Possile Unhandled Promise Rejection (id:0) I'm trying to connect my app to the google pay however when I try it I'm getting some sort of error!
I'm already tried to put in array but it didn't work.
global.PaymentRequest = require('react-native-payments').PaymentRequest;
export default class App extends Component<Props> {
render() {
const METHOD_DATA = [{
supportedMethods: ['android-pay'],
data: {
supportedNetworks: ['visa', 'mastercard', 'amex'],
currencyCode: 'USD',
environment: 'TEST', // defaults to production
paymentMethodTokenizationParameters: {
tokenizationType: 'NETWORK_TOKEN',
parameters: {
publicKey: 'my public key'
}
}
}
}];
const DETAILS = {
id: 'basic-example',
displayItems: [
{
label: 'Movie Ticket',
amount: { currency: 'USD', value: '15.00' }
}
],
total: {
label: 'Merchant Name',
amount: { currency: 'USD', value: '15.00' }
}
};
const paymentRequest = new PaymentRequest(METHOD_DATA, DETAILS);
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>paymentRequest.show()}>
<Text style={styles.welcome}>pay button!</Text>
</TouchableOpacity>
</View>
);
}
}
Please inform me if I'm doing something wrong.
the error is Possile Unhandled Promise Rejection (id:0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56275555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why async producer is not waiting for either linger.ms or batch.size to be full when i set them a custom value with autoFlush is set to false? I am using spring-kafka 2.2.8 and writing a simple async producer with the below settings:
linger.ms : 300000,
batch.size: 33554431,
max.block.ms: 60000.
Now i'm creating a KafkaTemplate with autoFlush as false by calling the below constructor
public KafkaTemplate(ProducerFactory<K, V> producerFactory, boolean autoFlush)
Now i've a simple test producing 10 message in the span of 10 sec using the above async producer and then stopped my producer using 'Cntrl+C'. Then surprisingly, i got all the 10 messages published onto the topic and i'm sure the size of these 10 messages combined is way less than my batch.size: 33554431
Now i've two questions
*
*How the messages are being published instead of waiting for either linger.ms or batch.size before producing the message?
*In this scenario, what is the significance of autoFlush= false?
A: If this is a Spring Boot application, Ctrl-C will close the application context and the DefaultKafkaProducerFactory will close the producer in its destroy() method (called by the application context during close()).
You will only lose records if you kill -9 the application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62807232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reading a .dat file and saving to a matrix in C I have some matrices in Matlab that I need to load as arrays in C. I used the dlmwrite function in MATLAB to do this. Can someone link to a tutorial on how to load in C? Or maybe there’s already a function someone has written that can do this?
Also, just curious how long this process takes to load. The matrices aren’t terribly large, with the largest being 3136 by 2. I’ve switched to C for this particular application since it’s proving to be much faster than MATLAB, but I don’t want to slow the C code down too much by loading too much stuff.
I’m being a bit lazy by not translating part of my code to C (it’s a mesh generator that I didn’t write, so I don’t know the finer details), but this would make my life a lot easier.
A: There is a C API for reading MATLAB .MAT files.
http://www.mathworks.se/help/matlab/read-and-write-matlab-mat-files-in-c-c-and-fortran.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20115840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to display certain columns from a table using HTML listbox and SQL code? Good day, I have the following request: A table with 2 columns: Country and Capital. The table contains every country with every capital from the world. There is a listbox where I can select the country and it will display only the capital from that country.
I created with HTML a listbox which let me to choose a Country:
< select> <br>
< option Country = "Brasil"> Brasil < /option> <br>
< option Country = "... "> .. < /option> <br>
< /select> </br>
How can i display a capital using a country from that HTML listbox? I was thinking to create an option for every capital, but then i'd need over 120 if-cases. (In SQL)
A: You can generate the select form:
<?php
$req = $pdo->query('SELECT * FROM table');
$rep = $req->fetchAll(); ?>
<select>
foreach($rep as $row) { ?>
<option value="<?= $row['country'] ?>"><?= $row['country'] ?></option>
<? } ?>
</select>
<?php foreach($rep as $row) {
<input style="display:none" id="<?= $row['country'] ?>" value="<?= $row['capital'] ?>" />
<?php } ?>
So you will have the select with all country, and an input for each Capital with their Country as id, so you can display it with javascript: (jQuery example)
<script>
$('select').change(function() {
$('input:visible').toggle();
$('input[id='+$(this).val()+']').toggle();
});
</script>
A: You can fetch the countries and ther capitals from the database using the following code in php
//This is where you put the fetched data
$entries = Array();
//Make new connection
$connection = new mysqli("127.0.0.1", "username", "password", "databasename");
//Create prepared statement
$statement = $connection->prepare("SELECT `country`, `capital` FROM `table`");
$statement->bind_result($country, $capital);
//Put the fetched data in the result array
while($statement->fetch()) {
$entry = Array();
$entry['country'] = $country;
$entry['capital'] = $capital;
$entries[] = $entry;
}
//Close the statement and connection
$statement->close();
$connection->close();
Next, you make the HTML select objects. It's important that the order of countries remains the same as the order of the capitals.
<!-- Country selection -->
<select id="select-country">
<?php $i = 0;
foreach ($entries as $c) { ?>
<option data-country="<?php echo $i++; ?>"><?php echo $c['country'] ?></option>
<?php } ?>
</select>
<!-- Capitals select -->
<select id="select-capital">
<?php $i = 0;
foreach ($entries as $c) { ?>
<option data-capital="<?php echo $i++ ?>"><?php echo $c['capital'] ?></option>
<?php } ?>
</select>
Finally, you add an event listener to the select with the id of select-country where you listen for the change event. Once called, you change the selected index of the second select to that of the first. That's why it's important that the order remains the same.
<script>
document.getElementById('select-country').addEventListener('change', function () {
document.getElementById('select-capital').getElementsByTagName('option')[this.selectedIndex].selected = true;
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52148932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Embedding tweets using URL received from Twitter API: some are returning errors I am using the TwitteroAuth API.
I am searching for Tweets using the search API: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Embedding via this method (as you will see from code): https://developer.twitter.com/en/docs/twitter-for-websites/embedded-tweets/guides/embedded-tweet-parameter-reference
Here is my PHP (having already gotten the json object from twitter):
<?php
$tweet_array = json_decode(json_encode($tweets), true);
// Turn each item into tweet
foreach ($tweet_array['statuses'] as $tweet ) {
// Variables
$tweet_text = $tweet['text'];
$twitter_username = $tweet['user']['name'];
$twitter_handle = $tweet['user']['screen_name'];
$output = "";
// Blockquote wrapper
$output .= "<blockquote class='twitter-tweet' data-lang='en'>";
// Text
$output .= "<p lang='en' dir='ltr'>$tweet_text</p>";
// User name and Handle
$output .= "— $twitter_username (@$twitter_handle)";
// Link to tweet
foreach ($tweet['entities'] as $key) {
// So don't break search
if (empty($key)) {
// Do nothing
} else {
// Check for extended_url key
if (array_key_exists("expanded_url",($key[0]))) {
// Boolean to confirm retrieval of URL
$url = true;
// URL output
$url_string = $key[0]['expanded_url'];
$output .= "<a href='$url_string'>$url_string</a>";
}
}
}
$output .= "</blockquote>";
// if URL present, output code
if ($url == true) {
echo $output;
}
}
That code outputs this, a mix of working and not working tweets:
The code being output looks like this (working and not working examples):
Working!
<twitterwidget class="twitter-tweet twitter-tweet-rendered" id="twitter-widget-1" style="position: static; visibility: visible; display: block; transform: rotate(0deg); max-width: 100%; width: 500px; min-width: 220px; margin-top: 10px; margin-bottom: 10px;" data-tweet-id="1057283419007143936"></twitterwidget>
Not working!
<blockquote class="twitter-tweet twitter-tweet-error" data-lang="en" data-twitter-extracted-i1540936951520207597="true"><p lang="en" dir="ltr">He’ll say anything before the election. Don’t take the bait. Focus on ending the hate. Hug a kid. Be nice to someon… <!-- SHORTENED LINK TAKEN OUT FOR STACK OVERFLOW --></p>— Amy Klobuchar (@amyklobuchar)<a href="https://twitter.com/i/web/status/1057234049587167232">https://twitter.com/i/web/status/1057234049587167232</a></blockquote>
Any help would be appreciated immensely
A: I found an answer. Rather than using the vague blockquote conversion method, I instead used PHP to print a JS script for each container with a unique twitter ID. 100% success rate:
<?php /* OUTPUT */
// Count tweets for debug
$number_tweets = count($tweet_array['statuses']);
echo "<div class='cols'>";
// Loop through each tweet
foreach ($tweet_array['statuses'] as $tweet ) {
// Get tweet ID
$id = $tweet["id"];
// Create grid item to be targeted by Twitter's widgets.js
echo "<div class='grid-item'><div id='container-$id'></div></div>";
// Add to array for JS objet
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
// Begin Javascript
echo '<script>';
// Print out JS to convert items to Tweets
$t = 1;
foreach ($js_array as $js ) {
echo $js;
$t++;
}
echo '</script>';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53073586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows Phone Background Application Service In my windows phone 8 application, I would like to refresh/load some data periodically (less than 10 minutes) from server, while application running in background (ie, in dormant and tombstoned). I tried scheduled task agent and resource intensive task agent, but they are called at rate of 30 minutes gap. Please let me know is there any other solution for implementing the above said requirement.
Thanks and Regards
@nish
A: If you need to get data more frequently than the default available in Windows Phone, you should think about using push notifications. This won't be suitable for a full data push, but if you use it correctly, you can get a user experience that you can live with.
One common approach to this is to set up your server to send a notification to the device when there is something new to report instead of pushing a "nothing has changed" message every 10 minutes or so. If you push out a tile update notification to say, for example, "You have x unread items", the user may then click on the tile for your app and you can poll the server for new items on launch/resume. If you want a more intrusive option, you can send a toast notification as well, but in most cases the tile update will be sufficient.
This method has a few advantages.
*
*You won't be burning through battery power polling every 10 minutes while the user is asleep
*Your server will have significantly less load since it is not having to process full data requests every 10 minutes per client.
*This fits in with the design philosophy of Phone apps - you are surfacing the required data to the user, while at the same time preserving battery life.
A: Do I understand correctly that your primary goal is to keep some host session alive by having the phone make a query periodically? If so...
I would not recommend this approach: 1) you cannot count on the phone having network connectivity when it tries to send its query. If the user puts the phone away in a pocket or purse, the odds worsen. 2) it's probably bad from a security perspective, and wasteful from a host resources perspective.
You might instead add logic to your app to resume a timed-out host session as seamlessly as possible. This would add real utility value to the mobile app value proposition over raw HTTP access to the same host.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19588073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone 4S - UnAuthorized Access Exception This is a question I am sure Xcode developers could also answer. I have a screenshot of my code below in Xamarin.
Why am I getting an Unauthorized access exception? I should be able to write to the documents folder right?
var webClient = new WebClient();
//var documentsFolder = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // iOS 7 and earlier
var documentsFolder = NSBundle.MainBundle.BundlePath;
var fileNameAndPath = Path.Combine (documentsFolder, "verses.xml");
if(!File.Exists(documentsFolder)){
Directory.CreateDirectory(documentsFolder);
if(!File.Exists(fileNameAndPath)){
//File.SetAttributes(fileNameAndPath, FileAttributes.Normal);
File.Create(fileNameAndPath);
//Throws exception here.
}
}
And ERRORs:
Access to the path "/var/mobile/Applications/1F95D694-BBA5-4FB3-AE6C-0C2CDD9DEDD8/comexample.app/verses.xml" is denied
Access to the path '/private/var/mobile/Applications/1F95D694-BBA5-4FB3-AE6C-0C2CDD9DEDD8/Documents/verses.xml' is denied.
I have tried both paths and I get access denied.
A: The BundlePath is not a writable area for iOS applications.
From the Xamarin notes at http://developer.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/
The following snippet will create a file into the writable documents area.
var documents =
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); // iOS 7 and earlier
var filename = Path.Combine (documents, "Write.txt");
File.WriteAllText(filename, "Write this text into a file");
There's a note on the page for iOS 8 that a change is required to get the documents folder
var documents = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomain.User) [0];
A: Assuming you're on iOS 8, the documents directory isn't connected to the bundle path. Use the function NSSearchPathForDirectoriesInDomains() (or URLsForDirectory:inDomains:) to find the documents directory.
A: I assume it should be a Directory.Exists() where you check if the directory exists:
if(!File.Exists(documentsFolder)){
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26845872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 500 Error When Adding Custom Django App With mod_fcgid I've been following the official Django 1.3 tutorial on their website. My issue comes when I add my custom app (polls) to the INSTALLED_APPS list in settings.py like such:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'polls',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
However, when I go back and look at the stack trace I get this:
mod_fcgid: stderr: TemplateSyntaxError: Caught ImportError while rendering: No module named polls
What am I doing wrong? Here is the entire stack trace:
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: Traceback (most recent call last):
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 574, in run
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 1159, in handler
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 272, in __call__
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: response = self.get_response(request)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 169, in get_response
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 203, in handle_uncaught_exception
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return debug.technical_500_response(request, *exc_info)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 59, in technical_500_response
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: html = reporter.get_traceback_html()
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 151, in get_traceback_html
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return t.render(c)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 123, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self._render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 117, in _render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.nodelist.render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 744, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: bits.append(self.render_node(node, context))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 73, in render_node
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: result = node.render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 90, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: output = self.filter_expression.resolve(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 536, in resolve
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: new_obj = func(obj, *arg_vals)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/defaultfilters.py", line 695, in date
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return format(value, arg)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 285, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return df.format(format_string)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: pieces.append(force_unicode(getattr(self, piece)()))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 191, in r
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.format('D, j M Y H:i:s O')
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: pieces.append(force_unicode(getattr(self, piece)()))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/encoding.py", line 71, in force_unicode
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: s = unicode(s)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 206, in __unicode_cast
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.__func(*self.__args, **self.__kw)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/__init__.py", line 81, in ugettext
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return _trans.ugettext(message)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 286, in ugettext
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return do_translate(message, 'ugettext')
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 276, in do_translate
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: _default = translation(settings.LANGUAGE_CODE)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 185, in translation
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: default_translation = _fetch(settings.LANGUAGE_CODE)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 162, in _fetch
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: app = import_module(appname)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/importlib.py", line 35, in import_module
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: __import__(name)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: TemplateSyntaxError: Caught ImportError while rendering: No module named polls
Edit...here is my sys.path:
/home/andydefo/andydeforest
/usr/lib/python2.4/site-packages/MySQL_python-1.2.3-py2.4-linux-i686.egg
/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg
/usr/lib/python2.4/site-packages/flup-1.0.3.dev_20110405-py2.4.egg
/usr/lib/python2.4/site-packages/pip-1.1-py2.4.egg
/usr/lib/python24.zip
/usr/lib/python2.4
/usr/lib/python2.4/plat-linux2
/usr/lib/python2.4/lib-tk
/usr/lib/python2.4/lib-dynload
/usr/lib/python2.4/site-packages
/usr/lib/python2.4/site-packages/Numeric
/usr/lib/python2.4/site-packages/gtk-2.0
And my urls.py:
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'andydeforest.views.home', name='home'),
# url(r'^andydeforest/', include('andydeforest.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
A: Is your app on the PYTHONPATH? You can check it in the shell by
$ python manage.py shell
and in the shell, check it using
> import sys
> print sys.path
If the app is not on PYTHONPATH, you can add it using project's settings.py.
In settings.py:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, "polls"))
If that is not the issue, could you also show the urls.py and views.py part of where the template is being invoked?
A: Had the same problem, solved it, try this in the settings.py:
import sys
sys.path.insert(0, "/home/user/django_projects/myproject/")
from here: http://www.bluehostforum.com/showthread.php?21680-DJANGO-Can-t-import-own-module
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11832842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to exclude moment locales from angular build? In my angular 5 application, when I create build using
ng build --prod --sm
and open source map explorer, moment takes lot of space in the main.js file. I have found all the locales gets loaded when I use
import * as moment from 'moment';
I have used material-moment-adapter to some functionality in the application that requires the moment package also.
I have created the application using angular-cli. I have found many links that excludes locales using settings in webpack.config.js
Is there any way to exclude locales using angular-cli ?
A: If you don't want to use any third party libraries the simplest way to do this is to add the following in compilerOptions of your tsconfig.json file
"paths": {
"moment": [
"../node_modules/moment/min/moment.min.js"
]
}
A: There is another solution in this Angular Issue:
https://github.com/angular/angular-cli/issues/6137#issuecomment-387708972
Add a custom path with the name "moment" so it is by default resolved to the JS file you want:
"compilerOptions": {
"paths": {
"moment": [
"./node_modules/moment/min/moment.min.js"
]
}
}
A: This article describe good solution:
https://medium.jonasbandi.net/angular-cli-and-moment-js-a-recipe-for-disaster-and-how-to-fix-it-163a79180173
Briefly:
*
*ng add ngx-build-plus
*Add a file webpack.extra.js in the root of your project:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
]
}
*Run:
npm run build --prod --extra-webpack-config webpack.extra.js
enter code here
Warning
moment.js has been deprecated officially
https://momentjs.com/docs/#/-project-status/ (try use day.js or luxon)
A: For anyone on angular 12 or latest
This does not work for me
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
]
}
However this does
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/
})
]
};
A: In Angular 12, I did the following:
npm i --save-dev @angular-builders/custom-webpack
to allow using a custom webpack configuration.
npm i --save-dev moment-locales-webpack-plugin
npm i --save-dev moment-timezone-data-webpack-plugin
Then modify your angular.json as follows:
...
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
...
and in the extra-webpack.config.js file:
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin');
module.exports = {
plugins: [
new MomentLocalesPlugin({
localesToKeep: ['en-ie']
}),
new MomentTimezoneDataPlugin({
matchZones: /Europe\/(Belfast|London|Paris|Athens)/,
startYear: 1950,
endYear: 2050,
}),
]
};
Modify the above options as needed, of course. This gives you far better control on which exact locales and timezones to include, as opposed to the regular expression that I see in some other answers.
A: the solutions above didn't work for me because they address the wrong path (don't use ../ ) in the tsconfig.app.json
{
...
"compilerOptions": {
"paths": {
"moment": [
"node_modules/moment/min/moment.min.js"
]
}
}
}
Works for me in Angular 12.2.X. The changes must be done in the tsconfig.app.json, than also the type information of your IDE will work.
Don't change it in the tsconfig.json or your IDE will lose type information.
This fix the usage in the app as in the lib. I used source-map-explorer to verify it.
ng build --sourceMap=true --namedChunks=true --configuration production && source-map-explorer dist/**/*.js
A: I had the same problem with momentjs library and solve it as below:
The main purpose of this answer is not to use IgnorePlugin for ignoring the library but I use ContextReplacementPlugin to tell the compiler which locale files I want to use in this project.
*
*Do all of the configurations mentioned in this answer: https://stackoverflow.com/a/72423671/6666348
*Then in your webpack.config.js file write this:
const webpack = require("webpack");
module.exports = {
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /(en|fr)$/)
]
};
This configuration will add only en and fr locale in your application dist folder.
A: You can try to use moment-mini-ts instead of moment
npm i moment-mini-ts
import * as moment from 'moment-mini-ts'
Don’t forget to uninstall moment
npm uninstall moment
I’m using angular 9
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49851277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: The animated text not working as the Javascript function I have coded a function to animate a texts by manipulating the ID and set animation delay to change the ID and start the animation again. The animation started well, however, after few minutes the animation delay does not work or take more time instead of was set.
setInterval(controlAninmation_A, 100);
function controlAninmation_A() {
var getId = document.getElementById('AA');
getId.setAttribute("id", "A");
var removeId = document.getElementById('A'),
setClass = removeId;
setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 30000);
function changeId() {
removeId.setAttribute("id", "AA");
console.log("The function was executed 100% ");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_A);
setInterval(controlAninmation_B, 4000);
function controlAninmation_B() {
var getId = document.getElementById('BB');
if (getId != "B") {
getId.setAttribute("id", "B");
}
var removeId = document.getElementById('B'),
setClass = removeId;
setTimeout(changeClass, 34000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 27000);
function changeId() {
removeId.setAttribute("id", "BB");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_B);
setInterval(controlAninmation_C, 11000);
function controlAninmation_C() {
var getId = document.getElementById('CC');
if (getId != "C") {
getId.setAttribute("id", "C");
}
var removeId = document.getElementById('C'),
setClass = removeId;
setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 41000);
function changeId() {
removeId.setAttribute("id", "CC");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_C);
setInterval(controlAninmation_D, 17000);
function controlAninmation_D() {
var getId = document.getElementById('DD');
if (getId != "D") {
getId.setAttribute("id", "D");
}
var removeId = document.getElementById('D'),
setClass = removeId;
setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 47000);
function changeId() {
removeId.setAttribute("id", "DD");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_D);
setInterval(controlAninmation_E, 20000);
function controlAninmation_E() {
var getId = document.getElementById('EE');
if (getId != "E") {
getId.setAttribute("id", "E");
}
var removeId = document.getElementById('E'),
setClass = removeId; setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 50000);
function changeId() {
removeId.setAttribute("id", "EE");
} clearTimeout(changeId);
}
clearInterval(controlAninmation_E);
setInterval(controlAninmation_F, 24000);
function controlAninmation_F() {
var getId = document.getElementById('FF');
if (getId != "") {
getId.setAttribute("id", "F");
}
var removeId = document.getElementById('F'),
setClass = removeId; setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 54000);
function changeId() {
removeId.setAttribute("id", "FF");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_F);
setInterval(controlAninmation_G, 27000);
function controlAninmation_G() {
var getId = document.getElementById('GG');
if (getId != "") {
getId.setAttribute("id", "G");
}
var removeId = document.getElementById('G'),
setClass = removeId;
setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 57000);
function changeId() {
removeId.setAttribute("id", "GG");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_G);
setInterval(controlAninmation_H, 30000);
function controlAninmation_H() {
var getId = document.getElementById('HH');
if (getId != "") {
getId.setAttribute("id", "H");
} moveId = document.getElementById('H'),
setClass = removeId;
setTimeout(changeClass, 20000);
function changeClass() {
var checkClass = setClass.getAttribute("class");
if (checkClass != "change") {
setClass.setAttribute("class", "change");
console.log("changed class");
}
}
clearTimeout(changeClass);
setTimeout(changeId, 60000);
function changeId() {
removeId.setAttribute("id", "HH");
}
clearTimeout(changeId);
}
clearInterval(controlAninmation_H);
#A{ animation-name: wave;animation-duration: 20s; animation-iteration-count: 1;animation-timing-function:linear; }
#B{ animation-name: QQQ;animation-duration: 20s; animation-iteration-count: 1;animation-timing-function:linear; }
#C{ animation-name: EEEE;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
#D{ animation-name: RRRR;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
#E{ animation-name: AAAA;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
#F{ animation-name: DDDDDD;animation-duration: 20s; animation-iteration-count: 1;animation-timing-function:linear; }
#G{ animation-name:GGGGGGG;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
#H{ animation-name:KKKKKKKK;animation-duration: 20s; animation-iteration-count: 1;animation-timing-function:linear; }
.hidden{
position: relative;
top: 160px;}
.change{
position: relative;
top: 160px;}
@keyframes A{0%{transform: translateX(0%); top:17px; margin-left: 10px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%); top:17px; margin-left: 10px;margin-right: 10px;visibility: visible; }}
@keyframes B{0%{transform: translateX(0%);top:0px; margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:0px; margin-right: 10px; visibility: visible; }}
@keyframes C{0%{transform: translateX(0%);top:-17px; margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-17px; margin-right: 10px;visibility: visible; }}
@keyframes D{0%{transform: translateX(0%);top:-34px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-34px;margin-right: 10px;visibility: visible; }}
@keyframes E{0%{transform: translateX(0%);top:-51px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-51px;margin-right: 10px;visibility: visible; }}
@keyframes F{0%{transform: translateX(0%);top:-68px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-68px;margin-right: 10px;visibility: visible; }}
@keyframes G{0%{transform: translateX(0%);top:-85px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-85px;margin-right: 10px;visibility: visible; }}
@keyframes H{0%{transform: translateX(0%);top:-102px;margin-right: 10px;margin-left: 10px;visibility: visible; }100%{transform: translateX(100%);top:-102px;margin-right: 10px;margin-left: 10px;visibility: visible; }}
<div id="AA" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="BB" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="CC" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="DD" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="EE" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="FF" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="GG" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
<div id="HH" class="hidden"><a href="#">Welcome to StackOvervlow</a></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54431032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Import styles into react-native I'm stying how to import styles from other sources into react native. I see that there are options like using styled-component or even importing scss files.
Anyway, Do you have any particular recommentations?
I'm currently exploring [this option] (https://github.com/kristerkari/react-native-sass-transformer/) but I'm getting a syntax error (Unexpected token), so I guess something in the loader is missing. Not sure.
I'd like to be able to serve styles into a react native project from an outside library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57399888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: check whether a string exists in list using for loop in c# I have a list arrString that contains string values. I need to check a string lookupvalue.Longname whether it exists in the list using for loop in C#.
for(int i = 0 ;i < ResoCustomFields.LongnameNotToBeTaken.Count ;i++)
{
string myStringList = ResoCustomFields.LongnameNotToBeTaken[i].ToString();
var arrString = myStringList.Trim('(',')').Split(',').ToList();
if(arrString.Contains(resoField))
{
// if(!arrString[i].Any(str=>str.ToString().Contains(lookupValue.LongName)))
// if(lookupValue.LongName.Contains(arrString.ToString()))
//(!arrString.Any(str => str.Equals(lookupValue.LongName)))
// if(!arrString.Equals(lookupValue.LongName))
{
}
}
A: You can try the following code :
int pos = Array.IndexOf(arrString, lookupValue.LongName);
if (pos > -1)
{
//// DO YOUR STUF
}
Following is the reference:
Checking if a string array contains a value, and if so, getting its position
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43338755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: lambda function to start aws workspaces - overcome client.start_workspaces limitation i have a lambda function to start all the workspaces machines in my env
Lambda Function :
import boto3
client = boto3.client('workspaces')
def lambda_handler(event,context):
workspaces = client.describe_workspaces()['Workspaces']
for workspace in workspaces:
if workspace['WorkspaceProperties']['RunningMode'] == 'AUTO_STOP':
if workspace['State'] == 'STOPPED':
workspaces_id = (workspace['WorkspaceId'])
client.start_workspaces(
StartWorkspaceRequests=[
{
'WorkspaceId': workspaces_id
},
]
)
The client.start_workspaces has a limitation of 25 workspaces per request , any idea how to overcome this ? im trying to build a robust solution for more then 25 workspaces .
https://docs.aws.amazon.com/workspaces/latest/api/API_StartWorkspaces.html#API_StartWorkspaces_RequestSyntax
Thanks in advance to the helpers
A: Probably you can use Paginator. Then call the client, to start the workspace workspaces."WorkSpaces.Paginator.DescribeWorkspaces"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74678009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change a button shape style at runtime? I am developing an app in java, android studio, where the user can choose the style color of the app.
With most components just use the .setBackground(colorUser);
The problem is in my buttons.
My buttons are all rounded, I created a shape for that.
My shape is in other file...
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/colorJetway" />
<corners
android:bottomLeftRadius="80dp"
android:bottomRightRadius="80dp"
android:topLeftRadius="80dp"
android:topRightRadius="80dp" />
</shape>
<Button
android:id="@+id/btnAdc"
android:layout_width="84dp"
android:layout_height="84dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="205dp"
android:background="@drawable/btns_border"
android:onClick="btnAdicionar_click"
android:text="+"
android:textColor="#FFFFFF"
android:textSize="40dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtQuantidade" />
That way if at runtime I make mybutton.setBackground(colorUser) my button loses its style ... it will have no rounded edges.
How can I do it?
A: It is not exactly what you are looking for.
However using the MaterialButton component it is very simple to have rounded buttons.
Just use app:cornerRadius to define the corner radius and app:backgroundTint to change the background color.
<com.google.android.material.button.MaterialButton
app:backgroundTint="@color/myselector"
app:cornerRadius="xxdp"
.../>
You can programmatically change these values using:
button.setCornerRadius(...);
button.setBackgroundTintList(..);
A: if your colors is limited you can create some drawables with the colors you want.
for example :
blackButton.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/black" />
<corners
android:bottomLeftRadius="80dp"
android:bottomRightRadius="80dp"
android:topLeftRadius="80dp"
android:topRightRadius="80dp" />
whiteButton.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/white" />
<corners
android:bottomLeftRadius="80dp"
android:bottomRightRadius="80dp"
android:topLeftRadius="80dp"
android:topRightRadius="80dp" />
and when you want change your button's background just use button.setBackground(getResources().getDrawable(R.drawable.blackButton)) or button.setBackground(getResources().getDrawable(R.drawable.whiteButton))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57777238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I want to control dynamic subMenu auto column in wpf. if 5 row auto break 1 column. how? I want to control dynamic subMenu auto column in wpf. if 5 row auto break 1 column. how?
I think if control grid in code bihinde but i dont' know. can you help me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63518669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: imagemagick doesn't delete tmp files I have an app that uses Carrierwave, S3 and rmagci.
more or less following http://railscasts.com/episodes/253-carrierwave-file-uploads but just upload to S3 instead of local.
I noticed the temp files in public/uploads/ does not get deleted after an image gets created. This causes my computer to feel up over time and crash.
I looked around and the only solution i found was to write a cron job to delete them http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=15960
any idea if there is a better way to do this in the code rather than a cronjob?
A: As of January 2013, there is no official way to delete temporary files, so imagemagic leaves you to do it yourself. I also use a cron job that runs every 20 minutes since the temporary files are 10+ GB in size.
A: It means your ImageMagick installation is NOT functioning properly!
The fact that it leaves magick-* files in tmp says that ImageMagick process died and that's why it didn't delete those files. You should configure memory limits etc. Refer http://www.imagemagick.org/script/resources.php
A: I've had this problem for a period of time, my code issue was that I didn't use the destroy function:
$im->destroy();
When calling the destroy function it will delete the temp files that are made under the /tmp directory.
This is for PHP and maybe it will help someone.
A: It is always better to use a task based approach and not to clog up the runtime with deleting stuff. just run the task once a day.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11875046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Tkinter Scrollbar question (independent scrollable length indexed to custom range) I'm having trouble wording this properly. What I'm looking to do is create a scrollbar that is indexed to a range I set that will return its position when it's moved/updated. In the simplest form, let's just say I print the position of the bar each time it's updated. Is there a way to accomplish this? I assume it involves setting a custom range and some sort of sensitivity.
The ultimate plan is to use the scrollbar to scroll through a matplotlib chart with a time series as the x-axis, but I believe that will be easy enough once I get the scrollbar setup.
Thanks!
self.scroll = ttk.Scrollbar(self, orient="horizontal",
command=lambda e1, e2, e3=None:
self.scroll_update(e1, e2))
def scroll_update(self, action, val):
if action == "moveto":
print(val)
elif action == "scroll":
pass
A: As @jasonharper pointed out, it's much easier to use a Scale in your case:
from tkinter import *
on_update = lambda e: print(e)
# |in pixels| |resolution| |the slider, pixels| |switch value display
s=Scale(command=on_update, length=250, to=1000, sliderlength=50, showvalue=False)
s.pack()
print(s.get())
s.set(20) # note, this also executes the "command" property
Hope that's helpful!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61741756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get range partition details from system catalogs I am looking for a solution that lists all the range partition information. Tried the below query.
SELECT c.relname as partition_list,p.relname as parent_tbl FROM pg_inherits i JOIN pg_class p ON i.inhparent = p.oid
JOIN pg_class c ON i.inhrelid = c.oid WHERE p.relkind IN ('r', 'p');
output
"testpartpartition_1" "parentpartiontbl"
"testpartpartition_2" "parentpartiontbl"
But since I created a range partition, want to know the range values for eg:
CREATE TABLE testpartpartition_1 PARTITION OF parentpartiontbl FOR VALUES FROM (1) TO (5)
CREATE TABLE testpartpartition_2 PARTITION OF parentpartiontbl FOR VALUES FROM (6) TO (10)
Want the output also which states startvalue and endvalue for each partition like below
child_partition parent_tbl min_rangeval max_rangeval
---------------------------------------------------------------------------------
"testpartpartition_1" "parentpartiontbl" 1 5
"testpartpartition_2" "parentpartiontbl" 6 10
A: Since the partition boundaries are stored in binary parsed form, all you can do is deparse them:
SELECT c.oid::regclass AS child_partition,
p.oid::regclass AS parent_tbl,
pg_get_expr(c.relpartbound, c.oid) AS boundaries
FROM pg_class AS p
JOIN pg_inherits AS i ON p.oid = i.inhparent
JOIN pg_class AS c ON i.inhrelid = c.oid
WHERE p.relkind = 'p';
child_partition │ parent_tbl │ boundaries
═════════════════╪════════════╪══════════════════════════════════════════════════════════════════════════
part_2022 │ part │ FOR VALUES FROM ('2022-01-01 00:00:00+01') TO ('2023-01-01 00:00:00+01')
(1 row)
Analyzing the boundary string is left as exercise to the reader.
A: You can find the information in the relpartbound column of the system catalog pg_class. Use the function pg_get_expr() to get the data readable:
select
relname as partition_table,
pg_get_expr(relpartbound, oid) as partition_range
from pg_class
where relispartition
and relkind = 'r';
partition_table | partition_range
---------------------+-----------------------------
testpartpartition_1 | FOR VALUES FROM (1) TO (5)
testpartpartition_2 | FOR VALUES FROM (6) TO (10)
(2 rows)
Use regexp_matches() to extract the numbers in parentheses
select
relname as partition_table,
matches[1] as min_rangeval,
matches[2] as max_rangeval
from pg_class
cross join regexp_matches(pg_get_expr(relpartbound, oid), '\((.+?)\).+\((.+?)\)') as matches
where relispartition
and relkind = 'r';
partition_table | min_rangeval | max_rangeval
---------------------+--------------+--------------
testpartpartition_1 | 1 | 5
testpartpartition_2 | 6 | 10
(2 rows)
A: Here's the query that gets generated by \d+:
edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid)
FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i
WHERE c.oid = i.inhrelid AND i.inhparent = '33245'
ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;
oid | relkind | inhdetachpending | pg_get_expr
---------------------+---------+------------------+-----------------------------
testpartpartition_1 | r | f | FOR VALUES FROM (1) TO (5)
testpartpartition_2 | r | f | FOR VALUES FROM (6) TO (10)
(2 rows)
Looks like you need to use pg_get_expr() to decode the stuff in pg_class.relpartbound to reconstruct the range partition parameters.
You can also replace i.inhparent = '33245' with a subquery to query by parent table name:
edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid)
FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i
WHERE c.oid = i.inhrelid AND i.inhparent = (SELECT oid from pg_class where relname = 'parentpartitiontbl')
ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73912445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Replace a full line every Nth line in a text file I'm trying to perform something that should be simple but I'm not quite understanding how to do it. I have a file that looks like this:
@A01182:104:HKNG5DSX3:3:1101:3947:1031 1:N:0:CATTGCCT+NATCTCAG
CNTCATAGCTGGTTGCACAGTTAACGTCGTTCAGGCCACGTTCCAGACCGTAGTTTGCCAGCGTCAGATCATAAACGGTGGTCACCAGGGCGGTGCTGCCA
+
F#FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFF,FFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:7997:1031 1:N:0:CATTGCCT+NATCTCAG
GNCGATCCCTTCGCTGCTGCTGGCAATTATCGTTGTAGCGTTTGCCGGACCGAGTTTGTCTCACGCCATGTTTGCTGTCTGGCTGGCGCTGCTGCCGCGTA
+
F#FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:5547:1047 1:N:0:CATTGCCT+NATCTCAG
GGTGATGATTGTCTTTGGCGCAACGTTAATGAAAGATGCGCCGAAGCAGGAAGTGAAAACCAGCAATGGTGTGGTGGAGAAGGACTACACCCTGGCAGAGT
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:20726:1063 1:N:0:CATTGCCT+GATCTCAG
GGGACGCCCATTACGCTGGTGAATCTGGCAACCCATACCAGCGCCCTGCCCCGTGAACAGCCCGGTGGCGCGGCACATCGTCCGGTATTTGTCTGGCCAAC
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFF
and goes on for a lot of lines (The actual file is 2.5 Gb). What I want to do is to replace every fourth line (all those that have a lot of F's) for another string, the same for all.
I have tried with sed but I don't seem to be able to get the script right since I produce and output without changes.
Any help would be really appreciated!
A: This might work for you (GNU sed):
sed -i '4~4s/.*/another string/' file(s)
Starting at the 4th line and every 4 lines thereafter, replace the whole line with another string.
A: I'd use awk for this
awk '
NR % 4 == 0 {print "new string"; next}
{print}
' file > file.new && mv file.new file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75208496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting error 'Microsoft.ACE.OLEDB.12.0' provider is not registered, however i was loading files earlier I am getting an error The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. However, I have loaded many files using same service two days earlier. Why this issue has started occuring.
My machine is 64 bit window 7 OS. Every project in .NET solution is configured for ANY CPU.
A: In the properties of your project try targeting x86 instead of AnyCPU:
Alternatively if you want to target AnyCPU you need to install the x64 bit Access OLEDB provider. You can download it from here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17262115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use and OR inside an AND operator for a where clause I would like my WHERE clause to evaluate the AND and the OR inside of an AND.
SELECT
ID,
Name,
CASE
WHEN EXISTS (SELECT * FROM date_hired dh WHERE id = e.id
AND (
(dh.datehired <= e.interview_start_date)
OR
(dh.datehired BETWEEN e.interview_start_date AND e.last_job_date)
)
AND dh.office = 'Med-office'
)
THEN 0 ELSE 1 END AS decision
FROM new_table n
JOIN old_table e ON e.id=n.id
A: Vertica is a mass data database, and it prefers more efficient joins and existence checks than correlated sub-selects - what an EXISTS predicate boils down to - and what results in a slowing-down nested loop.
Put the datehired check into a LEFT JOIN predicate with a Common Table Expression - in a WITH clause. If the joined table's columns are NULL, the matching id does not exist, so finally just check for being NULL.
WITH
dh AS (
SELECT
id
, datehired
FROM date_hired
WHERE dh.office = 'Med-office'
)
SELECT
id
, nam
, CASE WHEN dh.id IS NOT NULL
THEN 1
ELSE 0
END AS decision
FROM new_table n
JOIN old_table e USING(id)
LEFT JOIN dh
ON e.id = = dh.id
AND (
dh.datehired <= e.interview_start_date
OR
dh.datehired BETWEEN e.interview_start_date AND e.last_job_date
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71787111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Node.js - Infinite Loop in Custom Code (Custom business logic) Hi I'm making a business application in which user can write his custom code and execute it.
How can i handle situations when the custom code generates infinite loops ?
A way is to handle each request in separate child process and kill that process on request completion but if there are thousands of users this doesn't seem to be appropriate. What else can be done in such cases ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26559634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: opencv user drawing rectangle to crop I am trying to get a user to be able to draw a rectangle around an object and crop it-
with this code--
def click_and_crop(event, x, y, flags, param):
global refPt, drawing, cropping
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
refPt = [(x, y)]
cropping = True
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
refPt.append((x, y))
cropping = False
cv2.rectangle(closeres, refPt[0], refPt[1], (0, 255, 0), 2)
cv2.imshow("image", closeres)
it draws multiple rectangles not just one that changes size, it ends up looking like this-
anyone know how to fix this so it changes size instead?
if I change code to this-
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
closeres = cloneclone
cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)
to try to erase the rectangle each time it changes i end up seeing nothing , no rectangle and get this message-
Traceback (most recent call last):
File "project2.py", line 38, in click_and_crop
cv2.rectangle(closeres, refPt[0], refPt1, (0, 255, 0), 2)
UnboundLocalError: local variable 'closeres' referenced before assignment
A: You have to draw the image each time at the start of your event hanling routine instead of inside the last if condition.
THEN draw the sizer rectangle. Otherwise the previous rectangle is not deleted. Image is progressively destroyed.
The higher the refresh rate, the greener your image becomes.
A possible optimization is to use a XOR mode so if you draw previous rectangle again it restores the image (but rectangle cannot be plain green in that case) but it is more complex
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38466701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Web caching when retrieving lists of documents We have a need to leverage client side resources for lists containing tasks.
The client needs to:
*
*be notified of updates to the list
*be able to re-order/filter the list (requesting an update from the server with tasks that the client does not know of/have in cache)
The problem comes on initial load or large list updates (changing from "tasks assigned to me" to "tasks regarding x")
The fastest thing to do is get all the tasks back in a list, instead of individual (10+) requests.
But E-tags will not help when I request an update to a task in the list, as it was not downloaded individually.
Is there some way of getting the browser to cache items in a list against their individual urls?
Or a way of creating a javascript cache that will survive a navigation away?
*
*If I navigate away, and go to the task url, will my js objects survive? I suspect no.
*If I navigate away, then hit back, will my javascript objects survive? I suspect yes.
*
*If so, is it possible to have a "task list load" page that will inspect the history and go back to the existing task list? I think no - security.
I'm thinking I'll just have to take the initial loading hits and individually retrieve tasks, so that later requests are fast (and take the load off the server).
A: In HTML5, there is the Window.sessionStorage attribute that is able to store content against a specific session within a tab/window (other windows will have their own storage, even when running against the same session).
There is also localStorage, and database Storage options available in the spec as well.
A: HTML5 is still a bit far away from being implemented, but you might be able to use Google Gears for your local storage needs.
Also, I've no idea how many simultaneous clients and tasks we're talking about, how big the tasks are and what strain such a request might put on the database, but I'd think you should be able to run smooth without any caching, 10+ requests doesn't seem that much. If traffic is not the bottleneck, I would put caching on the server and keep the client 'dumb'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/303338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git add only some changed files I have a remote branch in Git called development and also local development branch. I modified lets say 3 files:
git status
modified file1
modified file2
modified file3
now I want to add and commit only file1 and push it to remote branch(file2 and file3 will be added later but not now). I try to push it but git doesn't allow to push because remote head is ahead than my local. Then I tried doing git fetch and git rebase but then, git says I have untracked files. Git suggested to stash them. I am new to git and what I know so far is git stash is to save the working changes in case of switching another branch. In my case I am not switching my branch. Is it safe to do proceed with git stash? or are there some other ways? I appreciate your explanations.
A: Before push, you need to commit your changes. It's done locally by:
#add files to specific commit
git add file1
# commit added files
git commit -m "init commit"
# stash file2 file3
git stash
# now, when working dir is clean you can safly pull updates from remote repo
git pull
# push your changes (your commit) to remote repo
git push origin master
#return file2 file3 changes
git stash apply
A: You can selectively stage files.
For example, let's say in the first commit you only wanted to use file1 and push only that:
git add file1
git commit -m "first bit of changes"
git push
With Git, you can stage files at a very granular level which allows you craft your commits in a logical way.
As for the other part of the question...
I try to push it but git doesn't allow to push because remote hed is
ahed than my local
Yes, this is definitly a good use-case for stash.
Do this:
git stash
git pull
git stash pop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36427032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Finding the physical size of the touch digitizer in Windows 8.1 Question
How does one go about determing the physical size of the touch (or pen) digitizer in Windows 8.1 using the WinAPI?
Scenario
I'm using the GetPointerFrameTouchInfo() API which returns a POINTER_TOUCH_INFO struct with an embedded POINTER_INFO struct.
The POINTER_INFO struct has a ptHimetricLocation member which indicates the physical location of a touch with 10 uM resolution (which is way more consistent to work with for gesture recognition).
But, after doing some calculations using the ptHiMetricLocation, it's not possible to accurately find the corresponding pixel location without knowing the physical size of the digitizer.
Qualifier
To clarify, this is not a question about the physical screen size. It's about the touch digitizer (or the pen digitizer).
A: Okay, it turns out this is actually really easy, as long as you have a handle to the device. Just use the GetPointerDeviceRects() function =]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25132940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Render observable in component while waiting for next value? I have a scenario were certain data may need to be refreshed on the server, but is a long running task.
What i need is to get the current state of the data and render it while I wait for the refreshed data from the server. I have a component that will render the obserable, while sending another call to refresh it. my getData service method looks like the following sudo code (creates a behavior subject with a false initial value, and then emits true to do the refresh)
behaviorsubject = new BehaviorSubject(false);
data$ = behaviorsubject.pipe(
refresh => swichMap(httpclientcall?refresh=${refresh})
.pipe(
tap(res => {
if(res.needsRefresh) behaviorsubject.next(true)
})
)
return data$
This sort of works. However, my page does not render until the second http call is returned. In my componet, I use the following to determine if the component will render. I see the spinner until the refresh call completes.
<div *ngIf="data$ | async as data; else spinner">
The desired result
Component after inital http call:
Data from server: (status loading)
Component after refresh http call:
Data from server: up-to-date
What is the best way to have the first call in the observable complete so the component can render without waiting for the second. Hopefully I explained this well enough.
A: You can use merge to return an observable that has two sources that emit independently into the same stream.
In this case, you don't even need to use a subject:
data$ = http.get(url_1).pipe(
switchMap(response1 => {
const call1 = of(response1);
const call2 = response1.needsRefresh ? http.get(url_2) : EMPTY;
return merge(call1, call2);
})
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67269736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: get out data from promise function in angular I have this service file part of angular project , issue is I cant back value to main function from promise.then function .. here is the code
angular.module('starter.services', [])
.factory('Services', function ($http,$q) {
var def = $q.defer();
// Might use a resource here that returns a JSON array
$http.get('JSONFILE').then(function (data) {
def.resolve(data.data);
});
this.result ={};
var var1 = def.promise;
var1.then(function (data){
this.result = data;
console.log(this.result);
});
// Some fake testing data
console.log(this.result);
return {
all: function () {
return var1;
},
remove: function (service) {
var1.splice(var1.indexOf(service), 1);
},
get: function (serviceId) {
for (var i = 0; i < var1.length; i++) {
if (var1[i].id === parseInt(serviceId)) {
return var1[i];
}
}
return null;
}
};
});
this.result will return empty object outside promise.then but get right data inside it.
A: Actually, if you are talking about this log statement here:
// Some fake testing data
console.log(this.result);
The reason why this.result doesn't have the same data is because the Promise is probably still pending (fulfilling the promise).
I suspect when you see these console logs, you see the one outside the Promise display first. This is to be expected.
Also, your block scope is different, meaning this.result can be different inside that Promise context.
Try changing:
this.result = {};
to:
var result = {};
And also change
var1.then(function (data){
result = data;
console.log(result);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32705734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I turn this oddly formatted looped print function into a data frame with similar output? There is a code chunk I found useful in my project, but I can't get it to build a data frame in the same given/desired format as it prints (2 columns).
The code chunk and desired output:
import nltk
import pandas as pd
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
# Step Two: Load Data
sentence = "Martin Luther King Jr. (born Michael King Jr.; January 15, 1929 – April 4, 1968) was an American Baptist minister and activist who became the most visible spokesman and leader in the American civil rights movement from 1955 until his assassination in 1968. King advanced civil rights through nonviolence and civil disobedience, inspired by his Christian beliefs and the nonviolent activism of Mahatma Gandhi. He was the son of early civil rights activist and minister Martin Luther King Sr."
# Step Three: Tokenise, find parts of speech and chunk words
for sent in nltk.sent_tokenize(sentence):
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
if hasattr(chunk, 'label'):
print(chunk.label(), ' '.join(c[0] for c in chunk))
Clean Output of tag in one column and entity in another:
PERSON Martin
PERSON Luther King
PERSON Michael King
ORGANIZATION American
GPE American
GPE Christian
PERSON Mahatma Gandhi
PERSON Martin Luther
I tried something like this, but the results are not nearly as clean.
for sent in nltk.sent_tokenize(sentence):
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
if hasattr(chunk, 'label'):
df.append(chunk)
Output:
[Tree('PERSON', [('Martin', 'NNP')]),
Tree('PERSON', [('Luther', 'NNP'), ('King', 'NNP')]),
Tree('PERSON', [('Michael', 'NNP'), ('King', 'NNP')]),
Tree('ORGANIZATION', [('American', 'JJ')]),
Tree('GPE', [('American', 'NNP')]),
Tree('GPE', [('Christian', 'JJ')]),
Tree('PERSON', [('Mahatma', 'NNP'), ('Gandhi', 'NNP')]),
Tree('PERSON', [('Martin', 'NNP'), ('Luther', 'NNP')])]
Is there a easy way to change the print format to df with just 2 columns??
A: Create nested lists and convert to DataFrame:
L = []
for sent in nltk.sent_tokenize(sentence):
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
if hasattr(chunk, 'label'):
L.append([chunk.label(), ' '.join(c[0] for c in chunk)])
df = pd.DataFrame(L, columns=['a','b'])
print (df)
a b
0 PERSON Martin
1 PERSON Luther King
2 PERSON Michael King
3 ORGANIZATION American
4 GPE American
5 GPE Christian
6 PERSON Mahatma Gandhi
7 PERSON Martin Luther
In list comperehension solution is:
L= [[chunk.label(), ' '.join(c[0] for c in chunk)]
for sent in nltk.sent_tokenize(sentence)
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent)))
if hasattr(chunk, 'label')]
df = pd.DataFrame(L, columns=['a','b'])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70677140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Use an external database in Django app on Heroku I am trying to deploy a Django REST API on Heroku. Normally I wouldn't have any issues with this but for this app, I am using a legacy database that exists on AWS. Is it possible for me to continue to use this remote database after deploying Django to Heroku? I have the database credentials all set up in settings.py so I would assume that it should work but I am not sure.
A: It should not pose any problem to connect with an database on AWS.
But be sure that the database on AWS is configured to accept external access, so that Heroku can connect.
And I would sugest that you take the credentials out of the source code and put it in the Config Vars that Heroku provide (environment variables).
A: Will it work? I think yes, provided you configure your project and database for external access.
Should you want it? How may queries does an average page execute? Some applications may make tens of queries for every endpoint and added wait can combine into seconds of waiting for every request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66403645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to handle user comments in a database I was planning to store user comments in a database and was wondering how to store the raw text that users will provide since it could contain anything. What is a common/good practice in regards to this? Do I need to parse the text or is there a special storage type that I should be using? It seemed like a lot of overhead to be parsing user comments that could potentially be quite long and I don't want to be tampering with the intended meaning of a message etc. It seemed strange to be treating a comment/forum post in the same manor as say a username/password and sanitize.
I am using sqlite3 and some scripts to query the db and was planning on implementing something along the lines of:
page_id post_number username content
------- ----------- -------- -------
1 1 user_23 blah there's blah "quote" blah;':".,-=.
But, of course, if I was to just expand my content param into my INSERT query, there is going to be all kinds of problems with ' " etc.
How should I be handling the content in this table; should it even be in the table like this? What data type should I be using etc.
A: To avoid SQL injection attacks, to make formatting of query strings easier, and to make handling of blob data possible, all databases support parameters.
In Python, it would look like this:
id = 1
text = "blah ..."
cursor.execute("INSERT INTO mytable(id, content) VALUES(?, ?)", (id, text))
A: The data type to use depends on the overall size of the input.
Text would be my first choice.
for more on sqlite3 datatypes see
http://www.sqlite.org/datatype3.html
I would recommend you
Sanitize the input, only allow necessary markup.
Encode the content so it's safe to insert into the database.
If security is a serious concern this processing should be done server side. It won't hurt to put some of this processing load to javascript this will reduce the work done at the server. Tho it would still catch user(s) trying to circumvent the feature.
A: I'm not into python, but doesn't your DB driver take care of it already? Otherwise, you have to replace escape those characters manually.
Take a look at this thread:
How to string format SQL IN clause with Python
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12875124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android custom camera issue in some devices Hi, I have a custom camera where I have click button, when clicked it captures the image... Everything is fine but in some devices the preview is stretching and also the preview is overlaying half the screen and flickering... some wierd unwanted effect. How to fix this?
This is my code:
Camera Activity:
preview = new Preview(this, (SurfaceView) findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
((FrameLayout) findViewById(R.id.preview)).addView(preview);
preview.setKeepScreenOn(true);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
// camera.setDisplayOrientation(90);
}
});
Preview class:
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
@SuppressWarnings("deprecation")
Preview(Context context, SurfaceView sv) {
super(context);
mSurfaceView = sv;
// addView(mSurfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
mSupportedPreviewSizes = params.getSupportedPreviewSizes();
requestLayout();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2);
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
mCamera.stopPreview();
}
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null)
return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
A: There is a known bug happening on some devices for the image captures described here:
https://code.google.com/p/android/issues/detail?id=1480
Not sure if your problem is the same, but you should try the code explained in this answer from another question:
https://stackoverflow.com/a/1932268/2206688
A: McAfee Antivirus may be the culprit in this case.
In which case, uninstalling it should solve the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15686218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to get the number of tasks that need to be executed right now on celery? I am using celery with two types of tasks
*
*Tasks that need to be executed with 0 delay
*Tasks that need to be executed with some delay (countdown or eta)
I am trying to autoscale my celery cluster and I need to know how many tasks are present in the queue right now to be executed.
When I inspect rabbitmq, I get both tasks to be executed and tasks scheduled.
I am not able to figure out the current load on celery so that I can decide on the number of worker nodes.
Only thing I can think of is to use the API /api/queues/vhost/name/get - this will alter the queue and I do not want that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73890804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sqlite 3 on Windows, records not viewable to other users when stored as Administrator? we use Sqlite 3 on windows to store our sync applications logs and state. Applications are written in c#, .net 4.5 and executed as windows services and/or console. We also use sqlite3.exe for debugging / log viewer.
Recently we found a odd thing, records generated by the windows services was not viewable from the sqlite3.exe tool, unless started as "Administrator". Services are running as "Local System".
I'v also tested to generate records by starting our console app as "Administrator". These records can then only be viewed in sqlite3.exe when started as "Administrator", otherwise they are "invisible". The same occurs when application is started as "normal" user (not as "Administrator" that is).
All application use the same database file, and during this testing file/folder security is set to "Everyone has full control".
Is this behavior by design, or I'm missing something here?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47353077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex - Match word/letters underneath a specific pattern Very unusual one but I'm trying to match output from an SSH session that may collapse view and fall underneath the output required (like a collapsed column)...
Take a look at the example output:
System Id Interface Circuit Id State HoldTime Type PRI
--------------------------------------------------------------------------------
rtr1.lab01.some GE0/0/1 0000000001 Up 22s L2 --
thing
rtr2.lab01.some GE0/0/2 0000000002 Up 24s L2 --
thingelse
I can match the the first line with:
^([a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9])
which returns (rtr1.lab01.some and rtr2.lab01.some) but I'm trying to find the easiest way to match it based on the full hostname (rtr1.lab01.something and rtr2.lab01.somethingelse)
I'm also matching the rest of the output perfectly fine and able to extract the data but really can't find a way to achieve what I'm trying... Can someone point me in the right direction? To expand further (for more context... I'm using the Google TextFSM in Python to match all this data from an SSH session)
A: import re
text = """System Id Interface Circuit Id State HoldTime Type PRI
--------------------------------------------------------------------------------
rtr1.lab01.some GE0/0/1 0000000001 Up 22s L2 --
thing
rtr2.lab01.some GE0/0/2 0000000002 Up 24s L2 --
thingelse
rtr2.lab01.abcd GE0/0/4 0000000003 Up 24s L2 --
rtr2.lab01.none GE0/0/24 0000000004 Up 24s L2 --
sense
rtr2.lab01.efgh GE0/0/5 0000000003 Up 24s L2 --
"""
lines = text.rstrip().split('\n')[2:]
n_lines = len(lines)
current_line = -1
def get_next_line():
# Actual implementation would be reading from a file and yielding lines one line at a time
global n_lines, current_line, lines
current_line += 1
# return special sentinel if "end of file"
return lines[current_line] if current_line < n_lines else '$'
def get_system_id():
line = None
while line != '$': # loop until end of file
if line is None: # no current line
line = get_next_line()
if line == '$': # end of file
return
m = re.search(r'^([a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9])', line)
id = m[1]
line = get_next_line() # might be sentinel
if line != '$' and re.match(r'^[a-zA-Z0-9]+$', line): # next line just single id?
id += line
line = None # will need new line
yield id
for id in get_system_id():
print(id)
Prints:
rtr1.lab01.something
rtr2.lab01.somethingelse
rtr2.lab01.abcd
rtr2.lab01.nonesense
rtr2.lab01.efgh
See Python Demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60319624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: System.IO.File.Delete throws "The process cannot access the file because it is being used by another process" Every time I save a file and delete it right away using the function below, I keep getting this error message: "System.IO.IOException: The process cannot access the file because it is being used by another process".
Waiting for a couple of minutes or closing visual studio seems to only unlock the files that you uploaded previously.
public static bool DeleteFiles(List<String> paths)
{ // Returns true on success
try
{
foreach (var path in paths)
{
if (File.Exists(HostingEnvironment.MapPath("~") + path))
File.Delete(HostingEnvironment.MapPath("~") + path);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
I think that the way I'm saving the files may cause them to be locked. This is the code for saving the file:
if (FileUploadCtrl.HasFile)
{
filePath = Server.MapPath("~") + "/Files/" + FileUploadCtrl.FileName;
FileUploadCtrl.SaveAs(filePath)
}
When looking for an answer I've seen someone say that you need to close the streamReader but from what I understand the SaveAs method closes and disposes automatically so I really have no idea whats causing this
A: After some testing, I found the problem. turns out I forgot about a function I made that was called every time I saved a media file. the function returned the duration of the file and used NAudio.Wave.WaveFileReader and NAudio.Wave.Mp3FileReader methods which I forgot to close after I called them
I fixed these issues by putting those methods inside of a using statement
Here is the working function:
public static int GetMediaFileDuration(string filePath)
{
filePath = HostingEnvironment.MapPath("~") + filePath;
if (Path.GetExtension(filePath) == ".wav")
using (WaveFileReader reader = new WaveFileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
else if(Path.GetExtension(filePath) == ".mp3")
using (Mp3FileReader reader = new Mp3FileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
return 0;
}
The moral of the story is, to check if you are opening the file anywhere else in your project
A: I think that the problem is not about streamReader in here.
When you run the program, your program runs in a specific folder. Basically, That folder is locked by your program. In that case, when you close the program, it will be unlocked.
To fix the issue, I would suggest to write/delete/update to different folder.
Another solution could be to check file readOnly attribute and change this attribute which explained in here
Last solution could be using different users. What I mean is that, if you create a file with different user which not admin, you can delete with Admin user. However, I would definitely not go with this solution cuz it is too tricky to manage different users if you are not advance windows user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73332282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Infer typescript function arguments Given the following
const action1 = (arg1: string) => {}
const action2 = (arg1: string, arg2: {a: string, b: number}) => {}
const actions = [action1, action2]
handleActions(actions)
... elsewhere ...
const handleActions = (actions: WhatTypeIsThis[]) => {
const [action1, action2] = actions;
action1(/** infer string */)
action2(/** infer string and object */)
}
How can I define the WhatTypeIsThis type in order for the action args to be inferable inside handleActions?
Is it possible to define it in such a way that actions can be any number of functions with varying argument lists?
Is it possible using generics?
My solution:
I've marked the accepted answer because it was the inspiration for my solution.
// get the types of the actions, defined in outer scope
type GET = typeof api.get;
type CREATE = typeof api.create;
...
// in controller
handleActions([api.getSomething, api.create])
...
// in service handler
const handleActions = (actions: [GET, CREATE]) => {
const [action1, action2] = actions;
// now we have all input / output type hints
}
This approach lets me isolate my logic from the http server, auth, and everything else I didn't write, so I can test the complexity within my service handlers in peace.
A:
Is it possible to define it in such a way that actions can be any number of functions with varying argument lists?
With a dynamic list, you need runtime checking. I don't think you can do runtime checking on these functions without branding them (I tried doing it on length since those two functions have different lengths, but it didn't work and it really wouldn't have been useful even if it had — (arg1: string) => void and (arg1: number) => void are different functions with the same length).
With branding and a runtime check, it's possible:
*
*Define branded types for the functions
*Create the functions
*Define the action list as an array of a union of the function types
*Have handleActions branch on the brand
Like this:
type Action1 = (
(arg1: string) => void
) & {
__action__: "action1";
};
type Action2 = (
(arg1: string, arg2: {a: string, b: number}) => void
) & {
__action__: "action2";
};
const action1: Action1 = Object.assign(
(arg1: string) => {},
{__action__: "action1"} as const
);
const action2: Action2 = Object.assign(
(arg1: string, arg2: {a: string, b: number}) => {},
{__action__: "action2"} as const
);
const actions = [action1, action2];
type ActionsList = (Action1 | Action2)[];
const handleActions = (actions: ActionsList) => {
const [action1, action2] = actions;
if (action1.__action__ === "action1") {
action1("x"); // <==== infers `(arg: string) => void` here
}
};
handleActions(actions);
Playground link
Before you added the text quoted at the top of the answer, it was possible with a readonly tuple type. I'm keeping this in the answer in case it's useful to others, even though it doesn't apply to your situation.
Here's what that looks like:
type ActionsList = readonly [
(arg1: string) => void,
(arg1: string, arg2: { a: string; b: number; }) => void
];
To make it readonly, you'll need as const on actions:
const actions = [action1, action2] as const;
// ^^^^^^^^^
A tuple is a kind of "...Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions." (from the link above)
Playground link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70015815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python Selenium CAN't scroll down users anymore browser.execute_script("""
var scrollt = document.querySelector('div[role="dialog"] ._aano')
scrollt.scrollTop = scrollt.scrollHeight
""")
This code for scrolling down a user followers at instagram is not working anymore.
I made it for a python selenium instagram code and after i access the user followers, on a pop up winddow, instagram changed something and this broke up :(
Any recomendation?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74048819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using Trusted Web Activity to link multiple websites with native application I've managed to link my native application to a website and launch the same on a button click. As the website is trusted, the URL bar is not visible. In the launched website there is a button which then further redirects to another website. I've created a digital asset link for both and have added the JSON file in <websitename>/.well-known/<json-file>.
Both the websites have also been referenced in strings.xml under
asset_statements. However, on launching the first website and then redirecting to the second website from the first, the second website launches as a regular custom chrome tab with the URL bar visible.
Is it possible to hide both the URL's? If so, how?
A: To enable multi-domain, you need to check 3 things
*
*Each origin has a .well-known/assetlinks.json file
*The android asset_statements contains all origins
*Tell the Trusted Web Activity about additional origins when launching.
It seems you have the first two points covered, but not the last one.
Using the support library LauncherActivity:
If using the LauncherActivity that comes with the library, you can provide additional origins by updating the AndroidManifest:
*
*Add a list of additional origins to res/values/strings.xml:
<string-array name="additional_trusted_origins">
<item>https://www.google.com</item>
</string-array>
*Update AndroidManifest.xml:
<activity android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"
android:label="@string/app_name">
<meta-data
android:name="android.support.customtabs.trusted.ADDITIONAL_TRUSTED_ORIGINS"
android:resource="@array/additional_trusted_origins" />
...
</activity>
Using a custom LauncherActivity
If using your own LauncherActivity, launching with additional origins can implemented like this:
public void launcherWithMultipleOrigins(View view) {
List<String> origins = Arrays.asList(
"https://checkout.example.com/"
);
TrustedWebActivityIntentBuilder builder = new TrustedWebActivityIntentBuilder(LAUNCH_URI)
.setAdditionalTrustedOrigins(origins);
new TwaLauncher(this).launch(builder, null, null);
}
Resources:
*
*Article with more details here: https://developers.google.com/web/android/trusted-web-activity/multi-origin
*Sample multi-origin implementation: https://github.com/GoogleChrome/android-browser-helper/tree/master/demos/twa-multi-domain
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62576723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: my caption on my image goes out of position each time i uses $.(class).loaded(); i have a thumbnail image, on hover it will transit out the caption.
HTML
<div class="img_thumb_holder float-l">
<img class="img_thumb" src="image/image1.jpg" alt="portfolio">
<h2 class="caption">jane<br />Featured Portfolio1</h2>
</div>
CSS
.caption{
height:90px;
margin:0px;
margin-left:-30px;
}
.container .img_thumb_holder h2 span {
color: white;
font: bold 20px/30px Helvetica, Sans-Serif;
letter-spacing: -1px;
padding: 10px;
}
.container .img_thumb_holder h2 span.spacer {
padding:0 5px;
}
JS
$(function() {
$("h2")
.wrapInner("<span>")
$("h2 br")
.before("<span class='spacer'>")
.after("<span class='spacer'>");
});
i am using ajax to load 3 different pages, all are showing thumbnails, and this code is shared among 3 pages, but each time i $.load another page my caption position will be off, the more pages i load, the more it goes off. Any idea?
A: It's hard to see without getting a look on the complete code. But every time your JS runs, you wrap every h2 element with a span. And then for every br-tag that is inside a h2-tag, it adds spans before and after.
A more robust way to do this would be to have the captions already in place and and with the correct CSS. But the captions are hidden (display:none;). Then you can load your data in to them and just do $(".caption").show(); on completion/success of your ajax callback.
Good luck :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26904644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF Button Command not firing, what am I missing? I feel bad posting this because I see a ton of similar posts, but after going through them all I can't quite diagnose my issue still. What I have is a WPF app designed with the MVVM pattern and using a RelayCommand() implementation for commands.
In my user control's XAML I set the data context here :
<UserControl.DataContext>
<viewModel:SidePanelViewModel />
</UserControl.DataContext>
Then further down in the XAML I have this snippet where I assign a button's command
<TextBlock FontWeight="Bold" Margin="0,0,0,10">Service List</TextBlock>
<ListBox MaxHeight="100"
ItemsSource="{Binding ServiceList}"
SelectedItem="{Binding ServiceToRemove}">
</ListBox>
<Button HorizontalAlignment="Left" Width="60" Margin="0,10"
Command="{Binding RemoveServiceCommand}">Remove</Button>
I am binding the button to the Command RemoveApplicationCommand which I define in the SidePanelViewModel here :
public ICommand RemoveServiceCommand
{
get { return new RelayCommand(RemoveService, CanRemoveService); }
}
private void RemoveService()
{
ServerList.Remove(ServiceToRemove);
}
private bool CanRemoveService()
{
return true;
}
The problem
If I debug, the getter for RemoveServiceCommand will be reached when the button starts up, but when I click the button the code doesn't reach it. I had a very similar implementation (or so I think) working before, so this is really puzzling me. How can I get the command to fire on click?
A: Command="{Binding RemoveApplicationCommand}"
Did you mean RemoveServiceCommand?
A: Turns out the debugger was going over RemoveService the entire time but I had not put a breakpoint there. I had a wrong name in my RemoveService implementation ServerList.Remove() should have been ServiceList.Remove(). I assumed the debugger would hit a breakpoint in the RemoveServiceCommand property's getter but it turns out it doesn't hit that when you click the button.
A: You're returning a new RelayCommand in your getting, but not saving / caching the instance. Save it in a member variable.
if (_cmd == null)
_cmd = new ....
return _cmd;
A: Try implementing like this
private ICommand finishCommand;
public ICommand FinishCommand
{
get
{
if (this.finishCommand == null)
{
this.finishCommand = new RelayCommand<object>(this.ExecuteFinishCommand, this.CanExecutFinishCommand);
}
return this.finishCommand;
}
}
private void ExecuteFinishCommand(object obj)
{
}
private bool CanExecutFinishCommand(object obj)
{
return true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32059694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to view hidden files in Nautilus in Debian 9 I'm getting up and running with Debian 9, but can't find a way to view hidden files (files that begin with a period) in folders via the default Debian file manager. With Ubuntu it was as simple as checking a box in the Nautilus preferences, but I can't find that option in Debian 9:
Note: Please don't answer that I should use ls -a, i want to be able to quickly see hidden files in the GUI. Also, I'd prefer not to completely change my file manager to, say, KDE. thanks!
A: Just click (ctr+h) on keyboard.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46305566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Decompile an executable file made by old Macromedia Director 7? The original question:
Now I am trying to extract the resources from this exe file made by old Macromedia Director 7, but I am in trouble.
First, I have tried the way of loading temp files, but they are inside Xtras folder and I also cannot find a way to open those .x32 files. And these .x32 files seem cannot be opened by the Director nowdays or other programs like Authorwave that I have downloaded. I have also tried MX2004, but it fails again. Are the media information coded inside these .x32 files?
Second, I tried using app like Reshacker or Muitextractor but neither of them can load the pictures inside.
I found one Adobe's technical document but not sure if it is useful to my question link. According to it, Win 95, NT and Win3.1 was the environment at that time. I am sure this exe was made by Macromedia Director 7 in Year 1999, as the file inforamtion tells me.Here is the screenshot of the file info.And it is shown as Director Player when I right click it on the task bar.
So, any tips on how to extract the resources I want???
If it is possbile, what are the softwares I need ? Really want to get the pictures inside.
A: If you're still looking to get the images from the Director .exe,(a Projector I presume?), you might be able to use a converter such as http://swftools.sourceforge.net/exe-to-swf.html which may end up porting the media to a folder. I suggest going down that route. Also try the unofficial Director communities if they are still active http://www.deansdirectortutorials.com/
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54787383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installing node once only and not each time with Maven build I need one help .
I am using grunt for compiling CSS/JS
I have an issue that my node package is getting created with each build and it is taking a lot of space in Jenkins . I am using maven front end plugin for the same .
I want that node package gets only created once initially and not again with each maven build .
<id>grunt</id>
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.26</version>
<!-- optional -->
<configuration>
<workingDirectory>DIR
</workingDirectory>
<nodeVersion>v4.2.1</nodeVersion>
<npmVersion>3.5.1</npmVersion>
<installDirectory>node</installDirectory>
</configuration>
<executions>
<execution>
<id>node and npm install</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
<installDirectory>node</installDirectory>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
<installDirectory>node</installDirectory>
</configuration>
</execution>
<execution>
<id>grunt build</id>
<goals>
<goal>grunt</goal>
</goals>
<configuration>
<arguments>build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
We are doing a build with maven -P grunt . It is creating and installing node with each maven build .
For having node globally I am trying maven -P grunt -g , but it is not working .
In the GitHub group , I saw people mentioning we can't do with maven frontend plugin , so I tried maven exec plugin .
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>prepare-dist-npm-runtime-dependency</id>
<phase>prepare-package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>node/node</executable>
<workingDirectory>dist</workingDirectory>
<arguments>
<argument>../node/npm/cli.js</argument>
<argument>install</argument>
<argument>--production</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
But I am not able to see it working . Can anyone help how to run maven to get it working for global node installation and not installing node with each build ?
If any other suggestion to have node installed only once and not globally will be grateful .
A: You can't install Node or NPM globally with the Frontend maven plugin. If we take a look at the documentation we'll see that the entire purpose of the plugin is to be able to install Node and NPM in an isolated environment solely for the build and which does not affect the rest of the machine.
Node/npm will only be "installed" locally to your project. It will not
be installed globally on the whole system (and it will not interfere
with any Node/npm installations already present.)
Not meant to replace the developer version of Node - frontend
developers will still install Node on their laptops, but backend
developers can run a clean build without even installing Node on their
computer.
Not meant to install Node for production uses. The Node usage is
intended as part of a frontend build, running common javascript tasks
such as minification, obfuscation, compression, packaging, testing
etc.
You can try to run the plugin with two different profiles, one for install and one for day-to-day use after installation. In the below example, you should be able to install Node and NPM by running:
mvn clean install -PinstallNode
Then every build after:
mvn clean install -PnormalBuild
Or because normalBuild is set to active by default, just:
mvn clean install
Notice install goals are not in the day-to-day profile:
<profiles>
<profile>
<id>installNode</id>
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.26</version>
<!-- optional -->
<configuration>
<workingDirectory>DIR</workingDirectory>
<nodeVersion>v4.2.1</nodeVersion>
<npmVersion>3.5.1</npmVersion>
<installDirectory>node</installDirectory>
</configuration>
<executions>
<execution>
<id>node and npm install</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
<installDirectory>node</installDirectory>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
<installDirectory>node</installDirectory>
</configuration>
</execution>
<execution>
<id>grunt build</id>
<goals>
<goal>grunt</goal>
</goals>
<configuration>
<arguments>build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>normalBuild</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.26</version>
<!-- optional -->
<configuration>
<workingDirectory>DIR</workingDirectory>
<nodeVersion>v4.2.1</nodeVersion>
<npmVersion>3.5.1</npmVersion>
<installDirectory>node</installDirectory>
</configuration>
<executions>
<execution>
<id>grunt build</id>
<goals>
<goal>grunt</goal>
</goals>
<configuration>
<arguments>build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38066685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: The issuer of the token is not a trusted issuer Sharepoint Provider Hosted App I created an app by using the following tutorial:
http://www.luisevalencia.com/2014/07/23/prepare-environments-sharepoint-provider-hosted-apps/
The app works perfectly if there are no sharepoint calls, I meant a response.write with hello world works.
But, if I add some sharepoint stuff like printing out the name of the user, I got a The remote server returned an error: (401) Unauthorized.
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
Response.Write(clientContext.Web.Title);
Response.Write("Hello World");
}
I get the following error on the logs.
SPApplicationAuthenticationModule: Failed to authenticate request, unknown error. Exception details: System.IdentityModel.Tokens.SecurityTokenException: The issuer of the token is not a trusted issuer.
at Microsoft.SharePoint.IdentityModel.SPTrustedIssuerNameRegistry`1.GetIssuerName(SecurityToken securityToken, String requestedIssuerName)
at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.GetIssuerNameFromIssuerToken(JsonWebSecurityToken token)
at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.GetIssuerName(JsonWebSecurityToken token)
at Microsoft.IdentityModel.S2S.Tokens.JsonWebSecurityTokenHandler.ValidateTokenCore(SecurityToken token, Boolean isActorToken)
at Microsoft.IdentityModel.S2S.Tokens.JsonWebSecurityTokenHandler.ValidateTokenCore(SecurityToken token, Boolean isActorToken)
at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.TryExtractAndValidateToken(HttpContext httpContext, SPIncomingTokenContext& tokenContext)
at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.ConstructIClaimsPrincipalAndSetThreadIdentity(HttpApplication httpApplication, HttpContext httpContext, SPFederationAuthenticationModule fam)
at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.AuthenticateRequest(Object sender, EventArgs e)
A: Do you have the SharePointContextFilterAttribute on the method? That filter handles the authentication bits from the request context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24913211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run Cypress tests in parallel using a single machine on Jenkins? So I have around 45 spec files that I want to execute in parallel on a single machine on Jenkins.
If I create a freestyle job on Jenkins and run this command "npx cypress run --record --key abc --parallel" it executes sequentially.
Do I need to set up nodes on Jenkins, in order to do parallel execution using this command? I am not able to find how exactly I can do that and I have tried various configurations but it still runs sequentially despite the "--parallel"
How do I specify how many threads I can execute it on? Or is that decided automatically by the number of machines? In my case, I can only do this using my single machine and local Jenkins.
Creating a pipeline and passing parallel{} in the stage as mentioned here is not working either so I don't know what I'm doing wrong.
Can someone please share a sample pipeline format for parallel Cypress test execution along with a guide to how nodes are created on Jenkins? Please tell me what additional steps I need to do as well. Thanks in advance
A: You will have to execute multiple cypress runners in order for Cypress to actually run in parallel. If you only have one npx cypress run command, then only one runner is being used.
I've found the easiest way to run multiple cypress runners is to use npm-run-all.
Assuming my script in my package.json is cypress-tests, my npm-run-all script to run the tests with three runners would be:
npm-run-all cypress-tests cypress-tests cypress-tests --parallel
Note: the --parallel flag here tells npm-run-all to run your commands in parallel. If the corresponding cypress flag is removed, your tests will not run in parallel (instead, npm-run-all will run two cypress runners in parallel, but each running your entire suite.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73691733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP access control list for hiding links I need to make a system in PHP which will use several links on the homepage but not all user are allowed to see these depending on which group of user logs in:
*
*Guests - may write something in the guestbook but may not alter them
*Employees - may create guests and see their booking and alter the guestbook
*Managers - they may have every link that's available.
But the links may not be scattered and must be contained to the homepage and must be hidden if you're not in the right group.
Can someone give an example of how something like this can be accomplished within PHP or send me in the right direction?
A: What you are looking for is often refered to as AC (access control). One of the most popular is an RBAC (role based access control) because it allows you to group your users/accounts into groups and give those groups certain privileges.
Let's go through the design steps of a minimal setup:
Basically what you are saying is, that you have some sort of accounts already for your users (except Guest, because that is a not-logged-in-user)
Now what the roles in RBA are, are basically groups that have or don't have certain privileges.
So that results in the following Relations:
*
*Zero to many Accounts belong to zero to many Roles (->group e.g. "Admin", "Manager", etc.)
*Zero to many Roles have zero to many privileges / rights (e.g. "Access the manager section" or "Update this record")
Now let's move on, what data for what part of that system you need to have in order to implement it
*
*Typically you have an ID on your account table for each account.
*Roles typically have an ID and a name.
*Privileges typically have at least a constant-like identifier (which should be the primary key, so that it's unique --- for example ACCESS_MANAGER - You can see why this is usefull in my code example below. It can be used to lookup ) and a name
That leads to the following tables:
Account(AccountID (PK), ...)
Account_Role(AccountID (PK, FK), RoleID (PK, FK))
Role(RoleID (PK), name)
Role_Privilege(RoleID (PK, FK), PrivilegeID (PK, FK));
Privilege(identify (PK), name)
Now you can manage roles and privileges these roles have.
If you want to check, if the current user has a specific privilege you can ask your DB, for example.
if(
$this
->getCurrentUser() //would return a dummy guest user with no roles assigned if no user is logged in
->hasPrivilege('ACCESS_MANAGER') //joins account via account_role to role to role_privilege and finally to privilege
) { /*display only links a manager would see*/ }
if($this->getCurrentUser()->hasPrivilege('ACCESS_ADMIN')) { /*display only links an admin would see*/ }
PS: The wiki articles provided are very theoretical. You might want to just google for queries like "php access control system" or similar to get you started with solutions others have come up with.
A: Give each user a number to identify what category they belong to. For example guests would be 1, employees would be 2 and managers would be 3. Then when they log in you store this inside a session.
To display a link for any given category you can do this. Just change the number for each category.
<?php if( $_SESSION[ 'user' ][ 'category' ] == 3 ) : ?>
<a href="www.google.co.uk">Link for a manager</a>
<?php endif; ?>
A: Assuming you have user roles set up already and some sort of class you can easily do this by:
if($users->role($userid) == "some role") //can be int or string which ever way you set it up
{
echo "a href='somelink.php'> Click to access</a>";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21432139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to know the value of input password field? Given a page with the following element:
<input name="my_field" type="password">
Obviously, I see only the dots in the browser. Is there a way to fetch the value from the developer console?
A: This will work for you
document.getElementsByName('my_field')[0].value
A: You may try this:
document.getElementsByName('my_field')[0].value
A: You can also do
document.getElementsByName("my_field")[0].type = "text"
Which will make the password field cleartext.
But the shortest way is to this is: Right click to the password field, click Inspect Element, find the type="password" and make it type="text"
Last one requires minimum time and typing, but the rest works too
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25464947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Having trouble with writing a simple python password reset code sample I'm new to Python and trying to wirte a simple password reset code sample to learn about sets, dictionaries, and exception handlers. To reset a password, the program must first take in both the student_id and user_id and confirms their ID against the list. If the student_id and user_id match, it will prompt the user for their admission term as an extra security measure. If all things match, the program will greet the user by name and prompt their to enter their new password. The new password cannot match any of the user's previous passwords. The program should not quit until the user asks to quit or successfully logs in (note, resetting the password should not be the end and we may give the user a "quit" option if they decide they do not want to change their password.).
The program should run similar to the following:
1. Login
2. Reset Password
3. Quit
What would you like to do? 1
User Name: afrank
Password: xyz123
Login Success!
------------------------------------------------
1. Login
2. Reset Password
3. Quit
What would you like to do? 1
User Name: afrank
Password: xyz1234
Incorrect Password
1. Login
2. Reset Password
3. Quit
What would you like to do? 3
------------------------------------------------
1. Login
2. Reset Password
3. Quit
What would you like to do? 2
Student ID: 392111111
User Name: afrank
What year were you admitted? 2018
New Password: abc456
Confirm New Password: abc456
Password Changed!
1. Login
2. Reset Password
3. Quit
What would you like to do? 3
------------------------------------------------
1. Login
2. Reset Password
3. Quit
What would you like to do? 2
Student ID: afrank
Error! Please enter your Student ID Number.
Student ID: 39211111x
Error! Please enter your Student ID Number.
Student ID: 39211111111
Error! Student ID Not Found
Student ID: 392111111
User Name: afrank
What year were you admitted? 2018
New Password: abc456
Confirm New Password: abc456
Password Changed!
1. Login
2. Reset Password
3. Quit
What would you like to do? 3
------------------------------------------------
1. Login
2. Reset Password
3. Quit
What would you like to do? 2
Student ID: 392111111
User Name: afrank
What year were you admitted? 2018
New Password: 123abc
Confirm New Password: 123abc
Error. Your password cannot be a previously used password.
New Password: abc456
Confirm New Password: abc456
1. Login
2. Reset Password
3. Quit
What would you like to do? 1
User Name: afrank
Password: abc456
Login Success!
I worte a few pieces but I have no idea how to continue:
idfile = open('student_password.csv', 'r') ## Read in Current File
header = idfile.readline()
allobs = idfile.readlines()
namedict = {}
userdict = {}
termdict = {}
pwdict = {}
p_pwdict = {}
for obs in allobs:
obslist=obs.split(",")
namedict2 = {int(obslist[0]): (obslist[1], obslist[2])}
userdict2 = {int(obslist[0]): obslist[3]}
termdict2 = {int(obslist[0]): int(obslist[4])}
pwdict2 = {int(obslist[0]): obslist[5]}
p_pwdict2 = {int(obslist[0]): obslist[6].replace('\n', '')}
namedict.update(namedict2)
userdict.update(userdict2)
termdict.update(termdict2)
pwdict.update(pwdict2)
p_pwdict.update(p_pwdict2)
idfile.close()
result = input(' 1. Login \n 2. Reset Password \n 3. Quit \n What would you like to do? \n ')
if result == '1':
...
A: This is not a real code. A real login code should include a lot more, like securing channels, ecryption, etc.
As an exercise to try a few concepts it's ok.
I see you are expecting to save everything to a file, I suggest you to try with logical structures first.
There is always messing with opened files not being able to be updated and the like.
Another recommendation is to keep distinct functions to distinct funcionalities, is easier to maintain and to debug.
I see a perfect use for dictionary, with key (login) and value (password).
Would be good to create a class and put options_menu() in main function.
dict_logs = {'afrank':'xyz123','lcroft':'xpto0007','happy_bird':'123abc'}
#check name and password are in a dictionary
def hello_login():
isUser = False #start as False
print('What is your user name?')
user = str(input())
for u,p in dict_logs.items():
if u == user:
dictpass = p
isUser = True
if isUser:
print('Enter password')
password = str(input())
if dictpass == password:
print('Login Success!')
else:
print('Error: wrong password')
options_menu()
else:
print('Error: wrong user name')
options_menu()
user_info = {392111111:['afrank',2018],392111131:['lcroft',2018],392113005:['happy_bird',2019]}
# check if information is in a dictionary and updates another dict
def reset_password():
isUser = False #start as False
changed = False #start as False
print('What is your student ID?')
sid = int(input())
for ui,data in user_info.items():
if ui == sid:
checksOn = data
isUser = True
if isUser:
print('What is your user name?')
uname = str(input()) #accept parameter user_name
if checksOn[0] == uname:
print('What year were you admitted?')
year = int(input()) #accept parameter year of admission
if checksOn[1] == year:
while not changed: #loop if changed not True
print('Enter a new password')
newPass = str(input()) #accept parameter password
if dict_logs[uname] != newPass: #must be distinct of saved password
print('Confirm password')
confPass = str(input())
if confPass == newPass: #confirmation ok
dict_logs.update({uname:confPass})
changed = True
print('Password changed!')
else:
print('Error:passwords are distincts!')
else:
print('Error. Your password cannot be a previously used password.')
else:
print('Error. Year of addmission is wrong')
else:
print('Error. User name is wrong')
else:
print('Error! Please enter your Student ID Number')
# menu of options
def options_menu():
print('1. Login'+'\n'+'2. Reset Password'+'\n'+'3. Quit'+'\n'+'What would you like to do?')
option = int(input())
if option == 1:
hello_login()
elif option == 2:
reset_password()
elif option == 3:
pass
A: Ok so quick disclaimer all the code in this is sudo code and is for example to give you the idea of my train of thought.
So that out of the way I see your problems as the following.
*
*User Input (Actions)
*DataBase Handling
If I am correct on this I would suggest that you take the following approach.
*
*Take care of the Database, by writing a class to handle the getting and setting of specific user in an out of the database that you are using and into a dictionary or any other data structure allows you to forget the structure of the underlying csv etc and will make you actions clearer and simpler later on. something like below would do the trick.
class UserDataBase(object):
def __init__(self):
self.database = db
def get_user(self, username) -> dict:
return {"Joe": {"password": "uber_secret"}}
def set_user(self, username, user_obj: dict) -> None:
db[username] = user_obj
*Next it would be time to take care of the user input, again this should be an object that would define and execute the actions that you define in your use cases.
class Actions(object):
def __init__(self, database):
self.database = UserDataBase()
def login(self, username, password) -> bool:
if self.database.get_user(username) == password:
return True
return False
def reset_password(self, old_password, new_password, confirmed_password) -> bool:
reset_code
def quit(self):
quit()
This would then leave you with two objects that you can tie together to get anything that you want to do done more simply.
def get_input():
actions = Actions(
database=UserDataBase()
)
i = input(' 1. Login \n 2. Reset Password \n 3. Quit \n What would you like to do? \n ')
if i == 1:
actions.login(username=input('username: '), password=input('password: '))
get_input()
if you have any specific questions about this approach please let me know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58909845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Having trouble with RBT tree and using methods on Node class So for class, I was given and RBT class that has a node class within in it. This node class was originally made generic, but I made it so it took the type StudentData. This StudentData class has getter and setter methods, along with a constructor for two fields: a string "name" and a double "grade." (StudentData (double grade, String name) { this.grade = grade; this.name = name; })
In my RBT class, we have a constructor in the node class that initializes a field of StudentData data to equal the parameter passed through which is StudentData data. (public Node(StudentData data) { this.data = data; this.isBlack = false;})
The problem I am running into is that I want the tree to insert based on the grade, not the overall object. So I tried using node.data.getGrade() and node.getGrade(), but it continues saying "the method getName() is undefined for the type StudentData" and has a quickfix of "add cast to node.data"
What exactly is the issue here? My student class DOES have the method .getGrade().
A: It's difficult to answer without a minimal working example. I'm going to give it a shot. Based on what you wrote the inference is you have the following. Forget for a moment that it's red-black, that detail doesn't really matter for this problem. With just a regular BST you have:
class Test<T extends Comparable<T>> {
class Node<T> {
T data;
Node<T> left;
Node<T> right;
Node(T data) {
this.data = data;
}
}
Node<T> search(Node<T> root, T data) {
if (root == null || root.data == data || root.data.equals(data)) {
return root;
}
if (root.data.compareTo(data) < 0) {
return search(root.right, data);
}
return search(root.left, data);
}
// etc ...
}
Looking at just the search method, you need to compare the whole data object.
Now throw a StudentData class into the mix. It has to implement Comparable otherwise you have no way of comparing it to another StudentData with a generic as just defined.
class StudentData implements Comparable<StudentData> {
final String name;
final double grade;
StudentData(String name, double grade) {
this.name = name;
this.grade = grade;
}
@Override
public int compareTo(StudentData o) {
return Double.compare(this.grade, o.grade);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StudentData that = (StudentData) o;
return Double.compare(that.grade, grade) == 0 && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, grade);
}
}
Note that here we can compare based on the grade because it's defined right within the student data class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69961868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I isolate a single value from a list within an awk field? Lets say i have a file called test and in this file contains some data:
jon:TX:34:red,green,yellow,black,orange
I'm trying to make it so it will only print the 4th field up until the comma and nothing else. But I need to leave the current FS in place because the fields are separated by the ":". Hope this makes sense.
I have been running this command:
awk '{ FS=":"; print $4 }' /test
I want my output to look like this.
jon:TX:34:red
or if you could even just figure out how i could just print the 4th field would be a good help too
red
A: It's overkill for your needs but in general to print the yth ,-separated subfield of the xth :-separated field of any input would be:
$ awk -F':' -v s=',' -v x=4 -v y=1 '{split($x,a,s); print a[y]}' file
red
A: Or
awk -F '[:,]' '{print $4}' test
output
red
A: It sounds like you are trying to extract the first field of the fourth field. Top level fields are delimited by ":" and the nested field is delimited by ",".
Combining two cut processes achieves this easily:
<input.txt cut -d: -f4 | cut -d, -f1
If you want all fields until the first comma, extract the first comma-delimited field without first cutting on colon:
cut -d, -f1 input.txt
A: if you want a purely regex approach :
echo 'jon:TX:34:red,green,yellow,black,orange' |
mawk NF=NF FS='.+:|,.+' OFS=
red
if you only want "red" without the trailing newline ("\n"), use RS/ORS instead of FS/OFS — (the % is the command prompt, i.e. no trailing \n):
mawk2 8 RS='.+:|,.+' ORS=
red%
if u wanna hard-code in the $4 :
gawk '$_= $4' FS=,\|: # gawk or nawk
mawk '$!NF=$4' FS=,\|: # any mawk
red
and if you only want the non-numeric text :
nawk NF=NF FS='[!-<]+' OFS='\f\b'
jon
TX
red
green
yellow
black
orange
A: If you have
jon:TX:34:red,green,yellow,black,orange
and desired output is
jon:TX:34:red
then just treat input as comma-separated and get 1st field, which might be expressed in GNU AWK as
echo "jon:TX:34:red,green,yellow,black,orange" | awk 'BEGIN{FS=","}{print $1}'
gives output
jon:TX:34:red
Explanation: I inform GNU AWK that , character is field separator (FS), for each line I print 1st column ($1)
(tested in GNU Awk 5.0.1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75088932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL - How to find records for yesterday when timestamp is part of date My MySQL table stores records with a date/time stamp. I am wanting to find records from the table that were created yesterday (as in have a creation date of yesterday - regardless of what the timestamp portion is)
Below is what a db record looks like:
I have tried the following select (and a few other variations, but am not getting the rows with yesterday's date.
SELECT m.meeting_id, m.member_id, m.org_id, m.title
FROM meeting m
WHERE m.create_dtm = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
Not exactly sure how I need to structure the where clause to get meeting ids that occurred yesterday. Any help would be greatly appreciated.
A: A naive approach would truncate the creation timestamp to date, then compare:
where date(m.create_dtm) = current_date - interval 1 day
But it is far more efficient to use half-open interval directly against the timestamp:
where m.create_dtm >= current_date - interval 1 day and m.create_dtm < current_date
A: You can try next queries:
SELECT
m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm
FROM meeting m
-- here we convert datetime to date for each row
-- it can be expensive for big table
WHERE date(create_dtm) = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
SELECT
m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm
FROM meeting m
-- here we calculate border values once and use them
WHERE create_dtm BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE_SUB(CURDATE(), INTERVAL 1 SECOND);
Here live fiddle: SQLize.online
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64211422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cannot invoke remote function inside match : Foreach loop I'm trying to set some property of User model inside a for-each loop, But I keep getting following error
cannot invoke remote function x.token/0 inside match
(elixir) src/elixir_fn.erl:9: anonymous fn/3 in :elixir_fn.translate/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(elixir) src/elixir_fn.erl:14: :elixir_fn.translate/3
Method:
Enum.each(users, fn(user) ->
user.token = Comeonin.Bcrypt.hashpwsalt(to_string(user.id))
end)
A: There are a few issues here. The = operator is the match operator, it is not assignment. To explain the error, syntax-wise, this looks like function invocation on the left hand side of a match, which is not allowed.
But this is besides the point of your actual goal. If you want a set of user models that are updated with the new bcrypt information, you need to use a map function:
users = Enum.map(users, fn %User{id: id}=user ->
%User{user| token: Comeonin.Bcrypt.hashpwsalt("#{id}")}
end)
You have to remember that everything in Elixir is immutable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35682499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Load sharedprefrence data to Textfield on page load flutter I have a shared data that contain mobile no of customer,in my profile,that need to be filled with in textfield when i open profile page,i'm getting the data from shard preference data,when i load data to textfield it's throws error
TextEditingController mobile = TextEditingController();
void initState() {
getMobile();
}
Get data From Sharedpreference
Future<String> getMobile() async {
Future notificatinstatus = SharedPrefrence().getUserMobile();
notificatinstatus.then((data) async {
var mobile_no=data;
mobile_no.text=mobile;
return mobile;
});
}
A: I think is better like this:
var mobileController = TextEditingController();
getMobile() async {
Future notificatinstatus = SharedPrefrence().getUserMobile();
notificatinstatus.then((data) async {
var mobile_no=data;
setState(() {
if(mobile_no.isNotEmpty){
mobileController.text = mobile_no;
}
});
});
}
@override
void initState() {
super.initState();
getMobile();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61815168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How merge list when combine two hashMap objects in Java I have two HashMaps defined like so:
HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();
Also, I have a 3rd HashMap Object:
HashMap<String, List<Incident>> map3;
and the merge list when combine both.
A: In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it.
However if it was also a HashMap<String, List<Incident>>. You could use the putAll method.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);
If you wanted to merge the lists inside the HashMap. You could instead do this.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
for(String key : map2.keySet()) {
List<Incident> list2 = map2.get(key);
List<Incident> list3 = map3.get(key);
if(list3 != null) {
list3.addAll(list2);
} else {
map3.put(key,list2);
}
}
A: create third map and use putAll() method to add data from ma
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
You have different type in question for map3 if that is not by mistake then you need to iterate through both map using EntrySet
A: Use commons collections:
Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);
If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map.
A: HashMap has a putAll method.
Refer this :
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17607850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Rotation animation for the background gradient of the view I want to add an animation to my app where I want the background gradient of my screen to rotate. I have tried a few things like ValueAnimator, PropertyAnimator etc but I am facing a problem.
When I run my animation the entire view starts rotating. It looks like the screen itself is rotating. Instead I want an effect where only the background gradient rotates not the entire screen.
What is the best way to get such effect?
Here is what I have so far
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val view: ConstraintLayout = findViewById(R.id.animation_view)
startAnimation(view)
}
private fun startAnimation(view: View) {
view.startAnimation(
AnimationUtils.loadAnimation(
this, R.anim.rotation_clockwise
)
)
}
}
animation resource xml
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"
android:duration="1200"/>
layout file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPurple_A400"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/animation_view"
android:background="@drawable/drawable_purple_gradient">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
A: Do you animate the root view of the activity or fragment?
If yes, that makes sense. The whole screen will be rotated.
If you want to animate the background of the view, you should add a new view which holds only the background then rotate it.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPurple_A400"
tools:context=".MainActivity">
<View
android:id="@+id/animation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/drawable_purple_gradient"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56311471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic table rows and columns I'd like to be able to add/remove rows/columns in my table but I don't how to achieve this given my knowledge in js/jquery is basic. I've search and seen related topics but none fits to what I wanted to happen.
As you can see in my code below I have 11 columns with the <th> tag and a default row and they must not be affected by remove. Also, when adding new column the PO increments like PO 10.
<table class="main-table" id="po-table" border="1">
<tbody>
<tr class="table-header">
<td>#</td>
<td>Course Code</td>
<td>Course Name</td>
<td>PO 1</td>
<td>PO 2</td>
<td>PO 3</td>
<td>PO 4</td>
<td>PO 5</td>
<td>PO 6</td>
<td>PO 7</td>
<td>PO 8</td>
<td>PO 9</td>
</tr>
<tr class="default-row">
<td>1</td>
<td><input type="text" name="course_code[]"></td>
<td><input type="text" name="course_name[]"></td>
<td><input type="checkbox" name="po1[]" value="Po1"></td>
<td><input type="checkbox" name="po2[]" value="Po2"></td>
<td><input type="checkbox" name="po3[]" value="Po3"></td>
<td><input type="checkbox" name="po4[]" value="Po4"></td>
<td><input type="checkbox" name="po5[]" value="Po5"></td>
<td><input type="checkbox" name="po6[]" value="Po6"></td>
<td><input type="checkbox" name="po7[]" value="Po7"></td>
<td><input type="checkbox" name="po8[]" value="Po8"></td>
<td><input type="checkbox" name="po9[]" value="Po9"></td>
</tr>
</tbody>
</table>
Picture of the output:
A: Add this to your body
http://www.redips.net/javascript/adding-table-rows-and-columns/
<button onclick="addRow()">Add Row</button>
<button onclick="addCol()">Add Column</button>
<button onclick="removeRow()">Remove Row</button>
<button onclick="removeCol()">Remove Column</button>
<script>
var table = document.getElementById("po-table");
function addRow() {
var lastrow = table.rows.length;
var lastcol = table.rows[0].cells.length;
var row = table.insertRow(lastrow);
var cellcol0 = row.insertCell(0);
cellcol0.innerHTML = "<input type='text' name='course_code[]'></input>";
var cellcol1 = row.insertCell(1);
cellcol1.innerHTML = "<input type='text' name='course_name[]'></input>";
for(i=2; i<lastcol;i++)
{
var cell1 = row.insertCell(i);
cell1.innerHTML = "<input type='checkbox' name='pos[]'></input>";
}
}
function addCol() {
var lastrow = table.rows.length;
var lastcol = table.rows[0].cells.length;
var headertxt = table.rows[0].cells[lastcol-1].innerHTML;
var headernum = headertxt.slice(headertxt.indexOf("PO")+2);
headernum = headernum.trim();
//for each row add column
for(i=0; i<lastrow;i++)
{
var cell1 = table.rows[i].insertCell(lastcol);
if(i==0)
cell1.innerHTML = "PO " + (Number(headernum)+1);
else
cell1.innerHTML = "<input type='checkbox' name='pos[]'></input>";
}
}
function removeRow(){
var lastrow = table.rows.length;
if(lastrow<2){
alert("You have reached the minimal required rows.");
return;
}
table.deleteRow(lastrow-1);
}
function removeCol(){
var lastcol = (table.rows[0].cells.length)-1;
var lastrow = (table.rows.length);
//disallow first two column removal unless code is add to re-add text box columns vs checkbox columns
if(lastcol<3){
alert("You have reached the minimal required columns.");
return;
}
//for each row remove column
for(i=0; i<lastrow;i++)
{
table.rows[i].deleteCell(lastcol);
}
}
</script>
A: You can just clone the current row and append it to the table with the following jQuery:
$(".default-row").clone().insertAfter(".default-row:last-child");
An example of it working is here: http://jsfiddle.net/05Lo1sm6/
A: For Dynamic creation of tables with respect to entered row and column, you can use this code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Table</title>
<script>
function createTable()
{
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
for(var r=0;r<parseInt(rn,10);r++)
{
var x=document.getElementById('myTable').insertRow(r);
for(var c=0;c<parseInt(cn,10);c++)
{
var y= x.insertCell(c);
y.innerHTML="Row-"+r+" Column-"+c;
}
}
}
</script>
<style type="text/css">
body {margin: 30px;}
</style>
</head><body>
<table id="myTable" border="1">
</table><form>
<input type="button" onclick="createTable()" value="Create the table">
</form></body></html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26845946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to change the queuing/stacking requests behaviour of Sanic Good day all
I'm tagging Sanic because that is what I'm using in my web app, but I'm not sure if this behaviour is due to Sanic or something underlying (like asyncio or even the network interface).
Please let me know if I need to write a quick example showing what I mean, my application is quite large so I can't share that here, but I think my problem is simple enough to explain.
I have a simple web application in Python using the Sanic framework. For my purposes, I actually need a server which is synchronous. As such, none of my endpoint functions are async, and I explicitly start my Sanic app with one worker.
This is because, when I send the server a number of requests, I need them to be performed in the order which they were sent.
However this does not happen.
Some of my requests take a lot of calculation, so they're not immediate. Meaning that consequent requests arrive while it is still processing.
In other words, imagine that I send 4 requests one after each other. Request 1 takes a few seconds to calculate, meaning that requests 2-4 arrive while request 1 is still being processed. What I want to happen is that requests are processed in order:
Request 1
Request 2
Request 3
Request 4
But what happens is that requests are processed out of order, in fact, after the first, it seems random:
Request 1
Request 3
Request 2
Request 4
So is there a way to force it to execute requests in order? Preferably at a high level (Sanic) ?
I've looked around but have not seen anyone talking about this behaviour. I suppose this is a rare case as my server is not RESTful and not stateless.
Any help is appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72882305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can i make 'individual' appended elements with onclick I keep getting stuck on this one little thing.
I append a checkbox and a remove button with an append button.
So every time the append button is clicked i get;
Checkbox and a remove button.
The remove button has to remove the checkbox.
My problem;
If i append a bunch of pairs, only the first pair seems to work :O !!
Thank you in advance
A: Make sure you are changing the name/id on the checkbox or you are using an array, for example
Checkbox 1 is named checkbox[1]
Checkbox 2 is named checkbox[2]
If they have the same name, they will only come through as 1 item in the POST/GET!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4339913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Initialization of for with char Can we use for loop in c++ as for(char ch : s) ? If yes then please explain it's meaning.
Where s is a string passed through argument .
A: Yes, you can. This is a "for each" loop. ch will have the value of each successive character in the string s.
A: This is named Range for loop and is a new syntax introduced in C++11.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51853756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: std::map initialization with a std::vector I want to initialize a std::map object with keys contained in a std::vector object.
std::vector<char> mykeys { 'a', 'b', 'c' ];
std::map<char, int> myMap;
How can I do that without a loop?
And can I add a default value to my int?
A: No, you cannot do that without a loop or equivalent construct. (full stop) You can hide the loop inside some functions, such as std::transform(), but not avoid it. Moreover, compilers are well trained to optimize loops (because they are ubiquotous), so there is no good reason to avoid them.
A: Without an explicit loop:
std::transform( std::begin(mykeys), std::end(mykeys),
std::inserter(myMap, myMap.end()),
[] (char c) {return std::make_pair(c, 0);} );
Demo.
A range-based for loop would be far more sexy though, so use that if possible:
for (auto c : mykeys)
myMap.emplace(c, 0);
A: You can not do this without a loop. What you can do is to hide a loop under a standard algorithm because you need to convert an object of type char to an object of type std::map<char, int>::value_type that represents itself std::pair<const char, int>
For example
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<char> v { 'a', 'b', 'c' };
std::map<char, int> m;
std::transform( v.begin(), v.end(), std::inserter( m, m.begin() ),
[]( char c ){ return std::pair<const char, int>( c, 0 ); } );
for ( const auto &p : m )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
return 0;
}
The output is
a 0
b 0
c 0
A: Using boost:
template<class Iterators, class Transform>
boost::iterator_range< boost::transform_iterator<
typename std::decay_t<Transform>::type,
Iterator
>> make_transform_range( Iterator begin, Iterator end, Transform&& t ) {
return {
boost::make_transform_iterator( begin, t ),
boost::make_transform_iterator( end, t )
};
}
A helper to map keys to pairs:
template<class T>
struct key_to_element_t {
T val;
template<class K>
std::pair< typename std::decay<K>::type, T > operator()(K&& k) const {
return std::make_pair( std::forward<K>(k), val );
}
};
template<class T>
key_to_element_t< typename std::decay<T>::type > key_to_element( T&& t ) {
return { std::forward<T>(t) };
}
template<class R>
struct range_to_container_t {
R r;
template<class C>
operator C()&& {
using std::begin; using std::end;
return { begin(std::forward<R>(r)), end(std::forward<R>(r)) };
}
};
template<class R>
range_to_container_t<R> range_to_container( R&& r ) { return std::forward<R>(r); }
after all that mess we get:
std::vector<char> mykeys { 'a', 'b', 'c' ];
std::map<char, int> myMap = range_to_container( make_transform_range( begin(mykeys), end(mykeys), key_to_element( 0 ) ) );
which constructs the std::map directly from a transformed sequence of elements in the mykeys vector.
Pretty silly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26606458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Three20 & XCode4: Unsupported compiler 'GCC 4.2' or Interface Declarations not found Over one Year ago I made a project in our company to work with Three20 and iOS3.1.3.
Up to 4.*, it worked fine with some iPhones. I had no need to correct anything or even recompile the package. Even later the Retina-Display of an iPhone4 did not make any problems.
Now on iOS5, the ipa didn´t work anymore. So I had to "re-setup" the whole thing.
iOS3 -> 5
XCode 3.2 -> 4.2
Three20 (old) -> 1.09 (downloaded the zip from here: https://github.com/facebook/three20)
After many tries, I wanted a clear state. So I deleted the old Three20-things in the project settings and simply integrated it like mentioned here:
http://three20.info/article/2011-03-10-Xcode4-Support
again.
Now I am getting:
Check dependencies
Unsupported compiler 'GCC 4.2' selected for architecture 'armv6'
Unsupported compiler 'GCC 4.2' selected for architecture 'armv7'
In former tries, I simply changed the compiler in each Three20-Module to the Apple LLVM 4.2 and removed all arm6-mentionings, as the oldest iPhone to use is now 3Gs with 5.0.1.
The 3G can use the old ipa, that worked formerly.
This only changed the errors to other ones.
So, is anyone expierienced with this problems?
Edit:
After I deleted all armv6-occurences, "surprisingly" only the second
Unsupported compiler 'GCC 4.2' selected for architecture 'armv7'
appears.. in principle no clue, BUT: build for archiving works and building for the simulator both work now. only i can not deploy a real iPhone 4 5.0.1.
A: I've seen this problem before with other projects. In my experience, xCode often struggles with old projects, especially big ones with other projects / frameworks linked in.
The 'official' way;
*
*try to compile the project.
*Navigate to the error by clicking the red exclamation mark in the central console. (upper-middle of the app)
*scroll down in the list to the left, find the red exclamation mark.
*click the project (blue icon, possible .xcodeproj extension) in the list to the left that's giving the error.
*go to 'Build settings'
*Find the 'Compiler for C/C++/Objective-C' setting in the 'Build Options' category.
*Change the compiler from GCC 4.2 to a supported one. (Now: Apple LLVM or LLVM GCC)
This approach might or might not work for you.
It might be my limited understanding, but it seems that in some cases, old settings 'linger' without begin accessible through the GUI, but they can still be causing problems. Moreover, if this error appears in a framework rather than a project, you're out of luck since you can't always change the settings for those.
In that case:
The dirty way;
*
*Use 'grep' to find the incorrect settings, should be in .pbxproj files. Open a command line of your project, and do:
grep -r "GCC_VERSION" * | grep 4.2
*You'll find lines like these:
GCC_VERSION = 4.2;
*Open the file in your favorite text editor, and change to:
GCC_VERSION = com.apple.compilers.llvmgcc42;
*
*or if you want to experiment with the latest compiler:
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
*
*Instead of using these values, you can look in the main project file or another project that works, to see which value is used there.
If that doesn't help either;
After converting projects between too many versions of xCode, eventually it will actually save you time to start with a clean slate, open a new empty xCode project, and manually drag-in all code from your old project.
A: Make sure you change the complier settings for the extensions as well. If it still says "Unsupported compiler", you probably forgot to change it in one of the three20 sub projects.
Also, check that you have both armv6 and armv7 under the Architectures
Can you send a screenshot of the build settings you have?
A: I solved this problem removing an old "Build" folder inside the Three20 folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8401290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Maximum checked-in files in Perforce We use perforce. In the repository, how can I find which files are checked-in maximum number of times?
I know via P4win, one can manually go to each folder and file and then see the number with file. I have really big repository and many folders & files. So, but I am looking an more automated way or better suggestion so that I can avoid manual work.
Thanks in advance
A: 'p4 files' will print the list of all the files in the repository, and for each file it will tell you the revision number. Then a little bit of 'awk' and 'sort' will find the files with the highest revision numbers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18481335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.