text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Deploying Java / JSP / Struts 2 web app on IIS on Windows server My client has a Windows Server and wants me to deploy a Java / JSP / Struts 2 based web application on the windows server that has IIS as an application server that is installed.
My web application uses MySQL 5.5 for storage of data.
I easily host my web applications on Linux based servers with Apache Tomcat installed on them.
Pls guide me on how do I proceed in case of windows server with IIS?
A: IIS is a web server, it is not java application server.
Normally IIS can not execute Servlets and Java Server Pages (JSPs), configuring IIS to use the JK ISAPI redirector plugin will let IIS send servlet and JSP requests to Tomcat (and this way, serve them to clients).
You can use IIS as proxy to tomcat.
Please read this link for configuring IIS to use the JK ISAPI redirector plugin.
How to configure IIS with tomcat?
How does it work??
*
*The IIS-Tomcat redirector is an IIS plugin (filter + extension), IIS load the redirector plugin and calls its filter function for each in-coming request.
*The filter then tests the request URL against a list of URI-paths held inside uriworkermap.properties, If the current request matches one of the entries in the list of URI-paths, the filter transfer the request to the extension.
*The extension collects the request parameters and forwards them to the appropriate worker using the defined protocol like ajp13 .
*The extension collects the response from the worker and returns it to the browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24743974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React: Using NavLink in a shared component library imported as a node_module I have a working shared component library that I import into my front end app as a node_module using package.json.
I have built a PaginationLinks component that uses NavLink:
PaginationLinks.js (in shared component library)
import { NavLink } from 'react-router-dom';
const PaginationLinks = {
return (
<Container>
...
<NavLink to={"/"}>Home</NavLink>
</Container>
);
};
export default PaginationLinks;
In my front end app, I have react-router and all of that set up already in my working app:
routes.js
import { Route, Switch, Redirect } from 'react-router';
import React from 'react';
import { history } from './redux/store';
import { ConnectedRouter } from 'connected-react-router';
...
function App() {
return (
<ConnectedRouter history={history}>
<Switch>
<BasePage>
<Switch>
<Route
exact
path="/"
component={HomePage}
/>
...
</Switch>
</BasePage>
</Switch>
</ConnectedRouter>
);
}
FYI this is already an app where I have existing routes and import NavLink with no problem.
However, when I try to import my component into my app, it is complaining that my NavLink is not inside a router:
Error: Invariant failed: You should not use <NavLink> outside a <Router>
import React from 'react';
import { NavLink } from 'react-router-dom';
import PaginationLinks from '@my-lib/ui/components/PaginationLinks';
import H1 from '@my-lib/ui/components/H1';
const HomePage = () => (
<div>
<H1>hello</H1> // this works
<NavLink to="/somewhere">somewhere</NavLink> // this works
<PaginationLinks /> // this breaks the app
</div>;
)
export default HomePage;
How would I use NavLink inside a shared component library? It doesn't make sense to wrap PaginationLinks inside of a Router in my shared component library.
A: I fixed it by using peerDependencies + moving those dependenecies into devDependencies. My assumption is that node will scan for dependencies in this order:
*
*dependencies in my shared component lib's package.json
*dependencies in my React app
therefore I had to move the react routing libs into devDependencies so that I could still run my storybook server locally and still have the shared component node_module load properly in production in my react app.
Here's my package.json
"name": "mypackage",
"version": "0.6.3",
"dependencies": {
...
},
"peerDependencies": {
"react": "^16.13.1",
"styled-components": "^4.4.1",
"react-dom": "^16.12.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0"
},
"scripts": {
"start": "start-storybook -p 9009",
"eslint": "eslint --ignore-path .gitignore ./",
"eslint:fix": "eslint --fix --ignore-path .gitignore ./",
"prettier": "prettier -c ./",
"prettier:fix": "prettier --write ./"
},
...
"devDependencies": {
...
"react": "^16.13.1",
"styled-components": "^4.4.1",
"react-dom": "^16.12.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0"
},
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged",
"pre-push": "npm run eslint"
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64177642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to replace double backslash with single backslash in string (Python) I have a list of strings:
list_of_strgs = ['if a+b > 10 and b+c < 20:',
'if a+b > 10 ||| b+c < 20 &&b<2:',
'x&& &&& and and x or | ||\\|| x']
In the third list, I need to replace the double backslash with a single backslash.
I tried this (see Python regex to replace double backslash with single backslash):
new = [i.replace('\\\\', '\\') for i in list_of_strgs]
This has no effect.
Any ideas what else I could try? Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68763768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VLOOKUP not working correctly between two different workbooks I'm trying to get some values between two different workbooks.
One workbook is named 'BSC_AGRvF.xlsm' and the other is 'BSC_AGERE_SQL_v1.xlsx', both are being used on excel office 365.
I used =VLOOKUP(A2;[BSC_AGERE_SQL_v1.xlsx]Variavéis'!$A$4:$E$1000;4;FALSE) to find the description of certain code that is stored in A2 in the current workbook ('BSC_AGRvF.xlsm') but the result is #N/A.
I also tried to use =INDEX([BSC_AGERE_SQL_v1.xlsx]Variavéis'!$D$4:$D$1000;MATCH(1;INDEX(([BSC_AGERE_SQL_v1.xlsx]Variavéis'!$C$4:$C$1000=A2););0)) but the result is the same (#N/A).
The formulas seem to be correct as far as I know but the error keeps occurring. What am I doing wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58801806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: One of Many Entity Relation On Symfony 4, I have an Entity (Address) which can be associated with ONE Of Many entities: e.g. Accounts, Contacts, Employees ..etc.
I essentially want to have "entity_type" and "entity_id" columns in Address but I am unsure if this is the best way to proceed since I would still like to be able to make use of Forms ...etc.
A: Yes you could do like that. But, that will limit the capabilities of one address being shared with multiplie entities such as contacts, employees and so on (unless duplicating the record). However, if one address record never shares with multiple entities you can go ahead and do that.
How about having third table which holds the mapping between address and employees, contacts and so on? Let's say a new table called entity_address, the structure would look like this,
*
*id
*entity_id
*entity_name
*address_id (foreign key to id column of address table)
I personally prefer this approach, instead of having the address table to have entity_id and entity_name due to the reason I mentioned in the first paragraph.
Having said that, someone else, might have a different approach.
Anyway, happy to help you :)
A: You can think your relation to the other side.
An account can have many addresses. A contact can have many addresses. An employee can have many addresses.
This is a Many-To-Many Unidirectionnal relation.
You can build the relation in the target entity, rather than in the address one.
class Accounts
{
// ...
/*
* @ORM\ManyToMany(targetEntity="Address")
* @ORM\JoinTable
* (
* name="accounts_addresses",
* joinColumns=
* {
* @ORM\JoinColumn(name="account_id", referencedColumnName="id")
* },
* inverseJoinColumns=
* {
* @ORM\JoinColumn(name="address_id", referencedColumnName="id", unique=true)
* }
* )
*/
private $addresses;
// ...
}
// And so on for the others entities
This will build an relationship table in your database with a unique constraint on the address_id foreign key.
For more informations, take a look at this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52760423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ruby-amqp and rspec messaging cleaner I am currently working on a messaging system with ruby-amqp, for testing I am using rspec.
If a test fails, I still have messages in queues after the test is finished. Is there a way to clean up all queues like the database_cleaner gem does it for databases?
A: You may delete the whole queue with AMQP::Queue#delete
Just take the AMQP::Queue instance and call
queue.delete
or
queue.delete do |_|
puts "Deleted #{queue.name}"
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10380378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Facebook : how to get number of friends? I would like to be able to retrieve some people number of friends on Facebook. However, I got some issue to achieve this goal. I tried two different ways:
1. With FQL:
I tried following query:
SELECT username, friend_count
FROM user
WHERE username = jonathan.petitcolas
But, as you can see, the friend_count property is always null. On my public profile, and also on other profiles.
2. With Facebook PHP SDK
Then, I installed the Facebook PHP SDK, created an application, and did the following:
$facebook = new \Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX'
));
$friends = $facebook->api('/jonathan.petitcolas/friends');
Then I got the following exception:
[FacebookApiException]
(#604) Can't lookup all friends of 676944843. Can only lookup for the
logged in user or the logged in user's friends that are users of your
app.
Indeed, I am logged in with another user.
So, is it possible to retrieve number of friends of a public profile on Facebook? Is so, how to do this?
Thanks a lot! :)
A:
I tried following query:
SELECT username, friend_count
FROM user
WHERE username = jonathan.petitcolas
But, as you can see, the friend_count property is always null. On my public profile, and also on other profiles.
Nope, it’s not always null. If I do that query with my own user name (and correcting the syntax error in your query), I get back the correct number of friends. Only if I authenticated that app making the query, of course.
So, is it possible to retrieve number of friends of a public profile on Facebook?
Nope.
That says enough already:
“Can only lookup for the logged in user or the logged in user's friends that are users of your app.”
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11598792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert float seconds to milliseconds using regex with Notepad++ I want to convert all seconds contained in the XML tag to milliseconds using regex with Notepad++.
Before converting:
<keepTime>3</keepTime>
<keepTime>4.5</keepTime>
<keepTime>0.7</keepTime>
<keepTime>1.85</keepTime>
The results I want after converting:
<keepTime>3000</keepTime>
<keepTime>4500</keepTime>
<keepTime>700</keepTime>
<keepTime>1850</keepTime>
Here is the regex I use: <keepTime>([0-9]*[.])?[0-9]+</keepTime>
It matches all the values in <keepTime>. However, I have no idea what to replace into milliseconds.
If your answer was helpful, I would appreciate it.
Thanks.
A: Even though I frequently use regular expressions (RE), I would be reluctant to use one complex RE for this job. The chances that it misses some of the tags, or wrongly converts others, seem too high and too risky. I would approach this sort of task using a series of simple REs that jointly give me confidence that I have done all the changes correctly.
Thus, with "Regular expression" and "Wrap around" selected:
Change <keepTime>(\d+)</keepTime> to <done>${1}000</done>
Change <keepTime>(\d+)\.(\d)</keepTime> to <done>${1}${2}00</done>
Change <keepTime>(\d+)\.(\d\d)</keepTime> to <done>${1}${2}0</done>
To remove all leading zeros but retain a single zero, use
Change <done>0+([1-9]\d*)</done> to <done>${1}</done>
For a variation on the above to remove some leading zeros but keep three digits, use:
Change <done>0+(\d\d\d)</done> to <done>${1}</done>
It is simple to modify it to keep two digits or four, etc.
Now do a search for any remaining occurrences of </?keepTime> and change them in the style above. Then when they are all changed, convert the "done"s with:
Change <done>(\d+)</done> to <keepTime>\1</keepTime>.
Now do a final check that all of the "done"s have been done, searching for </?done>
Note that done should be replaced throughout by some tag that is not used in the original file. Note also that this is complex editing, so make a backup before doing the changes.
A: Doing numeric multiplication using regular expressions feels like attempting to drive a nail using a screwdriver, and I certainly wouldn't attempt it in a single replace() call, but if you're allowed a bit of conditional logic then it's not too difficult:
(a) if there's no ".", append "000"
(b) otherwise:
(i) append "000"
(ii) replace ".xxx" by "xxx."
(iii) delete trailing zeroes
(iv) delete trailing "."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67256656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Docker Build Error failed to solve with frontend dockerfile.v0 Python i want to build docker image in local with my mac air m1 chip. but unfortunately i have an error like this. may i know why this error happen and what is the solution ? i think my problem is about connectivity with my network but i am not sure.
i have try to used my company virtual private network and did not work.
here is the code and the error
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 37B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> ERROR [internal] load metadata for docker.io/library/python:3.7.11 30.2s
=> [auth] library/python:pull token for registry-1.docker.io 0.0s
------
> [internal] load metadata for docker.io/library/python:3.7.11:
------
failed to solve with frontend dockerfile.v0: failed to create LLB definition: failed to authorize: rpc error: code = Unknown desc = failed to fetch oauth token: Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fpython%3Apull&service=registry.docker.io": dial tcp: i/o timeout
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71953392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TeamBuild build error: Unknown ProviderOption:DefiningProjectFullPath. Known ProviderOptions are:skipInvalid I have a solution created with VS2013 with this projects:
*
*WebApp (Asp.net mvc5 web app)
*Common (c# library project)
The solution is versioned on server TFS2013.
I Create and edited a build definition for my solution where i want create 2 build using Release and Debug configuration.
I have configured build definition like this article because i want tranform Web.Config
When i add MSBuild this arguments in my Team Build definition:
/p:DeployOnBuild=true /p:UseWPP_CopyWebApplication=True /p:PipelineDependsOnBuild=False
Now i have this error:
(PackageUsingManifest target) ->
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(3883,5): error : Web deployment task failed.
(Unknown ProviderOption:DefiningProjectFullPath. Known ProviderOptions are:skipInvalid.)
If i remove the MSBuild argument it works.
QUESTION: What's could be configured wrong?
A: I discovered that on my local machine there was Visual Studio 2013 Update 5 while on the server TFS there was Visual Studio 2013 RTM (no update).
I resolved with a update of Visual Studio 2013 at last version (Update 5) on server where is installed TFS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36934898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to declare Exchange Web Service I have in my c# application a new web service that I generated using Add Web Reference tool.
It is called ExchangeWebServices in my Solution Explorer.
But when I try to add the sample code that I found on StackOverflow: 652549: read-ms-exchange-email-in-c-sharp it won't compile.
I have a compile error message that
ExchangeWebServices is a namespace but is used as a type.
here is the line of code that I am trying to use.
ExchangeWebServices service =new ExchangeWebServices(ExchangeVersion.Exchange2013_SP3);
I have at the top of my form class this:
using email2case_winForm.ExchangeWebServices;
what am I doing wrong here please?
A: I am going to guess that the code in the answer to the other stack isn't quite correct, but is more of a concept for how things could be written (Edit - Or its written against an older version of EWS). Either way, there are some excellent examples here: http://msdn.microsoft.com/en-us/library/office/bb408521(v=exchg.140).aspx.
Taking the guts of it, you should probably end up with something like:
// Identify the service binding and the user.
ExchangeServiceBinding service = new ExchangeServiceBinding();
service.RequestServerVersionValue = new RequestServerVersion();
service.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;
service.Credentials = new NetworkCredential("<username>", "<password>", "<domain>");
service.Url = @"https://<FQDN>/EWS/Exchange.asmx";
From there you can use the service to create requests or whatever it is you need to do. Note this code was copied from the msdn link above so you'll want to refer back to that for further explanation. Best of luck!
A: Instead of using the Add Web Reference tool to generate the Web service client, I highly suggest that you use the EWS Managed API instead. It is a much easier object model to use and it has some useful business logic built into it. It will save you time and lines of code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22299299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variable changing when used in a forumula in php I hope that someone can help me figure this out because it is driving me crazy. First off some background and values of the variables below.
The $TritPrice variable fluctuates as it comes from another source but for an example, lets say that the value of it is 5.25
$RefineTrit is constant at 1000 and $Minerals[$oretype][0] is 333
When I first goto the page where this code is, and this function runs for some reason the $TritPrice var either get truncated to 5.00 or gets rounded down but only during the formula itself. I can echo each of variables and they are correct but when I echo the formula and do the math manually the $TritPrice is just 5 instead of 5.25.
If I put in $TritPrice = 5.25; before the if statement it works fine and after the form is submitted and this function is rerun it works fine.
The page that uses this function is at here if yall want to see what it does.
If ($Minerals[$oretype][1] <> 0) {
$RefineTrit = getmintotal($oretype,1);
if ($RefineTrit < $Minerals[$oretype][1]) {
$NonPerfectTrit = $Minerals[$oretype][1] +
($Minerals[$oretype][1] - $RefineTrit);
$Price = (($TritPrice * $NonPerfectTrit) / $Minerals[$oretype][0]);
} else {
$Price = $TritPrice * $RefineTrit / $Minerals[$oretype][0];
}
}
This is where the $TritPrice
// Get Mineral Prices
GetCurrentMineralPrice();
$TritPrice = $ItemPrice[1];
$PyerPrice = $ItemPrice[2];
$MexPrice = $ItemPrice[3];
$IsoPrice = $ItemPrice[4];
$NocxPrice = $ItemPrice[5];
$ZydPrice = $ItemPrice[6];
$MegaPrice = $ItemPrice[7];
$MorPrice = $ItemPrice[8];
and the GetCurrentMineralPrice() function is
function GetCurrentMineralPrice() {
global $ItemPrice;
$xml = simplexml_load_file("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=11399&usesystem=30000142");
$i = 1;
foreach ($xml->marketstat->type as $child) {
$ItemPrice[$i] = $child->buy->max;
$i++;
}
return $ItemPrice;
}
A: The problem is not in this piece of code. In some other part of the program, and I suspect it is the place where the values from the textboxes are accepted and fed into the formula - in that place there should be a function or code snippet that is rounding the value of $TritPrice. Check the place where the $_POST values are being fetched and also check if any javascript code is doing a parseInt behind the scenes.
A: EVE-Online ftw.
with that out of the way, it's possible that your precision value in your config is set too low? Not sure why it would be unless you changed it manually. Or you have a function that is running somewhere that is truncating your variable when you call it from that function/var
However, can you please paste the rest of the code where you instantiate $TritPrice please?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21465410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Elastic Beanstalk does not deploy the app after autoscaling So because of NetworkOut < 2000000 for 1 datapoints within 5 minutes policy in the autoscaling group my instance got terminated. Then it created a new instance but did not redeploy my app on the new instance. Why is that? Shouldn't it be automatically deploying the app on the new instance?
By the way, I am using Elastic Beanstalk and the flask backend.
If you can help me figure out why it is happening, then that would be awesome?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67696277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error while sourcing shell script In order to complete an installation, I need to source the following .sh file:
function addvar () {
local tmp="${!1}" ;
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
export $1="${2}:${tmp}" ;
}
if [ -z "${PATH}" ]; then
PATH=/share/MontePython/plc-2.0/bin
export PATH
else
addvar PATH /share/MontePython/plc-2.0/bin
fi
if [ -z "${PYTHONPATH}" ]; then
PYTHONPATH=/share/MontePython/plc-2.0/lib/python2.7/site-packages
export PYTHONPATH
else
addvar PYTHONPATH /share/MontePython/plc-2.0/lib/python2.7/site-packages
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/MontePython/plc-2.0/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/MontePython/plc-2.0/lib
fi
CLIK_PATH=/share/MontePython/plc-2.0
export CLIK_PATH
CLIK_DATA=/share/MontePython/plc-2.0/share/clik
export CLIK_DATA
CLIK_PLUGIN=rel2015
export CLIK_PLUGIN
but when I source it, I get the following error:
() not correctly positioned
Any idea why?
The curious thing is that this error is happening when I operate on a cluster, while I don't have it on my PC.
EDIT:
The output of lsb_release -a is:
LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description: CentOS release 6.9 (Final)
Release: 6.9
Codename: Final
The output of echo $0 is -tcsh.
A: I think you're using a different shell (tcsh) rather than sh or bash. Most probably you have to adapt your source code to make it load using tcsh. Under sh/bash works just fine
root@pve1:~# echo $0
-bash
A: In bash, your script is syntactically correct. But if you use sh, then there are a few errors. Check the shellcheck output:
$ shellcheck script.sh
In script.sh line 3:
function addvar () {
^-- SC2112: 'function' keyword is non-standard. Delete it.
In script.sh line 4:
local tmp="${!1}" ;
^-- SC2039: In POSIX sh, 'local' is undefined.
^-- SC2039: In POSIX sh, indirect expansion is undefined.
In script.sh line 5:
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
^-- SC2039: In POSIX sh, string replacement is undefined.
^-- SC2039: In POSIX sh, string replacement is undefined.
^-- SC2039: In POSIX sh, string replacement is undefined.
In summary:
*
*function keyword is not needed (or even recommended)
*local isn't supported in POSIX sh
*string replacement ${//} is not supported in sh.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44907080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I got this error NOT NULL constraint failed: accounts_user.password The problem is when i try to register this error show up:
django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.password
I tried to migrate and did all recommended things like migrations but it didn't work.
This is my files
views.py
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from django.views.generic import FormView,TemplateView,ListView
from django.conf import settings
from .forms import RegisterForm
from .models import User
# Create your views here.
#user-login view
def register(request):
registred=False
if request.method=="POST":
user_register=RegisterForm(data=request.POST)
if user_register.is_valid():
username=user_register.cleaned_data.get('username')
email=user_register.cleaned_data.get('email')
password=user_register.cleaned_data.get('password1')
user=User.objects.create(username=username,email=email,password=password)
user.set_password(user.password)
user.save()
registred=True
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse('there is a problem')
else:
return render(request,'register.html',{'registred':registred,'user_register':RegisterForm})
def user_login(request):
if request.method=='POST':
email=request.POST.get('email')
password=request.POST.get('password')
user=authenticate(email=email,password=password)
if user is not None:
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account not found")
else:
return render(request,'login.html')
#user-logout view
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
#registration view
forms.py:
# accounts.forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email','username','full_name','short_name','password')
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username__iexact=username).exists():
raise forms.ValidationError('This username already exists')
return username
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
class UserAdminCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'active', 'admin')
def clean_password(self):
return self.initial["password"]
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
# accounts.models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
# hook in the New Manager to our Model
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username=models.CharField(default='',unique=True,max_length=50)
full_name=models.CharField(default='',max_length=50)
short_name=models.CharField(default='',max_length=50)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return self.full_name
def get_short_name(self):
# The user is identified by their email address
return self.short_name
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
@property
def is_admin(self):
"Is the user a admin member?"
return self.admin
@property
def is_active(self):
"Is the user active?"
return self.active
objects = UserManager()
A: i just changed this password=user_register.cleaned_data.get('password') to this password=request.POST.get('password') and it worked
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60362818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to do URL rewriting in Classic ASP In Classic ASP I want to convert links into user friendly urs.For example
http://www.sportsmanager.us/links/AboutUs.asp?Org=504&Link=7514
should convert to
http://www.sportsmanager.us/links/demo/AboutUs
Please let me know is it possible in classic asp.We have window server 2003 standard edition and IIS6.0.
Thanks, Ravi
A: Try http://iirf.codeplex.com/ (free) or http://www.isapirewrite.com (free to try)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6717438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JS Dropbox API Account Secret I am using the Dropbox Core API for a web application. On my server, I want to have a profile for each user, that is linked with his Dropbox account. How can I ensure, that only this user has access to his information? Can I get some sort of a secure unique Dropbox password hash for the Dropbox user?
Thanks.
A: Maybe you could just store the profile in the user's Dropbox (e.g. via the Datastore API). Then you don't have to worry about it at all... only the authenticated user can see his or her own data.
Otherwise you could just use the user ID. If you're doing this server-side, pass the OAuth token to the server, and on the server call /account/info to get the user ID. Then just tie the profile to that user ID.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22336809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to define a CustomUser and still use the standard admin screen? A few different questions on the same topic:
I have defined a new CustomUser classes to the following, which is simply an extension of the default UserClass.
class customUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
first_name = models.CharField(max_length=50, null=True)
middle_name = models.CharField(max_length=50, null=True)
last_name = models.CharField(max_length=50, null=True)
date_of_birth = models.DateField(null=True)
Primary_address = models.CharField(max_length=50, null=True)
Primary_address_zipcode = models.CharField(max_length=5, null=True)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
Question 1: Is it possible to inherit attributes of the default UserClass (like first_name and last_name, last_login, first_created) without having to redefine in my new CustomUser class?
Question 2: Would it possible to use the existing User default page and just modifying it slightly to fit my CustomUser? I ask because the default admin page has nice Group control, last_login and first_created field that I would like to use and I don't want to "reproduce" the same page. It would be nice has to add the extra fields I have defined in CustomUser to Person Info section of default admin page.
A: Yes. You're going to want to use AbstractUser instead of AbstractBaseUser.
Details are provided here:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-django-s-default-user
It creates a different table in the database (not auth_user), but still fully extends into the Django Admin quite elegantly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33701199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 'ManagementForm data is missing or has been tampered with I am using the following code in my django app which is working fine if I use it as it is but when I extend the base to the following html it throws the following error:
django.core.exceptions.ValidationError: ['ManagementForm data is
missing or has been tampered with']
HTML
<html>
<head>
<title>gffdfdf</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/static/jquery.formset.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
{{ form.player.management_form }}
<h3> Product Instance(s)</h3>
<table id="table-product" class="table">
<thead>
<tr>
<th>player name</th>
<th>highest score</th>
<th>age</th>
</tr>
</thead>
{% for player in form.player %}
<tbody class="player-instances">
<tr>
<td>{{ player.pname }}</td>
<td>{{ player.hscore }}</td>
<td>{{ player.age }}</td>
<td><input id="input_add" type="button" name="add" value=" Add More "
class="tr_clone_add btn data_input"></td>
</tr>
</tbody>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
<script>
var i = 1;
$("#input_add").click(function () {
$("tbody tr:first").clone().find(".data_input").each(function () {
if ($(this).attr('class') == 'tr_clone_add btn data_input') {
$(this).attr({
'id': function (_, id) {
return "remove_button"
},
'name': function (_, name) {
return "name_remove" + i
},
'value': 'Remove'
}).on("click", function () {
var a = $(this).parent();
var b = a.parent();
i = i - 1
$('#id_form-TOTAL_FORMS').val(i);
b.remove();
$('.player-instances tr').each(function (index, value) {
$(this).find('.data_input').each(function () {
$(this).attr({
'id': function (_, id) {
console.log("id", id)
var idData = id;
var splitV = String(idData).split('-');
var fData = splitV[0];
var tData = splitV[2];
return fData + "-" + index + "-" + tData
},
'name': function (_, name) {
console.log("name", name)
var nameData = name;
var splitV = String(nameData).split('-');
var fData = splitV[0];
var tData = splitV[2];
return fData + "-" + index + "-" + tData
}
});
})
})
})
} else {
$(this).attr({
'id': function (_, id) {
console.log("id", id)
var idData = id;
var splitV = String(idData).split('-');
var fData = splitV[0];
var tData = splitV[2];
return fData + "-" + i + "-" + tData
},
'name': function (_, name) {
console.log("name", name)
var nameData = name;
var splitV = String(nameData).split('-');
var fData = splitV[0];
var tData = splitV[2];
return fData + "-" + i + "-" + tData
}
});
}
}).end().appendTo("tbody");
$('#id_form-TOTAL_FORMS').val(1 + i);
$("tbody tr:last :input").each(function () {
$(this).attr({
'id': function (_, id) {
return id.replace(/\d/g, i)
},
'name': function (_, name) {
return name.replace(/\d/g, i)
},
})
})
i++;
});
</script>
</body>
</html>
Code I am adding to it:
{% extends 'base.html' %}
{% block content %}
..The above code
{% endblock %}
Why is it happening ?
Forms.py
class PlayerForm(forms.ModelForm):
class Meta:
model = Player
fields = '__all__'
PlayerFormset= formset_factory(PlayerForm)
class TeamForm(forms.ModelForm):
player= PlayerFormset()
class Meta:
model = Team
fields = '__all__'
exclude = ["player"]
Views.py
def post(request):
if request.POST:
form = TeamForm(request.POST)
form.player_instances = PlayerFormset(request.POST)
if form.is_valid():
team= Team()
team.tname= form.cleaned_data['tname']
team.save()
if form.player_instances.cleaned_data is not None:
for item in form.player_instances.cleaned_data:
player = Player()
player.pname= item['pname']
player.hscore= item['hscore']
player.age= item['age']
player.save()
team.player.add(player)
team.save()
else:
form = TeamForm()
return render(request, 'packsapp/employee/new.html', {'form':form})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61320538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: inter servlet communication I have two servlets: LoginServlet and MailServlet. LoginServlet queries a mysql table using jdbc to get a string(eMail). What I want is to forward this string to MailServlet which in turn will send an email to that e-mail ID sent by LoginServlet.
My question is how do I call and send the variable eMail to MailServlet, from LoginServlet? I thought of creating an instance of the MailServlet as :
MailServlet servlet = new MailServlet();
And then use the servlet object to call the function doGet() in MailServlet.
But I am feeling that there is some error in this as this is not the right way to call a servlet. So how do I call and pass a variable to MailServlet?
A: The purpose of a servlet is to respond to an HTTP request. What you should do is refactor your code so that the logic you want is separated from the other servlet and you can reuse it independently. So, for example, you might end up with a Mailman class, and a MailServlet that uses Mailman to do its work. It doesn't make sense to call a servlet from another servlet.
If what you need is to go to a different page after you hit the first one, use a redirect:
http://www.java-tips.org/java-ee-tips/java-servlet/how-to-redirect-a-request-using-servlet.html
Edit:
For example, suppose you have a servlet like:
public class MailServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(...);
message.doSomeOtherStuff();
Transport.send(message);
out.println("mail has been sent");
}
}
Instead, do something like this:
public class MailServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
new Mailer().sendMessage("[email protected]", ...);
out.println("mail has been sent");
}
}
public class Mailer {
public void sendMessage(String from, ...) {
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(...);
message.doSomeOtherStuff();
Transport.send(message);
}
}
A: I think this may be what you were originally looking for: a request dispatcher. From the Sun examples documentation:
public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
request.setAttribute("selectedScreen",
request.getServletPath());
RequestDispatcher dispatcher =
request.getRequestDispatcher("/template.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) {
request.setAttribute("selectedScreen",
request.getServletPath());
RequestDispatcher dispatcher =
request.getRequestDispatcher("/template.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}
}
This appears to specify a new URL, for a different servlet, JSP, or other resource in the same container, to generate the response instead of the current servlet.
From the tutorial here:
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags6.html
A: You can use forward() method of
RequestDispatcher
So the code goes as follows:
LoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String emailID = "[email protected]"; //Write code to retrieve email id from MySql and store in emailID variable
request.setAttribute("emaiID", emailID);
RequestDispatcher rd = request.getRequestDispatcher("MailServlet");
rd.forward(request, response);
}
MailServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String value = (String) request.getAttribute("emaiID");
pw.println("The value of email id is: " + value);
}
Let me know if this answer is not clear to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2840638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I record a timestamp of when a record is created in Mongoose schema? I have an application that I'm building that allows users to enter records on a webpage. I want to display the date/time of when each record was submitted, I've tried several different methods and finally have the date/time to display in a format that I want, but it seems as though the timestamp is recorded when the server starts up instead of when the record is added. I'm using moment.js for formatting
Here is my schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
var d = new Date();
var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
let codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: formattedDate
},
},
{
collection: "codes"
}
);
module.exports = mongoose.model("Code", codeSchema);
This is how the records look, except the date & time is when I start the server instead of when the document was actually added
123456789789 12-09-2021, 12:59:33 pm
A: Interesting problem. I am using mongoose in an app and have not seen this issue. See schema below:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const schema = new Schema({
createdBy: Object,
created: { type: Date, default: Date.now },
matchName: { type: String, required: true },
matchType: { type: String, required: true },
matchActive: { type: Boolean, default: false },
matchPrivate: { type: Boolean, default: true },
matchTime: { type: String, required: true },
matchDate: { type: String, requried: true },
matchPassword: String,
matchMembers: [],
course: Object,
subCourse: Object,
par: { type: Number, required: true },
numberOfHoles: { type: Number, required: true },
frontBackNine: { type: String, required: true, default: null },
completed: { type: Boolean, default: false },
compeletedOn: { type: Date },
winner: { type: String },
startingHole: { type: Number, default: 1 },
scorecardSettings: { type: String, required: true },
tournamentGroups: { type: Array, default: [] },
});
module.exports = mongoose.model("Matches", schema);
However I am not using moment.js.
Two thoughts here:
*
*try removing commenting out moment.js code and use:
Date.now
in place of the moment formatted date. This is just to see if moment is causing the issue or not and will not actual give you a solution
*How are you creating the collection and document? Are you creating a document when the server is started or when the user uploads the file?
A: Think about when that variable is evaluated and assigned; is when the schema is created, that happens just one time. In any case, you should assign that value at the time when you save the record, assign the value as any other.
But, moongose already has an option to assign timestamps to records when are created and updated. See it here: https://mongoosejs.com/docs/guide.html#timestamps
Your code should look like:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: formattedDate
},
},
{
collection: "codes",
timestamps: true
}
);
module.exports = mongoose.model("Code", codeSchema);
About the format, I highlight recommend take care of that after at the final point when you use the data.
A: You are assigning a predefined value, that's why it is not working, you should create a function and assign the function as a default value to get the value when the document.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
var createdAt = function(){
var d = new Date();
var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
return formattedDate;
};
let codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: createdAt
},
},
{
collection: "codes"
}
);
module.exports = mongoose.model("Code", codeSchema);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70296156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to improve my current code to get correct result I have some events. event are show in application every week depend on inserted day.like
event one > Friday
event two > sat
event three > sun
so event one show in application every Friday 2 am to 2 am
I am confused how to manage and 2 am to 2 am. I already create a logic but its cant give me right calculation
$input = time();
$day = date('D', $input );
switch ($day) {
case 'Sun':
$finalday='0';
break;
case 'Mon':
$finalday='1';
break;
case 'Tue':
$finalday='2';
break;
case 'Wed':
$finalday='3';
break;
case 'Thu':
$finalday='4';
break;
case 'Fri':
$finalday='5';
break;
case 'Sat':
$finalday='6';
break;
}
$now = time();
$event_time = strtotime("02:00 am");
if( ($now - $event_time) < 0) // 5 minutes * 60 seconds, replace with 300 if you'd like
{
//before day
if($finalday=='0')
{
$query_day='6';
}
else
{
$query_day=$finalday-1;
}
}
else
{
//current day
$query_day=$finalday;
}
how can i show each event exactly 2 am to 2 am depend on inserted day
suppose now 12.00 AM so day is Friday but event one will be show from 2.00 AM to next 1.59AM then event two will be show from 2.00 AM to 1.59 AM (sat).
AS this way next weak automatically events will be shown
A: Try something like this just to make your code look a little bit more elegant and not so clunky
$dayOfWeek = date('w'); //0 for Sunday through 6 for Saturday
$hourOfDay = date('H'); //0-23
$eventOne = null;
$eventTwo = null;
$eventThree = null;
//logic structure to set events
if($hourOfDay >= 0 && $hourOfDay < 2){
$dayOfWeek -= 1; //set to previous day if earlier than 2AM
$dayOfWeek = $dayOfWeek == 0 ? 6 : $dayOfWeek; //quick check to set to Sunday if day was on Monday
$eventOne = $dayOfWeek;
$eventTwo = $dayOfWeek+1;
$eventThree = $dayOfWeek+2;
//single line if statements to correct weekly overflow
if($eventTwo == 7) $eventTwo = 0;
if($eventThree == 7) $eventThree = 0;
if($eventThree == 8) $eventThree = 1;
}else{
$eventOne = $dayOfWeek;
$eventTwo = $dayOfWeek+1;
$eventThree = $dayOfWeek+2;
//single line if statements to correct weekly overflow
if($eventTwo == 7) $eventTwo = 0;
if($eventThree == 7) $eventThree = 0;
if($eventThree == 8) $eventThree = 1;
}
function getDayOfEvent($event){
switch($event){
case 0: return "Sunday"; break;
case 1: return "Monday"; break;
case 2: return "Tuesday"; break;
case 3: return "Wednesay"; break;
case 4: return "Thursday"; break;
case 5: return "Friday"; break;
case 6: return "Saturday"; break;
}
}
print "Event One: ". getDayOfEvent($eventOne)."\nEvent Two: ".getDayOfEvent($eventTwo)."\nEvent Three: ".getDayOfEvent($eventThree);
Let me know if something like this works for you. I'm sorry but I was having a hard time translating your English, I tried my best :) I hope this helps you, if not please let me know and I will help you fix it so that it does.
Here's a paste on CodePad where you can play around with the code a little bit if you want http://codepad.org/SLcTeGEt
A: Try this program... maybe is what you want. (Your question is very confusing.)
/* Day Of Week 0 = Sun ... 6 = Sat
* ---------------------------------
* Day Hour Result Case
* ---------------------------------
* 5 00 - 02 No event C
* 5 02 - 24 Event 1 B
* 6 00 - 02 Event 1 A
* 6 02 - 24 Event 2 B
* 0 00 - 02 Event 2 A
* 0 02 - 24 Event 3 B
* 1 00 - 02 Event 3 A
* 1 02 - 24 No Event C
* Other Other No Event C
* ---------------------------------
*/
function getEvent( $timestamp, $eventTime ) {
$d = (int) date( 'w', $timestamp ); // Day
$h = (int) date( 'G', $timestamp ); // Hour
$event = $h < $eventTime && ( $d > 5 || $d < 2 ) // Case A
? ( $d + 2 ) % 7 // Case A Result
: ( $h >= $eventTime && ( $d > 4 || $d == 0 ) // Case B
? ( $d + 3 ) % 7 // Case B Result
: null ); // Case C Result
printf ( "\n%s %02d:00 :: %s", // ... and show
date( 'D', strtotime( "Sunday +{$d} days" ) ),
$h, $event ? "Event $event" : 'No event' );
}
$eventTime = 2;
echo '<pre>';
/* Testing the getEvent function */
for ( $timestamp = mktime( 23, 0, 0, 4, 30, 2015 ); // Thu at 23:00
$timestamp <= mktime( 22, 0, 0, 5, 7, 2015 ); // Thu at 22:00
$timestamp += 3600 * 2 ) { // Each 2 hours
getEvent( $timestamp, $eventTime );
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29990403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to disable users from accessing previous page by browser back button after logout in angular2? I am trying not to allow users to go to previous page using browser back button after logout. I wish to show users a messge like "Please login to continue".in Angular 2
A:
create a new file called authorization.guard.ts and add this
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {AppContextService} from './context';
@Injectable()
export class AuthorizationGuard implements CanActivate {
constructor(
private appContextService:AppContextService
){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
return this.appContextService.getAuthAdminLoggednIn();
}
}
later in your main module import {AuthorizationGuard}
add this in your each router path
{
path: 'dashboard',
canActivate:[AuthorizationGuard]
},
Refer this files for complete authorization
Refer this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51590678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: restructure json data into a same structure , by removing unwanted data This is my JSON Data using Mongo :
{
"status": 1,
"message": "",
"data": [
{
"_id": "5f489968a26b303c54d0a174",
"name": "Mobile",
"SubCategory": [
{
"_id": "5f5f3827c8f0c718c01428d2",
"name": "55",
"Brand": [
{
"_id": "5f607898fea6362dc4eeaa5e",
"name": "sub category test2",
"Offer": []
},
{
"_id": "5f6078a4fea6362dc4eeaa5f",
"name": "brand2",
"Offer": [
{
"_id": "5f63839a1f7f3f2ec01cb19d",
"title": "qsw",
"Likes": [],
"Comments": [],
"Shares": []
}
]
},
{
"_id": "5f686deb08a1272b003aa3c7",
"name": "Marvel",
"Offer": [
{
"_id": "5f69ad691af8e2202447432c",
"title": "Marvel offer",
"Likes": [
{
"_id": "5f6af7a3bb67241d881c3d0b",
"updatedAt": "2020-09-03T07:18:14.073Z"
},
{
"_id": "5f6af7afbb67241d881c3d0c",
"updatedAt": "2020-09-03T07:18:14.073Z"
}
],
"Comments": [],
"Shares": []
},
{
"_id": "5f69b124d1c0f13b806ea20d",
"title": "Marvel offer2",
"Likes": [
{
"_id": "5f6af7c5bb67241d881c3d0d",
"updatedAt": "2020-09-03T07:18:14.073Z"
},
{
"_id": "5f6af7cabb67241d881c3d0e",
"updatedAt": "2020-09-03T07:18:14.073Z"
}
],
"Comments": [
{
"_id": "5f6af7d5bb67241d881c3d0f",
"updatedAt": "2020-09-03T06:31:36.930Z"
}
],
"Shares": []
}
]
}
]
}
]
},
{
"_id": "5f4899c2a26b303c54d0a175",
"name": "Computer",
"SubCategory": []
},
{
"_id": "5f489ba4ce0bd10c2c7af0eb",
"name": "Clothing",
"SubCategory": []
},
{
"_id": "5f48ab999579ac3690cd6897",
"name": "abc",
"SubCategory": []
},
{
"_id": "5f4c9c2b4630711ae099cec3",
"name": "abcd",
"SubCategory": []
},
{
"_id": "5f4cb13dc7fd2024ec020269",
"name": "Kitchen",
"SubCategory": []
},
{
"_id": "5f59e258a54fc924e02b0152",
"name": "q",
"SubCategory": []
},
{
"_id": "5f59e2bea54fc924e02b0153",
"name": "qq",
"SubCategory": []
},
{
"_id": "5f59e345a54fc924e02b0154",
"name": "w",
"SubCategory": []
},
{
"_id": "5f59e361a54fc924e02b0155",
"name": "s",
"SubCategory": []
},
{
"_id": "5f59e37ca54fc924e02b0156",
"name": "Amitesh Category1",
"SubCategory": []
},
{
"_id": "5f59e506848bf9451cf4f32f",
"name": "laptop6",
"SubCategory": []
},
{
"_id": "5f59e5fba5ea37295c6b5f8b",
"name": "Electronic2",
"SubCategory": []
},
{
"_id": "5f59fa26b4c9893a5ca5e96f",
"name": "Electronic3",
"SubCategory": []
},
{
"_id": "5f59fa33b4c9893a5ca5e970",
"name": "Electronic4",
"SubCategory": []
},
{
"_id": "5f59fa48b4c9893a5ca5e971",
"name": "laptop",
"SubCategory": []
},
{
"_id": "5f59faaeb4c9893a5ca5e973",
"name": "amitesh c1",
"SubCategory": [
{
"_id": "5f5f68e563d63905b093ebca",
"name": "sub cat 1",
"Brand": []
}
]
},
{
"_id": "5f59fceeb4c9893a5ca5e976",
"name": "11",
"SubCategory": []
},
{
"_id": "5f59ffa1b4c9893a5ca5e977",
"name": "ccw",
"SubCategory": []
},
{
"_id": "5f5b7e1bab9a593bd6950aed",
"name": "test 1",
"SubCategory": []
},
{
"_id": "5f5b870b3d722c41cc2e5f2f",
"name": "qq wqwq wq",
"SubCategory": [
{
"_id": "5f5f680b578fea0b640fb754",
"name": "sub cat 2",
"Brand": []
}
]
},
{
"_id": "5f5b88033d722c41cc2e5f30",
"name": "cvcv",
"SubCategory": [
{
"_id": "5f5f384ac8f0c718c01428d3",
"name": "sub cat 4",
"Brand": [
{
"_id": "5f6078bafea6362dc4eeaa60",
"name": "brand2",
"Offer": [
{
"_id": "5f687de408a1272b003aa3c8",
"title": "Testing expire1 depndent1",
"Likes": [],
"Comments": [],
"Shares": []
}
]
},
{
"_id": "5f6078bffea6362dc4eeaa61",
"name": "brand3",
"Offer": []
},
{
"_id": "5f6078c2fea6362dc4eeaa62",
"name": "brand4",
"Offer": []
},
{
"_id": "5f6086c8fea6362dc4eeaa63",
"name": "brand 5",
"Offer": []
},
{
"_id": "5f608712fea6362dc4eeaa64",
"name": "xyz 5",
"Offer": [
{
"_id": "5f644628129ad62d301b4ca7",
"title": "Testing expire11",
"Likes": [
{
"_id": "5f50963ad4e7b82584f29718",
"updatedAt": "2020-09-03T07:18:14.073Z"
},
{
"_id": "5f50993117bdf8161875e534",
"updatedAt": "2020-09-03T07:21:08.659Z"
},
{
"_id": "5f5099770c5b262edcbc34f0",
"updatedAt": "2020-09-03T07:33:16.483Z"
}
],
"Comments": [
{
"_id": "5f50913a7480733a1cfb90d3",
"updatedAt": "2020-09-03T06:46:18.010Z"
},
{
"_id": "5f646ff7e9df61290c73369f",
"updatedAt": "2020-09-03T06:46:18.010Z"
},
{
"_id": "5f646fffe9df61290c7336a0",
"updatedAt": "2020-09-03T06:46:18.010Z"
},
{
"_id": "5f647008e9df61290c7336a1",
"updatedAt": "2020-09-03T06:46:18.010Z"
},
{
"_id": "5f64700fe9df61290c7336a2",
"updatedAt": "2020-09-03T06:46:18.010Z"
},
{
"_id": "5f647103e9df61290c7336a6",
"updatedAt": "2020-09-03T06:46:18.010Z"
}
],
"Shares": []
}
]
},
{
"_id": "5f61ea593a89c23ff074cc2f",
"name": "aaaaaa",
"Offer": [
{
"_id": "5f6330505c9ff214f8ed1bf1",
"title": "12",
"Likes": [],
"Comments": [
{
"_id": "5f508c55e0caf427404addea",
"updatedAt": "2020-09-03T06:31:36.930Z"
},
{
"_id": "5f647015e9df61290c7336a3",
"updatedAt": "2020-09-03T06:31:36.930Z"
},
{
"_id": "5f647079e9df61290c7336a4",
"updatedAt": "2020-09-03T06:31:36.930Z"
},
{
"_id": "5f6470bfe9df61290c7336a5",
"updatedAt": "2020-09-03T06:31:36.930Z"
}
],
"Shares": []
}
]
},
{
"_id": "5f69f5564e033228a41ed3fa",
"name": "Amitesh Kumar",
"Offer": []
}
]
},
{
"_id": "5f5f5cf2578fea0b640fb753",
"name": "sub cat 3",
"Brand": [
{
"_id": "5f61f3d62565d12a0c101c59",
"name": "qq",
"Offer": []
}
]
}
]
},
{
"_id": "5f5f7f528147c330a46b5ae5",
"name": "aa",
"SubCategory": []
},
{
"_id": "5f5f7f778147c330a46b5ae6",
"name": "qwerer",
"SubCategory": []
},
{
"_id": "5f5f7f848147c330a46b5ae7",
"name": "sasas",
"SubCategory": []
},
{
"_id": "5f5f7fa98147c330a46b5ae8",
"name": "a",
"SubCategory": []
},
{
"_id": "5f6071e352a7f61230cd77ad",
"name": "qw",
"SubCategory": []
},
{
"_id": "5f60727f52a7f61230cd77ae",
"name": "qqqq qq",
"SubCategory": []
},
{
"_id": "5f60cd856eaac2316cd66ce7",
"name": "Amitesh cat",
"SubCategory": []
},
{
"_id": "5f61bd9daffdaa06543a1102",
"name": "aaa",
"SubCategory": []
},
{
"_id": "5f63588f379ffc2e50a5f90a",
"name": "aa ewew wew",
"SubCategory": []
}
]
}
Query For This Data is :
categoryModel.aggregate(
[
{
$lookup:
{
'from': subcategoryModel.collection.name,
"let": { "categoryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$category", "$$categoryId"] } } },
{ '$project': { 'name': 1, '_id': 1 } },
{ '$match': req.body.subCategory ? { '_id': ObjectId(req.body.subCategory) } : {} },
{
"$lookup": {
"from": BrandModel.collection.name,
"let": { "subCategoryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$subCategory", "$$subCategoryId"] } } },
{ '$project': { 'name': 1, '_id': 1 } },
{ '$match': req.body.brand ? { '_id': ObjectId(req.body.brand) } : {} },
{
"$lookup": {
"from": offerModel.collection.name,
"let": { "brandId": "$_id" },
"pipeline": [
{
"$match": {
"$expr": {
"$eq": ["$brand", "$$brandId"],
}
}
},
{ '$project': { 'title': 1, '_id': 1 } },
{ '$match': req.body.offer ? { '_id': ObjectId(req.body.offer) } : {} },
{
"$lookup": {
"from": likeModel.collection.name,
"let": { "offerId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$offer", "$$offerId"] } } },
{ '$project': { 'updatedAt': 1, '_id': 1 } },
{
'$match': req.body.from && req.body.to ? {
'updatedAt': {
"$gte": new Date(req.body.from),
"$lte": new Date(req.body.to)
}
} : req.body.from ? {
'updatedAt': {
"$gte": new Date(req.body.from),
}
} : req.body.to ? {
'updatedAt': {
"$lt": new Date(req.body.to)
}
} : {}
},
],
"as": "Likes"
}
},
{
"$lookup": {
"from": CommentModel.collection.name,
"let": { "offerId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$offer", "$$offerId"] } } },
{ '$project': { 'updatedAt': 1, '_id': 1 } },
{
'$match': req.body.from && req.body.to ? {
'updatedAt': {
"$gte": new Date(req.body.from),
"$lte": new Date(req.body.to)
}
} : req.body.from ? {
'updatedAt': {
"$gte": new Date(req.body.from),
}
} : req.body.to ? {
'updatedAt': {
"$lt": new Date(req.body.to)
}
} : {}
},
],
"as": "Comments"
}
},
{
"$lookup": {
"from": ShareModel.collection.name,
"let": { "offerId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$offer", "$$offerId"] } } },
{ '$project': { 'updatedAt': 1, '_id': 1 } },
{
'$match': req.body.from && req.body.to ? {
'updatedAt': {
"$gte": new Date(req.body.from),
"$lte": new Date(req.body.to)
}
} : req.body.from ? {
'updatedAt': {
"$gte": new Date(req.body.from),
}
} : req.body.to ? {
'updatedAt': {
"$lt": new Date(req.body.to)
}
} : {}
},
],
"as": "Shares"
}
}
],
"as": "Offer"
}
}
],
"as": "Brand"
}
}
],
'as': 'SubCategory',
},
},
{
$project:
{
_id: 1,
name: 1,
SubCategory: 1
}
},
// { $unwind: '$Brand' },
{ $match: match },
// { $sort: sort },
// { $limit: pagination.perPage },
//{ $skip: pagination.skip },
])
What I need is, Only those record who have Offers, with its category and subCategory , I need offers like share comment as well , I search on google I tried many thing I reach to above code but I am stuck now. I am new in MongoDb , Even I tried to restructuring the Result of mongoQuery but got stuck any Ide
A: What if you match your output with:
{ $match: { "SubCategory.Brand.Offer": {"$exists": true} }
This should return only documents the have a Brand and an Offer.
You can check here: mongoplayground
EDIT: to remove also the Offers that are empty, please check this option here:
mongoplayground_2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64042989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Dynamically insert data into an APEX page item when a page item is entered a value I have a form in APEX that is used to add data into a table. Most of the items in the form are free form texts but there few items that are needed to auto filled when you enter a value in on of the page item.
For example.
There is form with Page Items. ID, Name, TitleLevel, Title_prefix, Salalry,
There is a table XYZ with Title_prefix and salary info which
ID Title_prefix Salaray
1 Junior 80000
2 Mid-Level 95000
3 Senior 115000
So you enter ID= 1, Name = ABCD, Titlelevel = 6 is entered and Title_prefix and salary should be populated based on the value that is entered in titlelevel. In this case it will be
Title_Prefix = (SELECT Title_Prefix FROM XYZ WHERE ID = (Case WHEN :P1_TitleLevel > 5 THEN 3 CASE WHEN :P1_TitleLevel = 5 THEN 2 ELSE 1 END))
Same thing for Salary as well.
Immediately after entering Titlelevel page item to 6 the Title_prefix and Salary should get refreshed and populate this items. Then the user will submit the form so that the information can be entered into the table.
A: Add a Dynamic Action on titlelevel (Key Release if Text Field, onChange if dropdown etc.)
Add a PL/SQL Action to the dynamic_action, using Items to Submit to pass fields in and Items to Return for the fields you modify.
Dynamic Action:
OR
Action:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63945584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to detect if user pressed back button in their mobile (browser) with JS I'm developing a PWA and there is a conflict between a library I use for loading and back button
The only thing I need to detect is whether user clicked back button in their mobile (PWA) or not. Then I can handle the rest.
I searched but did not find anything for my case.
I don't want to prevent it from happening, I just want to detect that's it.
And I think mobile back button and browser back button are the same in PWA
Detect if user clicked back button or not.
A: detect browser back
window.onhashchange = function() {
//blah blah blah
}
function goBack() {
window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
//blah blah blah
window.location.lasthash.pop();
}
A: use popstate on window obj window.addEventListener('popstate', callBackFn);
whenever use will click on back button popstate event will get triggered
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74839712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get result of two tables in sql? These are my two tables:
*
*Questions: QuestionID, Question, SubjectID, Totalmarks, IsActive
*RoundDetails: CandidateID, QuestionID, MarksObtain
How to write query to get result of all questions details from Questions table and also result should display whether candidate attempt that question or not?
This is my query but I get only question attempted by candidate but I want both attempted and not attempted:
select
q.QuestionID, q.TotalMarks, q.Question,
isnull(rd.MarksObtained, 0) MarksObtained,
convert(bit, isnull(rd.QuestionID, 0)) Attended
from
Questions q
full join
RoundDetails rd on q.questionID = isnull(rd.QuestionID, q.questionID)
where
q.SubjectID = 2 AND q.IsActive = 1 AND rd.CandidateID = 9
A: The problem with your query is that
AND rd.CandidateID = 9
on the WHERE clause effectively "kills" the full join by requiring that RoundDetails be present.
Move this part of the condition into the ON clause of the join, and replace the join with LEFT OUTER, because you do not need a full outer join anyway:
select
q.QuestionID
, q.TotalMarks
, q.Question
, isnull(rd.MarksObtained, 0) MarksObtained
, convert(bit, isnull(rd.QuestionID, 0)) Attended
from Questions q
left outer join RoundDetails rd
ON q.questionID = q.questionID AND rd.CandidateID = 9
where
q.SubjectID = 2 AND q.IsActive = 1
As a general rule, you should be extremely careful adding conditions on outer-joined tables in the WHERE clause, because any condition that is not null-preserving will convert your outer join to an inner join.
A: Different SQL JOINs
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
As you are using Full Join you will only get the questions that have an answer attempted. you need to use a Left Join instead.
take a look at the joins tutorials on W3Schools
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29516403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: ComponentOne reports : using IEnumerable as datasource I have business objects that implement IEnumerable and I and need to use them as datasource of a ComponentOne report. But, the "myreport.DataSource.Recordset" is only accepting a DataTable.
Could I have some help to find how can a C1Report datasource be fed with IEnumerable BOs ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5211945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AngularJS, Javascript - How to compare two dates that are of mm-yyyy format? I have two strings in mm-yyyy format (eg: 05-2012) and I need to compare them.
I tried using $filter and Date.parse, but no luck thus far. I don't want to append the string with a dummy 'day' part, unless there is no other way.
Below is my code. Any help would be much appreciated. Thanks.
var date1= $filter('text')($scope.date1, "mm-yyyy");
var date2= $filter('text')($scope.date2, "mm-yyyy");
if (date2 <= date1) {
$scope.hasInvalidDate = true;
}
<input type="text" ng-model="date1" placeholder="mm-yyyy">
<input type="text" ng-model="date2" placeholder="mm-yyyy">
A: @SmokeyPHP is right, you can do this with JS. See this SO question.
function parseDate(input) {
var parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[1], parts[0]-1); // Note: months are 0-based
}
> parseDate("05-2012")
Tue May 01 2012 00:00:00 GMT-0600 (MDT)
And you have the compare part correct.
> d1 = parseDate("05-2012")
Tue May 01 2012 00:00:00 GMT-0600 (MDT)
> d2 = parseDate("06-2012")
Fri Jun 01 2012 00:00:00 GMT-0600 (MDT)
> d1 < d2
true
If you do a lot with dates in JS then moment js is worth looking at. Specifically in this case it has a parse method which can take a format string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22359012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL REPLACE with Multiple [0-9] I have a string that I want to replace a group of numbers.
The string contains groupings of numbers (and a few letters). 'A12 456 1 65 7944'
I want to replace the group of 3 numbers with 'xxx', and the group of 4 numbers with 'zzzz'
I thought something like REPLACE(@str, '%[0-9][0-9][0-9]%', 'xxx') would work, but it doesn't. I can't even get '%[0-9]%' to replace anything.
If REPLACE is not suitable, how can I replace groups of numbers?
A: Please try the following solution based on XML and XQuery.
Notable points:
*
*We are tokenizing input string as XML in the CROSS APPLY clause.
*XQuery's FLWOR expression is checking for numeric integer values with
a particular length, and substitutes then with a replacement string.
*XQuery .value() method outputs back a final result.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(MAX));
INSERT INTO @tbl (tokens) VALUES
('A12 456 1 65 7944');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
SELECT t.*
, c.query('
for $x in /root/r/text()
return if (xs:int($x) instance of xs:int and string-length($x)=3) then "xxx"
else if (xs:int($x) instance of xs:int and string-length($x)=4) then "zzzz"
else data($x)
').value('.', 'VARCHAR(MAX)') AS Result
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
REPLACE(tokens, @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)) AS t1(c);
Output
+----+-------------------+-------------------+
| ID | tokens | Result |
+----+-------------------+-------------------+
| 1 | A12 456 1 65 7944 | A12 xxx 1 65 zzzz |
+----+-------------------+-------------------+
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70430718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using f:event to inject a ConversationScoped bean into a ViewScoped bean I can't inject a ConversationScoped bean into a ViewScoped bean, because the ConversationScoped bean could be shorter lived than the ViewScoped one, or vice versa, depending on whether or not the ConversationScoped bean is long-lived.
To get over this limitation, I tried using an f:event to perform the injection as a preRenderView listener:
<f:metadata>
<f:event type="preRenderView" listener="#{taskController.initializeTask(workPackageConversation.workPackage)}" />
</f:metadata>
This howver is not working, neither the listener initializeTask, nor the getter getWorkPackage are being called.
I realize I can lookup one managed bean from another, using the FacesContext, but I am curious why this isn't working. Is it because the f:event listener isn't called when I navigate to a view from another view? ie. without a redirect or direct page view?
I also tried the s:viewAction tag from Seam 3 Faces, to no avail. It does not get called either.
Thanks in advance.
A: I would think the lifetime issues would not come into play since you've always got a proxy to the normal-scoped bean anyway. You either dereference the conversation-scoped bean while the conversation is active, or it's not active -- but you'll always get the right conversation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4686311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git Jenkins Continous Integration Push Issue I have a git bare repository hosted on a server. I checked out a local git repository, made quite a few changes and then pushed it to the server. I also have a jenkins build box which uses a git hook to schedule a build on the develop branch and merge changes to master branch on the server if all is successful.
Those changes that I committed and pushed were reverted using a reset and merge. So the origin/develop origin/head and origin/master all point to a previous point in history.
Now the problem I have is on the continous integration box it fetches fine from the remote server builds the project fine, creates a tag but when it tries to do a push it spits out the following :
Pushing HEAD to branch master of origin repository
/usr/bin/git config --get remote.origin.url
/usr/bin/git push ssh://192.168.34.xxx/usr/git/xxxxxx-xxx.git HEAD:master
ERROR: Failed to push merge to origin repository
hudson.plugins.git.GitException: Command "/usr/bin/git push ssh://192.168.34.xxx/usr/git/xxxxxx-xxx.git HEAD:master" returned status code 1:
stdout:
stderr: remote: error: insufficient permission for adding an object to repository database ./objects
remote: fatal: failed to write object
error: unpack failed: unpack-objects abnormal exit
To ssh://192.168.34.xxx/usr/git/xxxxxx-xxx.git
! [remote rejected] HEAD -> master (unpacker error)
error: failed to push some refs to 'ssh://192.168.34.xxx/usr/git/xxxxxxx-xxx.git'
The issue is that this push worked fine before the reset to the server, I am assuming the push is failing because the server is modified and so a pull and merger or fetch needs to be done on the jenkins build box first locally.
I have also read a bit about permission issue that might be on the server I doubt this is the issue because this worked fine previously till I did the reset to the server. According to my understanding of git a push would fail if the place being pushed to was modified, so a pull and merge needs to be done first.
I was thinking to pull the origin/master branch down merge it with the local master and push those changes or reset the local master to be the same as origin/master.
I apologise in advance if I am not clear in places. I have limited experience with git but I have done quite a bit of reading recently. I am just scared to try stuff not knowing the implications and also I am not sure what I am thinking will actually work.
Please could I get assistance. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26448945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Running PHP inside of PHP? I am still learning and I found that I can't run PHP within PHP, after reading into it makes sense why you cannot do it (D'oh!), what I am struggling to find is the correct way to do this.
I have two buttons which link to different modals, if I do not use them within a IF Statement they work as expected as soon as I add to the IF Statement it breaks the page. (obviously because I am trying to run php within php)
What I'm trying to get working is to show a different button depending on the result of a column called "status" in the MySQL table, if it equals 1 it will show the edit button if anything else it will show a check-out button. I need to pass the <?php echo $fetch['id']?> to the data-target I'm not sure how to go about that.
<?php
$status_code = $fetch["status"];
if("$status_code" == "1")
{ echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<?
php echo $fetch['id']?>"><span class="glyphicon glyphicon-plus"></span>edit</button>';
} else
{ echo '<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal<?
php echo $fetch['id']?>"></span>Check-Out</button>';
} ?>
Any help is much appreciated.
A: You just need simple concatenation with the . (dot) operator.
E.g.
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal'.$fetch['id'].'"><span class="glyphicon glyphicon-plus"></span>edit</button>';
...etc.
This is used to join any two string values (whether hard-coded literals or variables) together. What's happening here is your code is building a string from several components and then echoing it.
Documentation: https://www.php.net/manual/en/language.operators.string.php
A: You don't need to run PHP inside PHP.
You may use a comma (or a dot):
<?php
if ($status_code == "1") {
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<'
, $fetch['id']
, '"><span class="glyphicon glyphicon-plus"></span>edit</button>';
} else {
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal'
, $fetch['id']
, '">Check-Out</button>';
}
Or using short tags:
<?php if ($status_code === '1') : ?>
<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<?= $fetch['id'] ?>">
<span class="glyphicon glyphicon-plus"></span>edit</button>'
<?php else: ?>
<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal<?= $fetch['id'] ?>">Check-Out</button>'
<?php endif; ?>
You can have conditions (and other expressions) in short tags:
<button
type="button"
class="button-7"
data-toggle="modal"
data-target="#<?=
$status_code === '1'
? 'update_modal'
: 'checkout_modal'
?><?= $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span class="glyphicon glyphicon-plus"></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>
And concatenate strings with dots:
<?php
$dataTargetPrefix =
$status_code === '1'
? 'update_modal'
: 'checkout_modal';
?>
<button
type="button"
class="button-7"
data-toggle="modal"
data-target="#<?= $dataTargetPrefix . $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span class="glyphicon glyphicon-plus"></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73628491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ubuntu etcd.service start failed with (code = exited, status=1/FAILURE) When I have written my etcd.service file, and run with the systemctl start etcd.service command, it gives this error:
etcd.service - ve489 etcd service
Loaded: loaded (/lib/systemd/system/etcd.service; enabled; vendor preset: enabled)
Active: activating (auto-restart) (Result: exit-code) since Sat 2022-06-18 20:59:50 PDT; 3s ago
Docs: https://github.com/etcd-io/etcd
Process: 13415 ExecStart=/usr/local/bin/etcd --name ubuntu20 --data-dir /var/lib/etcd --initial-advertise-peer-urls http://192.168.159.128:2380 --listen-peer-urls http://192.168.159.128:2380 --listen-client-urls http://192.168.159.128:2379,http://127.0.0.1:2379 --advertise-client-urls http://192.168.159.128:2379 --initial-cluster-token etcd-cluster-1 --initial-cluster etcd-1=http://192.168.159.128:2380,etcd-2=http://192.168.159.129:2380 --initial-cluster-state new --heartbeat-interval 1000 --election-timeout 5000 (code=exited, status=1/FAILURE)
Main PID: 13415 (code=exited, status=1/FAILURE)
And the source code in the file etcd.service is
[Unit]
Description=ve489 etcd service
Documentation=https://github.com/etcd-io/etcd
[Service]
User=root
Type=notify
ExecStart=/usr/local/bin/etcd \
--name ubuntu20 \
--data-dir /var/lib/etcd \
--initial-advertise-peer-urls http://192.168.159.128:2380 \
--listen-peer-urls http://192.168.159.128:2380 \
--listen-client-urls http://192.168.159.128:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.159.128:2379 \
--initial-cluster-token etcd-cluster-1 \
--initial-cluster etcd-1=http://192.168.159.128:2380,etcd-2=http://192.168.159.129:2380 \
--initial-cluster-state new \
--heartbeat-interval 1000 \
--election-timeout 5000
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
and the journalctl -xe command gives this:
Jun 18 21:03:57 ubuntu systemd[1]: etcd.service: Main process exited, code=exited, status=1/FAILURE
-- Subject: Unit process exited
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- An ExecStart= process belonging to unit etcd.service has exited.
--
-- The process' exit code is 'exited' and its exit status is 1.
Jun 18 21:03:57 ubuntu systemd[1]: etcd.service: Failed with result 'exit-code'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit etcd.service has entered the 'failed' state with result 'exit-code'.
Jun 18 21:03:57 ubuntu systemd[1]: Failed to start ve489 etcd service.
-- Subject: A start job for unit etcd.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit etcd.service has finished with a failure.
--
-- The job identifier is 38547 and the job result is failed.
I am a new guy to get in touch with etcd so I have no idea what was wrong, can someone help me with this problem?
A: I hava the same problem。this is my solution。
first stop etcd service using systemctl
systemctl stop etcd.service
and then, check port is occupied
lsof -i:2380
if occupied kill the pid
kill -9 xxx
last,start etcd service
systemctl start etcd.service
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72674204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mysql: see all open connections to a given database? With administrative permissions im mysql, how can I see all the open connections to a specific db in my server?
A: As well you can use:
mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects | 0 |
| Connections | 303 |
| Max_used_connections | 127 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 127 |
+--------------------------+-------+
7 rows in set (0.01 sec)
Feel free to use
Mysql-server-status-variables or Too-many-connections-problem
A: SQL:
show full processlist;
This is what the MySQL Workbench does.
A: In MySql,the following query shall show the total number of open connections:
show status like 'Threads_connected';
A: That should do the trick for the newest MySQL versions:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE DB like "%DBName%";
A: The command is
SHOW PROCESSLIST
Unfortunately, it has no narrowing parameters. If you need them you can do it from the command line:
mysqladmin processlist | grep database-name
A: If you're running a *nix system, also consider mytop.
To limit the results to one database, press "d" when it's running then type in the database name.
A: You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
A: From the monitoring context here is how you can easily view the connections to all databases sorted by database. With that data easily monitor.
SELECT DB,USER,HOST,STATE FROM INFORMATION_SCHEMA.PROCESSLIST ORDER BY DB DESC;
+------+-------+---------------------+-----------+
| DB | USER | HOST | STATE |
+------+-------+---------------------+-----------+
| web | tommy | 201.29.120.10:41146 | executing |
+------+-------+---------------------+-----------+
If we encounter any hosts hots max connections and then not able to connect, then we can reset host tables by flushing it and is as follows:
FLUSH HOSTS;
A: In query browser right click on database and select processlist
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1620662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "152"
}
|
Q: Permission ATTR{idVendor} for USB devices on linux mint to use table mobii protab2 XXL I am using linux mint, and consulting VendorIds from http://developer.android.com I don't know how to detect my tablet device correctly. My tablet device is Mobii protab 2 XXL, fabricated by Point of view.
I have created 50-android.rules at /etc/udev/rules.d/ and added line:
SUBSYSTEM=="usb|usb_device", SYSFS{idVendor}==”0955″, MODE=”0666″
But adb devices throw:
List of devices attached ???????????? no permissions
Does anyone know which idvendor do I have to use???
usb:
lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 002 Device 002: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUB
Bus 002 Device 005: ID 1058:1003 Western Digital Technologies, Inc.
Bus 007 Device 002: ID 1a34:0203
Bus 007 Device 003: ID 06f8:3008 Guillemot Corp.
Bus 008 Device 002: ID 046d:c050 Logitech, Inc. RX 250 Optical Mouse
Bus 002 Device 007: ID 0a81:0101 Chesen Electronics Corp. Keyboard
Bus 002 Device 008: ID 18d1:0003 Google Inc.
And I put in udev last time:
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1:0003", SYMLINK+="android_adb", MODE="0666" GROUP="plugdev"
It worked the first time, but when I restart the PC, the permissions are denied. I have tried to restart:
sudo service udev restart
adb kill-server
adb start-server
But it didn't work.
NOTE:
Some devices don't work propertly doing this process. If you still having problems, try execute
sudo adb start-server
It works with Point of view device.
A: On 51-android.rules:
SUBSYSTEMS=="usb", ATTRS{idVendor}=="18b1", ATTRS{idProduct}=="0003", MODE="0666".
And use chmod command to have permission 666 (the number of the beast, muahahhaha) on adb or will not work.
Good luck.
A: SUBSYSTEMS=="usb",
ATTRS{idVendor}=="0bb4",
ATTRS{idProduct}=="XXXX",
MODE="0660",
OWNER="`<your user name>`"
and try using upper case and lower case because in linux a lot of people are having problems to add permissions.
A: Following from the Arch Linux Wiki page I would create /etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="18D1", MODE="0666"
SUBSYSTEM=="usb",ATTR{idVendor}=="18D1",ATTR{idProduct}=="0003",SYMLINK+="android_adb"
SUBSYSTEM=="usb",ATTR{idVendor}=="18D1",ATTR{idProduct}=="0003",SYMLINK+="android_fastboot"
Then as root run udevadm control --reload-rules
You may need to replace 18D1 with 18d1. That is what I have done and it works great. You don't necessarily need the username as long as you give permission (MODE="0666") to everyone. If you require more security look at adding the OWNER tag. Again these are rules that I have used on Arch, they should work on Mint.
Good luck!
A: *
*Connect your device.
*Run lsusb.
*Disconnect your device and run it again.
*Find your device hex by comparing both lsusb results:Bus 001 Device 013: ID xxxx:2765 and note the xxxx
*Create a new rule:sudo nano /tmp/android.rules
*Insert:SUBSYSTEM=="usb", ATTRS{idVendor}=="xxxx", MODE="0666"
*Copy the rule:sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules
*Change permissions:sudo chmod 644 /etc/udev/rules.d/51-android.rulessudo chown root. /etc/udev/rules.d/51-android.rules
*Retstart ADB:sudo service udev restartsudo killall adb
*Reconnect your device.
*Test ADB: adb devicesList of devices attachedxyzxyzxyz device
Source: pts.blog: How to fix the adb no permissions error on Ubuntu Lucid
A: As suggested by Ethan, look at "lsusb" to locate the Mobii vendor ID. In the example below, 046d is the ID for Logitech. "0955" belongs to nVidia.
Bus 001 Device 006: ID 046d:c52b Logitech, Inc. Unifying Receiver
Also, don't forget to restart udev after you've changed the 50-android.rules file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9929649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: CLIENT_MISSING_INTENTS' enter image description here
i need help with that error when first coding discord bot
here code
const client = new Discord.Client()
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
if (msg.content === "ping") {
msg.reply("pong");
}
})
client.login(process.env.TOKEN)
i try many way on internet but it still not sold ;.;
pls help me
this is error
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (E:\bot\node_modules\discord.js\src\client\Client.js:544:13)
at new Client (E:\bot\node_modules\discord.js\src\client\Client.js:73:10)
at Object.<anonymous> (E:\bot\src\bot.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47 {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
A:
To specify which events you want your bot to receive, first think about which events your bot needs to operate. Then select the required intents and add them to your client constructor, as shown below.
All gateway intents, and the events belonging to each, are listed on the Discord API documentation. If you need your bot to receive messages (MESSAGE_CREATE - "messageCreate" in discord.js), you need the GUILD_MESSAGES intent. If you want your bot to post welcome messages for new members (GUILD_MEMBER_ADD - "guildMemberAdd" in discord.js), you need the GUILD_MEMBERS intent, and so on.
Example:
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES
]
});
A: The issue is exactly what the error says it is; your client is missing intents. You need to specify what events and data your bot intends to work with (e.g. guild member presences, messages, etc).
i try many way on internet but it still not sold
I don't know what tutorials or guides you're looking at, but only discord.js v11 and under can work without intents. Discord.js v12 and the latest version (v13) require intents to be specified. What intents you need to specify depends on what you want your bot to do. Does your bot need to detect messages and respond to them? Then enable the GUILD_MESSAGES intent. If your bot does not need to, for example, track guild member presences, you do not need to enable a GUILD_PRESENCES intent.
Before continuing, I would highly suggest you check out the official discord.js guide on how to create a bot on the latest version, which should have been the first place you looked for this information.
Here is a simple way to solve your issue based on the code on that guide, if you are using discord.js v13:
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
Here is another way of doing it, if you are on discord.js v12 (this may also work in v13):
// Require the necessary discord.js classes
const { Client } = require('discord.js');
// Create a new client instance
const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES"], ws: {intents: ["GUILDS", "GUILD_MESSAGES"]} });
Note that the intents I specified in the above examples may not be enough for you, depending on what your bot is supposed to do in the future. But I believe those examples will be enough to get your current code working without the error you are experiencing.
For a full list of intents, check the discord developer docs here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69201388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Error 10038 (Socket operation on invalid socket) when trying to send a string from Winsock2 C program I'm trying to make a C library that mimics Python socket library.
When i run my main function, an error occurs on simplesend(sucket, "foo");
the whole main function:
int main(){
struct SIMPLESOCKET sucket;
simpleinit(sucket);
simpleconnect(sucket, "ip", "port");
simplesend(sucket, "foo");
simpleclose(sucket);
return 0;
}
this is the definition of the SIMPLESOCKET struct:
#include <winsock2.h>
#include <ws2tcpip.h>
struct SIMPLESOCKET{
WSADATA wsaData;
int iResult;
struct addrinfo *result;
struct addrinfo *ptr;
struct addrinfo hints;
SOCKET ConnectSocket;
};
I get error 10038, which is "socket operation on invalid socket". But when i check s.ConnectSocket, it isn't equal to INVALID_SOCKET.
the simplesend function body:
int simplesend(struct SIMPLESOCKET s, char* msg){
s.iResult = send(s.ConnectSocket, msg, (int) strlen(msg), 0);
if (s.iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(s.ConnectSocket);
WSACleanup();
return 1;
}
}
and the only part of the code that does stuff to s.ConnectSocket doesnt give any errors, here it is:
int simpleconnect(struct SIMPLESOCKET s, char* ip, char* port){
memset(&s.hints, 0, sizeof(s.hints));
s.iResult = getaddrinfo(ip, port, &s.hints, &s.result);
if (s.iResult != 0) {
printf("getaddrinfo failed: %d\n", s.iResult);
WSACleanup();
return 1;
}
s.ConnectSocket = INVALID_SOCKET;
s.ptr=s.result;
s.ConnectSocket = socket(s.ptr->ai_family, s.ptr->ai_socktype, s.ptr->ai_protocol);
if (s.ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(s.result);
WSACleanup();
return 1;
}
//connect
s.iResult = connect(s.ConnectSocket, s.ptr->ai_addr, (int)s.ptr->ai_addrlen);
if (s.iResult == SOCKET_ERROR) {
printf("1977\n");
closesocket(s.ConnectSocket);
s.ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(s.result);
if (s.ConnectSocket == INVALID_SOCKET) {
printf("unable to connect to server\n");
WSACleanup();
return 1;
}
}
So, i really don't understand why i get an invalid socket error since i even get the successfull connection on my python server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74667888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Destroying file after HTTP response in Django I'm now making website that downloads certain images from other website, zip files, and let users download the zip file.
Everything works great, but I have no way to delete zip file from server, which has to be deleted after users download it.
I tried deleting temp directory that contains zip file with shutil.rmtree, but I couldn't find way to run it after HTTPResponse.
Here is my code in views.py.
zipdir = condown(idx)#condown creates zip file in zipdir
logging.info(os.path.basename(zipdir))
if os.path.exists(zipdir):
with open(zipdir, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="multipart/form-data")
response['Content-Disposition'] = 'inline; filename=download.zip'
return response
raise Http404
Thanks in advance.
A: You should looks to Celery project. It allows to schedule delayed function calls (after response generated).
So you can read that file to a variable and schedule task to remove that file.
# views.py
def some_view(request):
zipdir = condown(idx)#condown creates zip file in zipdir
logging.info(os.path.basename(zipdir))
response = HttpResponseNotFound()
if os.path.exists(zipdir):
with open(zipdir, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="multipart/form-data")
response['Content-Disposition'] = 'inline; filename=download.zip'
task_delete_zipfile.delay(zipdir)
return response
# tasks.py
import os
from webapp.celery import app
@app.task
def task_delete_zipfile(filePath):
if os.path.exists(filePath):
os.remove(filePath)
else:
print("Can not delete the file as it doesn't exists")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58581479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Omniauth localization in ruby on rails How do omniauth localize in ruby on rails project?
I want use :ru localization.
In my project I use:
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem 'omniauth-vkontakte'
gem 'omniauth-mailru'
gem "omniauth-google-oauth2"
A: I'm not sure that omniauth allows you to provide translations for the messages that come out of it. There don't seem to be any en.yml files in omniauth, omniauth-facebook or omniauth-twitter anyway.
I've only used omniauth with devise and devise provides a couple of omniauth-related messages which can be overridden, but they contain the untranslated error messages which come out of omniauth:
en:
devise:
omniauth_callbacks:
failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
success: "Successfully authenticated from %{kind} account."
These can be overridden in an app using devise by providing an en translations file containing these in config/locales in your app. You can of course also provide a ru translations file and set config.default_locale = :ru in application.rb or use some other way to decide which locale to use. You can see how devise builds an error message from an omniauth failure here:
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/omniauth_callbacks_controller.rb
You could use the same approach in your app without using devise, but as I say, the problem is that %{reason} would be the untranslated error (often an exception.message I think) from omniauth.
For general internationalisation, if you haven't read it already: Rails i18n
EDIT:
It sounded like you were asking about omniauth itself, but in case, as Ashitaka wondered in their comment, you were (also) asking about telling the services you call which locale to use, you've probably seen in the docs, but just for the sake of completeness it does indeed vary by service. For example, omniauth-facebook lets you add a locale parameter to the facebook call (e.g. locale=ru_RU) and omniauth-twitter lets you add a lang parameter to the twitter call (e.g. lang=ru).
A: If you browse under app/config/locales dir, there is a file en.yml. It is for english locale. If you would like to add other languages, just create (in your case) ru.yml file and place translations there.
This Rails guide is a nice staring point.
Recently I have tried another interesting approach : phrasing gem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21497319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I deal with old collected metrics in Prometheus? I am using a Gauge Vector in my application for collecting and exposing a particular metric with labels from my application in the Prometheus metrics format. The problem is that once I have set a metric value for a particular set of labels, even if that metric is not collected again it will be scraped by Prometheus until the application restarts and the metric is removed from memory. This means that even if that metric is no longer valid anymore (hasn't been set again for a day say) Prometheus will still be scraping it as if it's a fresh metric.
Is it possible to either set an expiry time for collected metrics or to remove the collected metric completely? Or are problems like this dealt with on the Prometheus server side?
A: These are the correct semantics. Prometheus deals with metrics and metrics don't go away just because they haven't changed in a while. What you should be doing is keeping the gauge up to date.
It sounds like you might want a logs-based monitoring system, such as provided by the ELK stack.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48324007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Nested query with aggregation in Mongo I have a document in MongoDB:
{
"_id" : ObjectId("111111111111111111111111"),
"taskName" : "scan",
"nMapRun" : {
...
"hosts" : {
...
"distance" : {
"value" : "1"
},..
}
I'm interested in the field: nMapRun.hosts.distance.value
How do I get ten maximum values of the field .
Could you give an example of a Java?
A: The aggregation operation in shell:
db.collection.aggregate([
{$sort:{"nMapRun.hosts.distance.value":-1}},
{$limit:10},
{$group:{"_id":null,"values":{$push:"$nMapRun.hosts.distance.value"}}},
{$project:{"_id":0,"values":1}}
])
You need to build the corresponding DBObjects for each stage as below:
DBObject sort = new BasicDBObject("$sort",
new BasicDBObject("nMapRun.hosts.distance.value", -1));
DBObject limit = new BasicDBObject("$limit", 10);
DBObject groupFields = new BasicDBObject( "_id", null);
groupFields.put("values",
new BasicDBObject( "$push","$nMapRun.hosts.distance.value"));
DBObject group = new BasicDBObject("$group", groupFields);
DBObject fields = new BasicDBObject("values", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );
Running the aggregation pipeline:
List<DBObject> pipeline = Arrays.asList(sort, limit, group, project);
AggregationOutput output = coll.aggregate(pipeline);
output.results().forEach(i -> System.out.println(i));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27201111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R Logistic Regression using summary table Can I run multiple logistic regression in R using data not from whole database, but only using summarized values?
In other words, can I still run the logistic regression and build a model only when I have a table like this:
Age Group
No outcome
Outcome
female, 18-39
130
9
female, 40-59
156
22
female, 60 and older
165
18:
male, 18-39
234
44
male, 40-59
156
34
male, 60 and older
90
5
A: Adding to my comment: You can do this by using the definiton of comparing 2 columns described in ?glm.
data <- data.frame(AgeGroup = c('female, 18-39', 'female, 40-59', 'female, 60 and older', 'male, 18-39', 'male, 40-59', 'male, 60- and older'),
NoOutcome = c(130, 156, 165, 234, 156, 90),
Outcome = c(9, 22, 18, 44, 34, 5))
fit <- glm(cbind(Outcome, NoOutcome) ~ AgeGroup, data = data, family = binomial)
This is equivalent to expanding each group to individual rows and doing a binary regression:
data_long <- do.call(rbind, lapply(split(data, data$AgeGroup),
\(data)data.frame(AgeGroup = data[, 1], outcome = rep(c(0, 1), c(data[,2], data[,3])))))
fit_long <- glm(outcome ~ AgeGroup, family = binomial, data = data_long)
summary(fit_long)
summary(fit) # identical
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73553056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kubernetes: Tasks that need to be done once per cluster or per statefulset or replicaset So i heard about initConainers which allow you to do pre-app-container initialization. However, i want initialization which are done either at the cluster level or statefulset, or even the whole pod.
For instance, I want to perform a one time hadoop namenode format on my persistent volumes and be done with that. After that is done my namenode statefulset and my datanode replicasets can proceed each time
Does kubernetes have anything to accommodate this?
How about its Extensions?
A: Kubernetes itself provides Jobs for ad hoc executions. Jobs do not integrate very tightly with existing Pods/Deployments/Statefulsets.
Helm is a deployment orchestrator and includes pre and post hooks that can be used during an install or upgrade.
The helm docco provides a Job example run post-install via annotations.
metadata:
annotations:
# This is what defines this resource as a hook. Without this line, the
# job is considered part of the release.
"helm.sh/hook": post-install
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": hook-succeeded
If you have more complex requirements you could do the same with a manager or Jobs that query the kubernetes API's to check on cluster state.
Helm 3
A warning that helm is moving to v3.x soon where they have rearchitected away a lot of significant problems from v2. If you are just getting started with helm, keep an eye out for the v3 beta. It's only alpha as of 08/2019.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57386429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to reference an assembly in GAC I'm trying to deploy an assembly in GAC, I did that successfully using Gacutil.exe utility.
Now, when I try to add a reference for it from Visual Studio - Add Reference - .Net tab, I don't find it!!
Any help!
A: I had this problem, the GAC'ed dlls arent included in the references.
Check out this post I made:
Add Reference in Framework 4 Application is not showing assemblies in GAC registered with GACUtil V 4
To make things easier, the link to the msdn article:
http://msdn.microsoft.com/en-us/library/wkze6zky(VS.100).aspx
And to paraphrase, create an entry along the lines of the following:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft.NETFramework\v4.0.30319\AssemblyFoldersEx\MyMagicAssemblies] and then set the (Default) value to be a string with the value being the path you want searched. Look at your registry for examples of how this is set up (so the default value becomes: c:\dlls\
v4.0.30319 would be replaced with the framework version you want the dlls to show up against.
because your dlls are in the GAC it will use those as the actual reference and not the files you are showing in the reference list. Only if the version number of the dlls are different will it use your local version.
A: I've created a sexy visual studio extension that will help you to achieve your goal. Muse VSReferences will allow you to add a Global Assembly Cache reference to the project from Add GAC Reference menu item.
Regards...
Muse Extensions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5016966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MAX IF INDEX Function? Currently, I have a table like the one below.
Jan-16 Feb-16 Mar-16 Apr-16 May-16 Jun-16 Jul-16 Aug-16 Sep-16 Oct-16 Nov-16 Dec-16
Forecast 5 8 7 - - - - - - - - -
The monthly forecast figure is set to populate only once that month closes.
In my dashboard, I am attempting to capture the most recent Forecast number in this table so the output would look something like...
Current Forecast 7
I would assume that to achieve this, Current Forecast would require a series of IF, INDEX, MATCH, and MAX (for max date) functions but I'm unable to figure this out.
From deleted comments:
Sorry I didn't clarify. That's correct-- the "-" are zeros with the number format applied.
A: I haven't tested this, but looks like it'll do what you're looking for.
=INDEX(B$2:M$2,MATCH(TRUE,INDEX(B2:M2<>"-",),0))
Modified from here
As Dirk pointed out, this actually returns the first match.
A: if there are no empty dates between the values then, then this formula will do:
=INDEX(B2:M2,COUNTIF(B2:M2,"<>-"))
and having empty dates inbetween then this array-formula will do
=INDEX(B2:M2,MAX(ISNUMBER(B2:M2)*COLUMN(A:L)))
Needs to be confirmed with Ctrl + Shift + Enter
A: The first question would be if those are real dates across row 1 or text-that-look-like-dates. Let's say those are real dates formatted as mmm-yy because that is the better method.
The second question is whether the inactive numbers in row 2 are showing hyphens because they are zeroes with an accounting style number format or if you have actually put hyphens in the cells. Let's say they are zeroes with an accounting style number format because that is the better way to do it.
=INDEX(B2:M2, MATCH(AGGREGATE(14, 6, (B1:M1)/(B2:M2<>0), 1), B1:M1, 0))
' for pre xl2010 systems w/o AGGREGATE
=INDEX(B2:M2, MATCH(MAX(INDEX((B1:M1)+(B2:M2=0)*-1E+99, , )), B1:M1, 0))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36393667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Python got many issues with Spyne Well, here's my Python code:
#!/usr/bin/env python
from spyne import Application, rpc, ServiceBase, Unicode
from lxml import etree
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
# Wsgi это Web server Getewap Interface - стандар взаимодействия с питон программой и серверо где он работает
class Soap(ServiceBase):
@rpc(Unicode, _return=Unicode)
def Insoap(ctx, words):
print("Connection detected: ", etree.tostring(ctx.in_document))
ww = str(words).capitalize()
return ww
app = Application([Soap], tns='Capitalize', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
application = WsgiApplication(app) # Важна названия переменной, иначе сервер не поймет
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8002, application)
server.serve_forever()
But get this error, what's the problem? What should I do for a solution? Please, get help me to solve this problem
Traceback (most recent call last):
File "C:/Users/David374/PycharmProjects/untitled8/venv/test.py", line 3, in <module>
from spyne import Application, rpc, ServiceBase, Iterable, UnsignedInteger, \
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\__init__.py", line 63, in <module>
from spyne.server import ServerBase, NullServer
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\__init__.py", line 23, in <module>
from spyne.server.null import NullServer
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\null.py", line 69
self.service = _FunctionProxy(self, self.app, async=False)
^
SyntaxError: invalid syntax
A: async is a reserved keyword in Python 3.7+, and you'll need to use the latest version of Spyne, which doesn't use that reserved keyword as a parameter in its functions, if you want to use it with Python 3.7+.
Either update Spyne to spyne-2.13.2-alpha, or use Python 3.6 or lower.
Sources:
*
*https://docs.python.org/3/whatsnew/3.7.html
*https://pypi.org/project/spyne/2.13.2a0/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61124164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to send array of dictionarys in swift by using alamafire(Post method) I am running with an issue where my server is expecting an array of dictionarys from the app side. Please suggest where I'm going wrong here, code below
{
let param : [String : AnyObject] =
["trf_id" : Constant.constantVariables.trfID,
"mode" : Constant.modeValues.createMode,
"to_city" : Constant.constantVariables.to_city,
"from_city" : Constant.constantVariables.from_city,
"description" : Constant.constantVariables.descrption,
"request_type" : Constant.constantVariables.request_type,
"to_date" : Constant.constantVariables.to_date!,
"from_date" : Constant.constantVariables.from_date!,
"travel_configs" : ["Config_id" : "9","values" : "train",
"Config_id" : "10","values" : "bus"]]
print(param)
}
*
*Where travel_configs is array of dictionaries
I have to send it like this because of server exceptions
trf_id:37
mode:1
request_type:0
from_city:sdfsd
to_city:qws
from_date:2016-08-17
to_date:2016-08-26
description:sdfsdf
travel_configs:[
{"config_id":"11","values":"1"}
,{"config_id":"2","values":"Flight"}]
A: Finally i got answer after 3 days of struggling
just send your array of dictionary into this
class func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{
let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)
if NSJSONSerialization.isValidJSONObject(value) {
do{
let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}catch {
print("error")
//Access error here
}
}
return ""
}
Hope this will help some one else Thank you..
A: First, it might come from the capital "C" instead of "c" in "config_id" ?
Secondary, you are actually missing [], your code should look like this :
let param : [String : AnyObject] =
["trf_id" : Constant.constantVariables.trfID,
"mode" : Constant.modeValues.createMode,
"to_city" : Constant.constantVariables.to_city,
"from_city" : Constant.constantVariables.from_city,
"description" : Constant.constantVariables.descrption,
"request_type" : Constant.constantVariables.request_type,
"to_date" : Constant.constantVariables.to_date!,
"from_date" : Constant.constantVariables.from_date!,
"travel_configs" : [["Config_id" : "9","values" : "train",
"Config_id" : "10","values" : "bus"]]]
Why?
Because your server is expecting an array of dictionary, and you are sending only a dictionary ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38889421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ubuntu WSL with docker could not be found The command $ docker could not be found in this WSL 1 distro.
We recommend to convert this distro to WSL 2 and activate
the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
Not able to change to WSL2 and not able to install docker:
A: My problem seems like it's the same, despite the integration WSL is already enabled since installation.
In the windows shell:
> wsl docker --version
The command 'docker' could not be found in this WSL 2 distro.
We recommend to activate the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
An option to resolve this problem is reinstalling Docker Desktop (https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-docker/configure-docker-daemon#how-to-uninstall-docker), but don't need to do this.
The steps below work for me (I found at https://github.com/docker/for-win/issues/7039).
Open windows shell (maybe as admin), and run:
> wsl -t docker-desktop
> wsl --shutdown
> wsl --unregister docker-desktop
Then go to windows services, stop the Docker Desktop Service, OR to do this running the command in windows shell as admin:
> Stop-Service -Name "com.docker.service"
And finally, restart the Docker Desktop App.
Test in the windows shell:
> wsl docker --version
Docker version 20.10.2, build 2291f61
A: For those still having issues with this, some of my symlinks magically vanished and no amount of reinstalling helped.
Make sure you have the following symlinks in your WSL2 installation:
$ ls -l /usr/bin/ | grep docker
lrwxrwxrwx 1 root root 56 Jul 14 13:01 com.docker.cli -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/com.docker.cli
lrwxrwxrwx 1 root root 48 Jul 14 13:01 docker -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker
lrwxrwxrwx 1 root root 56 Jul 14 13:01 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose
lrwxrwxrwx 1 root root 59 Jul 14 13:01 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1
lrwxrwxrwx 1 root root 71 Jul 14 13:01 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe
lrwxrwxrwx 1 root root 50 Jul 14 13:01 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool
lrwxrwxrwx 1 root root 48 Jun 29 09:27 notary -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/notary
A: WSL Integration under Resources was not showing for me.
I had to uncheck "Use the WSL2 based engine" under General settings, Apply, then Check it again, Apply, then WSL Integration showed up under resources and I could click the Ubuntu slider.
A: For me running the following command in wsl terminal worked
sudo apt-get update
apt-cache policy docker-ce
sudo apt-get install -y docker-ce
sudo apt-get install docker-compose
sudo apt-get upgrade
source- https://www.srcmake.com/home/fabric
A: I had this issue, for me running
$ ls -l /usr/bin/ | grep docker
showed all the correct symlinks as per this answer however I saw the following:
which docker
/mnt/c/Program Files/Docker/Docker/resources/bin/docker
The fix was to simply to set the PATH variable to have /user/bin as the first entry
PATH="/usr/bin:$PATH"
From the multitude of answers, it seems like there are many things that can cause this error, so your mileage may vary.
Another good thing to check is that Docker Desktop is actually running. If it isn't, which docker will result in the /mnt/c/... directory as above.
A: As Taylor wrote in his comment you need to connect from WSL to docker desktop.
In the image you attached there is a check box expose daemon on ...
Check this box.
Now you need docker cli, you can install Linux vm then install docker in that Linux vm you just installed.
Then run which docker and copy this file to your windows computer.
Copy the docker executable into /usr/local/bin on your WSL.
Now run the following in WSL
echo "export DOCKER_HOST=tcp://localhost:2375" >> ~/.bashrc
. ~/.bashrc
This worked for me on WSL 1.
Here is guide I found on the all process
A: Fabrício Pereiras answer was working for me, but I had to do it pretty often, which was still annoying.
Turns out the order of starting the systems is important too.
Start Docker first, then WSL2 after.
I don't start Docker Desktop with Windows and usually had opened a terminal in WSL already. Then Docker could not be found. Fabricios answer was working for me because I shutdown WSL2, then started it again when Docker was already running.
A: In my case, the integration was correctly set in the docker-app, WSL2 was correctly the default wsl, and I wasn't able to solve unregistering the wsl docker instance and restarting the docker service like mentioned in other answers.
After some time, I noticed that the command docker-compose successfully worked. The issue was limited to the docker command.
I looked for all docker commands in the directory usr/bin, that is the path where docker-compose is located (which docker-compose), so runnining ls -l /usr/bin | grep docker, I found
drwxrwxrwx 1 root root 48 Nov 29 10:59 docker
lrwxrwxrwx 1 root root 56 Nov 29 10:59 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose*
lrwxrwxrwx 1 root root 59 Nov 29 10:59 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1*
lrwxrwxrwx 1 root root 71 Nov 29 10:59 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe*
lrwxrwxrwx 1 root root 50 Nov 29 10:59 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool*
For some weird reason, docker wasn't a symbolic link but a directory.
I solved removing the directory and re-creating manually the symbolic link:
rm -rf /usr/bin/docker
sudo ln -s /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker /usr/bin/docker
A: I followed theses steps: https://learn.microsoft.com/en-us/windows/wsl/install-win10
Also, for docker into ubuntu, I enabled it in docker resources as a final step.
Settings > Resources > WSL Integration.
from: https://docs.docker.com/docker-for-windows/wsl/
A: Make sure that you have a distro that is compatible with wsl2:
https://ubuntu.com/wsl
A: I was experiencing the same issue with Ubuntu-20.04 (WSL2) and Docker Desktop (v4.11.1). For me, WSL integration and other flags are all set but still I was getting:
The command 'docker' could not be found in this WSL 2 distro.
I followed @r590 's method. I turned-off and then turned-on WSL Integration under:
Resources > WSL Integration
and then it worked for me.
A: You need to go to the docker desktop settings, and enable integration with your distro in "Resources -> WSL Integration".
A: I stuck with this error after remove Ubuntu 18.04 and install the 20.04.
Even with the WSL 2 enabled, I still face this error.
This is what works for me, go the Settings --> resource and toggle the "Ubuntu" then the error disappear :)
A: For me, nothing worked excepted : right click on running Docker icon (next to clock) and chose "Switch to Linux containers"
And here we go ! Now i can have the menu Settings > Resources > WSL integration.
A: Assuming you already have wsl 2 in your system, run powershell as admin:
run wsl --list --verbose which will give you a list of your wsl running processes:
> wsl --list --verbose
NAME STATE VERSION
Ubuntu-20.04 Running 1
Then to switch it with wsl --set-version <your proc> 2:
> wsl --set-version Ubuntu-20.04 2
Conversion in progress, this may take a few minutes...
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
Conversion complete.
A: Sometimes the simplest solution is the most effective solution, if you are installing docker desktop for the first time make sure you restart windows for the effects to take change. This is not guaranteed to work but it is always worth a shot.
A: I was having the same issue, however, for me, I installed docker using a different Windows account (admin) because my default account (under a domain) is a standard user and has no admin access.
After installing docker, I started docker and got an error that I'm not part of the docker-users group so I started docker using the admin account that I have. Docker started but it's not able to see the WSL integration. Similar to the screenshot below.
What fixed it for me is to add the domain account to the docker-users and restart my machine. After that WSL is visible in the configuration.
# For local account
net localgroup docker-users "your-user-id" /ADD
# For domain account
net localgroup docker-users "DOMAIN\your-user-id" /ADD
A: I reboot my machine and docker stopped work. I reinstall docker-decktop and did all the suggestion and nothing work.
I found that I have a directory here /usr/bin/docker. I deleted it and then reinstall docker which fixed the issue.
A: In my case my distribution was running in WSL 1 mode
To check the WSL mode, run:
wsl.exe -l -v
To upgrade your existing Linux distro to v2, run:
wsl.exe --set-version (distro name) 2
To set v2 as the default version for future installations, run:
wsl.exe --set-default-version 2
A: You need to run the WSL console as Admin.
If not, the docker command may be not recognized.
A: Switch to linux containers in docker desktop then it will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63497928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "135"
}
|
Q: Intellij IDEA create new class from undefined import Suppose I have a java file that has an import that currently is not referencing any real class, because I plan on defining it myself. Is there an easy way to have intellij create a stub class for me in my module by making the file in the right folder based on the package name? I know I can just manually do this but I'm looking for something a bit more automatic, like if I could just right click the import and say "Create class stub".
A: If you wait until it shows up as an error, you can ctrl+enter on the error to bring up idea's intentions, one of which should be an option to create the new class. You can also get the intentions by clicking the red lightbulb that appears next to the error when the cursor is on it. You should change your settings so that F2 Goes to Errors First, then you can press F2 and the cursor will jump to the error making invoking the intentions a little faster.
A: First thing import that currently is not referencing any real class it dont work like this in intelliJ. you cannot have an import statement for a non-existing thing. Suppose you have a package named mypackage. Then you can write something like -
import mypackage.*;
you can define a className inside the existing class then it will report you an error like the name appears to be RED just keep the cursor there Press alt+ins a menu pops up then select create class and then specify the package in Destination package field. In that way it will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24788538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ant runnable jar not working I created a runnable jar using ant but it is not running. when I run the jar I am getting following error
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: com/teamdev/jxbrowser/events/NavigationListener
at com.MainClass$2.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: java.lang.ClassNotFoundException: com.teamdev.jxbrowser.events.NavigationListener
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 15 more
but when I created jar using eclipse that jar worked fine. Menifest of jar I created with ant is as below
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.6.0_37-b06-434-11M3909 (Apple Inc.)
Main-Class: com.MainClass
Class-Path: ./ commons-cli.jar commons-codec-1.2.jar commons-httpclien
t-3.0.1.jar commons-logging-1.1.1.jar ffmpeg-java.jar fmj.jar jdom.ja
r logback-classic.jar logback-core.jar lti-civil-no_s_w_t.jar mail.ja
r mp3spi1.9.4.jar slf4j-api.jar tritonus_share.jar vorbisspi1.0.2.jar
xuggle-xuggler.jar comfyj-2.9.jar engine-gecko.jar engine-ie.jar eng
ine-webkit.jar jniwrap-3.8.4 jxbrowser-3.3.jar jxbrowserdemo.jar log4
j-1.2.15.jar MozillaInterfaces.jar runtime.jar slf4j-api-1.5.8.jar sl
f4j-log4j12-1.5.8.jar winpack-3.8.3.jar xulrunner-mac.jar
and menifest of jar I created with eclipse is as below
Manifest-Version: 1.0
Rsrc-Class-Path: ./ jniwrap-3.8.4.jar lti-civil-no_s_w_t.jar commons-h
ttpclient-3.0.1.jar slf4j-log4j12-1.5.8.jar vorbisspi1.0.2.jar slf4j-
api.jar ffmpeg-java.jar fmj.jar commons-codec-1.2.jar engine-ie.jar x
ulrunner-mac.jar commons-logging-1.1.1.jar winpack-3.8.3.jar mp3spi1.
9.4.jar tritonus_share.jar commons-cli.jar jdom.jar MozillaInterfaces
.jar comfyj-2.9.jar jxbrowser-3.3.jar runtime.jar logback-classic.jar
engine-gecko.jar mail.jar engine-webkit.jar log4j-1.2.15.jar jxbrows
erdemo.jar slf4j-api-1.5.8.jar logback-core.jar xuggle-xuggler.jar
Class-Path: .
Rsrc-Main-Class: com.MainClass
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
both are same and all dependencies are also inside the created jar but still the jar create with ant is not working.
I know you would recommend me to create jar with eclipse but I want to obfuscate my code that's why I am using ant to create runnable jar.
A: I guess that your jar file generated with Ant does not have jar-in-jar-loader, that's why it is not able to find classes inside embedded jars.
When you generate JAR with Eclipse you can Save Ant script, then jar-in-jar-loader.zip file would be added to project. Then use generated Ant file to create your JAR. This approach works for me.
Your Ant script should look like this:
<jar destfile="C:\Users\\workspace\Your.jar">
<manifest>
<attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/>
<attribute name="Rsrc-Main-Class" value="org.mypackage.MainClass"/>
<attribute name="Class-Path" value="."/>
<attribute name="Rsrc-Class-Path" value="./ libA.jar "/>
</manifest>
<zipfileset src="jar-in-jar-loader.zip"/>
<fileset dir="${ProjectPath}/bin"/>
<zipfileset dir="${ProjectPath}\lib" includes="libA.jar"/>
</jar>
First zipfileset would include jar-in-jar-loader.zip
fileset would add all your classes
Second zipfileset would add libA.jar as embedded jar and same should be mentioned in Rsrc-Class-Path
A: With your Ant-generated Manifest, it is looking for the library jar files outside of the main jar file, the Eclipse one uses a special Main-Class and class loader to get to the bundled dependencies.
You probably want to use the OneJar ant task (or something similar) to achieve something comparable to what Eclipse does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14134094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Outlook 2016 Credentials in Credentials Manager I'm writing a client application to access my mailbox using the Redemption/MAPI library. I used to be able to start a session by doing the following:
1.) Create a credentials MS.Outlook.15:{user's email} in windows credentials manager
2.) Create a profile
3.) Open a session using this: https://msdn.microsoft.com/en-us/library/office/cc842103.aspx
However, once i enable "EnableADAL" flag in the registry. I'm unable to open a session successfully.
What I notice is that Outlook creates a credential named: MicrosoftOiffce16_Data:ADALWAM:{unique identifier of the user authenticated during ADAL token acquisition}
With that credential, i'm able to open a session successfully.
Anyone know what is stored in this credential? I've tried the ADAL refresh token and access token but they don't seem to be correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47345185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Webpage in Iframe is showing without css? I have an IFRAME in a page. And i have loaded another web page in that IFRAME.
But this newly added web page is not showing properly, i.e., web page is displaying without css.
If i open same web page in another window it displays normally with css.
I have searched a lot but haven't found any solution to resolve it.
Any Suggestions,
Thanks
A: *
*Is the webpage from another domain?
*Does the webpage of the iframe start with http while the parent page is https? Make sure the protocols are the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26313726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unchecked operations in java I am completing a lab assignment and get this error when I compile. The program runs fine, bit would like to fix what is causing the error. The program code and the complete error is below. Thanks as always!
import java.util.HashSet;
import java.util.Scanner;
public class Problema4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n,s;
while(scan.hasNext()){
n=scan.nextInt();
s=scan.nextInt();
int A[] = new int[n];
for (int i =0; i < n; i++) {
A[i] =scan.nextInt();
}
find(A, s);
}
}
public static void find(int[] A, int sum) {
int[] solution = new int[A.length];
HashSet<String> conjuntos = new HashSet(); // usamos la estructura HashSet para que los subconjuntos no se repitan
find(A, 0, 0, sum, solution, conjuntos);
System.out.println(conjuntos.size());
}
public static void find(int[] A, int currSum, int index, int sum, int[] solution, HashSet<String> conjuntos) {
if (currSum == sum) {
String subConjunto = "";
for (int i = 0; i < solution.length; i++) {
if (solution[i] == 1) {
subConjunto += " " + A[i];
}
}
if (!subConjunto.trim().isEmpty()) {
conjuntos.add(subConjunto);
}
}
if (index == A.length) {
return;
} else {
solution[index] = 1; // selecionamos el elemento
currSum += A[index];
find(A, currSum, index + 1, sum, solution, conjuntos);
currSum -= A[index];
solution[index] = 0; // no seleccionamos el elemento
find(A, currSum, index + 1, sum, solution, conjuntos);
}
return;
}
}
A: This warning comes up when you are using a Set without type specifier. So new HashSet(); instead of new HashSet<String>(); It shows up because the compiler can't check that you are using the Set in a type-safe way.
If you specify the type of the objects you are storing the warning will go away:
Replace
HashSet<String> conjuntos = new HashSet();
with
HashSet<String> conjuntos = new HashSet<>();
More details can be found here: https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52962860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Inject aspx forms and functionality with jQuery Can you inject aspx forms along with their functionality into a div using the jQuery ajax load method. I am essentially trying to create a modal popup that allows me to load remote web forms into the popup and have the user use the form and submit.I have the modal built and it transitions in perfectly, however it isn't worth it to use if there is no functionality( i.e. I want the code behind of that page to be injected along with it).
Thanks,
-Seth
A: jQuery aside - making an AJAX request for any page will merely load the HTML generated by the web server. The corresponding page could be generated by any type of script that's supported by the server: PHP, ASP, whatever.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1089013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sp.gymtest.User.getName()' on a null object reference I am a beginner in java and this project is for one of my modules, so I really have no idea what is wrong with this.
I am trying to create a real-time chat system using Firebase in Android Studio, I also have real-time database and cloud storage enabled.
The app crashes everytime I try to click into a chat of another user.
This is the error code.
Error Code : FATAL EXCEPTION: main
Process: com.sp.gymtest, PID: 23627
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sp.gymtest.User.getName()' on a null object reference
at com.sp.gymtest.MessageActivity$2.onDataChange(MessageActivity.java:80)
at com.google.firebase.database.Query$1.onDataChange(Query.java:191)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
These are my other files
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private EditText edtMessageInput;
private TextView txtChattingWith;
private ProgressBar progressBar;
private ImageView imgToolbar, imgSend;
private MessageAdapter messageAdapter;
ArrayList<Message> messages;
String usernameOfFriend, emailOfFriend, chatRoomId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
usernameOfFriend = getIntent().getStringExtra("username_of_friend");
emailOfFriend = getIntent().getStringExtra("email_of_friend");
recyclerView = findViewById(R.id.recyclerMessages);
imgSend = findViewById(R.id.imgSendMessage);
edtMessageInput = findViewById(R.id.edtText);
txtChattingWith = findViewById(R.id.txtChattingWith);
progressBar = findViewById(R.id.progressMessages);
imgToolbar = findViewById(R.id.imageToolbar);
txtChattingWith.setText(usernameOfFriend);
messages = new ArrayList<>();
imgSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference("messages/"+chatRoomId).push().setValue(new Message(FirebaseAuth.getInstance().getCurrentUser().getEmail(),emailOfFriend,edtMessageInput.getText().toString()));
edtMessageInput.setText("");
}
});
messageAdapter = new MessageAdapter(messages, getIntent().getStringExtra("my_img"),getIntent().getStringExtra("img_of_friend"),MessageActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(messageAdapter);
Glide.with(MessageActivity.this).load(getIntent().getStringExtra("img_of_friend")).placeholder(R.drawable.account_img2).error(R.drawable.account_img2).into(imgToolbar);
setUpChatRoom();
}
private void setUpChatRoom(){
FirebaseDatabase.getInstance().getReference("user/"+ FirebaseAuth.getInstance().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String myUsername = snapshot.getValue(User.class).getName();
if(usernameOfFriend.compareTo(myUsername)>0){
chatRoomId = myUsername + usernameOfFriend;
}else if(usernameOfFriend.compareTo(myUsername) == 0){
chatRoomId = myUsername + usernameOfFriend;
}else {
chatRoomId = usernameOfFriend + myUsername;
}
attachMessageListener(chatRoomId);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void attachMessageListener(String chatRoomId){
FirebaseDatabase.getInstance().getReference("messages/" + chatRoomId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
messages.clear();
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
messages.add(dataSnapshot.getValue(Message.class));
}
messageAdapter.notifyDataSetChanged();
recyclerView.scrollToPosition(messages.size()-1);
recyclerView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHolder> {
private ArrayList<Message> messages;
private String senderImg, receiverImg;
private Context context;
public MessageAdapter(ArrayList<Message> messages, String senderImg, String receiverImg, Context context) {
this.messages = messages;
this.senderImg = senderImg;
this.receiverImg = receiverImg;
this.context = context;
}
@NonNull
@Override
public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.message_holder,parent, false);
return new MessageHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MessageHolder holder, int position) {
holder.txtMessage.setText(messages.get(position).getContent());
ConstraintLayout constraintLayout = holder.ccLayout;
if(messages.get(position).getSender().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
Glide.with(context).load(senderImg).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.profImage);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.clear(R.id.prof_cardView,constraintSet.LEFT);
constraintSet.clear(R.id.txt_message,constraintSet.LEFT);
constraintSet.connect(R.id.prof_cardView,constraintSet.RIGHT,R.id.ccLayout,ConstraintSet.RIGHT, 0);
constraintSet.connect(R.id.txt_message,constraintSet.RIGHT,R.id.prof_cardView,ConstraintSet.LEFT, 0);
constraintSet.applyTo(constraintLayout);
}else {
Glide.with(context).load(receiverImg).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.profImage);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.clear(R.id.prof_cardView, constraintSet.RIGHT);
constraintSet.clear(R.id.txt_message, constraintSet.RIGHT);
constraintSet.connect(R.id.prof_cardView, constraintSet.LEFT, R.id.ccLayout, ConstraintSet.LEFT, 0);
constraintSet.connect(R.id.txt_message, constraintSet.LEFT, R.id.prof_cardView, ConstraintSet.RIGHT, 0);
constraintSet.applyTo(constraintLayout);
}
}
@Override
public int getItemCount() {
return messages.size();
}
class MessageHolder extends RecyclerView.ViewHolder{
ConstraintLayout ccLayout;
TextView txtMessage;
ImageView profImage;
public MessageHolder(@NonNull View itemView) {
super(itemView);
ccLayout = itemView.findViewById(R.id.ccLayout);
txtMessage = itemView.findViewById(R.id.txt_message);
profImage = itemView.findViewById(R.id.small_profImg);
}
}
}
ChatActivity.java
public class ChatActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<User> users;
private ProgressBar progressBar;
private UserAdapter usersAdapter;
UserAdapter.OnUserClickListener onUserClickListener;
private SwipeRefreshLayout swipeRefreshLayout;
String myImageUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
progressBar = findViewById(R.id.chatProgressBar);
users = new ArrayList<>();
recyclerView = findViewById(R.id.recycler);
swipeRefreshLayout = findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getUsers();
swipeRefreshLayout.setRefreshing(false);
}
});
onUserClickListener = new UserAdapter.OnUserClickListener() {
@Override
public void onUserClicked(int position) {
startActivity(new Intent(ChatActivity.this, MessageActivity.class)
.putExtra("username_of_friend", users.get(position).getName())
.putExtra("email_of_friend", users.get(position).getEmail())
.putExtra("image_of_friend", users.get(position).getProfilePic())
.putExtra("my_img", myImageUrl)
);
}
};
getUsers();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profile_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.menu_item_profile){
startActivity(new Intent(ChatActivity.this, ChatProfile.class));
}
return super.onOptionsItemSelected(item);
}
private void getUsers(){
users.clear();
FirebaseDatabase.getInstance().getReference("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
users.add(dataSnapshot.getValue(User.class));
}
usersAdapter = new UserAdapter(users,ChatActivity.this,onUserClickListener);
recyclerView.setLayoutManager(new LinearLayoutManager(ChatActivity.this));
recyclerView.setAdapter(usersAdapter);
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
for(User user: users){
if(user.getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
myImageUrl = user.getProfilePic();
return;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
Message.java
public class Message {
private String sender;
private String receiver;
private String content;
public Message(){
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Message(String sender, String receiver, String content) {
this.sender = sender;
this.receiver = receiver;
this.content = content;
}
}
User.java
public class User {
public String fullName, age, email, profilePic;
public User(){
}
public User(String fullName, String age, String email, String profilePic){
this.fullName = fullName;
this.age = age;
this.email = email;
this.profilePic = profilePic;
}
public String getName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
}
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder> {
private ArrayList<User> users;
private Context context;
private OnUserClickListener onUserClickListener;
public UserAdapter(ArrayList<User> users, Context context, OnUserClickListener onUserClickListener) {
this.users = users;
this.context = context;
this.onUserClickListener = onUserClickListener;
}
interface OnUserClickListener {
void onUserClicked(int position);
}
@NonNull
@Override
public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_holder,parent, false);
return new UserHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UserHolder holder, int position) {
holder.username.setText(users.get(position).getName());
Glide.with(context).load(users.get(position).getProfilePic()).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.imageProf);
}
@Override
public int getItemCount() {
return users.size();
}
class UserHolder extends RecyclerView.ViewHolder{
TextView username;
ImageView imageProf;
public UserHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onUserClickListener.onUserClicked(getAdapterPosition());
}
});
username = itemView.findViewById(R.id.username);
imageProf = itemView.findViewById(R.id.imageProf);
}
}
}
I have tried going through all the layouts, java classes and trying to find if I missed out anything or typo'd anything but to no avail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75346168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: tomcat session not serializable for spring component with @Value injection It's a rather strange problem. In Spring I've configured a bean as session.
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserSession implements Serializable{...}
There is an interceptor which who interact with this session.
public class UserInterceptor extends HandlerInterceptorAdapter{
...
@Autowired private UserSession userSession;
@Autowired private WebUser webUser;
public boolean preHandle(...){
userSession.setUserId(webUser.getUserId());
userSession.setUserList(webUser.getUsers());
...
}
...
}
The WebUser is an interface, in which depend on environment it will inject different WebUser. In profile LOCAL, in will inject LocalWebUser
@Component
@Primary
@Profile({"LOCAL"})
public class LocalWebUser implements WebUser, Serializable{
@Autowired private transient UserManager userManager;
@Value("${env.tester.userId}")
private transient String userId;
@Override
public List<String> getUsers() {
return this.userManager.getUsers();
}
...
}
Notice that I did give make field as transient to prevent common serialization problem. However, in tomcat it throws that LocalWebUser is not serializable.
Caused by: java.io.NotSerializableException:
com.company.component.web.LocalWebUser$1
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
....
LocalWebUser is actually not stored in session, it's just that session retrieve value from it. Why it complains about it is not serializable?
I did found out a solution that by removing @Value injection from properties, the exception went away, which confuse me even more....
A: It's not complaining about LocalWebUser. It's complaining about LocalWebUser$1 which is an anonymous inner class within LocalWebUser. Look through the code in LocalWebUser for something like this:
Object something = new Something() { .... };
That's an anonymous inner class. If that isn't serializable and a reference to that is being leaked into an object stored in the session, then there's your problem.
A: One possibility is that the @Value annotation modifies the type of the userId field to some other, non serializable type, through bytecode manipulation.
So when you call userSession.setUserId(webUser.getUserId()) it copies that non serializable type to the UserSession.
However I could not find any reference about the @Value annotation to support that, so this is just a hunch.
You could probably validate this by inspecting the type of the userId field at runtime with a debugger.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20414696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make responsive larger image of a div I'm trying to make a responsive email template, with a letter that gets it out from an envelope.
The letter is smaller than the envelope and I can't resize it in the same way as the div.
If I put width: 100% on the envelope, I get the same div resize so not good.
If I put margin-left: -50px;, it gets to the right on the left, but on the right the envelope remains on default size and div resize.
I am using bootstrap for grid system.
This is the template: http://www.kakaostudio.it/newsletter_v1/index_test.html
And this is the final result:
A: The brute force approach would be as follows, this will give you a good idea on how to proceed.
.envelop img {
margin-top: 50px;
margin-left: -60px;
width: 113%;
}
.envelop {
padding: 0;
margin: 0;
}
By doing this you're giving the envelop a bigger width so it matches the div above it. Then move it to the left with negative margin-left.
I have a 1920px width screen and it shows perfectly in sync for me, but it's not responsive with this approach. You'd need to use many media queries to adjust the size as it goes.
You can try playing around with negative % for the margin-left or even better the "vw" values. Position: relative and a negative value for left will give you the same result as margin-left.
Image of my approach's result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41169142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Quick image search using histograms of colors I want to search images using their histograms of colors. For extracting these histograms I will use OpenCV, I also found examples which describes how to compare two images using histograms of colors. But I have some issues:
*
*Google and another search-engines uses these histograms for searching by image, but I do not think that they iteratively compare described image with images in the database (as it done in the OpenCV examples). So how can I implement quick image search using histograms?
*Can I use for this purpose and another image searching purposes common RDBMS like MySQL?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40820900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to put text after the input field in python? In python if I wanted to have someone enter a loan amount in dollars, I could code something like this:
# Loan amount
L = float(input("Enter the loan amount: $"))
But what if I want, let's say the interest rate, which is a percentage. If I coded:
# Interest rate
I = float(input("Enter the interest rate: "))
How could I get the percentage sign, %, to show up after what they input?
A: What you need is controlling the terminal's cursor.
After user giving input and hit enter, cursor moves to next line.
You need to move the cursor up one line then move it to end of that line, print % then move cursor back to the new line.
You can do that using Terminal's escape sequence.
This library can make it easier for you to perform cursor movement
http://code.activestate.com/recipes/475116-using-terminfo-for-portable-color-output-cursor-co/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34408264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: is an android API essentially just using GET/POST to get information? I'm trying to get the root of an API and I'm just wondering if most APIs are essentially using GET/POST requests to send and receive information?
My thought is that anything that android does with an API has to connect to some server somewhere, but is there a connecting language between the server and android? or can it essentially be explained like Android is sending a GET/POST request to a PHP page that makes calls to a database (if a database is involved)?
Example. If I'm very comfortable with php, can I make an API that references the php page?
A: yes u can use php or there is some backend providers that offer alot of good stuff
backendless or parse.com
but if u already have your php services dame u can use them by the HTTPRequests / HTTPResponses using this in some asynch task will make it eazy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36843461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento 2: Error during compile Incompatible argument type I have below error while running
php bin/magento setup:di:compile
Errors during compilation:
Ves\Blog\Model\ResourceModel\Author\Grid\Collection
Incompatible argument type: Required type: \Magento\Framework\DB\Adapter\AdapterInterface. Actual type: \Magento\Store\Model\StoreManagerInterface; File:
app/code/Ves/Blog/Model/ResourceModel/Author/Grid/Collection.php
Ves/Blog/Model/ResourceModel/Author/Grid/Collection.php
namespace Ves\Blog\Model\ResourceModel\Author\Grid;
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Ves\Blog\Model\ResourceModel\Author\Collection as AuthorCollection;
class Collection extends AuthorCollection implements SearchResultInterface
{
protected $aggregations;
public function __construct(
\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Store\Model\StoreManagerInterface $storeManager,
$mainTable,
$eventPrefix,
$eventObject,
$resourceModel,
$model = 'Magento\Framework\View\Element\UiComponent\DataProvider\Document',
$connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$storeManager,
$connection,
$resource
);
$this->_eventPrefix = $eventPrefix;
$this->_eventObject = $eventObject;
$this->_init($model, $resourceModel);
$this->setMainTable($mainTable);
}
Edit 1:
\app\code\Ves\Blog\Model\ResourceModel\Author\Collection.php
<?php
namespace Ves\Blog\Model\ResourceModel\Author;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init('Ves\Blog\Model\Author', 'Ves\Blog\Model\ResourceModel\Author');
}
}
Please let me know how to fix this issue.
A: check the construct of the class : AuthorCollection . it seems that it si not supporting ; \Magento\Store\Model\StoreManagerInterface; but need an \Magento\Framework\DB\Adapter\AdapterInterface object . so when you call the construct of the class AuthorCollection you should use exactly the same type
share your class AuthorCollection so I could help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46726636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why despite "drush" being installed via `composer global install` during image build, I cannot find the tool from within a running PHP script? I am developing a PHP web application inside of a Docker container. Using volumes: inside of my docker-compose.yml file, I have specified a local directory so that any files generated are dumped and persist after the container is destroyed.
volumes:
- ./docroot:/var/www/html
Inside my Dockerfile, I RUN a command that installs a command line management tool:
RUN curl -sS https://getcomposer.org/installer | php && \
mv composer.phar /usr/local/bin/composer && \
ln -s /root/.composer/vendor/bin/drush /usr/local/bin/drush
RUN composer global require drush/drush:8.3.3 && \
composer global update
When the container comes up, I can use docker-compose exec -it <container> bash to get inside the container, and everything works fine. drush is in my path, and I can use it globally throughout the container to manage the app.
Now here is the strange part. Part of my application is that I have to run that command from a PHP script inside the container to help automatically manage some of the build process.
Using php, I run exec('drush dbupdate', $output, $retval); $retval returns a exit status of 127, or command not found and $output is empty. If I switch up the exec to use the full path I get an exit status 126.
If I go back into the container, I can run that command just fine. Note all other cli commands work as expected with exec (ls, whoami, etc but which drush returns exist status 1)
What am I missing? Why can I use it with no problems manually, but PHP exec() can't find it? passthru(), shell_exec(), and others have the same behavior.
A: composer global install will not install the command "globally" for all users, but "globally" as in "for all projects".
Generally, these packages are installed in the home directory for the user executing the command (e.g. ~/.composer), and if they are available in your path is because ~/.composer/vendor/bin is added to the session path.
But when you run composer global require (while building the image) or when you "log in" to the running container (using exec [...] bash) the user involved is root. But when your PHP script runs, it's being executed by another user (presumably www-data). And for that user, ~/.composer does not contain anything.
Maybe do not install drush using composer, but rather download the PHAR file directly or something like that while you are building the image, and put it in /usr/local/bin.
If you are using Drupal >= 8, the recommended way of installing Drush is not as a "global" dependency, but as "project" dependency, so that the appropriate drush version is installed. This comes straight from the docs:
It is recommended that Drupal 8 sites be built using Composer, with Drush listed as a dependency. That project already includes Drush in its composer.json. If your Composer project doesn't yet depend on Drush, run composer require drush/drush to add it. After this step, you may call Drush via vendor/bin/drush
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67788318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: TypeError: undefined is not an object (evaluating 'items.filter') in react native Why I am getting that error TypeError: undefined is not an object (evaluating 'items.filter') when using react-native-dropdown-autocomplete in my react native app?
I am getting data from fetch method and store that data in arrayholder
My code is like that
<Autocomplete
style={styles.input}
scrollToInput={ev => {}}
keyExtractor={(item, index) => index + ""}
handleSelectItem={(item, id) => this.handleSelectItem(item, id)}
onDropdownClose={() => onDropdownClose()}
onDropdownShow={() => onDropdownShow()}
onChangeText={(text) => this.searchFilterFunction(text)}
data={this.state.data}
minimumCharactersCount={0}
highlightText
valueExtractor={item => item.name}
rightContent
/>
searchFilterFunction = (text) => {
this.setState({
value: text,
});
const newData = this.arrayholder.filter(item => {
const itemData = `${item.name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({ data: newData });
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68712441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails helper recursive block strange behaviour Following code should accept nested code and yield in 'li' tag
def sidebar_link(text,link, color = nil)
recognized = Rails.application.routes.recognize_path(link)
output = ""
content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
output << link_to( text, link, :class => 'lead')
else
output << link_to( text, link)
end
output << yield if block_given?
raw output
end
end
in HAML view:
%ul
= sidebar_link 'Tickets', tickets_path, :orange do
%ul.sub-menu
= sidebar_link "Service Requests #{ServiceRequest.all.count}", service_requests_path
= sidebar_link 'Problems', problems_path, :green
%li.divider
= sidebar_link 'Clients', clients_path, :blueDark
= sidebar_link 'Services', services_path, :red do
%ul.sub-menu
= sidebar_link 'Categories', categories_path
This produces correct HTML except first link. Output does not contain "Tickets" word, but everything else seems to be fine.
So why this strange behaviour can occure? Helper recursion messes "output" variable?
A: I found solution to explicit use &block as following
def sidebar_link(text,link, color = nil, &block)
recognized = Rails.application.routes.recognize_path(link)
output = ""
content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
output << link_to( text, link, :class => ( 'lead' if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]) )
output << capture(&block) if block_given?
raw output
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13684126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I get, "SyntaxError: function statement requires a name" in FF, and "Uncaught SyntaxError: Unexpected token (" in IE, when importing D3 into Angular5 UPDATE: My lead was able to solve this probllem. Please see answer below, and I hope that this helps at least some people
The following code throws the exception, but note that when I don't import/use d3-selection, then the whole app runs without errors. As soon as I import select from 'd3-selection', I get the error that I mentioned in the title.
import { Component, ElementRef, ViewChild } from '@angular/core';
import { select } from 'd3-selection';
@Component({
selector: 'pie',
template: `<ng-content></ng-content>`
})
export class PieChartComponent {
@ViewChild('containerPieChart')
private element: ElementRef;
constructor() {
select(this.element.nativeElement);
}
}
I checked the possible dupes in here, and none applied to me, so here I am.
The code that is bundled/imported from TypeScript is:
function(name) {
return select(creator(name).call(document.documentElement));
}
I know this is invalid in JS, because functions must have names, or be IIFEs in order to omit the name. Or object declarations. So, why is d3 transpiling into invalid JS?
EDIT: I am using rollup.config.dev.js with the following code:
import bundles from './bundles.json';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import scss from 'rollup-plugin-scss';
import sourcemaps from 'rollup-plugin-sourcemaps';
const
DEV_DIRECTORY = `dev`
, MODULE_NAME_PATH = 'AST.app'
;
function createDevBundle(bundle) {
let bundleDirectory = `${DEV_DIRECTORY}/${bundle.name}`;
return {
input: bundle.input,
name: `${MODULE_NAME_PATH}.${bundle.name}`,
output: {
file: `${bundleDirectory}/${bundle.name}.js`,
format: 'umd'
},
exports: 'default',
plugins: [
resolve({
jsnext: true,
module: true
}),
commonjs(),
sourcemaps(),
scss({
output: `${bundleDirectory}/${bundle.name}.css`,
includePaths: ['../global/scss/base']
})
],
onwarn: function(warning) {
// Recommended warning suppression by angular team.
if (warning.code === 'THIS_IS_UNDEFINED') {
return;
}
// eslint-disable-next-line no-console
console.error(warning.message);
},
treeshake: false,
sourcemap: true
};
}
export default bundles.map(createDevBundle);
A: I wasn't able to, but my lead was able to fix this problem. The following packages were updated in the package.json:
"rollup-plugin-commonjs": "8.3.0",
"rollup-plugin-execute": "1.0.0",
"rollup-plugin-node-resolve": "3.0.3",
"rollup-plugin-sourcemaps": "0.4.2",
"rollup-plugin-uglify": "3.0.0"
An update was made to rollup.config.js and rollup.config.dev.js. The sections of name, exports, and sourcemap were moved over to the output section. See below:
function createDevBundle(bundle) {
let bundleDirectory = `${DEV_DIRECTORY}/${bundle.name}`;
return {
input: bundle.input,
output: {
file: `${bundleDirectory}/${bundle.name}.js`,
name: `${MODULE_NAME_PATH}.${bundle.name}`,
exports: 'default',
sourcemap: true,
format: 'umd'
}
... [omitted for brevity]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48916085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: yupError.inner is undefined while integrating schema with Formik I tried integrating the Yup's Schema validation with formik. But receiving error as yupError.inner is undefined
Here's a link to codesandbox!
I have'nt tried much. But found this bug report. which was later realized to be resolved. But still i'm recieving the same. Link to issue #1486!.
// VALIDATION SCHEMA
const formSchema = Yup.object().shape({
emailId: Yup.string("Enter a valid string")
.email("Please enter a valid Email ID")
.required("Need your Email ID, we won't spam you!"),
confirmMail: Yup.string("Enter a valid string")
.matches(Yup.ref("emailId"), "Email ID's are not matching")
.required("Please enter a valid mailid"),
mobileNo: Yup.number("Please enter number")
.max(10, "You've entered more than 10 numbers")
.min(10, "You've entered less than 10 numbers")
.required("Password is required"),
password: Yup.string("Enter a valid password").required(
"Password field is required"
),
confirmPassword: Yup.string("Enter a valid password").required(
"Password fields are not matching"
)
});
//Integration of Validation
<Formik
validate
initialValues={this.initialValues}
validationSchema={this.formSchema}
onSubmit={this.handleSubmit}
>
{props => this.renderForm(props)}
</Formik>
Recieving the error yupError.inner is undefined
A: Bumpup yup to latest and use mixed().test() instead of string().test()
example :
passwordConfirm: Yup.mixed().test('is-same', 'Passwords not match.', value => value === values.newPassword)
A: The issue is the custom validation for matching the e-mail fields. I made a fork here which I fixed using the method from this Github issue to add a custom validation method to Yup for comparing equality of fields, a feature which is apparently not well-supported.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57260806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Query cannot be updated because the FROM clause is not a single simple table name We just moved our SQL 2000 databases to a new SQL 2008 box. After the move, we bound the IP address of the SQL 2000 box to the new SQL 2008 box. This works, except in a VB6 application running on a Windows 2000 SP4 box where we are getting the error:
"Query cannot be updated because the FROM clause is not a single simple table name"
View the actual error message screenshot below:
http://screencast.com/t/MTViNDBh
Doing some searching, I find that this is an ODBC error-- not sure how to fix? This app has been working flawlessly until we moved all db's to SQL 2008 (which all work well, except this one app!).
Edit:
Looking into his code, it does not appear to be using ODBC:
sEncCn = "PROVIDER=" & strEncProvider & "Driver=" & strEncDriver & "Server=" & strEncServer & "UID=" & sUID & "PWD=" & sPWD & "Database=" & strEncDb
strEncProvider is "MSDASQL" Driver is "SQL Server" ..Any Ideas?
A: My guess is that your VB6 app is attempting to open an write-able recordset (rather than a read-only recordset) and because of something in your FROM clause, SQL Server cannot make this write-able.
That being said, help us help you by including:
*
*the code that's failing in VB6 along with relevant "setup" code (i.e. the code used to create your connection and your recordset object variables, etc.)
*the SQL statement you are trying to execute
A: Consider setting the compatibility mode for the database to SQL Server 2000. The option is available from Database properties in SQL Server Management Studio.
A: Take a look at the ODBC data source in Administrative Tools\Data Sources (ODBC) -- if you are positive this is what the application is using. Can you test the connection from there? Is it using the IP address or maybe a server name?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1942063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript : add/remove json element in json object I need to modify my JSON Object by add/remove Json element. Here is my JSON Object,
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
I need to remove the element "skills" and output should be like,
{
"name":"lokesh",
"age":26
}
And I again I need to add the element "skills" as string and the output should be like,
{
"name":"lokesh",
"age":26,
"skills":"javascript"
}
Please help,
Thanks in advance.
A: Other ways it can be achieved.
For Adding:
candidate["skills"] = "javascript";
For Deleting:
var skill = "javascript";
delete candidate[skill];
or
delete candidate.skills;
A: Removing a property of an object can be done by using the delete keyword:
candidate.delete("skills");
OR
delete candidate["skills"];
To add a property to an existing object in JS you could do the following.
candidate["skills"] = "javscript";
OR
candidate.skills = "javscript";
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
A: For removing:
How do I remove a property from a JavaScript object?
For adding, just set the new value for that property.
A: You can directly assign "javscript" to "skills" key.
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
You can directly do this.
candidate.skills = "javascript";
Or you can delete the "skills" key and add it again.
e.g.
delete candidate["skills"];
candidate["skills"] = "javascript";
A: You should use delete method to delete members of an object.
delete candidate.skills;
Note: You cannot delete objects or functions in the global scope with delete keyword. However you can delete a function which is a member of an object.
A: For removing:
candidate.delete("skills");
For adding:
candidate.skills = "javscript"
A: This piece of coude should do it:
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
delete candidate.skills;
console.log(candidate);
candidate["skills"] = "javascript";
console.log(candidate);
A: this is your json object
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
to read any prop you can call like:
var name = candidate.name; or candidate[0].name
var age = candidate.age; or candidate[0].age;
var skills = candidate.skills; or candidate[0].skills;
to write any of prop:
candidate.name = 'moaz';
candidate.age = 35;
remove skills value:
candidate.skills = null; or candidate.skills = '';
here skills is list of json if I use as string value or list of string:
candidate.skills = 'javasccript'; //Use skills as string value
candidate.skills.push('javascript'); //Use skills as list of string
to read skills:
for (var i = 0; i < candidate.skills.length; i++) {
var skill = candidate.skills[i];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38010518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Does std::string::c_str() always return a null-terminated string?
Possible Duplicate:
string c_str() vs. data()
I use strncpy(dest, src_string, 32) to convert std::string to char[32] to make my C++ classes work with legacy C code. But does std::string's c_str() method always return a null-terminated string?
A:
Does std::string's c_str() method always return a null-terminated string?
Yes.
It's specification is:
Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].
Note that the range specified for i is closed, so that size() is a valid index, referring to the character past the end of the string.
operator[] is specified thus:
Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT()
In the case of std::string, which is an alias for std::basic_string<char> so that charT is char, a value-constructed char has the value zero; therefore the character array pointed to by the result of std::string::c_str() is zero-terminated.
A: According to this, the answer is yes.
A: c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.
Null terminating strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12697788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Convert multiple numbers or text from a column into a row without duplicates
See the image. I want the column to be converted into the row as in the image. Even if there are multiple text or numbers with commas in any single row within the column, then those needs to be considered as duplicates. How do I make the row that I have using a formula?
A: Try this small user defined function:
Public Function MakeList(rng As Range) As String
Dim c As Collection, r As Range, s As String
Set c = New Collection
For Each r In rng
ary = Split(r.Value, ",")
For Each a In ary
On Error Resume Next
c.Add a, CStr(a)
If Err.Number = 0 Then
MakeList = MakeList & "," & a
Else
Err.Number = 0
End If
On Error GoTo 0
Next a
Next r
MakeList = Mid(MakeList, 2)
End Function
For example:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41491280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL: Fill column from other table with different identifier/key and different number of data set Assuming the dataTarget column is empty, how do I fill it with data from the dataSource like shown below?
Source
id otherSubId dataSource
------------------------------
4000 10 DataA
4000 20 DataB
4000 30 DataC
4000 40 DataD
6000 1000 DataAA
6000 2000 DataBB
6000 3000 DataCC
6000 4000 DataDD
Target
id subId dataTarget
--------------------------
4000 100 DataA
4000 200 DataB
4000 300 DataC
6000 100 DataAA
6000 300 DataCC
6000 400 DataDD
6000 500
6000 200 DataBB
Please note that -
*
*DataD from dataSource is not used
*dataTarget with an id value of 6000 and a subId value of 500 is left empty because no more data for the last set.
I am thinking creating a tempId column filled with sequential number needed (1, 2, 3, ...) for each unique id ordered by otherSubId on both tables and combine it with id to create something to connect between both tables, but I want to know if someone has a better approach without altering the table.
A: For PostgreSQL, you can use ROW_NUMBER() to basically mimic the plan you have for a tempid, but all within one query:
SELECT *
FROM (SELECT id, subID, dataTarget,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
FROM target
) T
JOIN (SELECT id, othersubID, dataSource,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
FROM source
) S ON S.id = T.id
AND S.RN = T.RN
The update would be:
UPDATE T
SET T.dataTarget = S.dataSource
FROM (SELECT id, subID, dataTarget,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
FROM target
) T
JOIN (SELECT id, othersubID, dataSource,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
FROM source
) S ON S.id = T.id
AND S.RN = T.RN
I'm also curious how representative your example data is of the actual table. If it really looks just like that, you can add or remove a 0 in your join predicate:
SELECT *
FROM Target T
JOIN Source S ON T.id = S.id
AND (t.subId * 10 = s.othersubID OR
t.subId / 10 = s.othersubID)
This should work in any RDBMS, assuming subID is not a string. If it is, you have to concatenate or remove a 0 instead of doing math.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44931455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do i change the file attributes? I am using the the GetFileAttributes() function in my code. Its return the value as 0x2010. Because, Its saying, "FILE_ATTRIBUTE_NOT_CONTENT_INDEXED". I need output as 0x10.
Please help me to resolve this. I am using empty folder to get file attributes.
A: The output is 0x10. I.e., it's 0x2000 which means FILE_ATTRIBUTE_NOT_CONTENT_INDEXED and it's also 0x10 which means FILE_ATTRIBUTE_DIRECTORY. The values are bitwise-or'ed together. You can test them like this:
if (file_attr & 0x10)
puts("FILE_ATTRIBUTE_DIRECTORY");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23004454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can someone please explain this macro definition? The macro definition is as follows:
#define open_listen_fd_or_die(port) \
({ int rc = open_listen_fd(port); assert(rc >= 0); rc; })
open_listen_fd() is a function, that returns integer value.
My question: What is the significance of third statement rc; ?
A: You're looking at a gcc extension that allows you to treat multiple statements as a single expression. The last one needs to be an expression that is used as the result of the entire thing. It's meant for use in macros to allow the presence of temporary variables, but in modern C it's better to use inline functions instead of function like macros in this and many other cases (and not just because this is a non-standard extension and inline functions are standard):
inline int open_listen_fd_or_die(int port) {
int rc = open_listen_fd(port);
assert(rc >= 0); // maybe not the best approach
return rc;
}
More information can be found in the gcc documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64040245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Java non-recursive filesystem walking I need to create app which uses non-recursive walk through filesystem and prints out files which are on a certain depth.
What I have:
public void putFileToQueue() throws IOException, InterruptedException {
File root = new File(rootPath).getAbsoluteFile();
checkFile(root, depth);
Queue<DepthControl> queue = new ArrayDeque<DepthControl>();
DepthControl e = new DepthControl(0, root);
do {
root = e.getFileName();
if (root.isDirectory()) {
File[] files = root.listFiles();
if (files != null)
for (File file : files) {
if (e.getDepth() + 1 <= depth && file.isDirectory()) {
queue.offer(new DepthControl(e.getDepth() + 1,file));
}
if (file.getName().contains(mask)) {
if (e.getDepth() == depth) {
System.out.println(Thread.currentThread().getName()
+ " putting in queue: "
+ file.getAbsolutePath());
}
}
}
}
e = queue.poll();
} while (e != null);
}
And helper class
public class DepthControl {
private int depth;
private File file;
public DepthControl(int depth, File file) {
this.depth = depth;
this.file = file;
}
public File getFileName() {
return file;
}
public int getDepth() {
return depth;
}
}
I received answer, that this program uses additional memory because of Breadth-first search(hope right translation). I have O(k^n), where k - average amount of subdirectories, n - depth. This program could be easily done with O(k*n). Please help me to fix my algorithm.
A: I think this should do the job and is a bit simpler. It just keeps track of files at next level, expands them, then repeats the process. The algorithm itself keeps track of depth so there is no need for that extra class.
// start in home directory.
File root = new File(System.getProperty("user.dir"));
List<File> expand = new LinkedList<File>();
expand.add(root);
for (int depth = 0; depth < 10; depth++) {
File[] expandCopy = expand.toArray(new File[expand.size()]);
expand.clear();
for (File file : expandCopy) {
System.out.println(depth + " " + file);
if (file.isDirectory()) {
expand.addAll(Arrays.asList(file.listFiles()));
}
}
}
A: In Java 8, you can use stream, Files.walk and a maxDepth of 1
try (Stream<Path> walk = Files.walk(Paths.get(filePath), 1)) {
List<String> result = walk.filter(Files::isRegularFile)
.map(Path::toString).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
A: To avoid recursion when walking a tree there are basically two options:
*
*Use a "work list" (similar to the above) to track work to be done. As each item is examined new work items that are "discovered" as a result are added to the work list (can be FIFO, LIFO, or random order -- doesn't matter conceptually though it will often affect "locality of reference" for performance).
*Use a stack/"push down list" so essentially simulate the recursive scheme.
For #2 you have to write an algorithm that is something of a state machine, returning to the stack after every step to determine what to do next. The stack entries, for a tree walk, basically contain the current tree node and the index into the child list of the next child to examine.
A: Assuming you want to limit the amount of space used and:
*
*you can assume the list of files/directories is static over the course of your traversal, AND
*you can assume the list of files/directories in a give directory are always returned in the same order
*you have access to the parent of the current directory
Then you can traverse the directory using only the information of the last node visited. Specifically, something along the lines of
1. Keep track of the last Entry (directory or file) visited
2. Keep track of the current directory
3. Get a list of files in the current directory
4. Find the index of the last Entry visited in the list of files
5. If lastVisited is the last Entry in the current directory,
5.1.1 If current directory == start directory, we're done
5.1.2 Otherwise, lastVisited = the current directory and current directory is the parent directory
5.2. Otherwise, visit the element after lastVisited and set lastVisited to that element
6. Repeat from step 3
If I can, I'll try to write up some code to show what I mean tomorrow... but I just don't have the time right now.
NOTE: This isn't a GOOD way to traverse the directory structure... its just a possible way. Outside the normal box, and probably for good reason.
You'll have to forgive me for not giving sample code in Java, I don't have the time to work on that atm. Doing it in Tcl is faster for me and it shouldn't be too hard to understand. So, that being said:
proc getFiles {dir} {
set result {}
foreach entry [glob -tails -directory $dir * .*] {
if { $entry != "." && $entry != ".." } {
lappend result [file join $dir $entry]
}
}
return [lsort $result]
}
proc listdir {startDir} {
if {! ([file exists $startDir] && [file isdirectory $startDir])} {
error "File '$startDir' either doesn't exist or isnt a directory"
}
set result {}
set startDir [file normalize $startDir]
set currDir $startDir
set currFile {}
set fileList [getFiles $currDir]
for {set i 0} {$i < 1000} {incr i} { # use for to avoid infinate loop
set index [expr {1 + ({} == $currFile ? -1 : [lsearch $fileList $currFile])}]
if {$index < ([llength $fileList])} {
set currFile [lindex $fileList $index]
lappend result $currFile
if { [file isdirectory $currFile] } {
set currDir $currFile
set fileList [getFiles $currDir]
set currFile {}
}
} else {
# at last entry in the dir, move up one dir
if {$currDir == $startDir} {
# at the starting directory, we're done
return $result
}
set currFile $currDir
set currDir [file dirname $currDir]
set fileList [getFiles $currDir]
}
}
}
puts "Files:\n\t[join [listdir [lindex $argv 0]] \n\t]"
And, running it:
VirtualBox:~/Programming/temp$ ./dirlist.tcl /usr/share/gnome-media/icons/hicolor
Files:
/usr/share/gnome-media/icons/hicolor/16x16
/usr/share/gnome-media/icons/hicolor/16x16/status
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-high.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-low.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-medium.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-muted.png
/usr/share/gnome-media/icons/hicolor/22x22
[snip]
/usr/share/gnome-media/icons/hicolor/48x48/devices/audio-subwoofer-testing.svg
/usr/share/gnome-media/icons/hicolor/48x48/devices/audio-subwoofer.svg
/usr/share/gnome-media/icons/hicolor/scalable
/usr/share/gnome-media/icons/hicolor/scalable/status
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-high.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-low.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-medium.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-muted.svg
A: If you're using Java 7, there is a very elegant method of walking file trees. You'll need to confirm whether it meets your needs recursion wise though.
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.*;
public class myFinder extends SimpleFileVisitor<Path> {
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) { }
public FileVisitResult postVisitDirectory(Path dir, IOException exc) { }
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { }
public FileVisitResult visitFileFailed(Path file, IOException exc) { }
<snip>
}
Essentially it does a depth first walk of the tree and calls certain methods when it enters/exits directories and when it "visits" a file.
I believe this to be specific to Java 7 though.
http://docs.oracle.com/javase/tutorial/essential/io/walk.html
A: And - of course - there's always the multi-threaded option to avoid recursion.
*
*Create a queue of files.
*If it's a file add it to the queue.
*If it's a folder start a new thread to list files in it that also feeds this queue.
*Get next item.
*Repeat from 2 as necessary.
Obviously this may not list the files in a predictable order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9606312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Loop through nested JSON array using PHP I have a JSON array as follows:
[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]
I want to loop through this nested JSON array to retrieve all the "desc" from the "custClass" list using PHP.
Any help would be appreciated.
A: You can try this way
$json='{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}';
$decode=json_decode($json,true);
$desc=[];
foreach($decode['custClass'] as $cust){
$desc[]=$cust['desc'];
}
var_dump($desc);
A: You can decode data and loop it
$s = '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
$data =json_decode($s,true);
foreach($data as $obj){
foreach($obj['custClass'] as $val){
echo "Desc ".$val['desc']."<br/>";
}
}
A: Try decoding data and retrieve it using foreach:
$your_data = your_data;
$decoded_data = json_decode($your_data [0], true);
$final_data = [];
foreach($decoded_data['custClass'] as $data) {
$final_data[] = $data['desc'];
}
print_r($final_data);
A: try this code
loop this array like below
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
json_decode() the data
<?php
$data= '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
?>
A: You can loop through all JSON Arrays by using a recursive algorithm.
$myJsonArray = '<as-your-above-json-array>';
# Convert $myJsonArray into an associative array
$myJsonArray = json_decode($myJsonArray, true);
recursiveArray($myJsonArray);
# A recursive function to traverse the $myJsonArray array
function recursiveArray(array $myJsonArray)
{
foreach ($myJsonArray as $key => $hitElement) {
# If there is a element left
if (is_array($hitElement)) {
# call recursive structure to parse the jsonArray
recursiveArray($hitElement);
} else {
if ($key === 'desc') {
echo $hitElement . PHP_EOL;
}
}
}
}
/**
OUTPUT
e1f96b98047adbc39f8baf8f4aa36f41
d0e850f728b2febee79e1e7d1186c126
bee3120e77092d889c3b9e27cbee75bd
32a81cb610805d9255d5f11354177414
88a8e85db11976082fed831c4c83838e
39c4d4bca1578194801f44339998e382
6b4c4d5f4ae609742c1b6e62e16f8650
*/
Live code -> https://wtools.io/php-sandbox/bFEJ
OR use the RecursiveArrayIterator to traverse the $myJsonArray array
$myJsonArray = json_decode($myJsonArray, true);
$myIterator = new RecursiveArrayIterator($myJsonArray);
recursiveArray($myIterator);
function recursiveArray(RecursiveArrayIterator $myIterator)
{
while ($myIterator->valid()) {
if ($myIterator->hasChildren()) {
recursiveArray($myIterator->getChildren());
} else {
if ($myIterator->key() === 'desc') {
echo $myIterator->current() . PHP_EOL;
}
}
$myIterator->next();
}
}
Live code -> https://wtools.io/php-sandbox/bFEL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50755781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change background color from js I would set the background color of an element by onclick javascript function.
My code is:
function changeBg( el ) {
if( $( el ).css( "background-color" ) === "rgb(255,255,0)" ) {
$( el ).css( "background-color", "red" );
}
else {
$( el ).css( "background-color", "rgb(255,255,0)" );
}
}
This code works for change the default background color to yellow (rgb(255, 255,0)) but it doesn't work from yellow to red. The first condition is always skipped
A: For more better way use with toggleClass() instead of color value matching with in dom
function changeBg(el) {
$(el).toggleClass('red')
}
.red {
background-color: red;
}
button{
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="changeBg(this)">change</button>
A: Try This:
$(document).ready(function(){
$('button').click(function(){
$(this).toggleClass('redColor');
})
})
button {
background-color: yellow;
}
.redColor {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Click Me!</button>
A: Try this
$(document).ready(function() {
$('.container').on('click',function(){
var el = ".container";
if ($(el).css("background-color") === "rgb(255, 255, 0)") {
$(el).css("background-color", "red");
} else {
$(el).css("background-color", "rgb(255, 255, 0)");
}
});
});
.container {
background-color: rgb(255, 255, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
Test
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45055096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Custom EditText vertical alignment I created a custom EditText (actually, I just set a background drawable). The problem is that its text is always top-aligned, and I want it to be vertical-center-aligned. I've already tried to set its gravity to CENTER_VERTICAL, but it doesn't work. This is the drawable I created:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:gravity="center_vertical">
<solid android:color="#FFFFFF"/>
<stroke android:width="1dp" android:color="#88BA52" />
<corners
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
</shape>
And here's how I create it:
searchEditText = new EditText(getContext());
searchEditText.setTextSize(12);
searchEditText.setSingleLine();
searchEditText.setGravity(Gravity.CENTER_VERTICAL);
searchEditText.setHint(R.string.search_hint);
searchEditText.setBackgroundDrawable(
getResources().getDrawable(R.drawable.search_field));
addView(searchEditText);
A: searchEditText.setGravity(Gravity.CENTER | Gravity.LEFT);
This might help
A: Try reducing your font size. For whatever reasons, I have found if your font size is too large, even if it appears to you the EditText should be tall enough to hold the text, the text will appear to be higher than properly centered vertically.
Adjust your font size down, or specify a font size if you are using default value, until you find a font size value small enough for it to appear properly centered.
A: I'm seeing the same issue. Programmatically creating an EditText resulted in the gravity being vertically forced to TOP (while horizontal centering still works) ... until I commented out the calls that set the background! In this case, vertical and horizontal gravity are both honored.
Here is my code:
inputField.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
inputField.setLinksClickable(false);
inputField.setInputType(ie.getInputType());
inputField.setFadingEdgeLength(0);
inputField.setHorizontalFadingEdgeEnabled(false);
inputField.setPadding(borderWidth.left,borderWidth.top,borderWidth.right,borderWidth.bottom);
inputField.setOnEditorActionListener(this);
inputField.setHint(hint);
inputField.setCompoundDrawables(null, null, null, null);
// comment out the next two lines to see gravity working fine
inputField.setBackgroundDrawable(null);
inputField.setBackgroundColor(Color.WHITE);
inputField.setTextColor(Color.BLACK);
inputField.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
inputField.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
Now, step tracing in the OS source code reveals that the computation for vertical centering strangely relies on the height reported by the background. Defaut in EditText is a NinePatchDrawable with a 64 pixels high default bitmap. If your EditText is this height, your text will be centered. Otherwise, it will be closer to top than it should. Setting a background color will internally use a ColorDrawable which reports an intrinsic height of zero, therefore only using the text height and vertically aligning it to TOP.
The way to fix this issue is to create your own Drawable subclass, set it as the background of the EditText instance, make sure you call setBounds() on the drawable so it has a height to report, and override the getIntrinsicHeight() method of the drawable to report the height that was set using setBounds().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5017513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to prevent or disable deletion of array formula in a particular cell in the google sheet? I have an array formula in the particular cell. And I want to prevent / disable for accidentally deleting this array formula. I would like ask for advice on how to do it.
A: Simple, protect the range using Data/Protected Sheets & Ranges.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67005323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to stop recursion in dynamically generated HTML table See jsfiddle for working example of issue.
http://jsfiddle.net/grdhog/Wng5a/5/
When I add a row to the table. I send it first to the server by ajax then completely rebuild the table from an ajax json call.
When I delete a row I sent it first to the server by ajax then completely rebuild the table from an ajax json call.
The delete is going recursive - see console output
Click on a few rows to "delete" them and you'll see the recursion.
This simplified example doesn't actually add or delete rows but hopefully you get the idea.
Can you explain why I have the issue and how to resolve it please.
I suspect my call to get_rows() from the delete click is part of the problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body><p>Turn on the Javascript console to see output:</p>
<button id="add">add new row</button>
<table id="rows">
</table>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
get_rows();
$('#add').click(function() {
// ajax call to server to add row
console.log("add row");
get_rows();
return false;
});
function get_rows(){
console.log("inside get_rows!");
$("#rows").empty();
// ajax call to return all rows
for (i=0; i < 5;i++){
var item = '<tr><td id="' + i + '" class="del_row">delete row ' + i + ' by clicking me!</td></tr>';
$("#rows").append(item);
}
$(document).on("click", ".del_row", function(){
id = $(this).prop('id');
console.log("delete row " + id);
// ajax call to delete on server
get_rows();
});
}
}); // end ready
</script>
</body>
</html>
A: The id attribute mustn't be a number, you can read more here What are valid values for the id attribute in HTML?
Surely this don't answer your question but you can prevent others problems in the future.
A: You have to move the .on call out of the get_rows function. Because otherwise every time you call get_rows it adds a new listener.
function get_rows(){
console.log("inside get_rows!");
$("#rows").empty();
// ajax call to return all rows
for (i=0; i < 5;i++){
var item = '<tr><td id="' + i + '" class="del_row">delete row ' + i + ' by clicking me!</td></tr>';
$("#rows").append(item);
}
}
$(document).on("click", ".del_row", function(){
id = $(this).prop('id');
console.log("delete row " + id);
// ajax call to delete on server
get_rows();
});
http://jsfiddle.net/Wng5a/6/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23308805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to avoid refreshing and flickering while loading json with p5.js I'm trying to use p5.js to render a 3d cube on the webpage, and need to load one constantly updating JSON files to get the color features. The JSON files would be updated per second as I run a python script.
The problem is, my result web page keeps refreshing and sometimes has flickers, which is not what I wanted. How can I adjust my code so that the visual features from JSON could be rendered smoothly without any interruption? Any help would be appreciated.
Here's my p5.js code below:
var color_data
var urls = "http://127.0.0.1:5500/data.json";
let fr = 500
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
setInterval(loadData, 100)
frameRate(fr);
easycam = createEasyCam();
document.oncontextmenu = () => false;
easycam.setDistance(800, 0);
}
function gotData(data) {
color_data = data
}
function loadData() {
loadJSON(urls, gotData)
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight)
}
function draw() {
function colorPart(x_value, y_value, z_value) {
let arr = color_data[5 - y_value][5 - z_value][x_value]
return arr.split(',')
}
function forRange(fn) {
const cubeSpacing = 100
for (let i = -250; i <= 250; i += cubeSpacing) {
fn(i);
}
}
function coordToIndex(num) {
return (num / 50 + 5) / 2
}
background(155);
translate(0, 0, -500);
rotateY(millis() / 2000);
// let size = Math.random() % 10 *25
// let volume = Math.random() % 1 + 1
let volume = 1
forRange(x => forRange(y => forRange(z => {
let pos = createVector(x, y, z);
noStroke()
push();
translate(volume * pos.x, volume * pos.y, volume * pos.z);
let index_x = coordToIndex(x)
let index_y = coordToIndex(y)
let index_z = coordToIndex(z)
if (color_data) {
let tem_arr = colorPart(index_x, index_y, index_z)
fill(parseInt(tem_arr[0]), parseInt(tem_arr[1]), parseInt(tem_arr[2]));
}
sphere(18)
pop();
})))
}
A: Here is an example of what I meant on my comment.
I moved most of the calculations out of the draw, in setup we load the spheres array with the positions and an initial color then the setInterval(changeColor, 500) changes the color, on this case is just something random but you could do the same with data coming from a json like you are doing.
colors = ["red", "blue", "green", "cyan", "white", "black", "yellow"]
function setup() {
spheres = []
forRange(x => forRange(y => forRange(z => {
color = "red"
spheres.push({ x, y, z, color })
})))
createCanvas(windowWidth, windowHeight, WEBGL);
frameRate(500);
document.oncontextmenu = () => false;
setInterval(changeColor, 500)
}
function changeColor() {
spheres.forEach(obj => {
obj.color = colors[int(random(colors.length))]
})
}
function forRange(fn) {
const cubeSpacing = 120
for (let i = -250; i <= 250; i += cubeSpacing) {
fn(i);
}
}
function draw() {
background(155);
translate(0, 0, -500);
rotateY(millis() / 2000);
rotateX(millis() / 8000);
spheres.forEach(obj => {
noStroke()
push();
translate(obj.x, obj.y, obj.z);
fill(obj.color)
sphere(18)
pop();
})
}
Here is that in action:
https://raw.githack.com/heldersepu/hs-scripts/master/HTML/p5_spheres.html
no-refresh and no flickers (at least not in google chrome, I only tested there)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60761089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: View is not getting displayed after starting a service I am starting a service from activity.The problem here is the service gets started started but the activity is not getting displayed.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, ServerActivity1.class));
}
In the service I am opening a socket via a simple function like this by using a timer.The service gets started as I am able to see in logs but the view(R.layout.main) never gets displayed and after some time the force close pop is displayed.
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "sasa", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
read();
}
}, 0,50000);
Log.i("NoServer","Started1");
read();
}
@Override
public void onDestroy() {
}
@Override
public void onStart(Intent intent, int startid) {
Log.i("Home","Listening on IP: " + SERVERIP+"\n");
}
public void read()
{
SERVERIP = getLocalIpAddress();
Log.i("Home","Listening on IP: " + SERVERIP+"\n");
if (SERVERIP != null) {
Log.i("Home","Listening on IP: " + SERVERIP+"\n");
}
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
Socket client;
Log.i("Home","Listening on IP: " + SERVERIP+"\n");
try {
client = serverSocket.accept();
Log.i("Home","Listening on IP: " + SERVERIP+"\n");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = in.readLine()) != null) {
serverSocket.close();
read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
A: Its because your UI thread (main) is being shared by service unless you define your service in a separate process in manifest. If you start your service in activity's onResume method, till then your service would be visible but still may cause ANR depending on the time (max 5 secs) it takes to complete requests in service.
Its better to put all the socket stuff (or any expensive calls) of your service in a separate thread. In that case, your app will not hang or crash due to ANR.
You should use ThreadHandler and Handler to execute Messages and/or Runnables in a separate thread inside Service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10595002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the purpose of the implicit mode in Spring open id connect? I'm currently using the Authorisation Code Flow of openid connect in spring which is the default mode. In this mode, the response type used is code and I get an access_token and an id_token. So here, all seem ok.
But when I try to use the Implicit Flow by setting authorizationGrantType=implicit the response type used is token and I get only an access_token. This reflects the Authorisation Request part of OAuth 2.0 specification. Moreover the token value for response type does not seems to be used by OpenId Connect spec :
So what is the purpose of the implicit mode in Spring open id connect ?
A:
NOTE: While OAuth 2.0 also defines the token Response Type value for the Implicit Flow, OpenID Connect does not use this Response Type, since no ID Token would be returned.
As OpenID Connect specification highlights, response_type=token is not a valid response type for OpenID Connect. So what you are observing is falling back to OAuth 2.0 and hence receiving an access token.
I do not come from Spring background, but you should be able to define/configure the appropriate response_type values from your code. If this is not the case, you were merely lucky with Authorization code flow observation. Depending on authorization server configurations/preference it may send an id token. For example, Azure AD sends id token for OAuth 2.0 code grant
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50489850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deserialize XML into a C# object How can I desearlize the below CatalogProduct tags into my CatalogProduct object using C#?
<?xml version="1.0" encoding="UTF-8"?>
<CatalogProducts>
<CatalogProduct Name="MyName1" Version="1.1.0"/>
<CatalogProduct Name="MyName2" Version="1.1.0"/>
</CatalogProducts>
Note i don't have a CatalogProducts object so want to skip that element when pulling back the into to deserialize
Thanks
A: var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<CatalogProducts>" +
"<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" +
"<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" +
"</CatalogProducts>";
var document = XDocument.Parse(xml);
IEnumerable<CatalogProduct> catalogProducts =
from c in productsXml.Descendants("CatalogProduct")
select new CatalogProduct
{
Name = c.Attribute("Name").Value,
Version = c.Attribute("Version").Value
};
A: Just for your information, here's an example how to really serialize and deserialize an object:
private CatalogProduct Load()
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
using (var xmlReader = new XmlTextReader("CatalogProduct.xml"))
{
if (serializer.CanDeserialize(xmlReader))
{
return serializer.Deserialize(xmlReader) as CatalogProduct;
}
}
}
private void Save(CatalogProduct cp)
{
using (var fileStream = new FileStream("CatalogProduct.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
serializer.Serialize(fileStream, cp);
}
}
A: The canonical method would be to use the xsd.exe tool twice. First, to create a schema from your example XML as so:
xsd.exe file.xml will generate file.xsd.
Then:
xsd.exe /c file.xsd will generate file.cs.
File.cs will be the object(s) you can deserialize your XML from using any one of the techniques that you can easily find here, e.g. this.
A: Without "CatalogProduct" object i think it's very difficult, maybe with the dynamic type of .net 4.0 it's possible, but i'm not sure.
The only way i know, is to utilize the XmlSerializer class with Deserialize method, but you need the object CatalogProduct.
I hope the following link is useful:
Link
A: Assuming your CatalogProduct object looks something like this:
public class CatalogProduct {
public string Name;
public string Version;
}
I think Linq to Xml will be the simplest and fastest way for you
var cps1 = new[] { new CatalogProduct { Name = "Name 1", Version = "Version 1" },
new CatalogProduct { Name = "Name 2", Version = "Version 2" } };
var xml = new XElement("CatalogProducts",
from c in cps1
select new XElement("CatalogProduct",
new XAttribute("Name", c.Name),
new XAttribute("Version", c.Version)));
// Use the following to deserialize you objects
var cps2 = xml.Elements("CatalogProduct").Select(x =>
new CatalogProduct {
Name = (string)x.Attribute("Name"),
Version = (string)x.Attribute("Version") }).ToArray();
Please note that .NET offers true object graph serialization which I have not shown
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4135150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why there might a memory leak occus when using Handler There is a warning if we use non-static Handler: 'handler should be static, else it is prone to memory leaks.'
I have read below links and I know what their mean.
https://stackoverflow.com/a/7909437/619424
https://stackoverflow.com/a/11336822/619424
But after read the source of Handler.java, Message.java and Looper.java, I'm confused...
In Looper.loop() method, we can see below statements:
msg.target.dispatchMessage(msg);
...
msg.recycle();
the variable msg holds a reference named target to a corresponding Handler. When a Message is proceessed by Looper, msg is dispatched to the Handler (target reference), after that, msg is recycled.
Message.recycle() method calls Message.clearForRecycle() method, in that, we see:
...
target = null;
...
target is set to null, that means, Message doesn't holds the reference to Handler. Non-static Handler will be GCed, and both Activity and Views will be GCed.
So my question is, why there might a memory leak occurs?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14078136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Uploading file using getElementByClassName I have the code as shown below. I am trying to upload multiple files onchamge,
document.getElementsByClassName('fileUpload').onchange = function () {
alert("changed");
/* var field = document.getElementsByClassName('fileUpload');
var file = field[0].files[0];*/
var filename = this.value;
alert(filename);
var a = filename.split(".");
alert(a);
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
var suffix = a.pop().toLowerCase();
//if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'pdf' && suffix != 'doc'){
if (!(suffix in {jpg:'', jpeg:'', png:'', pdf:'', doc:''})){
document.getElementById('fileUpload').value = "";
alert('Please select an correct file.');
}
};
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
but since an ID is set only to one element I am trying to change the code to use getElementByClassName. Please help me alter my code to get this to work thanks.
A: You need to create a shared onchange function, then apply that to each element:
// Iterate over each element with the fileUpload class and assign the handler
[].forEach.call(document.getElementsByClassName('fileUpload'), function(element) {
element.onchange = onFileChanged;
});
// Shared handler for the event
function onFileChanged() {
alert("changed");
var field = this; // 'this' is the current file element
var file = field.files[0];
var filename = this.value;
alert(filename);
var a = filename.split(".");
alert(a);
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
var suffix = a.pop().toLowerCase();
//if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'pdf' && suffix != 'doc'){
if (!(suffix in {jpg:'', jpeg:'', png:'', pdf:'', doc:''})){
field.value = "";
alert('Please select an correct file.');
}
};
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
A: This
getElementsByClassName('fileUpload')
returns an Array of items and not a single one. Just make a loop through instead:
var array = getElementsByClassName('fileUpload');
for (var i=0;i<array.length;i++) {
array[i].onchange = ...
}
A: <!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
Here, good luck, useful me, thanks you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32112372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: modifying vtk array in python without copying it I want to be able to modify vtk arrays in python without the need to copy them, modify them and then add them back to vtk polydata. In C++, I assume that this is feasible using references. Is there a solution a similar solution in python?
A MWE is as follows
from os import read
import vtk as vtk
import numpy as np
from helpers.numpy_support import *
def main():
sphere = vtk.vtkPolyDataReader()
sphere.SetFileName('sphere.vtk')
sphere.Update()
polyData=sphere.GetOutput()
array = vtk_to_numpy(polyData.GetPointData().GetAbstractArray('Result'))
for a in array:
a*=5.0
writer = vtk.vtkPolyDataWriter()
writer.SetFileName('modifiedSphere.vtk')
writer.SetInputData(polyData)
writer.Write()
main()
A: using the indices in the iteration solves the problem!
for i in range(len(array)):
array[i]*=5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69181589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can an Ember-data PromiseArray be rejected? I have a list of a couple thousand people that has a search and filter functionality. The search box is doing a google like search as you type and there is a drop down to filter by the person's status. If you select the drop down and start typing quickly sometimes the results do not come back in the same order and the last one to return is rendered without the status filter, or without the search.
I would like to reject the previous promise if it is still pending any time a new search is fired. The problem is, the last search is being stored as a PromiseArray, which I can call reject on, but it does not seem to actually reject the promise.
I am using ember 1.5.1 and ember-data 1.0.0.beta.7 on ember-cli 0.0.28
Here is the generated person search controller:
Controller = Em.ArrayController.extend({
lastFetchedPage: 1,
searchTerms: "",
isFreshSearch: false,
statusToFilterBy: null,
statuses: (Em.computed(function() {
return this.get("store").find("status");
})).property(),
statusToFilterByDidChange: (function() {
return this.conductSearch();
}).observes("statusToFilterBy"),
searchTermsDidChange: (function() {
this.haltCurrentSearch();
this.set("searchTermsDirty", true);
return Em.run.debounce(this, this.conductSearch, 750);
}).observes("searchTerms"),
conductSearch: function() {
this.set("lastFetchedPage", 1);
this.set("isFreshSearch", true);
return this.fetchPeople();
},
haltCurrentSearch: function() {
if (this.get("currentSearch.isPending")) {
this.get("currentSearch").reject(new Error("Terms outdated"));
}
},
fetchPeople: function() {
var search;
search = this.get("store").find("person-summary", {
page: this.get("lastFetchedPage"),
terms: this.get("searchTerms"),
status_id: this.get("statusToFilterBy.id")
});
search.then((function(_this) {
return function(personSummaries) {
return _this.displayResults(personSummaries);
};
})(this));
this.set("currentSearch", search);
return this.set("searchTermsDirty", false);
},
displayResults: function(personSummaries) {
if (this.get("isFreshSearch")) {
this.set("isFreshSearch", false);
return this.set("model", personSummaries);
} else {
return personSummaries.forEach((function(_this) {
return function(personSummary) {
return _this.get("model").addRecord(personSummary);
};
})(this));
}
}
bottomVisibleChanged: function(person) {
if (person === this.get("lastPerson")) {
this.incrementProperty("lastFetchedPage");
return this.fetchPeople();
}
},
lastPerson: (Em.computed(function() {
var people;
people = this.get("model.content");
return people[people.length - 1];
})).property("model.@each")
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24813232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: html form unable to find setter method for attribute name I get error html form unable to find setter method for attribute name when I add name attribute in form action
like
<html:form action="updateBOEMedicalAccept" name="updateBOEMedicalAcceptForm">
I need name attribute to use it in javascript
like
document.updateBOEMedicalAcceptForm.BOE_NO.disabled = true;
and id attribute is also not working
Please guide.
A: For getting element by name,
document.getElementsByName('BOE_NO').disabled = true;
For getting element by id
document.getElementsById('idOfBOE_NO').disabled = true;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12813588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Search and lookup Search values from one dataframe in another dataframe and populate new column based on look up values in pandas I have 2 dataframes - df1 and df2 which look like below. I need to search the values from df2['Pid'] in all columns of df1 (columns - a through f) and then create a new column df1['ind'], which will hold values from df2['ind'] wherever a match between values of df2['Pid'] is found in df1. To me it looks like a expanded look up case. I used df2.isin(df1['PERSON_UID']) to find to mark value found = true/ false in df1, but stuck at the creation of df1['ind'] column.
df1:
a b c d e f
0 0 2106 0 0 0
0 2103 0 0 0 0
0 2104 0 0 0 0
0 2105 0 0 0 0
2100 0 0 0 0 0
2101 0 0 0 0 0
2102 0 0 0 0 0
0 0 2107 0 0 0
0 0 2108 0 0 0
0 0 2109 0 0 0
0 0 2110 0 0 0
0 0 2111 0 0 0
0 0 0 2112. 0 0
0 0 0 2113 0 0
0 0 0 2114 0 0
0 0 0 0 2115 0
0 0 0 0 2116 0
0 0 0 0 0 2117
0 0 0 0 0 2118
0 0 0 0 0 2119
0 0 0 0 2120 0
df2:
Pid ind
2100 y
2101 n
2102 y
2103 n
2104 y
2105 n
2106 n
2107 n
2108 y
2109 y
2110 n
2111 y
2112 y
2113 y
2114 n
2115 n
2116 y
2117 y
2118 n
2119 y
2120 n
Desired op:
a b c d e f ind
0 0 2106 0 0 0 n
0 2103 0 0 0 0 n
0 2104 0 0 0 0 y
0 2105 0 0 0 0 n
2100 0 0 0 0 0 y
2101 0 0 0 0 0 n
2102 0 0 0 0 0 y
0 0 2107 0 0 0 n
0 0 2108 0 0 0 y
0 0 2109 0 0 0 y
0 0 2110 0 0 0 n
0 0 2111 0 0 0 y
0 0 0 2112. 0 0 y
0 0 0 2113 0 0 y
0 0 0 2114 0 0 n
0 0 0 0 2115 0 n
0 0 0 0 2116 0 y
0 0 0 0 0 2117 y
0 0 0 0 0 2118 n
0 0 0 0 0 2119 y
0 0 0 0 2120 0 n
A: @jezrael's answer is perfect, if the Pid is not a duplicate, then you need the sum I was thinking of combining them as an index.
df['Pid'] = df.sum(axis=1)
df['Pid'] = df['Pid'].astype(int)
df = pd.merge(df, df2, on='Pid', how='inner')
df.drop('Pid', axis=1, inplace=True)
df
a b c d e f ind
0 0 0 2106 0.0 0 0 n
1 0 2103 0 0.0 0 0 n
2 0 2104 0 0.0 0 0 y
3 0 2105 0 0.0 0 0 n
4 2100 0 0 0.0 0 0 y
5 2101 0 0 0.0 0 0 n
6 2102 0 0 0.0 0 0 y
7 0 0 2107 0.0 0 0 n
8 0 0 2108 0.0 0 0 y
9 0 0 2109 0.0 0 0 y
10 0 0 2110 0.0 0 0 n
11 0 0 2111 0.0 0 0 y
12 0 0 0 2112.0 0 0 y
13 0 0 0 2113.0 0 0 y
14 0 0 0 2114.0 0 0 n
15 0 0 0 0.0 2115 0 n
16 0 0 0 0.0 2116 0 y
17 0 0 0 0.0 0 2117 y
18 0 0 0 0.0 0 2118 n
19 0 0 0 0.0 0 2119 y
20 0 0 0 0.0 2120 0 n
A: Use:
df1['ind'] = df1.mask(df1.eq(0)).ffill(axis=1).iloc[:, -1].map(df2.set_index('Pid')['ind'])
print (df1)
a b c d e f ind
0 0 0 2106 0.0 0 0 n
1 0 2103 0 0.0 0 0 n
2 0 2104 0 0.0 0 0 y
3 0 2105 0 0.0 0 0 n
4 2100 0 0 0.0 0 0 y
5 2101 0 0 0.0 0 0 n
6 2102 0 0 0.0 0 0 y
7 0 0 2107 0.0 0 0 n
8 0 0 2108 0.0 0 0 y
9 0 0 2109 0.0 0 0 y
10 0 0 2110 0.0 0 0 n
11 0 0 2111 0.0 0 0 y
12 0 0 0 2112.0 0 0 y
13 0 0 0 2113.0 0 0 y
14 0 0 0 2114.0 0 0 n
15 0 0 0 0.0 2115 0 n
16 0 0 0 0.0 2116 0 y
17 0 0 0 0.0 0 2117 y
18 0 0 0 0.0 0 2118 n
19 0 0 0 0.0 0 2119 y
20 0 0 0 0.0 2120 0 n
Details:
First replace 0 values to missing values by DataFrame.mask:
print (df1.mask(df1.eq(0)))
a b c d e f
0 NaN NaN 2106.0 NaN NaN NaN
1 NaN 2103.0 NaN NaN NaN NaN
2 NaN 2104.0 NaN NaN NaN NaN
3 NaN 2105.0 NaN NaN NaN NaN
4 2100.0 NaN NaN NaN NaN NaN
5 2101.0 NaN NaN NaN NaN NaN
6 2102.0 NaN NaN NaN NaN NaN
7 NaN NaN 2107.0 NaN NaN NaN
8 NaN NaN 2108.0 NaN NaN NaN
9 NaN NaN 2109.0 NaN NaN NaN
10 NaN NaN 2110.0 NaN NaN NaN
11 NaN NaN 2111.0 NaN NaN NaN
12 NaN NaN NaN 2112.0 NaN NaN
13 NaN NaN NaN 2113.0 NaN NaN
14 NaN NaN NaN 2114.0 NaN NaN
15 NaN NaN NaN NaN 2115.0 NaN
16 NaN NaN NaN NaN 2116.0 NaN
17 NaN NaN NaN NaN NaN 2117.0
18 NaN NaN NaN NaN NaN 2118.0
19 NaN NaN NaN NaN NaN 2119.0
20 NaN NaN NaN NaN 2120.0 NaN
Then forward filling missing values:
print (df1.mask(df1.eq(0)).ffill(axis=1))
a b c d e f
0 NaN NaN 2106.0 2106.0 2106.0 2106.0
1 NaN 2103.0 2103.0 2103.0 2103.0 2103.0
2 NaN 2104.0 2104.0 2104.0 2104.0 2104.0
3 NaN 2105.0 2105.0 2105.0 2105.0 2105.0
4 2100.0 2100.0 2100.0 2100.0 2100.0 2100.0
5 2101.0 2101.0 2101.0 2101.0 2101.0 2101.0
6 2102.0 2102.0 2102.0 2102.0 2102.0 2102.0
7 NaN NaN 2107.0 2107.0 2107.0 2107.0
8 NaN NaN 2108.0 2108.0 2108.0 2108.0
9 NaN NaN 2109.0 2109.0 2109.0 2109.0
10 NaN NaN 2110.0 2110.0 2110.0 2110.0
11 NaN NaN 2111.0 2111.0 2111.0 2111.0
12 NaN NaN NaN 2112.0 2112.0 2112.0
13 NaN NaN NaN 2113.0 2113.0 2113.0
14 NaN NaN NaN 2114.0 2114.0 2114.0
15 NaN NaN NaN NaN 2115.0 2115.0
16 NaN NaN NaN NaN 2116.0 2116.0
17 NaN NaN NaN NaN NaN 2117.0
18 NaN NaN NaN NaN NaN 2118.0
19 NaN NaN NaN NaN NaN 2119.0
20 NaN NaN NaN NaN 2120.0 2120.0
Select last column by position with DataFrame.iloc:
print (df1.mask(df1.eq(0)).ffill(axis=1).iloc[:, -1])
0 2106.0
1 2103.0
2 2104.0
3 2105.0
4 2100.0
5 2101.0
6 2102.0
7 2107.0
8 2108.0
9 2109.0
10 2110.0
11 2111.0
12 2112.0
13 2113.0
14 2114.0
15 2115.0
16 2116.0
17 2117.0
18 2118.0
19 2119.0
20 2120.0
Name: f, dtype: float64
And last use Series.map.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62421990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: insert icons to text messages with javascript I have angularjs phonegap application with backend on nodejs.
I have a simple chat page with input for text of message, but user can choose a smile picture from list and put it among text. I didn't find any solutions for my questions.
Thanks.
A: To use emoji icons with angularjs, you could use angular-emoji-filter module: https://github.com/globaldev/angular-emoji-filter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24287506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to work with a Generic List of a Generic Type in a Generic Class In the example console app below, you will notice that the program is attempting to create a basketball team and, then, add a player and a coach to the team.
The design of the application implements generic classes (Team and Person) which concrete classes (Lakers(), Player(), and Coach()) will inherit.
The program throws build exceptions at the point where I attempt to add the Person object to the team.Members list.
The exception reads:
The best overloaded method match for
'System.Collections.Generic.List>.Add(Person)' has some invalid
arguments.
I don't understand why the compiler doesn't allow me to add the generic Player (Kobe and Phil) to the Members list when Members is defined as a generic list of a generic Player.
Can you explain the cause of the error and how to work around it?
Also, can you fill me in on whether or not the example program below is not typically how we should be implementing generics? In other words, given the errors in the program below, it makes me wonder why I should implement generics and not stick with a normal abstract class.
By the way, please don't down-vote simply because you don't like the Lakers ;)
class Program
{
static void Main(string[] args)
{
//Create a team
Team<Lakers> team = new Lakers();
//Create a player then add the player to the list of team members
Person<Player> p = new Player();
p.Name = "Kobe";
team.Members.Add(p); //Invalid argument exception here
//Create a coach then add the coach to the list of team members
Person<Coach> c = new Coach();
c.Name = "Phil";
team.Members.Add(c); //Invalid argument exception here
//Display the members of the team
team.Members.ForEach(n => Console.WriteLine(n.Name));
Console.ReadLine();
}
}
//A generic class containing a generic list of a generic type
abstract class Team<T>
{
public List<Person<T>> Members = new List<Person<T>>();
}
//A concrete basketball team
class Lakers : Team<Lakers>
{
}
//A generic class that represents a person
abstract class Person<T>
{
public string Name { get; set; }
}
//A concrete person that represents a basketball player
class Player : Person<Player>
{
}
//A concrete person that represents a basketball coach
class Coach : Person<Coach>
{
}
A: Why not just:
//An abstract class that represents a person
abstract class Person
{
public string Name { get; set; }
}
//A concrete person that represents a basketball player
class Player : Person
{
}
//A concrete person that represents a basketball coach
class Coach : Person
{
}
The usage of generics seems totally unnecessary. the simple hierarchy should be enough for you.
A: You seem to be mixing up inheritance and generics. While technically different, you can see a generic class as template, and not as an is-a relationship. Normal inheritance is all you want here.
A: Because you declare Team as type Lakers and Person as type Player. Those are not equal.
Do you need to constrain your List with ? Can't you just declare it as Person?
abstract class Team<T>
{
public List<Person> Members = new List<Person>();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5275123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting type of not initialized variable There is main a variable which has uninitialized variables. I need to retrieve the Type of uninitialized varible type with reflection. Because I am generating the values dynamically but can't get the types of main variable's type of vars.
In the picture Quick Watch is showing the type name of ameliyatGirisBilgileri variable even it is not initialized.
A: You should be able to get the FieldInfo for the variables within the type using the GetField(...) or GetFields(...) method on the main type. Below is a short program demonstrating how you might go about it:
class Program
{
public string mStringType = null;
static void Main(string[] args)
{
var program = new Program();
try
{
var field = program.GetType().GetField("mStringType");
Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program));
program.mStringType = "Some Value";
Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program));
}
catch (NullReferenceException)
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
}
This gives the following output on the Console window:
Field 'mStringType' is of type 'System.String' and has value ''.
Field 'mStringType' is of type 'System.String' and has value 'Some Value'.
Note: If the fields are not public, you will have to pass some BindingFlags into the GetField(...) or GetFields(...) methods.
A: FieldInfo fieldInfo = typeof(MyClass).GetField("ameliyatGirisBilgileri", BindingFlags.Public | BindingFlags.Instance);
Type fieldType = fieldInfo.FieldType;
Sorry but I'm too lazy to type the name of your class completely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9021005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to call enum with a value from a another method In Interfaces.cs I have:
private enum InstructionType
{
ADD = 1,
UPDATE = 2,
DELETE = 3
}
What I want to do is call each TransactionType individually in IWorks.svc.cs that will handle the logic for adding updating and deleting.
How is this done?
A: If you simply want to enumerate through your enum type you can use this:
foreach (InstructionType type in Enum.GetValues(typeof(InstructionType)))
{
if (type.ToString() == "ADD")
//do sth here
}
Problem is your enum is private, so it's not realy a possibility. The only option you have is to write a public method in IWorks.svc.cs that will do what you need, f.e:
public void foreachType(Action<T> action) {
//action can be invoked so it should be exacly what you want
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29600579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can extract Custom Property value from lambda expression? I have the following class definition
Person.cs
class Person {
[Column("first_name")]
public string FirstName { get; set; }
[Column("last_name")]
public string LastName { get; set; }
}
I wrote an HTML Helper extension to extract the ColumnAttribute value from a given instance. However, it does not work as I expect.
Here is what I tried:
Index.cshtml
@model Person
<p>ColumnName is @Html.ColumnNameFor( model => model.FirstName )</p>
HtmlExtensions.cs (public static class)
public static string ColumnNameFor<T, P>(this HtmlHelper<T> helper, Expression<Func<T, P>> expression)
{
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
// this line causes a runtime error:
// Sequence contains no elements
var attr = (ColumnAttribute)metadata.GetType().GetCustomAttributes(typeof(ColumnAttribute), false).First();
return attr.Name; // ColumnAttribute stores the value in .Name
}
For the record, I am able to extract the value using GetCustomAttributes, provided that I pass a reference to the property, which I think will make the code in the View look very different from the built in ASP MVC code for Html.TextBoxFor and Html.DisplayFor, etc.
A: Thanks to @benuto for his answer, I was able to find out how I could extract any required custom attribute or property using MemeberExpress. I wanted the answer to help others, so I made a working example. Bear in mind that you will need to check if the object does have a custom property or not, to avoid crashing when accessing FirstOrDefault().Name.
public static string ColumnNameFor<T, P>( this HtmlHelper<T> helper,
Expression<Func<T, P>> expression)
{
var name = ExpressionHelper.GetExpressionText(expression);
MemberExpression me = expression.Body as MemberExpression;
var cp = (ColumnAttribute)me
.Member
.GetCustomAttributes(typeof(ColumnAttribute), false)
.FirstOrDefault();
return (cp == null) ? null : cp.Name;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68228703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing in C# using JSON.Net (very confusing!) I want to parse the following JSON:
{"0":{"igloo_id":"0","name":"Igloo Removal","cost":"0"},"1":{"igloo_id":"1","name":"Basic Igloo","cost":"1500"},"2":{"igloo_id":"2","name":"Candy Igloo","cost":"1500"},"3":{"igloo_id":"3","name":"Deluxe Blue Igloo","cost":"4000"},"4":{"igloo_id":"4","name":"Big Candy Igloo","cost":"4000"},"5":{"igloo_id":"5","name":"Secret Stone Igloo","cost":"2000"},"6":{"igloo_id":"6","name":"Snow Igloo","cost":"1000"},"8":{"igloo_id":"8","name":"Secret Deluxe Stone Igloo","cost":"5000"},"9":{"igloo_id":"9","name":"Deluxe Snow Igloo","cost":"3000"},"10":{"igloo_id":"10","name":"Bamboo Hut","cost":"3200"},"11":{"igloo_id":"11","name":"Log Cabin","cost":"4100"},"12":{"igloo_id":"12","name":"Gym","cost":"4800"},"13":{"igloo_id":"13","name":"Split Level Igloo","cost":"4600"},"14":{"igloo_id":"14","name":"Candy Split Level Igloo","cost":"4600"},"15":{"igloo_id":"15","name":"Snowglobe","cost":"3700"},"16":{"igloo_id":"16","name":"Ice Castle","cost":"2400"},"17":{"igloo_id":"17","name":"Split Level Snow Igl","cost":"4600"},"18":{"igloo_id":"18","name":"Fish Bowl","cost":"2400"},"19":{"igloo_id":"19","name":"Tent","cost":"2700"},"20":{"igloo_id":"20","name":"Jack O' Lantern","cost":"2700"},"21":{"igloo_id":"21","name":"Backyard Igloo","cost":"4200"},"22":{"igloo_id":"22","name":"Pink Ice Palace","cost":"2400"},"23":{"igloo_id":"23","name":"Ship Igloo","cost":"4300"},"24":{"igloo_id":"24","name":"Dojo Igloo","cost":"1300"},"25":{"igloo_id":"25","name":"Gingerbread House","cost":"2100"},"26":{"igloo_id":"26","name":"Restaurant Igloo","cost":"4800"},"27":{"igloo_id":"27","name":"Tree House Igloo","cost":"4500"},"28":{"igloo_id":"28","name":"Theatre Igloo","cost":"4600"},"29":{"igloo_id":"29","name":"Circus Tent","cost":"0"},"30":{"igloo_id":"30","name":"Snowy Backyard Igloo","cost":"3000"},"31":{"igloo_id":"31","name":"Cave Igloo","cost":"1500"},"32":{"igloo_id":"32","name":"Green Clover Igloo","cost":"2050"},"33":{"igloo_id":"33","name":"Grey Ice Castle","cost":"2400"},"35":{"igloo_id":"35","name":"Cozy Cottage Igloo","cost":"2500"},"36":{"igloo_id":"36","name":"Estate Igloo","cost":"2500"},"37":{"igloo_id":"37","name":"In Half Igloo","cost":"2300"},"38":{"igloo_id":"38","name":"Shadowy Keep","cost":"2400"},"39":{"igloo_id":"39","name":"Dragon's Lair","cost":"3000"},"40":{"igloo_id":"40","name":"Mermaid Cove","cost":"3030"},"41":{"igloo_id":"41","name":"Whale's Mouth","cost":"2700"},"42":{"igloo_id":"42","name":"Trick-or-Treat Igloo","cost":"2000"},"43":{"igloo_id":"43","name":"Deluxe Gingerbread House","cost":"0"},"45":{"igloo_id":"45","name":"Invisible Snowy","cost":"0"},"46":{"igloo_id":"46","name":"Invisible Beach","cost":"0"},"47":{"igloo_id":"47","name":"Invisible Forest","cost":"0"},"48":{"igloo_id":"48","name":"Invisible Mountain","cost":"0"},"49":{"igloo_id":"49","name":"Shipwreck Igloo","cost":"900"},"50":{"igloo_id":"50","name":"Wildlife Den","cost":"900"},"51":{"igloo_id":"51","name":"Medieval Manor","cost":"1200"},"52":{"igloo_id":"52","name":"Warehouse","cost":"950"},"53":{"igloo_id":"53","name":"Pineapple Igloo","cost":"0"},"54":{"igloo_id":"54","name":"Creepy Cavern","cost":"1500"},"55":{"igloo_id":"55","name":"Frost Bite Palace","cost":"0"},"56":{"igloo_id":"56","name":"Fresh Baked Gingerbread House","cost":"2500"},"57":{"igloo_id":"57","name":"Penthouse","cost":"4000"},"58":{"igloo_id":"58","name":"VIP Penthouse","cost":"0"},"59":{"igloo_id":"59","name":"Invisible Age of Dinosaurs","cost":"0"},"60":{"igloo_id":"60","name":"Puffle Tree Fort","cost":"0"},"61":{"igloo_id":"61","name":"Secret Base","cost":"1600"},"62":{"igloo_id":"62","name":"Death Star Igloo","cost":"1000"},"63":{"igloo_id":"63","name":"Beach Party Igloo","cost":"1500"},"64":{"igloo_id":"64","name":"Gymnasium Igloo","cost":"0"},"65":{"igloo_id":"65","name":"Magical Hideout","cost":"1500"},"66":{"igloo_id":"66","name":"Eerie Castle","cost":"2000"},"67":{"igloo_id":"67","name":"Sweet Swirl Igloo","cost":"0"},"68":{"igloo_id":"68","name":"Train Station Igloo","cost":"1100"},"69":{"igloo_id":"69","name":"Main Event Igloo","cost":"1000"},"70":{"igloo_id":"70","name":"CP Airliner","cost":"1200"}}
I need a way to retrieve igloo_id, name and cost.
I've tried the following, but it's not what I want
List<Igloo> igloosList = JsonConvert.DeserializeObject<List<Igloo>>(itemJson);
This is the structure of my class
namespace Canvas
{
public class Igloo
{
public int cost;
public int igloo_id;
public string name;
public int Cost
{
get
{
return cost;
}
}
public int Id
{
get
{
return igloo_id;
}
}
public string Name
{
get
{
return name;
}
}
}
}
A: Use the JsonProperty attribute :
[JsonProperty(PropertyName = "cost")]
public int Cost
{
get
{
return cost;
}
private set { cost = value; }
}
[JsonProperty(PropertyName = "igloo_id")]
public int Id
{
get
{
return igloo_id;
}
private set { igloo_id = value; }
}
[JsonProperty(PropertyName = "name")]
public string Name
{
get
{
return name;
}
private set { name = value; }
}
Basically you need to say for each property what is the Json key that will match. Plus, you will need to have a setter for each of your property, but it can be private.
A: I'm not entirely sure I understand what you want. The code you posted generated an exception when I tried running it,
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[ConsoleApplication2.Program+Igloo]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
It did deserialize correctly if I used:
var igloosList = JsonConvert.DeserializeObject<Dictionary<string, Igloo>>( json );
If you want to loop through it you could then use:
foreach( var igloo in igloosList.Values )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22925446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I have a web page store changes made by javascript? I have a form on a simple web page that has a series of checkboxes. These options represent items that may be retrieved from a database upon clicking the submit button. In addition, there is a place to add an extra option to the page at the bottom. Here is what I am going for:
I would like to be able to add the new option using javascript, so that it show up quickly and seamlessly to the user, rather than having to send the request back to the server and add it server-side, then have the user reload the page. However, I also want to make sure that these added fields are preserved so that the next time I load the page, they show up.
Unfortunately, my code is proprietary, so I cannot post it here. I hope that people can help me this some ideas without having to actually see the code.
Thanks
A: When these checkboxes are added you don't want to go the server but when user presses submit you are anyways going to server, so at that time you can persist this information about new checkboxes on server.
Another option is to call to server asynchronously using AJAX to update the server about the state change.
A: If you still want to store the changes server-side, you can do so quietly in the background.
Just use XmlHttpRequest(), together with a PHP script.
A: You can use the HTML5 local storage API to store your changes.
localStorage.setItem('favoriteflavor','vanilla');
A: If you want session related information to pass thru multiple requests, you can either put the data in a cookie, or with php you can use sessions.
http://php.net/manual/en/features.sessions.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7919891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: HTML Meta and Body parts from JSON Is it possible to load html meta attributes from JSON?
for example:
<!DOCTYPE html>
<head>
<title>{{title}}</title>
<meta charset="{{charset}}">
<meta name="description" content="{{description}}">
<meta name="keywords" content="{{keywords}}">
<script type="text\javascript" src="some_kind_of_script_to_work_with_json_or_so.js">
</script>
</head>
<body>
<h1>{{H1}}</h1>
<div>{{some_kind_of_text}}</div>
<div>{{some_kind_of_text2}}</div>
</body>
</html>
A: Yes.
You can fetch data from a URL using XMLHttpRequest and then use standard DOM methods to change the content of the document.
That said, meta data is generally consumed either as the document loads (so it would be too late to change it for any practical effect by the time JS ran) or is consumed by tools that are likely to not execute JavaScript.
A: Yes as Quentin said, it is possible but any content you change with JS might not be seen by Google or other search engines.
If your purpose is to load content that needs to be read by a search engine you will want to 'build' the HTML on the server side, using a server side language like PHP for instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37046428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to echo the results from 2 columns within the same table - PHP I just want to echo out two columns from the same table using php. What I have below which pulls out all the members first names:
<div class="grid-2">
<p><b>MY DETAILS</b></p>
<?php $query = "SELECT * FROM `tblMember`";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldFName']."<br>";
}
$conn -> close();
?>
</div>
This does give the first names, but I also want the surnames to be pulled out from the same table, called fldSName. Is it a simple AND statement?
A: It is already in the results since you are using a * in the query.
echo $row['fldFName'] . ' ' . $row['fldSName'] . '<br />';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55024093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CKEDITOR - Wordwrap seems to be posted I have a very interesting issue, using CKEDITOR. I'm doing the following:
I have an instance of CKEDITOR, and I have a form with hidden inputs. Before submitting the form, the value of CKEDITOR is entered in a hidden input field. So I have:
$('#form_hidden_input').val(CKEDITOR.instances.editor.getData());
When posting (so submitting the form, I am able, to access the value of the input with $_POST['form_hidden_input']. So far, so good. But when I now try, to insert the value I got into CKEDITOR again, it fails. What I do is
CKEDITOR.instances.editor.insertHtml('<?=$_POST['form_hidden_input'];?>');
When I echo the content of $_POST['form_hidden_input'] everything seems to be fine, but with insertHtml(), I get a "Uncaught SyntaxError: Unexpected token ILLEGAL", in Sources of of Developer Console (or when clicking on the error), the line looks like that:
CKEDITOR.instances.editor.insertHtml('<p>asfa</p>
');
Be aware, that '); appears in the next line, anyway it should work, but I think, this is the only point, where the problem could appear... The question is, why is there a wordwrap, and how can I prevent that, or get it working anyway?
A: Figured out how to do it:
when I do that:
$content = $_POST['form_old_data'];
$content = str_replace("\n", "", $content);
$content = str_replace("\r", "", $content);
CKEDITOR.instances.editor.insertHtml('<?=$content;?>');
it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32452283",
"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.