text
stringlengths
15
59.8k
meta
dict
Q: React Native, AWS, Error only on Android "TypeError: Cannot read Property 'handle' of null" I ran into a bug whenever I run my React Native app on an Android device (physical and emulator). Yet, no problem at all on iOS. These functions are supposed to scan the database table for user handles and return an object if the handle already exists. This is what the error looks like: TypeError: Cannot read property 'handle' of null at exports.handler (/var/task/index.js:7:36) I'm using React Native, AWS Lambda, and EXPO. This code lives within dbfunctions.js on the front end. export async function scanHandles(){ return new Promise((resolve, reject) => { let { auth } = store.getState() let reqBody = { userId: auth.user.username, handle: auth.handle_update, } let path = '/u/scan-handle' let myInit = { headers: { 'Content-Type': 'application/json' }, body: reqBody, } console.log('myInit', myInit) console.log('handle', auth.handle_update) API.get(apiName, path, myInit) .then((resp) => { // if false, then handle does not exist // if true, then handle already exists resolve(resp) }) .catch((error) => { console.warn('Scan Handle', error) reject(error) }) }) } Console logging auth.handle_update does print out the expected string. myInit also prints out the expected object. On the back end, I'm using this for my scan: const AWS = require("aws-sdk"); const docClient = new AWS.DynamoDB.DocumentClient({ region: "us-west-1" }); exports.handler = (event, context, callback) => { let e = JSON.parse(event.body); var params = { TableName: event.stageVariables.user, FilterExpression: "handle = :handle", ExpressionAttributeValues: { ":handle": e.handle } }; docClient.scan(params, function(err, data) { if (err) { console.log("ERROR:", err); let response = { statusCode: err.statusCode, headers: {}, body: JSON.stringify(err) }; callback(response); } if (data.Count >= 1) { // if user name exists // call back handle exists response let handleExistsResponse = { statusCode: 200, body: JSON.stringify({ Success: true }) }; callback(null, handleExistsResponse); } else { let response = { statusCode: 200, body: JSON.stringify({ Success: false }) }; callback(null, response); } }); }; Any idea as to why this would work on iOS and not Android? EDIT: Upon further testing, let e = JSON.parse(event.body) is returning null. So I console logged event and got a big ol object. Within this object, I found body and it's still null. So the body object isn't being passed it properly. Still confused about it working on iOS and not Android. A: Did it! Okay so API.get doesn't like body's being passed in. Instead, it wants a query parameter. So the lambda params looks like: var params = { TableName: event.stageVariables.user, FilterExpression: "handle = :handle", ExpressionAttributeValues: { ":handle": event["queryStringParameters"]["handle"] } }; And the front end function is: export async function scanHandles(){ return new Promise((resolve, reject) => { let { auth } = store.getState() let handle = auth.handle_update let path = `/u/scan-handle?handle=${handle}` let myInit = { headers: { 'Content-Type': 'application/json' }, } API.get(apiName, path, myInit) .then((resp) => { // if false, then handle does not exist // if true, then handle already exists resolve(resp) }) .catch((error) => { console.warn('Scan Handle', error) reject(error) }) }) } Works on both iOS and Android. Wonder why it wasn't working before?
{ "language": "en", "url": "https://stackoverflow.com/questions/53489605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop div overlapping a container Ok so I am currently building a bespoke WordPress theme and I'm just having one of those moments where my head is completely blank... It's like I know it but I just can't figure it out! Basically I have a spotlight section where it has an image, and then a container at the bottom of that image which displays the title and a short description etc... See screenshot: http://prntscr.com/ksh0tf Basically I've done the img with an to style it (set height / width, object fit etc) and then I have done the container div that holds the content, as a position: absolute and put a bottom: 0 - (in this case bottom: 4px due to it being out of place a tiny bit) as I want it to be at the bottom of the image each time no matter the height of the box etc. On the black container I have a width: 100% set and as you can see, it's causing it to overlap right over to the other div. This is also built off bootstrap too so it's a col-sm-8 and col-sm-4 but it just seems the text container div doesn't wanna just fit across the length of the image etc. Here is my HTML code: <?php if ($atts['spotlightcolour'] == 'black' ) : ?> <div class="spotlight-container"> <img class="spotlight" src="<?php echo $atts['bgimage']['data']['icon']; ?>" /> <div class="spotlight-box" style="background-color: rgba(0, 0, 0, 0.3);"> <?php echo $atts['title']; ?> <br /> <?php echo $atts['description']; ?> </div> </div> <?php endif; ?> CSS: img.spotlight{ height: 256px; width: 100%; object-fit: cover; position: relative; z-index: 1; } .spotlight-box{ position: absolute; width: 100%; bottom: 4px; z-index: 3; display: block; color: #fff; padding: 20px; } I just want the container div that has the content in, to sit across the length of the image when width: 100% is set due to these could all be different sizes so I don't want to give set widths etc. Thanks in advance for any help! A: Since .spotlight-box is absolutely positioned, its parent needs to be relatively positioned if you want it to sit properly inside the parent: .spotlight-container { position: relative; } Fiddle: http://jsfiddle.net/ctdu9bzk/4/
{ "language": "en", "url": "https://stackoverflow.com/questions/52248939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python appending to List from a nested Dictionary I have a nested dictionary like the example below: dev_dict = { "switch-1": {"hostname": "switch-1.nunya.com", "location": "IDF01"}, "switch-2": {"hostname": "switch-2.nunya.com", "location": "IDF02"}, "...": {"hostname": "...", "location": "..."}, "switch-30": {"hostname": "switch-30.nunya.com", "location": "IDF30"}, "router-1": {"hostname": "router-a-1.nunya.com", "location": "MDF"}, "core-1": {"hostname": "core-1.nunya.com", "location": "MDF"}, "...": {"hostname": "...", "location": "..."}, } I'm appending the dictionaries to a list using this code: dev_list = [] for i in dev_dict: dev_list.append(dev_dict[i]) Which generates a list like this: dev_list = [ {"hostname": "switch-30.nunya.com", "location": "IDF30"}, {"hostname": "core-1.nunya.com", "location": "MDF"}, {"hostname": "switch-2.nunya.com", "location": "IDF02"}, {"hostname": "...", "location": "..."}, {"hostname": "router-1.nunya.com", "location": "MDF"} {"hostname": "...", "location": "..."}, ] What I would like to accomplish is to have the list that's generated be in a certain order based on the location's key value. The order I'd like it to be is if the location is in the MDF then append those first, then if the location is in an IDF append those to the list after the MDF but in ascending order. So the final list would look like this: [ {"hostname": "router-1.nunya.com", "location": "MDF"}, {"hostname": "core-1.nunya.com", "location": "MDF"}, {"hostname": "...", "location": "..."}, {"hostname": "switch-1.nunya.com", "location": "IDF01"}, {"hostname": "switch-2.nunya.com", "location": "IDF02"}, {"hostname": "...", "location": "..."}, {"hostname": "switch-30.nunya.com", "location": "IDF30"}, ] How can I modify my code to accomplish this? A: Try this # add a white space before MDF if location is MDF so that MDF locations come before all others # (white space has the lowest ASCII value among printable characters) sorted(dev_dict.values(), key=lambda d: " MDF" if (v:=d['location'])=='MDF' else v) # another, much simpler way (from Olvin Roght) sorted(dev_dict.values(), key=lambda d: d['location'].replace('MDF', ' MDF')) # [{'hostname': 'router-a-1.nunya.com', 'location': 'MDF'}, # {'hostname': 'core-1.nunya.com', 'location': 'MDF'}, # {'hostname': '...', 'location': '...'}, # {'hostname': 'switch-1.nunya.com', 'location': 'IDF01'}, # {'hostname': 'switch-2.nunya.com', 'location': 'IDF02'}, # {'hostname': 'switch-30.nunya.com', 'location': 'IDF30'}] Click here to see the complete ASCII table.
{ "language": "en", "url": "https://stackoverflow.com/questions/72481157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In reactstrap, how do I customize the alert message and visible state from a child component? I'm using React 16.13.0 and trying to use the reactstrap Alert component to display messages when certain forms are submitted. I have positioned the Alert component where I want in my App template ... import { Alert } from 'reactstrap'; function App() { return ( <Router> <div className="App"> <nav className="navbar navbar-expand-lg navbar-light fixed-top"> <div className="container"> <Link className="navbar-brand" to={"/add"}> Chicommons </Link> <NavBar /> </div> </nav> <div className="auth-wrapper"> <div className="auth-inner"> <Alert color="info" isOpen={this.state.visible} > I am an alert and I will disappear in 2sec.! </Alert> <Switch> <Route exact path="/" component={Add} /> <Route path="/add" component={Add} /> <Route path="/edit/:id" component={Edit} /> <Route path="/search" component={Search} /> <Route path="/:coop_id/people" component={AddPerson} /> <Route path="/:coop_id/listpeople" component={ListPeople} /> </Switch> </div> </div> </div> </Router> ); } export default App; I'm having trouble with a couple of things. One of my form components, src/containers/FormContainer.jsx, has this submit handler ... const handleFormSubmit = (e) => { e.preventDefault(); // Make a copy of the object in order to remove unneeded properties const NC = JSON.parse(JSON.stringify(coop)); delete NC.addresses[0].country; const url = coop.id ? REACT_APP_PROXY + "/coops/" + coop.id : REACT_APP_PROXY + "/coops/"; const method = coop.id ? "PATCH" : "POST"; fetch(url, { method: method, body: JSON.stringify(NC), headers: { Accept: "application/json", "Content-Type": "application/json", }, }) .then((response) => { if (response.ok) { return response.json(); } else { throw response; } }) .then((data) => { const result = data; history.push({ pathname: "/" + result.id + "/people", state: { coop: result }, }); window.scrollTo(0, 0); /** Would like to place alert here **/ }) .catch((err) => { console.log(err); err.text().then((errorMessage) => { setErrors(JSON.parse(errorMessage)); }); }); }; I would like to enable the reactstrap alert with a custom message generated within the above handler. However, I don't know how to control state of the parent component. I assume I would have to create some message state in the parent component as well as control the visible state, which I already have, but not sure how to do it from the child. A: You can make a context which enables easy access to the alert anywhere in the application. AlertProvider.js import React, { useState, useCallback, useContext, createContext } from 'react' const AlertContext = createContext() export function AlertProvider(props) { const [open, setOpen] = useState(false) const [message, setMessage] = useState() const handleClose = useCallback(() => { setOpen(false) }, [setOpen]) const handleOpen = useCallback(message => { setMessage(message) setOpen(true) }, [setMessage, setOpen]) return ( <AlertContext.Provider value={[handleOpen, handleClose]}> {props.children} <Alert color="info" isOpen={open} toggle={handleClose} > {message} </Alert> </AlertContext.Provider> ) } export function useAlert() { const context = useContext(AlertContext); if (!context) throw new Error('`useAlert()` must be called inside an `AlertProvider` child.') return context } Update your App.js import { Alert } from 'reactstrap'; import { AlertProvider } from './AlertProvider'; function App() { return ( <AlertProvider> <Router> <div className="App"> <nav className="navbar navbar-expand-lg navbar-light fixed-top"> <div className="container"> <Link className="navbar-brand" to={"/add"}> Chicommons </Link> <NavBar /> </div> </nav> <div className="auth-wrapper"> <div className="auth-inner"> <Switch> <Route exact path="/" component={Add} /> <Route path="/add" component={Add} /> <Route path="/edit/:id" component={Edit} /> <Route path="/search" component={Search} /> <Route path="/:coop_id/people" component={AddPerson} /> <Route path="/:coop_id/listpeople" component={ListPeople} /> </Switch> </div> </div> </div> </Router> </AlertProvider> ); } export default App; You can then use this in functional components: import React, { useEffect } from 'react' import { useAlert } from './AlertProvider' function MyComponent() { const [open, close] = useAlert(); useEffect(() => { // when some condition is met open("Hi") // closable with the toggle, or in code via close() }) } This uses an imperative mood to open and close by calling open() and close(). If you want a declarative mood, the context should instead directly return the setMessage and setOpen functions. You can also play around to place the alert component in some other place. A: Just below function App() {. add: const [alertMessage, setAlertMessage] = React.useState("") And change your alert to: <Alert color="info" isOpen={alertMessage!=""} toggle={()=>setAlertMessage("")} > {alertMessage} </Alert> And then I don't know how the rest of your app is laid out, but you want to pass in the setAlertMessage function into handleFormSubmit as a callback, and call it in/near setErrors
{ "language": "en", "url": "https://stackoverflow.com/questions/62882456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: my users not null but showing cannot read user.name when I try to fetch all the post.user.name it shows error like Cannot read properties of undefined (reading 'name') I just wanna display all the user in my node Although user is not null when I write like post.user it shows me result like { _id: new ObjectId("632eab0e9b9ae6bbb44fce38"), email: 'temp@gmail.com', password: '1', name: 'sahil ', createdAt: 2022-09-24T07:00:30.925Z, updatedAt: 2022-09-24T07:00:30.925Z, __v: 0 } In above name is present So why it show error when I do post.user.name Below all the code home.ejs-> <section id="feed-posts"> <h4>Posts</h4> <% if (locals.user) { %> <form action="/posts/create" id="new-post-form" method="POST"> <textarea name="content" cols="30" rows="3" placeholder="Type Here..."></textarea> <input type="submit" value="Post"> </form> <div id="posts-list-container"> <ul> <% for(post of posts){ %> <li> <p> <%= post.content %> <br> <small> <%= post.user.name%> </small> </p> </li> <%} %> </ul> </div> <% } %> </section> In above code post.content and post.user work fine but post.user.name showing error. Although it contain name. index.js const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); const port = 8000; const expressLayouts = require('express-ejs-layouts'); const db = require('./config/mongoose'); // used for session cookie const session = require('express-session'); const passport = require('passport'); const passportLocal = require('./config/passport-local-strategy'); const MongoStore = require('connect-mongo')(session); const sassMiddleware = require('node-sass-middleware'); app.use(sassMiddleware({ src: './assets/scss', dest: './assets/css', debug: true, outputStyle: 'extended', prefix: '/css' })); app.use(express.urlencoded()); app.use(cookieParser()); app.use(express.static('./assets')); app.use(expressLayouts); // extract style and scripts from sub pages into the layout app.set('layout extractStyles', true); app.set('layout extractScripts', true); // set up the view engine app.set('view engine', 'ejs'); app.set('views', './views'); // mongo store is used to store the session cookie in the db app.use(session({ name: 'codeial', // TODO change the secret before deployment in production mode secret: 'blahsomething', saveUninitialized: false, resave: false, cookie: { maxAge: (1000 * 60 * 100) }, store: new MongoStore( { mongooseConnection: db, autoRemove: 'disabled' }, function (err) { console.log(err || 'connect-mongodb setup ok'); } ) })); app.use(passport.initialize()); app.use(passport.session()); app.use(passport.setAuthenticatedUser); // use express router app.use('/', require('./routes')); app.listen(port, function (err) { if (err) { console.log(`Error in running the server: ${err}`); } console.log(`Server is running on port: ${port}`); }); Controllers/home_controller.js const Post = require('../models/post'); module.exports.home = function (req, res) { // populate the user of each post Post.find({}).populate('user').exec(function (err, posts) { return res.render('home', { title: "Codeial | Home", posts: posts }); }) } controllers/posts_controller.js const Post = require('../models/post') module.exports.create = function (req, res) { Post.create({ content: req.body.content, user: req.user._id }, function (err, post) { if (err) { console.log('error in creating a post'); return; } return res.redirect('back'); }); } config/mongoose.js const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/codeial_development'); const db = mongoose.connection; db.on('error', console.error.bind(console, "Error connecting to MongoDB")); db.once('open', function () { console.log('Connected to Database :: MongoDB'); }); module.exports = db; models/post const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ content: { type: String, required: true }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }, { timestamps: true }); const Post = mongoose.model('Post', postSchema); module.exports = Post; models/user const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String, required: true } }, { timestamps: true }); const User = mongoose.model('User', userSchema); module.exports = User; P.S:- As per @Ogoh.cyril when I log Post.find({}).populate('user').exec(function (err, posts) { console.log(posts)}) and instead of writing post.user.name(which give error) I replace it with post.user in my home.ejs file. I got the below output [ { _id: new ObjectId("63355014bd69c27e240429b7"), content: 'hi mere bhai', user: { _id: new ObjectId("632eab0e9b9ae6bbb44fce38"), email: 'sahilgagan227temp@gmail.com', password: '1', name: 'sahil ', createdAt: 2022-09-24T07:00:30.925Z, updatedAt: 2022-09-24T07:00:30.925Z, __v: 0 }, createdAt: 2022-09-29T07:58:12.104Z, updatedAt: 2022-09-29T07:58:12.104Z, __v: 0 }, { _id: new ObjectId("63355047bd69c27e240429bf"), content: '1st comment on that', user: { _id: new ObjectId("632eab0e9b9ae6bbb44fce38"), email: 'sahilgagan227temp@gmail.com', password: '1', name: 'sahil ', createdAt: 2022-09-24T07:00:30.925Z, updatedAt: 2022-09-24T07:00:30.925Z, __v: 0 }, createdAt: 2022-09-29T07:59:03.972Z, updatedAt: 2022-09-29T07:59:03.972Z, __v: 0 } ] Please help me...... A: Update package -> connect-mongo Then change the code of index.js-> const MongoStore = require('connect-mongo'); store: MongoStore.create( { mongoUrl: 'mongodb://localhost/codeial_development', mongooseConnection: db, autoRemove: 'disabled' } It will work 100%
{ "language": "en", "url": "https://stackoverflow.com/questions/73888848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can resolve Shibboleth error: Invalid Attribute Id I integrated Siteminder with shibboleth using SAML2. In the saml2 response, in the Assertion section, I have the double "Id" : In the shibboleth I've the following error: Invalid attribute Id. It's possibile to ignore the attribute "Id"? I am not able to resolve this prolem...somebody can help me?
{ "language": "en", "url": "https://stackoverflow.com/questions/57954773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: changing element value with event onkeyup() javascript Please help me with my script. I don't understand why my script does not working :( <html> <body> <input type="text" id="input" onkeypress="myFunction()"> <input type="button" value="Hallo" id="but"> <script> function myFunction{ document.getElementById('but').value = "changed"; } </script> </body> </html> A: Very simple you have forgotten to place parantheses after myFunction. your code should be: <script> function myFunction(){ document.getElementById('but').value = "changed"; } </script> A: This way it work. Function needs parenthesis function myFunction() { document.getElementById('but').value = "changed"; } <html> <body> <input type="text" id="input" onkeypress="myFunction()"> <input type="button" value="Hallo" id="but"> </body> </html> an alternative way is myFunction = function () { document.getElementById('but').value = "changed"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/45847192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework Scaffold-DbContext Login failed for user I am trying to build an API using Visual Studio 2017 and .NET Core 2 with Entity Framework Core. I am following the directions from This Link. I am on the section titled: Reverse engineer your model The command they give to run is as follows: Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models My database is an Azure SQL database so I am trying to run this command using the connection string provided from the Azure portal: Scaffold-DbContext "Server=tcp:dbname.database.windows.net,1433;Initial Catalog=DBNAME_DB;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models I am getting returned a System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'username'. at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(DbConnection connection, IEnumerable`1 tables, IEnumerable`1 schemas) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.Create(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, Boolean useDatabaseNames) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ModelScaffolder.Generate(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, String projectPath, String outputPath, String rootNamespace, String contextName, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames) at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) ClientConnectionId:ba6ca255-04c8-46c2-9d4f-77204728e9f2 Error Number:18456,State:1,Class:14 Login failed for user 'username'. From this same machine and username and password I am able to login to the database using SSMS. Does anyone have any suggestions why I am unable to run this command from Visual Studio? A: Change double quotes " for single quotes ' It is not necessary to add a escape character individually, it works for the rest of the parameters too. Scaffold-DbContext 'Server=tcp:dbname.database.windows.net,1433;Initial Catalog=DBNAME_DB;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models A: I figured out my problem. My password contained the character $ and this needs to be escaped out by using ` before the $. A: Did you tried to update your web.config file for connection string. This might be a reason which doesn't allow you to login to azure. A: Please make sure the user login exists on the target SQL Azure database and not only on the Azure SQL Database server. -- On master database CREATE LOGIN MaryLogin WITH PASSWORD = ''; -- On the user database CREATE USER MaryUser FROM LOGIN MaryLogin; Create a firewall rule on Azure portal to allow access to the Azure SQL Database as explained here. Make sure port TCP 1433 is open from your computer. A: For me the below command worked when executed in Package Manager console:PM> Scaffold-DbContext "Server=.;Database=Employee;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
{ "language": "en", "url": "https://stackoverflow.com/questions/47399666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: How do I retrieve the row with the max value from this table? Hopefully this is the correct place to ask this question. In this SQL cross-join exercise from codeacademy with the following code: SELECT month, COUNT(*) FROM newspaper CROSS JOIN months WHERE (start_month<=month) & (end_month>=month) GROUP BY month; Returns a table month COUNT(*) 1 2 2 9 3 13 4 17 5 27 6 30 7 20 8 22 9 21 10 19 11 15 12 10 How can I then retrieve the row with the max COUNT(*) from this table? {month:6, COUNT( * ):30}? I tried the following which doesn't work (returns blank on the website): SELECT * FROM (SELECT month, COUNT(*) FROM newspaper CROSS JOIN months WHERE (start_month<=month) & (end_month>=month) GROUP BY month) WHERE COUNT(*)=( SELECT MAX(COUNT(*)) FROM (SELECT month, COUNT(*) FROM newspaper CROSS JOIN months WHERE (start_month<=month) & (end_month>=month) GROUP BY month) ); Preferably, I would to this to work without renaming COUNT(*). P.S: No idea which SQL dialect codeacademy uses. A: I realized we don't need a CTE to do this, you can simply do: SELECT TOP(1) month, COUNT(*) FROM newspaper CROSS JOIN months WHERE (start_month<=month) & (end_month>=month) GROUP BY month ORDER BY 2 DESC ; This will grab the top row, and it will be ordered by the highest count. I am unsure of language used by CodeAcademy, but every language I know of can grab the top row in some fashion. Edit: I see someone posted that CodeAcademy uses SQLite, which uses Limit to get X amount of rows. So you can use: SELECT month, COUNT(*) FROM newspaper CROSS JOIN months WHERE (start_month<=month) & (end_month>=month) GROUP BY month ORDER BY 2 DESC LIMIT 1 ;
{ "language": "en", "url": "https://stackoverflow.com/questions/69315831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Angular-formly: Why does the directive behave differently from the type? I have two input fields, both generated by the same template. On both I am setting ... templateOptions: { ... required: true } One input field is registered using formlyConfig.setType the other using a directive. I have created a JS Bin here. Only the first is getting the required attribute, the second is not. In the docs for custom templates (controller option) it says: Provides you the ability to add custom behavior to the type without having to make an entire directive (you can make a directive instead if you wish). What am I doing wrong? A: The problem in the second example that when angular-formly is processing the options with the template, all angular-formly sees is: <plain-text> for the template. Hence, it doesn't know what element to place the required attribute on. angular-formly will only attach attributes like these to elements that have an ng-model on them because those are the only elements where that attribute makes sense. Again, the key here is what angular-formly sees when it's processing the template (before it's compiled). It doesn't matter what the directive compiles to. So yes, you can use your own directive, but if you want to leverage the features of angular-formly, it needs to utilize the ng-model controller (like directive used in this example). Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/34660454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identifying the data type of an input I am trying to print the data type of a user input and produce a table like following: ABCDEFGH = String 1.09 = float 0 = int true = bool etc. I'm using Python 3.2.3 and I know I could use type() to get the type of the data but in Python all user inputs are taken as strings and I don't know how to determine whether the input is a string or Boolean or integer or float. Here is that part of the code: user_var = input("Please enter something: ") print("you entered " + user_var) print(type(user_var)) which always returns str for string. A: input() will always return a string. If you want to see if it is possible to be converted to an integer, you should do: try: int_user_var = int(user_var) except ValueError: pass # this is not an integer You could write a function like this: def try_convert(s): try: return int(s) except ValueError: try: return float(s) except ValueError: try: return bool(s) except ValueError: return s However, as mentioned in the other answers, using ast.literal_eval would be a more concise solution. A: from ast import literal_eval def get_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): # A string, so return str return str print(get_type("1")) # <class 'int'> print(get_type("1.2354")) # <class 'float'> print(get_type("True")) # <class 'bool'> print(get_type("abcd")) # <class 'str'> A: Input will always return a string. You need to evaluate the string to get some Python value: >>> type(eval(raw_input())) 23423 <type 'int'> >>> type(eval(raw_input())) "asdas" <type 'str'> >>> type(eval(raw_input())) 1.09 <type 'float'> >>> type(eval(raw_input())) True <type 'bool'> If you want safety (here user can execute arbitrary code), you should use ast.literal_eval: >>> import ast >>> type(ast.literal_eval(raw_input())) 342 <type 'int'> >>> type(ast.literal_eval(raw_input())) "asd" <type 'str'> A: The problem here is that any input is taken a 'string'. So we need to treat 'string' as a special case, and keep it separate from everything else. x = input("Enter something: ") try: if type(eval(x)) == float: print(x, " is floating point number") elif type(eval(x)) == int: print(x, " is interger number") elif type(eval(x)) == bool: print(x, " is a boolean") except: print("That is a string") Here the input is first evaluated. If it's anything other than a string, the eval function shall show the type. If it's a string, it is considered as an "error", and the error message is given as "That is a string".
{ "language": "en", "url": "https://stackoverflow.com/questions/22199741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: adding dashboard state (as described in get started tutorial) failed Hi I am following the get started video tutorial and stuck when I try to add the dashboard state. After filling in the Name and id I press the add button and the state window is closed and the edit modus is cancelled. Am I doing something wrong or is this a bug? I am using ThingsBoard 2.2.0
{ "language": "en", "url": "https://stackoverflow.com/questions/54080881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stay on the page after minimizing the app with WebView Xamarin Forms I try to keep the contents of webView after minimizing the application. how to do? here are my codes public partial class ItemCompte : ContentPage { string _fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "notes.txt"); public ItemCompte() { InitializeComponent(); var current = Connectivity.NetworkAccess; var profiles = Connectivity.ConnectionProfiles; if (current == NetworkAccess.Internet) { if (File.Exists(_fileName)) { string para = File.ReadAllText(_fileName); ; Webview.Source = "https://www.bcongres.com/?param=" + para; } } else if (profiles.Contains(ConnectionProfile.Ethernet)) { if (File.Exists(_fileName)) { string para = File.ReadAllText(_fileName); ; Webview.Source = "https://www.bcongres.com/?param=" + para; } } else { DisplayAlert( "Connection Error", "Venez activer vos données de l'internet, et demarrer l'application", "Try again"); } } public async void Conn() { } protected async override void OnAppearing() { base.OnAppearing(); await progress.ProgressTo(0.9, 100, Easing.SpringIn); } protected void OnNavigating(object sender, WebNavigatingEventArgs e) { progress.IsVisible = true; } protected void OnNavigated(object sender, WebNavigatedEventArgs e) { progress.IsVisible = false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/63602426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Scanf with pointers I am fairly new to C and I am having trouble using scanf with pointers. I have been told to get user inputs for 3 int and 1 char values and then print them back out using pointers. This is the best I could come up with so far: int a, b, c; char d; int *x = &a; int *y = &b; int *z = &c; char *e = &d; scanf("Enter 3 Ints and 1 Char:%d %d %d %c", x, y, z, e); printf("The numbers are:\n"); printf("%d\n %d\n %d\n %c\n", a, b, c, d); return 0; When I enter the values the following is printed out: 2 3 4 c The numbers are: 32708 -613084440 32708 � Again, I'm very new to programming so I apologize if this is a stupid mistake or something obvious that I have missed. A: You are not checking the return value of your scanf, otherwise you would know that it returns 0, as in 'no elements read'. Your scanf expects you to write exactly what you are putting in there, so, if you entered Enter 3 Ints and 1 Char:2 3 4 c, it would probably work. What you want, however, is this: printf("Enter 3 Ints and 1 Char: "); if (scanf("%d %d %d %c", &a, &b, &c, &d) != 4) printf("Invalid input detected\n"); else printf("The numbers are:\n%d\n %d\n %d\n %c\n", a, b, c, d); The first line will print the prompt to the console, the second will read the values into variables. There is no need to create separate pointer variables for this purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/73996103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding a JavaScript array of dates to a page's view model on form submit I added the following field to my form: <input asp-for="MyDates" type="hidden" name="MyDates" id="MyDates" /> In my JavaScript I allow the user to select multiple dates from a schedule and store them in an array. Everytime the array is updated I additionally update the hidden input field's value using JSON.stringify(array). The html ends up looking like this before form submission: <input type="hidden" name="MyDates" id="MyDates" value="[&quot;2016-02-17T05:00:00.000Z&quot;,&quot;2016-02-16T05:00:00.000Z&quot;,&quot;2016-02-11T05:00:00.000Z&quot;,&quot;2016-02-12T05:00:00.000Z&quot;,&quot;2016-02-19T05:00:00.000Z&quot;]"> When the user clicks submit I expect these dates to get bound to the IList MyDates property in my ViewModel. Can someone tell me why it is not? Additionally if there is a better way to do things like this please let me know. Here is what my JavaScript function looks like and it is working... It handles displaying the dates to the user and additionally creating hidden input fields for submission. Is there a better way though? function refreshDates() { var dateListHtml = ""; var baselineDatesHtml = ""; for (var i = 0; i < dates.length; ++i) { dateListHtml = dateListHtml + dates[i].toLocaleDateString() + ' <i onclick="removeDate(' + i + ')" class="fa fa-minus-circle pull-right" style="cursor: pointer;"></i></span>' + '<br>'; baselineDatesHtml = baselineDatesHtml + '<input asp-for="MyDates" type="hidden" name="MyDates" id="MyDates" value="' + dates[i].toLocaleDateString() + '" />'; } $("#dateList").html(dateListHtml); $('#myDates').html(baselineDatesHtml); } A: For model binding to work, your form element's name should match with the your view model property name(s)/hierarchy. So if you are doing a normal form submit, it is best if you add a new form element to your form ( a hidden element) and store the value there. As long as you have the name attribute value matching with the view model property name, model binding will simply work. Assuming you have a view model like this public class CreatePost { public IList<DateTime> MyDates { set; get; } //Some other properties for the view } Now, lets create a javascript method which will create a new form element and append that to the form.The below example assumes you included jQuery in your page. function addHiddenDate(dateString) { var itemCount = $("input.myDates").length; var dat = $("<input type='hidden' class='myDates' name='MyDates[" + itemCount++ + "]' />").val(dateString); $("form").append(dat); } And whenver user add's a new date, instead of adding to the array, call this method and pass the date value. $(function(){ $("#addBtn").click(function(e){ e.preventDefault(); addHiddenDate($("#DateInputField").val()); }); }); Now when you submit the form, Model binding will correctly map the posted form data to the action method parameter, assuming the parameter is of type CreatePost [HttpPost] public ActionResult Create(CreatePost model) { // check model.MyDates // to do : Return something }
{ "language": "en", "url": "https://stackoverflow.com/questions/35186942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call external JS file based on "media screen" value I'm trying this but it is not working: <html> <head> <script src="js/menu-collapser.js" type="text/javascript" media="media screen and (max-width: 599px)"></script> </head> ... </html> //menu-collapser.js : jQuery(document).ready(function($){ $('.main-navigation li ul').hide(); $('.main-navigation li').has('ul').click(function() { $(this).children().toggle(); }); }); Do you have an idea on how to do this in the right way? The script work if used directly in the header with the tags. A: Why not just load in a script conditionally? (function() { if( window.innerWidth > 600 ) { var theScript = document.createElement('script'); theScript.type = 'text/javascript'; theScript.src = 'js/menu-collapser.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(theScript, s); } })(); Or better yet, only execute the code if the window.innerWidth > 600 ? Anyway, there are a lot of solutions you can use. A: media is not a valid attribute for <script>, check it here. So you should detect media types by manually than load the script dynamically. There is a plug-in for css media detection in javascript, you can use it. <script type="text/javascript" src="js/mediatypechecker.js"></script> $(function() { if(IsMediaType('screen') > 0 && parseInt(screen.width) < 599) { $.getSscript("js/menu-collapser.js"); } }); A: You can't do that directly using Javascript <script> tags. Media queries are used in linked CSS files or inline CSS styles. A basic example: <link rel="stylesheet" media="screen and (min-width: 900px)" href="desktop.css"/> <link rel="stylesheet" media="screen and (min-width: 571px)" href="tablet.css"/> <link rel="stylesheet" media="screen and (max-width: 570px)" href="mobile.css"/> Or directly in your stylesheets: @media screen and (max-width: 599px) { #mobile { display: block; } } However, you can use an external asset loader/media query library to do this (require.js, modernizr.js, enquire.js and others), In this case, I'm setting an example using enquire.js, as I think it's very effective and doesn't require jQuery by default: Full example 1) Include enquire.js (available here): <script type="text/javascript" src="/js/enquire.js"></script> 2) Create a load function - to load JS files: <script type="text/javascript"> // This loads JS files in the head element function loadJS(url) { // adding the script tag to the head var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // fire the loading head.appendChild(script); } </script> 3) Fire enquire.js and listen for media query changes (both on-load and on-resize): <script type="text/javascript"> enquire.register("screen and (max-width: 599px)", { match : function() { // Load a mobile JS file loadJS('mobile.js'); } }).listen(); enquire.register("screen and (min-width: 600px) and (max-width: 899px)", { match : function() { // Load a tablet JS file loadJS('tablet.js'); //console.log('tablet loaded'); } }).listen(); enquire.register("screen and (min-width: 900px)", { match : function() { // Load a desktop JS file loadJS('desktop.js'); //console.log('desktop loaded'); } }).listen(); </script> Putting it all together Using a simple HTML page with enquire.js loaded from an external file: <html> <head> <script type="text/javascript" src="/enquire.js"></script> <script type="text/javascript"> // This loads JS files in the head element function loadJS(url) { // adding the script tag to the head var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // fire the loading head.appendChild(script); } </script> <style> body { font-family: arial; } h1 { font-size: 50pt; } #mobile { display: none; } #tablet { display: none; } #desktop { display: none; } @media screen and (max-width: 599px) { #mobile { display: block; } } @media screen and (min-width: 600px) and (max-width: 899px) { #tablet { display: block; } } @media screen and (min-width: 900px) { #desktop { display: block; } } </style> </head> <body> <div id="desktop"> <h1>Desktop</h1> </div> <div id="tablet"> <h1>Tablet</h1> </div> <div id="mobile"> <h1>Mobile</h1> </div> <script type="text/javascript"> enquire.register("screen and (max-width: 599px)", { match : function() { // Load a JS file loadJS('mobile.js'); } }).listen(); enquire.register("screen and (min-width: 600px) and (max-width: 899px)", { match : function() { loadJS('tablet.js'); //console.log('tablet loaded'); } }).listen(); enquire.register("screen and (min-width: 900px)", { match : function() { loadJS('desktop.js'); //console.log('desktop loaded'); } }).listen(); </script> </body> </html> In addition to loading JS files, you could create a CSS loader too, which would work in the same way (conditionally), but that defeats the object of using @media in CSS. It's worth reading the usage explanations for enquire.js, as it can do a lot more than I've illustrated here. Caveat: Nothing above uses jQuery, but you could take advantage of some of the functions it offers; loading scripts for example - or executing other functions that you need to. A: If you want it to react to later resizing events (e.g. on desktop) as well, you can do it like this: <script> moby = window.matchMedia("(max-width: 500px)"); moby.addListener( moby=>{ if(moby.matches){ document.head.innerHTML+="<script src='wonderfulScreenAffectedScript.js'></script>"; } } ); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/15823137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Native Base picker for iOS and Android with dynamically created item list I'm trying to write a Native Base Picker component in a Vue Native project that's compatible with both iOS and Android. The following code works properly on both: <template> <nb-content> <nb-text>Picker</nb-text> <nb-picker mode="dropdown" :selectedValue="selected1" :onValueChange="onValueChange" > <item label="Wallet" value="key0" /> <item label="ATM Card" value="key1" /> <item label="Debit Card" value="key2" /> <item label="Credit Card" value="key3" /> <item label="Net Banking" value="key4" /> </nb-picker> </nb-content> </template> <script> import { Picker } from 'native-base'; export default { components: { Item: Picker.Item }, data() { return { selected1: "key1" }; }, methods: { onValueChange(value) { this.selected1 = value; } } } </script> That's well and good, but the next step is to make the component more reusable by having it generate the picker items from an array. Here is my attempt at that: <template> <nb-content> <nb-text>Picker</nb-text> <nb-picker mode="dropdown" :selectedValue="selected1" :onValueChange="onValueChange" > <nb-text v-for="choice in choices" :key="choice.id"> <item :label="choice.name" :value="choice.id" /> </nb-text> </nb-picker> </nb-content> </template> <script> import { Picker } from 'native-base'; export default { components: { Item: Picker.Item }, data() { return { selected1: "key1", choices: [ { id: 'key0', name: 'wallet' }, { id: 'key1', name: 'ATM card' }, { id: 'key2', name: 'debit card' }, { id: 'key3', name: 'credit card' }, { id: 'key4', name: 'net banking' } ] }; }, methods: { onValueChange(value) { this.selected1 = value; } } } </script> This fails on both iOS and Android. On iOS no items are displayed for the picker. On Android an error is thrown which says "Error while updating property 'items' of a view managed by: AndroidDropdownPicker" followed by a new line that says "null" followed by another new line that says "label". What should be changed to get it to work?
{ "language": "en", "url": "https://stackoverflow.com/questions/60386455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Varnish Service + PHP URL Paramaters I am using varnish service to speed up my website, but I cannot make work basic php function. Can you please help me with that ? $purecookie = $_GET['id']; setcookie( 'purecookies', $purecookie, time() + (10 * 365 * 24 * 60 * 60), "/", ".domain.com" ); If I turn down varnish service it works correctly, can you please help me? :)
{ "language": "en", "url": "https://stackoverflow.com/questions/32456988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Escape HTML on ExtJS application generally? I have already develop ExtJS application that application has more than 200 grids. Some of grid have <> like HTML. My grid can't view HTML So i change Server side function(common get function) as htmlspecialchars($value, ENT_QUOTES); After that grid can view HTML value like problem is when rowediting mode view value as encode value(&lt;start) note: this happen every form, grid-rowediting, i try to override every input filed as answer but that is not work for me launch: function() { panel = Ext.create('me_project.view.me_panel', {renderTo: 'form'}); Ext.override(Ext.form.field.Base, { setValue: function(val) { val = Ext.util.Format.htmlDecode(val); return this.callParent([val]); } }); } A: The htmlDecode function only decodes the < > & ' symbols as shown in documentation http://dev.sencha.com/deploy/ext-1.1.1/docs/output/Ext.util.Format.html. You can try setting the autoEncode: true property as shown in http://all-docs.info/extjs4/docs/api/Ext.grid.Editing.html. To decode something that is html encoded with jquery you can use val = $('<\div>').html(val).text(); With javascript you can use var textArea = document.createElement("textarea"); textArea.innerHTML =val; val = textArea.value;
{ "language": "en", "url": "https://stackoverflow.com/questions/29115500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find the data from the array? First, I apologize asking about the code that I didn't understood. Here is the code that is currently used to find from the array. In this code there is a function findProducts(p). I am confused about the way this function is being called this.findProducts, [p.id]. Can anybody please help me, I am a complete beginner in JavaScript. Thank You. products = []; ngOnInit() { this.products = this.getProducts(); } getProducts() { return [ { 'id': '1', 'title': 'Screw Driver', 'price': 400, 'stock': 11 }, { 'id': '2', 'title': 'Nut Volt', 'price': 200, 'stock': 5 }, { 'id': '3', 'title': 'Resistor', 'price': 78, 'stock': 45 }, { 'id': '4', 'title': 'Tractor', 'price': 20000, 'stock': 1 }, { 'id': '5', 'title': 'Roller', 'price': 62, 'stock': 15 }, ]; } updateStock(p) { console.log(p); //{id: "1", updatedStockValue: 23} console.log("final", this.products.find(this.findProducts, [p.id])); } findProducts(p) { console.log(p); //{id: "1", title: "Screw Driver", price: 400, stock: 11…} console.log(this); //["1"] return p.id === this[0]; } A: Javascript has a Array.find(function(element(){}) function that you can use to look up values in an array, and inside the function(element){} you define the matching criteria . Here the parameter to the Array.find() function is passed as the function(element), in this case, findProducts(), and additional parameters to the find function is given as another argument following the comma (in this case p.id). You can pass any number of arguments while calling the function, and they'll all be accessible using an array indexing approach. For example, you can do somefunction(someOtherFunction, a, b, c)... ... Later you can access these values: a will be this[0] b will be this[1] c will be this[2] A: this.products.find(this.findProducts, [p.id]) findProducts(p) { return p.id === this[0]; } above function is the expansion of this.products.find(product=>product.id == p.id) It will iterate through all array element and returns matching product with given p.id A: The Mozilla documentation gives some insight into what the second argument to find is, namely thisArg: Object to use as this when executing callback. So in your example, the callback is findProducts and thisArg is an array containing one element (which is a slightly weird approach to be honest). Without thisArg, this inside findProducts would not be that array. Below is a working demo. Note that without thisArg, this in findProducts is the window object. With thisArg, it is the second array parameter: var arr = [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'} ]; function findProducts(p) { console.log('in findProducts', p); console.log(this); return p.id === this[0]; } var f = arr.find(p => findProducts(p)); console.log('without thisArg', f); f = arr.find(findProducts, [1]); console.log('with thisArg', f); A: You can do is in your findProducts fn findProducts(p) { let result = this.products.findIndex(item=>item.id === p.id); return result // here the result will contain -1 if value is not present else it will contain some value } read more about find and findIndex
{ "language": "en", "url": "https://stackoverflow.com/questions/53531710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cast a list column into dummy columns in Python Polars? I have a very large data frame where there is a column that is a list of numbers representing category membership. Here is a dummy version import pandas as pd import numpy as np segments = [str(i) for i in range(1_000)] # My real data is ~500m rows nums = np.random.choice(segments, (100_000,10)) df = pd.DataFrame({'segments': [','.join(n) for n in nums]}) userId segments 0 885,106,49,138,295,254,26,460,0,844 1 908,709,454,966,151,922,666,886,65,708 2 664,713,272,241,301,498,630,834,702,289 3 60,880,906,471,437,383,878,369,556,876 4 817,183,365,171,23,484,934,476,273,230 ... ... Note that there is a known list of segments (0-999 in the example) I want to cast this into dummy columns indicating membership to each segment. I found a few ways of doing this: In pandas: df_one_hot_encoded = (df['segments'] .str.split(',') .explode() .reset_index() .assign(__one__=1) .pivot_table(index='index', columns='segments', values='__one__', fill_value=0) ) (takes 8 seconds on a 100k row sample) And polars df2 = pl.from_pandas(df[['segments']]) df_ans = (df2 .with_columns([ pl.arange(0, len(df2)).alias('row_index'), pl.col('segments').str.split(','), pl.lit(1).alias('__one__') ]) .explode('segments') .pivot(index='row_index', columns='segments', values='__one__') .fill_null(0) ) df_one_hot_encoded = df_ans.to_pandas() (takes 1.5 seconds inclusive of the conversion to and from pandas, .9s without) However, I hear .pivot is not efficient, and that it does not work well with lazy frames. I tried other solutions in polars, but they were much slower: _ = df2.lazy().with_columns(**{segment: pl.col('segments').str.contains(segment) for segment in segments}).collect() (2 seconds) (df2 .with_columns([ pl.arange(0, len(df2)).alias('row_index'), pl.col('segments').str.split(',') ]) .explode('segments') .to_dummies(columns=['segments']) .groupby('row_index') .sum() ) (4 seconds) Does anyone know a better solution than the .9s pivot? A: This approach ends up being slower than the pivot but it's a got a different trick so I'll include it. df2=pl.from_pandas(df) df2_ans=(df2.with_row_count('userId').with_column(pl.col('segments').str.split(',')).explode('segments') \ .with_columns([pl.when(pl.col('segments')==pl.lit(str(i))).then(pl.lit(1,pl.Int32)).otherwise(pl.lit(0,pl.Int32)).alias(str(i)) for i in range(1000)]) \ .groupby('userId')).agg(pl.exclude('segments').sum()) df_one_hot_encoded = df2_ans.to_pandas() A couple of other observations. I'm not sure if you checked the output of your str.contains method but I would think that wouldn't work because, for example, 15 is contained within 154 when looking at strings. The other thing, which I guess is just a preference, is the with_row_count syntax vs the pl.arrange. I don't think the performance of either is better (at least not significantly so) but you don't have to reference the df name to get the len of it which is nice. I tried a couple other things that were also worse including not doing the explode and just doing is_in but that was slower. I tried using bools instead of 1s and 0s and then aggregating with any but that was slower.
{ "language": "en", "url": "https://stackoverflow.com/questions/74432537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using html-base tag in aspx page I have an aspx page which shows preview of html-email. The html email comes from DB as text. This is assigned to a div. Now i have a base tag which carries a url which is dynamic based on the DB server name. When i assign the html from DB to the div, the base for the relative url of the images inside the html are taking the base url of the page instead of the base url from the html text. basically, the page is rendered as, <html> .... <div> <html> <head> <base href="dynamic url" /> </head> <body> <img src="images/header.jpg" /> ..... </body> </html> </div> ..... </html> The 2nd html comes from DB. How to force the dynamic url of the img tag to take the base url from base tag. Now the img src is coming as, page_url/images/header.jpg. I want it as dynamic_url/images/header.jpg. A: I think you should be able to do this in two different methods. First replace the text "images/" to your dynamic URL on the server side before you assign the email HTML to the container. It should be straight forward whatever language you are using. If that is not possible then you can do that on client side with JQuery. The code below loops through all the img tags on the page and replaces to a path you specify. This does not actually change the source code but it renders the images with the new path. $(document).ready(function(){ $("img").each(function(i) { $(this).attr('src', $(this).attr('src').replace('old_path', 'new_Path')); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/6436490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Google Geocode Returning Undefined (Can't figure callback function) I'm trying to store the values of the latitude and the longitude from the response that I get from the Google Geocoding API. Right now I am using a fixed location in California. My HTTP request keeps returning undefined. I've been looking around a lot and I see that people have this same problem, but I can't wrap my head around making a callback function which seems to be the solution, could anybody explain to me how to do this? I know that my CORS request is working because I am using it to talk GET from a Heroku server that I set up. var geocode = new XMLHttpRequest(); geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key='); geocode.onload = function() { var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response var results = geoData["results"]; // create variable for results var userLong = results["geometry"]["location"]["lng"]; // parse the latitude var userLat = results["geometry"]["location"]["lat"]; // parse the longitude console.log(userLong); console.log(userLat); } createCORSRequest() // Create the XHR object. function createCORSRequest(method, url) { if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, false); } else if (typeof XDomainRequest != "undefined") { // XDomainRequest for IE. xhr = new XDomainRequest(); xhr.open(method, url); } else { // CORS not supported. xhr = null; } return xhr; } A: Assuming createCORSRequest returns an xhr or xhr-like object (which seems to be the typical boilerplate for createCORSRequest from places like the HTML5 Rocks website), you need to include geocode.send(); at the end of your code. Otherwise the request never fires and therefore the onload handler never gets called. A: Look like you're following HTML5Rocks site Using CORS article. Once you create the xhr request. You must invoke send() method to trigger the ajax call. var geocode = new XMLHttpRequest(); geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key='); geocode.onload = function() { var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response var results = geoData["results"]; // create variable for results var userLong = results["geometry"]["location"]["lng"]; // parse the latitude var userLat = results["geometry"]["location"]["lat"]; // parse the longitude console.log(userLong); console.log(userLat); } geocode.send(); Unless you call geocode.send(), the value will be undefined as no request has been fired.
{ "language": "en", "url": "https://stackoverflow.com/questions/29666093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running flutter web app locally without android studio I have a flutter app using Firebase's cloud firestore. I've done the web build and running it on Chrome through Android Studio works well. I would like to share my web app progress to my client but don't want to host it (because it's not finished yet). Hence I'd like to find a way to run it locally the same way you can do it with Android Studio but without needing to install Android Studio (and hopefully not requiring to install flutter either), so that I can send the build file to my client and they can run it in their machine (with a script to start the web server locally and run the web app). I have tried the following script included inside the web build folder (where the index.html is) from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from httplib import HTTPResponse from os import curdir,sep #Create a index.html aside the code #Run: python server.py #After run, try http://localhost:8080/ class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/index.html' try: sendReply = False if self.path.endswith(".html"): mimeType = 'text/html' sendReply = True if sendReply == True: f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', mimeType) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File not found!') def run(): print('http server is starting...') #by default http server port is 80 server_address = ('127.0.0.1', 8080) httpd = HTTPServer(server_address, RequestHandler) try: print 'http server is running...' httpd.serve_forever() except KeyboardInterrupt: httpd.socket.close() if __name__ == '__main__': run() But when opening http://localhost:8000 on Chrome I get a blanc page and the console shows the errors: Failed to load resource: net::ERR_EMPTY_RESPONSE main.dart.js:1 Failed to load resource: net::ERR_EMPTY_RESPONSE manifest.json:1 Failed to load resource: net::ERR_EMPTY_RESPONSE :8080/favicon.png:1 I also tried NPM local-web-server by running ws --spa index.html but just getting a ERR_EMPTY_RESPONSE response. This is what I have in my build/web after running flutter build web: How can I create a local server where I can host my web app locally and run it locally without hosting it on the internet? A: as you mentioned in the comment here you go. Create a file app.js with the following: const express = require('express') const app = express() const port = 8000 app.get('/', (req, res) => { console.log('getting request') res.sendFile('website/y.html',{root:__dirname}) }) app.use(express.static(__dirname + '/website')) app.use((req, res)=>{ res.redirect('/') }) app.listen(port, () => { console.log(`app listening at http://localhost:${port}`) }) Here my website files exist at website folder and my entry point is y.html. Set the static file directory (your website page) and then serve the .html for the root request example project: https://github.com/ondbyte/website Finally, to run it open terminal and move to the root folder. Then do npm init npm install express --no-save node app.js A: Here is the more simpler way. NO NEED to setup server open your Build/web folder in vscode. install Live server Plugin in vscode. hit Golive Button Here you go your flutter web app would be running locally without android studio.
{ "language": "en", "url": "https://stackoverflow.com/questions/65036423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why can't I use IIFE with "this"? My test code: var colorChanged = function (c) { //valid syntax: (function (x) { x.css('color', '#f00') })($('.' + c)); //invalid syntax: (function (this) { //Uncaught SyntaxError: Unexpected token this this.css('color', '#f00') })($('.' + c)); }; <div class="demo">Div text</div> <button onclick="colorChanged('demo')">Change color</button> I'd reference Immediately-invoked function expression but it didn't mention about using this in this case. My question is: Is there any way to use this as an element (this = $('.' + c)) in the example? A: Yes, there is a way to use this inside your IIFE's, you can bind the thisValue with bind() before calling the IIFE. (function() { this.css('color', '#f00') }).bind($('.' + c))(); A: You can use bind() or call() or apply() and pass 'this' through them as your scope changed for 'this'... It's always a good practice using these functions in javascript, rather then attach it to the function... The best option is call for your code... (function() { this.css('color', '#f00') }).call($('.' + c)); Also using click handler in your javascript, make your code much cleaner and can make your coding structure better, you also can use multiple selection in jQuery to keep HTML clean if needed more selectors handle this function...
{ "language": "en", "url": "https://stackoverflow.com/questions/34172799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve next id in database which may not be the next auto incremented number php mysql apologies as this seems to me to be a very simple answer, but am struggling to find a solution having searched around. I have a pretty simplistic table that stores a series of info for booking a caravan - options are one week or two week bookings. I've previously used (and successfully for the last however many years) a simple if else statement to check availability. The weeks are sequential in the database on an auto incremented basis and i simply searched for the next week and a third week as a fail safe by $next_week_id1 = $row['id'] + 1; and $next_week_id2 = $row['id'] + 2;. Basic I know, but it has worked until now where there has been some kind of discrepancy with the auto increment - I have an id which misses the next incremental value so from id 91 for example it goes to 93, which messes up the whole script. Its been a while since I touched this, just wondering how you'd hit the next value in the database (for the second week and then the third week) without using the id as an incremental stepping stone? They will always be the next one in the list, but clearly using id+1 or id+2 is a non-reliable way of accessing this... Thanks for any advice.
{ "language": "en", "url": "https://stackoverflow.com/questions/26253322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: hMailServer adress of recipient instead of distribution list We use the hMailServer to forward incoming mails via distribution list. The problem is that the recipient receives the mail with the address of the distribution list instead of the actual recipient address. Is there a possibility that the recipient receives the mail with the real recipient address instead of the address of the distribution list. So that it appears to the recipient as if he had received the message directly and not via the distribution list.
{ "language": "en", "url": "https://stackoverflow.com/questions/75285459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert dynamic image as option in php and mysql im currently developing a small school project that involve creating a style survey for an interior design website to identify the type of room that a client wish to decorate. i created a dynamic list that will return the list of option from the database which will show the options in the form of images. when the user click one of the image that shows the type of room, the page should automatically bring the user to next question and save the option that the user has clicked. my problem now is I cannot insert the option chosen by the user into my database, the image that the user has click. below is my code <?php $dynamicList = ""; $sql = mysqli_query($con,"SELECT * FROM room ORDER BY room_date"); $roomCount = mysqli_num_rows($sql); if ($roomCount > 0) { while($row = mysqli_fetch_array($sql)){ $id = $row["room_id"]; $room_name = $row["room_name"]; $room_date = strftime("%b %d, %Y", strtotime($row["room_date"])); $dynamicList .= '<ul class="room"><li><a href="#"> <center><a href="stylesurvey.php?id=' . $id . '"><img src="uploads/' . $id . '.jpg" alt="' . $room_name . '" width="170" height="170" /></a> <h4>' . $room_name . '</h4> </center> </a> </li> </ul'; } } else { $dynamicList = "No room listed"; } mysqli_close($con); ?> <?php if (isset($_POST["id"])) { $id = $row["room_id"]; $room_name = $row["room_name"]; $survey_id = $row["survey_id"]; $room_id = $row["room_id"]; $date = strftime("%b %d, %Y", strtotime($row["date"])); $sql = mysqli_query($con,"INSERT INTO survey (survey_id , room_id, user_id, room_name, date) VALUES('$survey_id','$room_id','$_SESSION[usr_name]','$room_name',now())") or die (mysql_error()); echo "Unable to insert data"; exit(); } ?> A: Here you pass values as a get method you need to use $_GET['id'] like this while($row = mysqli_fetch_array($sql)){ $id = $row["room_id"]; $room_name = $row["room_name"]; $room_date = strftime("%b %d, %Y", strtotime($row["room_date"])); $dynamicList .= '<ul class="room"><li><a href="#"> <center><a href="stylesurvey.php?id=' . $id . '&room_name= .$room_name.'&room_date=.$room_date.'"><img src="uploads/' . $id . '.jpg" alt="' . $room_name . '" width="170" height="170" /></a> <h4>' . $room_name . '</h4> </center> </a> </li> </ul>'; } } else { $dynamicList = "No room listed"; } mysqli_close($con); ?> <?php if (isset($_GET["id"])) { $id = $_GET["room_id"]; $room_name = $_GET["room_name"]; $survey_id = $_GET["survey_id"]; $date = $_GET["room_date"]; $sql = mysqli_query($con,"INSERT INTO survey (survey_id , room_id, user_id, room_name, date) VALUES('$survey_id','$room_id','$_SESSION[usr_name]','$room_name',now())") or die (mysql_error()); echo "Unable to insert data"; exit(); } ?> Now try this it should work
{ "language": "en", "url": "https://stackoverflow.com/questions/39689702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails Searchable plugin and GORM marshalling I have an one-to-one relationship (hasOne in User domain and belongsTo in UserInfo domain). When the BootStrap is executing I get an exception: org.compass.core.converter.ConversionException: Trying to marshall a null id [id] for alias [UserInfo] this line of code produces it: def user = new User(....., new UserInfo()).save() A: According to Peter Ledbrook, this is a non-trivial conflict between Hibernate and Searchable: http://jira.grails.org/browse/GPSEARCHABLE-19 The solution is to turn off mirroring in the Searchable plugin and handle updating indexes manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/13358117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ignite topology and partition owners left am facing below issue either when the Kubernetes or Ignite client nodes are getting restarted then we are not able to establish the connection to Ignite pods. We deployed the ignite as a Service and running in a Client/server mode. Caused by: org.apache.ignite.internal.processors.cache.CacheInvalidStateException: Failed to execute the cache operation (all partition owners have left the grid, partition data has been lost) class org.apache.ignite.internal.cluster.ClusterTopologyCheckedException: Failed to send message (node left topology): TcpDiscoveryNode [ And the below are the deployment and config details <property name="dataStorageConfiguration"> <bean class="org.apache.ignite.configuration.DataStorageConfiguration"> <!-- Redefining the default region's settings --> <property name="defaultDataRegionConfiguration"> <bean class="org.apache.ignite.configuration.DataRegionConfiguration"> <property name="name" value="18GB_Region"/> <!-- 2 GB initial size (RAM). --> <property name="initialSize" value="#{2L * 1024 * 1024 * 1024}"/> <!-- Setting the size of the default region to 20GB. --> <property name="maxSize" value="#{20L * 1024 * 1024 * 1024}"/> <!--property name="persistenceEnabled" value="true"/--> <!-- Enabling RANDOM_LRU eviction for this region. --> <property name="pageEvictionMode" value="RANDOM_2_LRU"/> <!-- Increasing the buffer size to 2 GB. --> <property name="checkpointPageBufferSize" value="#{2L * 1024 * 1024 * 1024}"/> </bean> </property> <!-- Set the page size to 8 KB --> <property name="pageSize" value="#{8 * 1024}"/> <!-- Changing WAL Mode. --> <property name="walMode" value="NONE"/> <!-- Enable write throttling. --> <property name="writeThrottlingEnabled" value="false"/> </bean> </property> <property name="discoverySpi"> <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi"> <property name="ipFinder"> <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.kubernetes.TcpDiscoveryKubernetesIpFinder"> <property name="masterUrl" value=""/> </bean> </property> </bean> </property>
{ "language": "en", "url": "https://stackoverflow.com/questions/73237161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt - Keyboard Hook I'm using Qt 5.1.1 and I want make keyboard hooks, but Qtx do not accept my version, but I REALLY need this, for an autoclicker project. Any lib is good to me, but it need to be multiplatform, and what's the best way to "click" in Qt?
{ "language": "en", "url": "https://stackoverflow.com/questions/19470827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking CSS file in php document nested in pages folder Web development newbie here. My site is becoming large enough that recently took a few steps to help manage it including: * *Using a separate header.php; footer.php; and navigation.php file with an includes tag. *Filed additional pages under root/pages. Below is a snapshot of my current folders: * *root * *pages *assets *images *js *php My issue now that I have nested additional pages (other than index.html) in the pages folder. When coding these files, the link/include files are causing issues, because of the relative/absolute file reference. Through some research I was able to use this php code which seems to work for the header, footer, and navigation menu: <?php set_include_path( implode( PATH_SEPARATOR, array( $_SERVER['DOCUMENT_ROOT'], get_include_path() ) ) ); include 'root/assets/header.php'; ?> The issue I have now is the css link no longer works either: <link rel="stylesheet" href="css/style-services.css"> I have tried doing this with no luck: <?php set_include_path( implode( PATH_SEPARATOR, array( $_SERVER['DOCUMENT_ROOT'], get_include_path() ) ) ); include 'root/css/style-services.css'; ?> How do I insure the referenced css also gets included when using a file structure and php include functions? A: Don't include the CSS file, just echo it. Like: <?php // // your other cods here // $style_services = file_get_contents ("root/css/style-services.css"); echo $style_services; // // your other cods here // ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/64668065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WinCE 6.0 device not responding to ping i am working on WinCE 6.0(On ARM9) based (Headless)Device. i established a ethernet(EMACB1) connection between My Desktop(XP-SP3) and WinCE Device. the device shows network established but wince device not respong to ping. Below are my TCP/IP Settings: Desktop: IP Address: 192.168.1.176 SubnetMask: 255.255.255.0 Default Gateway : 192.168.1.1 WinCE Device: IP Address: 192.168.1.21 SubnetMask: 255.255.255.0 Default Gateway : 192.168.1.1 and i had set same primery and Alternative DNS for both. My aim is to collect any data from the WinCE device. As Activesync is not secured (No Authentication), I wish to use Ethernet(TCPIP) Connection. What am I missing? also i have some doubts: 1) is NIC mondatory for TCPIP? as i am not using any NICs. 2) is there any way to give authorization for Activesync. 3) which protocol is better to communicate locally between PC and WinCE Device(Headless) over ethernet.(Like VPN or TFTP or TCPIP etc) Any suggestions would be appreciated Thanks in Advance rocky A: Your Linksys router at 192.168.1.1 could be blocking ActiveSync. Also, make sure the USB connections in settings are set to ActiveSync (enable advanced network functionality), and not Mass Storage. Here are some notes copied over from PocketPC FAQ: (re-posted here in case the website goes away) You must follow a few preliminary steps before loading new components for Ethernet. * *Establish a serial cable, infrared, or USB connection to the PC with which you are going to use ActiveSync. This is required to put the PC's computer name in your Pocket PC for use with Ethernet. *Install the Ethernet drivers from the Ethernet vendor's installation disk. This will add a Network Control Panel as well as other relevant files. This installation requires less than 250 kilobytes of free memory for storage. You may also use the built-in NE-2000 drivers if you prefer to save the storage space. *Reset the device to load the new components. Next, configure the Network Control Panel for Ethernet on your Pocket PC. * *Click Start. *Click Settings. *Click Network. Figure 1: Example of the TCP/IP Properties for Socket's Low Power Ethernet CF+ Card. * *Enter the IP address for the Pocket PC. I suggest the TCP/IP address 192.168.1.2 with subnet mask 255.255.255.0, and the WINS server address, which is the PC's IP address (192.168.1.1 using my recommended setting). *Leave the other fields blank. Figure 2: Properly configured Network Control Panel settings on the Pocket PC. Connecting * *Plug both the Pocket PC and the PC into the hub. (If you are using a crossover cable, you can connect the Pocket PC and PC directly without a hub.) *Turn on the PC and the Pocket PC and plug the Ethernet PC card into your Pocket PC. *To start an ActiveSync session, select ActiveSync on your Pocket PC (choose Start, then Programs, and then Connections). Make sure the Method is set to Network Connection and the Connect To matches the PC computer's name. Then click Connect to start ActiveSync communications. If you enable continuous ActiveSync synchronization, your Pocket PC will stay up-to-date, downloading new e-mail, tasks, contacts, and other files and data whenever it's connected to your desktop PC. Gotcha After plugging your Ethernet PC card into your Pocket PC, check for a link light on the PC's Ethernet card. If it is not lit, you are having a cable or hub problem. A: How are the network cables and devices connected? Did you use a hub or a switch (do they support MDI/X?). I ask, as normally you cannot simply connect two devices with a standard cable. Best is to use a small switch that support Auto-MDI/X and switches correctly to use normal or reversed cabling.
{ "language": "en", "url": "https://stackoverflow.com/questions/11985853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to wrap Erlang code to a certain character limit Suppose I have a method timer:apply_after(timeout, module, method, [Hosts]) Is there a tool that can help format this into something like: timer:apply_after( timeout, module, method, [Hosts] ) I don't think erl_tidy does this. A: You could give prettypr a try. I've never used it myself, and might not give the exact output you specified, but it does format the source code according to the available horizontal space. A: It should be possible to do this through erl_tidy, by passing an option {printer, fun (Tree, Opts) -> erl_prettypr:format(Tree, [{paper, P}, {ribbon, R} | Opts]) end}. See http://erlang.org/doc/man/erl_prettypr.html#format-2 for details about the ribbon and paper options, and http://erlang.org/doc/man/erl_tidy.html#file-2 for info about the printer option.
{ "language": "en", "url": "https://stackoverflow.com/questions/39695448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding delete button to a div I am going to add a delete button to new items made. This delete button removes the item my-item from the page without affecting others. Code I have tried: <!DOCTYPE HTML> <html> <head> <meta charset = "UTF-8"> <title>Simple Demo</title> <style> .my-item{ width:250px; heigth:180px; margin:10px; padding:20px; background:green; border:2px solid black; } .item-header{ width:150px; heigth:120px; margin:5px; padding:10px; background:yellow; border:1px solid black; } .item-body{ width:70px; heigth:50px; margin:3px; padding:5px; background:purple; border:1px solid black; } </style> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $("#divButton").click(function(){ $(".my-item").clone().appendTo("body") }); $("#toggle").click(function(){ if ($(".item-body").is(":visible")){ $(".item-body").slideUp("normal"); }else{ $(".item-body").slideDown("normal"); } }); $("#deleteButton").click(function(){ $(".my-item").append(".my-item"+ "button class="deleteButton">Delete</button>"); }); }); </script> </head> <body> <div class="my-item"> <div class="item-header"> <h2 id="toggle">Click Me!</h2> <div class="item-body">My Text! </div> </div> </div> <button id="divButton">Click!</button> <button id="deleteButton">Delete!</button> </body> </html> I'll be glad if you can help me. :) A: As simple as that : $(".my-item").remove(); (if I understood your question correctly) A: I have found some things which could be improved. First of all. An id is unique, so whenever you start to clone elements, the id is cloned as well. I made a few adjustments and this is how it works: HTML <div class="my-item"> <div class="item-header"> <h2 id="toggle">Click Me!</h2> <div class="item-body">My Text! </div> </div> <button class="divButton">Click!</button> <button class="deleteButton">Delete!</button> </div> CSS (still the same) .my-item { width: 250px; heigth: 180px; margin: 10px; padding: 20px; background: green; border: 2px solid black; } .item-header { width: 150px; heigth: 120px; margin: 5px; padding: 10px; background: yellow; border: 1px solid black; } .item-body { width: 70px; heigth: 50px; margin: 3px; padding: 5px; background: purple; border: 1px solid black; } jQuery function addEvents() { $(".divButton").unbind("click").click(function() { $(this).parent().clone().appendTo($("body")); addEvents(); }); $(".deleteButton").unbind("click").click(function() { $(this).parent().remove(); }); } addEvents(); The reason why I put both click events in a separate function, is when the element is cloned, the events are not cloned. Therefor, you will have to rebind them. This doesn't have to happen when you delete an element. I hope this solves your question FIDDLE A: Guess you mean something like this: $("#deleteButton").click(function(){ $(this).nextAll(".my-item").remove(); }); This will remove all .my-item after the delete button and not your template. Just a notice, when you're cloning your .my-item element, you'll get multiple "toggle" IDs in the DOM, which is not good. A: I recommend to use single instead of the double quotation marks for js: $('selector'); The following line is wrong: $(".my-item").append(".my-item"+ "button class="deleteButton">Delete</button>"); Correct is: $(".my-item").append("<button class=\"deleteButton\">Delete</button>"); or $('.my-item').append('<button class="deleteButton">Delete</button>'); Your code will not produce new elements by clicking on button "Click!" and adding new delete buttons by clicking on the "Delete"-Button. I guess what you want to archive is to duplicate an Item and add a delete button to the item itself. Just clone your element without appending and save it to a var. ( var newElement = $.('selectpr').clone(); ) Then append the delete button to the newElement object and append the object to the target. Another approach would be appending the clone to a container and then selecting it by looking for the last element in the container. Then bind a click event to the delete button. Please check jQuery and CSS manual for correct selectors. A: Ok, here's a different solution for you with cached element and no duplicate IDs. <script> $(document).ready(function() { var $myItem = $(".my-item"); var $deleteBtn = $("<button/>",{"class":"deleteButton"}).text('Delete').on({ click: function() { $(this).closest('.my-item').remove(); // delete item } }); // enable toggle of item body $(".toggle").click(function() { $(this).next(".item-body").slideToggle("normal"); }); // Add new item $("#divButton").click(function(){ var $newItem = $myItem.clone(true); $("body").append($newItem.append($deleteBtn.clone(true))); }); }); </script> And here is your HTML body part: <body> <div class="my-item"> <div class="item-header"> <h2 class="toggle">Click Me!</h2> <div class="item-body">My Text!</div> </div> </div> <button id="divButton">Click!</button> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/34613076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: SQL query to group multiple groups I'm parsing some IIS server logs (with LogParser) and I'm having a little trouble creating a query that will give me the aggregate count of each type of browser (user agent). Here is my query so far: SELECT COUNT(*) as totalHits, CS(User-Agent) as browser FROM E:\Logs\ex111101.log WHERE (CS(User-Agent) LIKE '%ipad%' OR CS(User-Agent) LIKE '%iphone%' OR CS(User-Agent) LIKE '%blackberry%' OR CS(User-Agent) LIKE '%windows cs%' OR CS(User-Agent) LIKE '%android%') AND cs-uri-stem LIKE '%.asp%' GROUP BY browser ORDER BY totalHits DESC This givse me a list of user-agents like I want, and gives me a hit count for each group of browser: Total Hits | Browser 467 | AndroidA 45 | AndroidB 23 | BlackberryC 233 | BlackberryD What I want is THIS: Total Hits | Browser 512 | Android 256 | Blackberry Where All Android entries are counted and totaled under a generic Android row. In this case Total Hits for Android would be 467 + 45, Blackberry would be 233 = 33, etc. From there I would want to provide a Percent column for each browser so I can represent the total hits as a percentage. Any help is appreciated. Thanks! *UPDATE Followed the suggestion below but had to make a few tweaks in order for it to be executed correctly by LogParser. For some reason Log Parser didn't like the LIKE keyword in the CASE statement. The following worked fine though: select case strcnt(TO_LOWERCASE(cs(user-agent)),'android') WHEN 1 THEN 'Android' else case strcnt(TO_LOWERCASE(cs(user-agent)),'ipad') WHEN 1 THEN 'iPad' else case strcnt(TO_LOWERCASE(cs(user-agent)),'blackberry') WHEN 1 THEN 'Blackberry' else case strcnt(TO_LOWERCASE(cs(user-agent)),'windows ce') WHEN 1 THEN 'Windows' else case strcnt(TO_LOWERCASE(cs(user-agent)),'iphone') WHEN 1 THEN 'iPhone' ELSE 'Non-Mobile' End End End End End as Browser, count(*) as TotalHits from MYLOG group by Browser order by TotalHits desc A: try select case when cs(User-Agent) like "%android%" then "Android" when cs(User-Agent) like "%black%" then "Blackberry" when cs(User-Agent) like "%windows%" then "Windows" when cs(User-Agent) like "%iphone%" then "iPhone" else "Other" end as Browser, count(*) as TotalHits from YourTable.logFile group by Browser order by TotalHits desc The group by and order by respect the ordinal column position instead of re-copying the entire case/when and count(*)... Since there's only two columns, no problem...
{ "language": "en", "url": "https://stackoverflow.com/questions/9012613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javax.el.ELException: Property 'askQuestiοn' not found on type trainforjava.domain.Questiοn My problem is the following. I've a list which i s well created, but I can't manage to display it on my web page. Here is the pojo : package trainforjava.domain; public class Question { public int id; public String askedQuestion; public String proposal; public Question() { super(); } public Question(int id, String askedQuestion, String proposal) { super(); this.id = id; this.askedQuestion = askedQuestion; this.proposal = proposal; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setAskedQuestion(String askedQuestion) { this.askedQuestion = askedQuestion; } public String getAskedQuestion() { return askedQuestion; } public void setQuestion(String askedQuestion) { this.askedQuestion = askedQuestion; } public String getProposal() { return proposal; } public void setProposal(String proposal) { this.proposal = proposal; } @Override public String toString() { return "Question [id=" + id + ", askedQuestion=" + askedQuestion + "]"; } } Here is the managed bean : package trainforjava.domain; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import trainforjava.util.QuestionCreator; @ManagedBean public class QuestionBean { public List<String> proposals; public List<Question> questions; public QuestionCreator creator = new QuestionCreator(); public QuestionBean() { System.out.println("beforecreate"); questions = creator.createQuestions(); System.out.println(questions); // proposals = creator.createProposals(0); } public List<String> getProposals() { return proposals; } public void setProposals(List<String> proposals) { this.proposals = proposals; } public List<Question> getQuestions() { return questions; } public void setQuestions(List<Question> questions) { this.questions = questions; } } Here is the pojo creating from a properties file : package trainforjava.util; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.springframework.stereotype.Component; import trainforjava.domain.Question; public class QuestionCreator { List<Question> questions =new ArrayList<Question>(); List<String> proposals = new ArrayList<String>(); public List<Question> createQuestions() { final Properties properties = new Properties(); InputStream input = null; System.out.println("createQuestions"); try { input = getClass().getResourceAsStream("/questions.properties"); // load a properties file properties.load(input); // get the property value and print it out for (int i = 0; i < properties.size(); i++) { Question question = new Question(); StringBuilder sb = new StringBuilder(); sb.append("question-").append(i); String askedQuestion = properties.getProperty(sb.toString()); question.setAskedQuestion(askedQuestion); question.setId(i); questions.add(question); } } catch (final IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (final IOException e) { e.printStackTrace(); } } } return questions; } public List<String> createProposals(int key) { final Properties properties = new Properties(); InputStream input = null; System.out.println("createProposals"); try { input = getClass().getResourceAsStream("/proposals.properties"); // load a properties file properties.load(input); for(int i =0 ; i < proposals.size(); i++){ int idQuestion = key; System.out.println("createProposals id" + idQuestion); StringBuilder sb = new StringBuilder(); sb.append("proposal-").append(idQuestion).append("-").append(i); String proposal = properties.getProperty(sb.toString()); proposals.add(proposal); System.out.println(proposals); } } catch (final IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (final IOException e) { e.printStackTrace(); } } } return proposals; } } The console print me the list created, which name is "questions", but also print me a stacktrace : beforecreate createQuestions [Question [id=0, askedQuestion=Quelle interface est implémentée par la Classe ArrayList ?], Question [id=1, askedQuestion=Quelle interface est implémentée par la Classe HashMap ?], Question [id=2, askedQuestion=Quelle interface est implémentée par la Classe Vector ?]] août 23, 2016 2:29:19 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException GRAVE: Error Rendering View[/index.xhtml] javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88) at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302) at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385) at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) at javax.faces.render.Renderer.encodeChildren(Renderer.java:176) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log 1100: JSF1073 : javax.el.ELException intercepté durant le traitement de RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=/index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log 1100: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88) at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302) at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385) at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) at javax.faces.render.Renderer.encodeChildren(Renderer.java:176) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) And then, the index.xhtml which is supposed to display this list : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:head> <title>Test</title> </h:head> <h:body> Question : <h:form> <h:dataTable value="#{questionBean.questions}" var="question"> <h:column> #{question.askQuestion} </h:column> </h:dataTable> </h:form> </h:body> </html> Can someone help me please ? A: The property name is actually askedQuestion, and not askQuestion.
{ "language": "en", "url": "https://stackoverflow.com/questions/39090700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Space Complexity of generating all possible binary search trees I used the following recursion algorithm to calculate the possible cases of binary search trees given its number of nodes being n public List<TreeNode> generateTrees(int n) { if(n == 0){ List<TreeNode> empty = new ArrayList<TreeNode>(); return empty; } return recurHelper(1, n); } public List<TreeNode> recurHelper(int start, int end){ if(start > end){ TreeNode nan = null; List<TreeNode> empty = new ArrayList<TreeNode>(); empty.add(nan); return empty; } List<TreeNode> result = new ArrayList<TreeNode>(); for(int i = start; i <= end; i++){ List<TreeNode> left = recurHelper(start, i-1); List<TreeNode> right = recurHelper(i+1, end); for(TreeNode leftBranch:left){ for(TreeNode rightBranch:right){ TreeNode tree = new TreeNode(i); tree.left = leftBranch; tree.right = rightBranch; result.add(tree); } } } return result; } I wonder what is the space complexity for the recursion, should it be O(h), where h is the height of the tree? I do not think so because at each level we are storing a result consisting of O(lG_l) elements, where l stands for the level and G_l stands for the number of possible trees with l nodes. Then it seems to me that the space complexity of the recursion should be nG_n + ... + 1G_1.
{ "language": "en", "url": "https://stackoverflow.com/questions/61577493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: zypper dependency resolution I am facing problem while installing an "Company-hardening-1.0-1.noarch.rpm" RPM through zypper. There are 2 systems involved. Both are SUSE-Linux-Enterprise-Server-11-SP3 VMs. System 1: (working) In this system I am able to install the rpm, in this case, zypper is automatically resolving the dependency. susevm1:~ # zypper install Company-hardening-1.0-1.noarch.rpm Loading repository data... Reading installed packages... Resolving package dependencies... The following NEW packages are going to be installed: Company-hardening openscap-engine-sce The following packages are not supported by their vendor: Company-hardening openscap-engine-sce 2 new packages to install. Overall download size: 195.0 KiB. After the operation, additional 1.0 MiB will be used. Continue? [y/n/?] (y): n System 2: (Not working) In this system RPM is not getting installed, as zypper is not able to resolve the dependency. linux-g33k:~/Desktop/RPMS # zypper install Company-hardening-1.0-1.noarch.rpm Loading repository data... Reading installed packages... Resolving package dependencies... Problem: nothing provides openscap-engine-sce >= 1.2.5-2 needed by Company-hardening-1.0-1.noarch Solution 1: do not install Company-hardening-1.0-1.noarch Solution 2: break Company-hardening-1.0-1.noarch by ignoring some of its dependencies Choose from above solutions by number or cancel [1/2/c] (c): c Note that, both system are having same version of zypper. I know, this might a simple and silly question. :) This might be because of some repository diff. Thanks, Hemant A: It means you don't have the same repositories activated on both machines. Comparing the output of zypper lr -u on both machines should show you which repository to add or enable.
{ "language": "en", "url": "https://stackoverflow.com/questions/40262734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Black bar when increasing window size in WPF I have a small program with two checkboxes. The window height is 120. When one of them is checked the windows height should increase to 180. If both are checked it should increse to 220. If you uncheck them they should decrease to 180 for 1 checkbox and 120 if none are checked. I make it smooth, that means i calculate the windowHeightOld and windowHeightNew difference, divide it through 30 and increase it in 30 small steps so it seems smooth. The problem is that the decrease to a smaller window size looks great, the increase gives on the area that increases a black bar for a few milliseconds, then dissapears again. Sadly i could not make a screenshot because of how short its there. I dont know where that comes from and how that could be fixed. Here a code snipped from the increase/decrase of the window height: private void CheckBoxSetup_Click(object sender, RoutedEventArgs e) { if (CheckBoxSetup.IsChecked == false && CheckBoxUpdate.IsChecked == false) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 180; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } } if (CheckBoxSetup.IsChecked == true || CheckBoxUpdate.IsChecked == true) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 220; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } //MainWindow1.MinHeight = 220; } if (CheckBoxSetup.IsChecked == true && CheckBoxUpdate.IsChecked == true) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 260; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } //MainWindow1.MinHeight = 260; } if (CheckBoxSetup.IsChecked == true) { LabelDestinationSetup.Visibility = Visibility.Visible; TextBoxDestinationpathSetup.Visibility = Visibility.Visible; CheckCountSetup++; } else { LabelDestinationSetup.Visibility = Visibility.Hidden; TextBoxDestinationpathSetup.Visibility = Visibility.Hidden; CheckCountSetup--; } if (CheckCountSetup == 1) { LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0); LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop2, 0, 0); } if (CheckCountSetup == 0 && CheckCountUpdate == 1) { LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0); LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0); } if (CheckCountSetup == 0) { LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0); LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0); } } private void CheckBoxUpdate_Click(object sender, RoutedEventArgs e) { if(CheckBoxUpdate.IsChecked == true && CheckBoxFTP.IsChecked == false){ CheckBox64Bit.IsEnabled = true; }else if(CheckBoxUpdate.IsChecked == false){ CheckBox64Bit.IsEnabled = false; CheckBox64Bit.IsChecked = false; } if (CheckBoxSetup.IsChecked == false && CheckBoxUpdate.IsChecked == false) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 180; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } //MainWindow1.MinHeight = 180; } if (CheckBoxSetup.IsChecked == true || CheckBoxUpdate.IsChecked == true) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 220; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } //MainWindow1.MinHeight = 220; } if (CheckBoxSetup.IsChecked == true && CheckBoxUpdate.IsChecked == true) { MainWindow1.MinHeight = 50; OldWindowHeight = MainWindow1.Height; int NewWindowHeigth = 260; WindowDiff = NewWindowHeigth - OldWindowHeight; WindowDiff = WindowDiff / 30; for (int a = 0; a < 30; a++) { OldWindowHeight = OldWindowHeight + WindowDiff; MainWindow1.Height = OldWindowHeight; MainWindow1.MinHeight = OldWindowHeight; } //MainWindow1.MinHeight = 260; } if (CheckBoxUpdate.IsChecked == true) { LabelDestinationUpdatepackage.Visibility = Visibility.Visible; TextBoxDestinationpathUpdatePackage.Visibility = Visibility.Visible; CheckCountUpdate++; } else { LabelDestinationUpdatepackage.Visibility = Visibility.Hidden; TextBoxDestinationpathUpdatePackage.Visibility = Visibility.Hidden; CheckCountUpdate--; } if (CheckCountUpdate == 1) { LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0); LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0); } if (CheckCountSetup == 1 && CheckCountUpdate == 0) { LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop2, 0, 0); LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0); } if (CheckCountUpdate == 0) { LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0); TextBoxDestinationpathUpdatePackage.Margin = new Thickness(181, thickTop2, 0, 0); LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0); TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0); } } Sorry for the long line of code but i thought it to be nessecary to have insight. Basically it checks if these two are checked or not in different combinations. And increases or decreases the window height according to it. And because i also have textboxes there (thats the reason i do it. When checkboxes are checked i want to show the according textbox) which i set visible or invisible according to the checkboxes. So basically its two methods (click Checkbox1 and click Checkbox2) and both are build the same. When one is clicked it checks for the combination, sets the window height accordingly and shows or sets the according textboxes invisible. 0 Checkboxes checked: 1 Checkbox checked: 2 Checkboxes checked: I hope i explained it good enough. A: XAML: <Window x:Class=......... DataContext="{StaticResource MainViewModel}" Name="MyWindow" > <Window.Triggers > <EventTrigger RoutedEvent="CheckBox.Unchecked" > <BeginStoryboard > <Storyboard > <DoubleAnimation Storyboard.TargetName="MyWindow" Storyboard.TargetProperty = "(Window.Height)" Duration="0:0:0.5" To="{Binding WindowHeight}" RepeatBehavior="1x" /> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="CheckBox.Checked" > <BeginStoryboard > <Storyboard > <DoubleAnimation Storyboard.TargetName="MyWindow" Storyboard.TargetProperty = "(Window.Height)" Duration="0:0:0.5" To="{Binding WindowHeight}" RepeatBehavior="1x" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Window.Triggers> <Grid Row="0" > ............ <CheckBox Grid.Column="4" Content="UpadatePack" IsChecked="{Binding PackegeCheck, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" Name="CheckUpadatePack" /> <CheckBox Grid.Column="5" Content="Setup" IsChecked="{Binding SetupCheck, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" Name="CheckSetup" /> ...... </Grid> <Grid Row="5" Visibility="{Binding SetupDestinationVisibility, Converter={StaticResource BoolToVisibilityConverter}}" > <Grid.ColumnDefinitions> <ColumnDefinition Width="120"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Content="Setup Destination" Margin="5" Grid.Column="0"/> <TextBox Margin="5" Grid.Column="1"/> </Grid> <Grid Row="6" Visibility="{Binding PackageDestinationVisibility, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="120"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Content="Package Destination" Margin="5" Grid.Column="0"/> <TextBox Margin="5" Grid.Column="1"/> </Grid> </Window> MainViewModel: public class MainViewModel : ViewModelBase { private bool _sixtyFourBitCheck; private bool _packegeCheck; private bool _setupCheck; private bool _ftpUploadCheck; public int _windowHeight; public int _origSize = 200; public bool SixtyFourBitCheck { get => _sixtyFourBitCheck; set { if (value == _sixtyFourBitCheck) return; _sixtyFourBitCheck = value; OnPropertyChanged(); } } public bool PackegeCheck { get => _packegeCheck; set { if (value == _packegeCheck) return; _packegeCheck = value; OnPropertyChanged(); OnPropertyChanged(nameof(PackageDestinationVisibility)); ChangeWindowsHeght(); } } public bool SetupCheck { get => _setupCheck; set { if (value == _setupCheck) return; _setupCheck = value; OnPropertyChanged(); OnPropertyChanged(nameof(SetupDestinationVisibility)); ChangeWindowsHeght(); } } public bool FtpUploadCheck { get => _ftpUploadCheck; set { if (value == _ftpUploadCheck) return; _ftpUploadCheck = value; OnPropertyChanged(); } } public bool SetupDestinationVisibility => SetupCheck; public bool PackageDestinationVisibility => PackegeCheck; public int WindowHeight { get => _windowHeight; set { if (value == _windowHeight) return; _windowHeight = value; OnPropertyChanged(); } } public MainViewModel() { WindowHeight = _origSize; } private void ChangeWindowsHeght() { WindowHeight = _origSize; if (PackageDestinationVisibility) WindowHeight += 35; if (SetupDestinationVisibility) WindowHeight += 35; OnPropertyChanged(nameof(WindowHeight)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/47451882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split from list in python In my list I have few items, i.e., List=['a/c/d/eww/d/df/rr/e.jpg', 'ss/dds/ert/eww/ees/err/err.jpg','fds/aaa/eww/err/dd.jpg'] I want to keep only from 'eww' till last '/' Modified_list=['eww/d/df/rr/', 'eww/ees/err/err.jpg','eww/err/'] A: Use find(sub_str) function. new_list = [item[item.find("eww"):] for item in List] print(new_list) Output: ['eww/d/df/rr/e.jpg', 'eww/ees/err/err.jpg', 'eww/err/dd.jpg'] A: new_list2=[item[item.find('eww'):item.rfind('/')+1] for item in List] print(new_list2) output= ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/'] A: Here are the steps I would do: * *split the string after eww assuming that each string contains 'eww' you can split the string like this: split = 'eww'+string.split('eww')[1] *Now, you have to loop over each character in the remaining string and save the index of the last / *Remove everything after the last / with the index from step 3: split = split[:splitIndex] *Now, you just have to put everything in a loop that iterates over the list and execute each of the steps above on each element of the list and save the modified string to the ModiefiedList list. A: You can use a regex in a list comprehension. A perfect use case for the new walrus operator (python ≥3.8): List=['a/c/d/eww/d/df/rr/e.jpg', 'ss/dds/ert/eww/ees/err/err.jpg', 'fds/aaa/eww/err/dd.jpg'] import re out = [m.group() if (m:=re.search('eww/(.*)/', s)) else s for s in List] output: ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/'] NB. this keeps the original string in case of no match, if you rather want to drop it: out = [m.group() for s in List if (m:=re.search('eww/(.*)/', s))]
{ "language": "en", "url": "https://stackoverflow.com/questions/72272668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One Click at .click(function() Not Working in Ajax I want to open another page on my site with this ajax: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <div onclick="$(this).click(function(){$(this).html(loadE);$(this).load('http://domain/page2 #idContent')});">OPEN</div> <script> var loadE = "<img src='data:image/gif;base64,R0lGODlhEAAQAPIAAP////8AAP7Cwv5CQv8AAP5iYv6Cgv6SkiH/C05FVFNDQVBFMi4wAwEAAAAh/h1CdWlsdCB3aXRoIEdJRiBNb3ZpZSBHZWFyIDQuMAAh/hVNYWRlIGJ5IEFqYXhMb2FkLmluZm8AIfkECQoAAAAsAAAAABAAEAAAAzMIutz+MMpJaxNjCDoIGZwHTphmCUWxMcK6FJnBti5gxMJx0C1bGDndpgc5GAwHSmvnSAAAIfkECQoAAAAsAAAAABAAEAAAAzQIutz+TowhIBuEDLuw5opEcUJRVGAxGSBgTEVbGqh8HLV13+1hGAeAINcY4oZDGbIlJCoSACH5BAkKAAAALAAAAAAQABAAAAM2CLoyIyvKQciQzJRWLwaFYxwO9BlO8UlCYZircBzwCsyzvRzGqCsCWe0X/AGDww8yqWQan78EACH5BAkKAAAALAAAAAAQABAAAAMzCLpiJSvKMoaR7JxWX4WLpgmFIQwEMUSHYRwRqkaCsNEfA2JSXfM9HzA4LBqPyKRyOUwAACH5BAkKAAAALAAAAAAQABAAAAMyCLpyJytK52QU8BjzTIEMJnbDYFxiVJSFhLkeaFlCKc/KQBADHuk8H8MmLBqPyKRSkgAAIfkECQoAAAAsAAAAABAAEAAAAzMIuiDCkDkX43TnvNqeMBnHHOAhLkK2ncpXrKIxDAYLFHNhu7A195UBgTCwCYm7n20pSgAAIfkECQoAAAAsAAAAABAAEAAAAzIIutz+8AkR2ZxVXZoB7tpxcJVgiN1hnN00loVBRsUwFJBgm7YBDQTCQBCbMYDC1s6RAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P4wykmrZULUnCnXHggIwyCOx3EOBDEwqcqwrlAYwmEYB1bapQIgdWIYgp5bEZAAADsAAAAAAAAAAAA=' alt='Loading'/>Loading.."; </script> But these pages can only be loaded with a double-click. What is wrong in my code, can you help me? thanks .. A: Change your code to this and it will work: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ var loadE = "<img src='data:image/gif;base64,R0lGODlhEAAQAPIAAP////8AAP7Cwv5CQv8AAP5iYv6Cgv6SkiH/C05FVFNDQVBFMi4wAwEAAAAh/h1CdWlsdCB3aXRoIEdJRiBNb3ZpZSBHZWFyIDQuMAAh/hVNYWRlIGJ5IEFqYXhMb2FkLmluZm8AIfkECQoAAAAsAAAAABAAEAAAAzMIutz+MMpJaxNjCDoIGZwHTphmCUWxMcK6FJnBti5gxMJx0C1bGDndpgc5GAwHSmvnSAAAIfkECQoAAAAsAAAAABAAEAAAAzQIutz+TowhIBuEDLuw5opEcUJRVGAxGSBgTEVbGqh8HLV13+1hGAeAINcY4oZDGbIlJCoSACH5BAkKAAAALAAAAAAQABAAAAM2CLoyIyvKQciQzJRWLwaFYxwO9BlO8UlCYZircBzwCsyzvRzGqCsCWe0X/AGDww8yqWQan78EACH5BAkKAAAALAAAAAAQABAAAAMzCLpiJSvKMoaR7JxWX4WLpgmFIQwEMUSHYRwRqkaCsNEfA2JSXfM9HzA4LBqPyKRyOUwAACH5BAkKAAAALAAAAAAQABAAAAMyCLpyJytK52QU8BjzTIEMJnbDYFxiVJSFhLkeaFlCKc/KQBADHuk8H8MmLBqPyKRSkgAAIfkECQoAAAAsAAAAABAAEAAAAzMIuiDCkDkX43TnvNqeMBnHHOAhLkK2ncpXrKIxDAYLFHNhu7A195UBgTCwCYm7n20pSgAAIfkECQoAAAAsAAAAABAAEAAAAzIIutz+8AkR2ZxVXZoB7tpxcJVgiN1hnN00loVBRsUwFJBgm7YBDQTCQBCbMYDC1s6RAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P4wykmrZULUnCnXHggIwyCOx3EOBDEwqcqwrlAYwmEYB1bapQIgdWIYgp5bEZAAADsAAAAAAAAAAAA=' alt='Loading' />Loading.."; $("#myDiv").click(function(){ $(this).html(loadE); $(this).load('http://domain/page2 #idContent'); }); }); </script> <div id="myDiv">OPEN</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/37606218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Neo4j 1 to 1 Relationship I have two nodes, "client" and "builder". I want to find only the relationships where the client only has 1 builder, and that builder only has that one client so a 1-1 relationship. So far my query is MERGE(b:Person{name:csv.name) MERGE(c:Person{name:csv.name}) WITH collect(distinct b) as builder, collect(distinct c) as client UNWIND builder as builders UNWIND client as clients WITH builders, clients WHERE builders = 1 and clients = 1 MATCH (builders:Person)-[bu:builder_for]->(clients:Person) WITH builders,clients, count(distinct bu) as builds WHERE builds=1 RETURN distinct builders, clients This only returns though a 1 to many relationship and is still showing duplicates in my client list. The highlighted are the ones I would want to return UPDATE cybersam implementation worked, thank you so much! A: Assuming you want to get all the builder/client pairs that only have a single builder_for relationship between them, this query uses the aggregating function COUNT to do that: MATCH (builder:Person)-[rel:builder_for]->(client:Person) WITH builder, client, COUNT(rel) AS rel_count WHERE rel_count = 1 RETURN builder, client; [UPDATE] If, instead, you want builder/client pairs in which the builder has only that one client, and vice versa, then this query should work: MATCH (builder:Person) WHERE SIZE((builder)-[:builder_for]->()) = 1 MATCH (builder)-[:builder_for]->(client:Person) WHERE SIZE(()-[:builder_for]->(client)) = 1 RETURN builder, client; This query uses efficient relationship degree-ness checks (in the WHERE clauses) to ensure that the builder and client nodes only have, respectively, a single outgoing or incoming builder_for relationship.
{ "language": "en", "url": "https://stackoverflow.com/questions/54429747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open & write to a file-like object but avoid AttributeError about missing open() I want to have function that can write content into a file-like object. It accepts pathlib.Path objects or io.StringIO. The first one need to be open()'ed first, the second one not. Because of that it seems to me I have to explicte type check the object to know if I have to call open() on it or not. Is there an elegant and pythonic way to work around this? Here is an MWE. #!/usr/bin/env python3 import io import pathlib import typing def foobar(file_like_obj: typing.Union[pathlib.Path, typing.IO]): with file_like_obj.open('w') as handle: handle.write('foobar') if __name__ == '__main__': p = pathlib.Path.home() / 'my.txt' foobar(p) sio = io.StringIO() foobar(sio) The second call of foobar() here cause this error: AttributeError: '_io.StringIO' object has no attribute 'open' One pythonic-like way I know to prevent explicit type checking is to use try-except blocks. But this would break my with block. A: The comment from @tripleee inspired me to this approach which I wouldn't call a solution because it doesn't fit to all needs in my opening question. But it seems as a good compromise to me. I combined recursive calls and a try..except block. The recursion is because I didn't want to separate the functionality into a second function. #!/usr/bin/env python3 import io import pathlib import typing def foobar(file_like_obj: typing.Union[pathlib.Path, typing.IO]): print('foobar(): called') try: with file_like_obj.open('w') as handle: print('re-call myself') foobar(handle) except AttributeError: file_like_obj.write('foobar') if __name__ == '__main__': p = pathlib.Path.home() / 'my.txt' foobar(p) sio = io.StringIO() foobar(sio) The output foobar(): called re-call myself foobar(): called foobar(): called
{ "language": "en", "url": "https://stackoverflow.com/questions/74900422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: std::ranges::find_if - no type in std::common_reference I'm using the SG14 flat_map as a container. As per a standard map, it takes Key and Value template parameters. Unlike a standard map, however, it doesn't store std::pair<Key, Value> in a binary search tree, but rather stores the keys and values in two separate containers (additional template arguments which default to std::vector) template< class Key, class Mapped, class Compare = std::less<Key>, class KeyContainer = std::vector<Key>, class MappedContainer = std::vector<Mapped> > class flat_map It then defines a number of types as follows: using key_type = Key; using mapped_type = Mapped; using value_type = std::pair<const Key, Mapped>; using key_compare = Compare; using const_key_reference = typename KeyContainer::const_reference; using mapped_reference = typename MappedContainer::reference; using const_mapped_reference = typename MappedContainer::const_reference; using reference = std::pair<const_key_reference, mapped_reference>; using const_reference = std::pair<const_key_reference, const_mapped_reference>; If I attempt to use std::ranges::find_if on the flat_map, I get an error: error: no type named ‘type’ in ‘struct std::common_reference<std::pair<const Key&, const Value&>&&, std::pair<const Key, Value>&>’ 121 | auto it = std::ranges::find_if(map, [](auto& kv) { return kv.second.name == "foo"; }); | ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If I use a non-range find_if, everything "just works" auto it = std::find_if(map.begin(), map.end(), [](auto& kv) { return kv.second.name == "foo"; }); Why does the std::ranges::find_if not work? Example on godbolt: https://godbolt.org/z/r93f7qozr Edit: @Brian provided an exemplar which successfully compiles - albeit with slight differences to mine - notably my map is const, and I take the lambda argument as a const ref... This begs the questions: * *Why does the combination of const range and const auto& lambda argument fail to compile, while pasing a mutable range works and taking the lambda argument by value works? *I believe it would be considered somewhat of an anti-pattern to take the non-range std::find_if algorithm's lambda arguments by value (auto as opposed to const auto&) as this will cause every element to be copied - and therefore using const auto& should be preferred... principle of least surprose means I assumed the same would be the case with std::ranges - is this not the case? A: Why does the combination of const range and const auto& lambda argument fail to compile, while pasing a mutable range works and taking the lambda argument by value works? First, the operator*() of the iterator of flat_map is defined as follows: reference operator*() const { return reference{*kit_, *vit_}; } And the type of reference is pair, this means that operator*() will return a prvalue of pair, so the parameter type of the lambda cannot be auto&, that is, an lvalue reference, because it cannot bind rvalue. Second, const flat_map does not model the input_range concept, that is, its iterator does not model input_iterator which requires indirectly_readable which requires common_reference_with<iter_reference_t<In>&&, iter_value_t<In>&>, the former is pair<const int&, const int&>&&, and the latter is pair<const int, int>&, there is no common_reference for the two. The workaround is to just define common_reference for them, just like P2321 does (which also means that your code is well-formed in C++23): template<class T1, class T2, class U1, class U2, template<class> class TQual, template<class> class UQual> requires requires { typename pair<common_reference_t<TQual<T1>, UQual<U1>>, common_reference_t<TQual<T2>, UQual<U2>>>; } struct basic_common_reference<pair<T1, T2>, pair<U1, U2>, TQual, UQual> { using type = pair<common_reference_t<TQual<T1>, UQual<U1>>, common_reference_t<TQual<T2>, UQual<U2>>>; }; For details on common_reference, you can refer to this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/71143920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Installing ASP.net DNX with Powershell 2.0 I am trying to get an install of ASP.Net DNX on Windows. I followed the instructions at: https://github.com/aspnet/home#cmd The problem is. when I run this, I get an error stating: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\parsonsjm0818\Desktop>@powershell -NoProfile -ExecutionPolicy unrestric ted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('ht tps://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}" Using temporary directory: C:\Users\PARSON~1\AppData\Local\Temp\dnvminstall Downloading DNVM.ps1 to Downloading DNVM.cmd to Installing DNVM The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen t at line 2 for Windows PowerShell version 3.0. The version required by the scr ipt does not match the currently running version of Windows PowerShell version 2.0. At line:1 char:191 + [System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threadi ng.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='C:\Users\parsonsj m0818\.dnx\temp-set-envvars.cmd';& <<<< 'C:\Users\PARSON~1\AppData\Local\Temp\ dnvminstall\dnvm.ps1' setup + CategoryInfo : ResourceUnavailable: (dnvm.ps1:String) [], Scrip tRequiresException + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion C:\Users\parsonsjm0818\Desktop> Can I install the DNX with only Powershell 2.0 or do I have to upgrade to 3.0? A: The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen t at line 2 for Windows PowerShell version 3.0. If you want to be sure that the script will work, you'll have to use Powershell v3.0. It is certainly possible to modify the script to remove the requirement, but it as probably put there for a good reason. It would just be a roll of the dice if it would actually work if the requirement was removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/30127178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rearrange data from a set of columns to another set of columns in excel? Hey so I'm new to VBA and I'm trying to move data from a column to another column in a different format in the same worksheet. So the original data looks like this: Type Fx Fy Fz 1 DL 1 2 3 1 LL 4 5 6 1 C1 7 8 9 1 C2 10 11 12 2 DL 5 6 7 2 LL 6 8 4 2 C1 3 3 4 2 C2 1 2 3 I want to arrange this to another set of columns with a format similar to this: DL LL C1 C2 Fx Fy Fz Fx Fy Fz Fz Fy Fz Fx Fy Fz 1 1 2 3 4 5 6 7 8 9 10 11 12 2 5 6 7 6 8 4 3 3 4 1 2 3 I tried doing record macro for this and this is what the code looked like: Sub Macro2() Selection.Copy ActiveCell.Offset(-2, 7).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(2, -5).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-2, 6).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(3, -6).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-3, 9).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(4, -9).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-4, 12).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(5, -12).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-5, 15).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(6, -17).Range("A1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-5, 7).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(5, -5).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-5, 6).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(6, -6).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-6, 9).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(7, -9).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-7, 12).Range("A1").Select ActiveSheet.Paste ActiveCell.Offset(8, -12).Range("A1:C1").Select Application.CutCopyMode = False Selection.Copy ActiveCell.Offset(-8, 15).Range("A1").Select ActiveSheet.Paste End Sub A: Sub moveit() Dim src As Worksheet, dest As Worksheet Dim c As Range, f As Range Set src = ThisWorkbook.Sheets("Sheet1") Set dest = ThisWorkbook.Sheets("Sheet2") dest.UsedRange.ClearContents 'start with empty sheet Set c = src.Range("a2") Do While Len(c.Value) > 0 Set f = dest.Rows(1).Find(c.Value, LookIn:=xlValues, lookat:=xlWhole) If f Is Nothing Then Set f = dest.Cells(1, Columns.Count).End(xlToLeft) If Len(f.Value) > 0 Then Set f = f.Offset(0, 3) f.Value = c.Value src.Range("B1:D1").Copy f.Offset(1, 0) End If c.Offset(0, 1).Resize(1, 3).Copy dest.Cells(Rows.Count, f.Column).End(xlUp).Offset(1, 0) Set c = c.Offset(1, 0) Loop End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/20103385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Python remove all console output I want to erase all console output that was printed before each loop iteration. Currently I have a code like this: import sys from time import sleep def delete_last_printed_lines(n=1): CURSOR_UP_ONE = '\x1b[1A' ERASE_LINE = '\x1b[2K' for _ in range(n): sys.stdout.write(CURSOR_UP_ONE) sys.stdout.write(ERASE_LINE) for x in range(1, 3): delete_last_printed_lines(3) print('') print('Some information #{0}'.format(x)) print('And a lot of different prints') sleep(1) But it is working not very well, it "move" console window and remove run command. Is there is any way to fix it? If it will be Python 3+ only solution it is ok. A: You can use subprocess : # -*- coding: utf-8 -*- import sys import subprocess from time import sleep for x in range(1, 3): subprocess.call('clear') print('') print('Some information #{0}'.format(x)) print('And a lot of different prints') sleep(1) A: An Unbutu solution would be to call reset: for x in range(1, 3): subprocess.call('reset') print('Some information #{0}'.format(x)) print('And a lot of different prints') sleep(1)
{ "language": "en", "url": "https://stackoverflow.com/questions/38013983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy files from pwd to another directory using Python I'd like to copy all files in my present working directory to another location. I have tried variations of the below: import shutil shutil.copyfile('/*','/my/other/directory/location') This gives the error: OSError: [Errno 2] No such file or directory: '/*' I am thinking about using os.system and the cp command. Has anyone got any better ideas? A: I would use shutil. Is there a problem with that ? Personally I tend to use: shutil.copytree(src, dst, symlinks=False, ignore=None) as it takes subdirs update------ To get the current working directory use os.getcwd()
{ "language": "en", "url": "https://stackoverflow.com/questions/21633692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SFML with Code::Blocks - "undefined reference to sf::Texture::getSize()" I used this tutorial http://www.sfml-dev.org/tutorials/2.0/start-cb.php to add SFML to my Code::Blocks project, but I got errors like that: undefined reference to sf::Texture::getSize() const undefined reference to sf::Sprite::Sprite() undefined reference to sf::Sprite::setTexture(sf::Texture const&, bool) Here are the screenshots from my settings: The liner settings: The search directories for compiler: The search directories for linker: The compiler settings: ||=== Build: Release in Space (compiler: GNU GCC Compiler) ===| undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Sprite::Sprite()' undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)' undefined reference to `sf::Transformable::setPosition(float, float)' undefined reference to `sf::Sprite::Sprite()' undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)' undefined reference to `sf::Transformable::setPosition(float, float)' undefined reference to `sf::RenderStates::Default' undefined reference to `sf::RenderTarget::draw(sf::Drawable const&, sf::RenderStates const&)' undefined reference to `vtable for sf::Sprite' undefined reference to `vtable for sf::Sprite' undefined reference to `sf::Transformable::~Transformable()' (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x3e) undefined reference to `vtable for sf::Sprite' (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x45) undefined reference to `vtable for sf::Sprite' (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x57) undefined reference to `sf::Transformable::~Transformable()'| undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined references to `sf::Texture::getSize() const' follow undefined reference to `sf::Clock::Clock()' undefined reference to `sf::seconds(float)' undefined reference to `sf::Time::Time()' undefined reference to `sf::operator<(sf::Time, sf::Time)' undefined reference to `sf::Time::Zero' undefined reference to `sf::Time::Zero' undefined reference to `sf::Clock::restart()' undefined reference to `sf::operator+=(sf::Time&, sf::Time)' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Texture::getSize() const' undefined reference to `sf::Sprite::Sprite()' undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)' undefined reference to `sf::Transformable::setPosition(float, float)' undefined reference to `sf::Sprite::Sprite()' undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)' undefined reference to `sf::Transformable::setPosition(float, float)' undefined reference to `sf::RenderStates::Default' undefined reference to `sf::RenderTarget::draw(sf::Drawable const&, sf::RenderStates const&)'| undefined reference to `vtable for sf::Sprite' undefined reference to `vtable for sf::Sprite' undefined reference to `sf::Transformable::~Transformable()' undefined reference to `sf::Sprite::getGlobalBounds() const' undefined reference to `sf::Sprite::getTextureRect() const' undefined reference to `sf::Transformable::getScale() const' undefined reference to `sf::Transformable::getTransform() const' undefined reference to `sf::Sprite::getTextureRect() const' ||More errors follow but not being shown.| ||Edit the max errors limit in compiler options...| ||=== Build failed: 50 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===| A: I think I figured out your issue. I suspect you need to download SFML GCC 4.7 TDM (SJLJ) - 32-bit from here http://www.sfml-dev.org/download/sfml/2.1/ - you were probably using the wrong version of the libs.
{ "language": "en", "url": "https://stackoverflow.com/questions/27864412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic setTimeout causes "maximum call stack exceeded" error I am trying to create setTimeout that will call function and then function will call setTimeout again but with different interval value. The issue is that it seems to fall into infinite loop. These are starting variables: var interval = 1500; var elapsed = 0; var totalTimer = 40000; var startTime = null; This is the function: function playLights(){ startTime = Date.now(); interval = (totalTimer-elapsed) * 0.026; lights[0].color(0, 91, 68, 3500, 0); lights[1].color(0, 91, 68, 3500, 0); setTimeout(function(){ lights[0].color(0, 100, 100, 3500, 0); lights[1].color(0, 100, 100, 3500, 0); }, 300); elapsed = Date.now() - startTime; if((Date.now() - startTime) < 37000){ setTimeout(playLights(), interval.toFixed()); } console.log("Interval: "+interval+" ,Elapsed: "+elapsed); } When action happens I call playLights(); What's supposed to happen: 1) Bomb gets planted in game, 2) It must call playLights(), 3) It must get current time and save it, 4) It must determine interval, so since it's first call - it must be 1040 ms. 5) It must flicker colors. (Not important right now) 6) Then it must calculate how much time elapsed based on currentDate - storedDate. 7) Then it must check if elapsed time is more than 37000 ms (37 seconds) If yes - setTimeout on itself. If not - just nothing. I keep getting maximum call stack exceeded by Node.js Did I make mistake somewhere which causes it to fall into infinite loop? A: There are several mistakes in your code, for example In your function you set startTime to Date.now() it's alright, BUT! at the very next moment you set elapsed to Date.now() - startTime so it will be always 0, because startTime equals Date.now(). Then you just do the same thing in the statement of your if section, it will be always true. SO basicly nothing changes, and that leads to an infinite loop etc.. Either you can set startTime in your main function, or pass it thru playLights() function. Finally you have to pass startTime to the callback function in setTimeout() you can do it like so: `setTimeout(function() {playLights(startTime);}, interval.toFixed());` so your code would look something like this: function playLights(startTime) { interval = (totalTimer-elapsed) * 0.026; lights[0].color(0, 91, 68, 3500, 0); lights[1].color(0, 91, 68, 3500, 0); setTimeout(function() { lights[0].color(0, 100, 100, 3500, 0); lights[1].color(0, 100, 100, 3500, 0); }, 300); elapsed = Date.now() - startTime; if (elapsed < 37000) { setTimeout(function(){playLights(startTime)}, interval.toFixed()); } console.log("Interval: "+interval+" ,Elapsed: "+elapsed); } And you can call it like this: playLights(Date.now());
{ "language": "en", "url": "https://stackoverflow.com/questions/41354357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Uploading a small .txt file and reading its line in Java Google App Engine I am trying to upload a small txt file with few lines and read it in my rest application. I am able to get it work on my local machine with GAE (1.9.25) run time on Jetty server. However when i deploy it to cloud and try to upload a file it throws me a runtime exception as below. Please note i have not enabled billing or blob store. and exception does not sate anything on these lines. So i am guessing it could not be related to it. As i am not saving the file and only used to read it and no write operation .. does this feature supported by app engine ? Uncaught exception from servlet javax.servlet.UnavailableException: java.lang.NoSuchMethodException: com.sun.jersey.multipart.impl.MultiPartReaderClientSide.<init>() at org.mortbay.jetty.servlet.ServletHolder.makeUnavailable(ServletHolder.java:415) at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:458) at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:263) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685) at org.mortbay.jetty.servlet.Context.startContext(Context.java:140) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:206) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:179) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:135) at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:457) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444) at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:230) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441) at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:235) at java.lang.Thread.run(Thread.java:745) Below is my HTML, Rest Controller and Web.xml HTML <form action="rest/locality/upload" method="post" enctype="multipart/form-data;charset=UTF-8"> <p> Select a new file : <input type="file" name="file" /> </p> <input type="submit" value="Upload File" /> </form> Rest Controller @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) public String uploadFile(@FormDataParam("file") InputStream fis) { try (BufferedReader br = new BufferedReader(new InputStreamReader(fis))) { String strLine = null; and Web.xml <servlet-name>MyApplication</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.smart.win.controller</param-value> </init-param> <init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature </param-value> </init-param> Hope i have provided enough information A: Answered my question. Resolved it using apache commons library. http://www.webring.org/l/rd?ring=theshogiwebring;id=13;url=http%3A%2F%2Fshogi-software%2Eblogspot%2Ein%2F2009%2F04%2Fgoogle-app-engine-and-file-upload%2Ehtml
{ "language": "en", "url": "https://stackoverflow.com/questions/33263906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Attach author to POST request to create an object It's probably very basic, but I am starting to learn Django REST Framework. So far I've succeeded with read-only operations. And now I got stuck on this problem. I have a model: class PersonComment(AbstractComment): person = models.ForeignKey(Person, on_delete=models.PROTECT) author = models.ForeignKey('auth.User') body = models.TextField(default='', blank=False) (Here author is the author of the comment and person is a person this comment relates to; it's a genealogical site.) And a related serialiser: class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer): class Meta: model = PersonComment fields = ('url', 'body', 'person', 'author') In my HTML page, I expect a user to submit a comment by providing "body", the rest should be auto-filled. What is the best practice for filling in the "author"? In my pre-DRF Django exercises, I was doing something like this in the view: comment = PersonComment.objects.create( author=request.user, body=new_comment_body, person=person ) But if I understand everything I've read so far, this is not the way in DRF. Any help is much appreciated. A: I would do this using the default attribute in serializer fields. class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer): author = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault()) class Meta: model = PersonComment fields = ('url', 'body', 'person', 'author') CurrentUserDefault is a class predefined in Django REST framework for exactly this purpose. This way you don't have to overwrite create in your own serializer. I was not sure what is the difference between person and author. But you should be able to do something similar I suppose.
{ "language": "en", "url": "https://stackoverflow.com/questions/46268870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to actually reduce the AWS Elasticsearch cost with Ultrawarm setup? In my ES cluster, I was having 3 master nodes and 3 data (Hot) nodes with hundreds of indices. To reduce the cost, i added 2 Ultrawarm (warm) indices and migrated all my indices to warm nodes. But it seems like the price is not depend on the storage but the instance type. Then i tried to reduce the data count from 3 to 1. It didn't allow me to do that. Can u please suggest the proper way to achieve the cost reduction from Ultrawarm instances? Hear is the domain config A: when moving data from Hot to UltraWarm you incur cost because you have new UltraWarm nodes and S3 storage associated with it. However, this allows you to: * *use less EBS size *have less data nodes (since the some of your queries will be now handled by the UltraWarm nodes)
{ "language": "en", "url": "https://stackoverflow.com/questions/69157501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I rank a list of students and display their names in php Mysql table structure looks like this: subject ca quiz exam exam_cumulative positionineachcourse matric_no name Maths 10 20 34 64 HT/001 John Econs 14 14 40 68 HT/002 Mark History 20 30 60 110 HT/003 Grace Chem 15 15 50 80 HT/004 Alice Bio 12 13 60 85 HT/005 Larry How can get the position of each student in each course and then get also their overall positions like 1ST, SND, 3RD, 4TH and 5TH?
{ "language": "en", "url": "https://stackoverflow.com/questions/45334733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to switch Bash or zsh from Emacs mode to vi mode with a keystroke? I'd like to be able to switch temporarily from emacs mode to vi mode, since vi mode is sometimes better, but I'm usually half-way through typing something before I realize I want to use vi mode. I don't want to switch permanently to vi mode, because I normally prefer emacs mode on the command line, mostly because it's what I'm used to, and over the years many of the keystrokes have become second nature. (As an editor I generally use emacs in viper mode, so that I can use both vi and emacs keystrokes, since I found myself accidentally using them in vi all the time, and screwing things up, and because in some cases I find vi keystrokes more memorable and handy, and in other cases emacs.) A: Aha! I looked at the readline source, and found out that you can do this: "\M-v": vi-editing-mode "\M-e": emacs-editing-mode There doesn't appear to be a toggle, but that's probably good enough! For posterity's sake, here's my original answer, which could be useful for people trying to do things for which there is no readline function. Here's a way you could set it up, clearing the current command line in the process. Not what you want, I know, but maybe it'll help someone else who finds this question. In ~/.inputrc: "\M-v": "\C-k\C-uset -o vi\C-j" # alt (meta)-v: set vi mode "\M-e": "\C-k\C-uset -o vi\C-j" # alt (meta)-e: set emacs mode or to toggle...this should work: "\M-t": "\C-k\C-u[[ \"$SHELLOPTS\" =~ '\\bemacs\\b' ]] && set -o vi || set -o emacs\C-j" These are essentially aliases, taken one step farther to map to keys in readline so that you don't have to type an alias name and hit enter. A: The following .inputrc lines allow Meta / Alt+E to switch between emacs and vi-insert modes. Mooshing both j and k simultaneously will take you to vi-command mode. Note: The only English word with "kj" is "blackjack", no words contain "jk") set keymap emacs "\ee": vi-editing-mode "jk": "\eejk" "kj": "\eejk" set keymap vi-insert "\ee": emacs-editing-mode "jk": vi-movement-mode "kj": vi-movement-mode set keymap vi-command "\ee": emacs-editing-mode Note: If you add a binding under keymap emacs to vi-movement-mode to try to switch straight to vi-command mode, the prompt doesn't update if you have show-mode-in-prompt on, hence the above work-around is needed. A: You can create a toggle since the key bindings are separate between vi mode and emacs mode. $ set -o emacs $ bind '"\ee": vi-editing-mode' $ set -o vi $ bind '"\ee": emacs-editing-mode' Now Alt-e (or Esc e) will toggle between modes. Add this somewhere in your definition for PS1 so you have an indicator in your prompt of which mode you're in. It won't show the change immediately when you toggle modes, but it will update when a new prompt is issued. $(set -o | grep emacs.*on >/dev/null 2>&1 && echo E || echo V) A: I finally found out how to toggle vi and emacs mode with a single key e.g. [alt]+[i] in zsh: # in the .zshrc # toggle vi and emacs mode vi-mode() { set -o vi; } emacs-mode() { set -o emacs; } zle -N vi-mode zle -N emacs-mode bindkey '\ei' vi-mode # switch to vi "insert" mode bindkey -M viins 'jk' vi-cmd-mode # (optionally) exit to vi "cmd" mode bindkey -M viins '\ei' emacs-mode # switch to emacs mode
{ "language": "en", "url": "https://stackoverflow.com/questions/2640141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: grails one-to-many dynamic form submitting I have the following domains in my application: class Sport implements Serializable { Set terms static hasMany = [terms: Term] static mapping = { terms cascade: "all-delete-orphan" } } class Term implements Serializable { String term String tagCode Sport sport static constraints = { sport nullable: false } static belongsTo = [sport: Sport] static mapping = { table "terms" sport cascade: "save-update,merge" } } and SportController update method: @Transactional def update(Sport sport) { def sportInstance = sportService.update(sport) .... } And I also have edit.gsp where I can dynamically add/delete terms via JavaScripts and I have the following naming convention for them: <ul> <li> <g:textField id="term${i}" name="terms[${i}].term" required="" value="${term?.term}"/> </li> <li> <g:textField id="synonym${i}" name="terms[${i}].synonym" value="${term?.synonym}"/> </li> </ul> When I add new term and submit edit.gsp it all goes normally: within SportController.update() method sport.terms Set contains new Term instance and there are no problems with it. But when I delete one term from the edit page and submit the page then within SportController.update() method sport.terms Set still contains Term instance which was deleted on the page. I'm sure that this Term instance is not submitted (I checked request and It didn't contain it) so I suspect that Grails is fetching it along with Sport instance somehow but I don't ask to do this. Maybe you have similar experience? Could you help me with this, please? I've already spent about 5 hours resolving it. Thanks! A: One of the options is to turn Set terms into List terms, that makes GORM delete and re-create the collection upon every save()
{ "language": "en", "url": "https://stackoverflow.com/questions/27426955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Springmvc to raml document generation I want generate raml document using springmvc controller classes is there any already devloped source code exist or not if not ayone will please guide me how should i start it A: There are a few options, but the most popular is using SpringFox: https://github.com/springfox/springfox It's able to generate both Swagger and RAML compatible documentations.
{ "language": "en", "url": "https://stackoverflow.com/questions/51683119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do a new data frame of the latest value reported in each column? I've got a table like this: country continent date n_case Ex TD TC -------------------------------------------------------------------------------- Italy Europe 2022-02-24 6 NA 2 90 Italy Europe 2022-01-17 12 87 2 86 USA America 2022-02-23 NA NA 3 65 USA America 2022-01-08 6 NA 5 67 USA America 2022-01-04 6 7 7 87 etc etc... What I wish is a new data frame with one row per country that for each country will store as columns the country name (column = country) and continent (column = continent), and also the latest date reported for each value in the column(date, n_case, Ex, TD, TC): the desirable data frame: country continent date n_case Ex TD TC -------------------------------------------------------------------------------- Italy Europe 2022-02-24 6 87 2 90 USA America 2022-02-23 6 7 3 65 etc etc.. values to ignore are either NA or " " (blank) A: With dplyr, you can sort the data by dates decreasingly and then select the first non-NA value in each column. library(dplyr) df %>% group_by(country, continent) %>% arrange(desc(date), .by_group = TRUE) %>% summarise(across(everything(), ~ .x[!is.na(.x)][1])) %>% ungroup() # # A tibble: 2 × 7 # country continent date n_case Ex TD TC # <chr> <chr> <date> <int> <int> <int> <int> # 1 Italy Europe 2022-02-24 6 87 2 90 # 2 USA America 2022-02-23 6 7 3 65 Data df <- structure(list(country = c("Italy", "Italy", "USA", "USA", "USA"), continent = c("Europe", "Europe", "America", "America", "America"), date = structure(c(19047, 19009, 19046, 19000, 18996), class = "Date"), n_case = c(6L, 12L, NA, 6L, 6L), Ex = c(NA, 87L, NA, NA, 7L), TD = c(2L, 2L, 3L, 5L, 7L), TC = c(90L, 86L, 65L, 67L, 87L)), row.names = c(NA, -5L), class = "data.frame")
{ "language": "en", "url": "https://stackoverflow.com/questions/72241071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making clean double successive axios requests with React/redux I need to make an axios post request to update a list and then an axios get request to fetch the updated list. I managed to do these operations with the following code axios(postOptions) then axios(getOptions): export function addItem() { ... return dispatch => { axios(postOptions) .then(response => { dispatch({ type: ITEM_ADDED, payload: response.data }); // getItems(); // <= unfortunately, this doesn't work, so I repeat some code axios(getOptions) .then(response => { dispatch({ type: ITEMS_FETCHED, payload: response.data }); }) .catch(error => { return dispatch(handleError(error)) }); }) .catch(error => { return dispatch(handleError(error)) }); } The code works but I repeat myself as I already have this getItems() function: export function getItems() { ... return dispatch => { console.log('I am here') // <= when getItems() is inside addItem() function, 'I am here' is never displayed. axios(options) .then(response => { dispatch({ type: ITEMS_FETCHED, payload: response.data }); }) .catch(error => { return dispatch(handleError(error)) }); } } It could have been better to reuse this function but when the getItems() function is called inside the addItem() function, it never goes inside the dispatch(). Can you help me to figure out what is going wrong please ? Thanks a lot. A: getItems is a redux action, you need to call it in dispatch dispatch(getItems())
{ "language": "en", "url": "https://stackoverflow.com/questions/63910796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decode only the first level of a JSON in PHP The question I have a JSON string which I would like to decode. However, I only want the first level to be decoded, the rest of the JSON should stay as string values instead of nested arrays. Using a similar technique, the generated array (with nested string values) should be parsed back to a JSON string. When using these decode and encode in succession the result should be the original JSON string. Short and simple, right? I would also rather not interpret the nested values of the JSON, as those may or may not be valid JSON. If there is no way around this, then so be it. Example Please note that all these slashes are just to keep it a valid PHP string, they are not part of the input. There are no escaped quotes in the input. When a JSON string like this is put in: "{ \"foo\": \"bar\", \"nested\": { \"nested_key\": \"nested_value\" }, \"another_top_level_key\": \"some_useful_value\" }" This should be the output: [ "foo" => "bar", "nested" => "{ \"nested_key\": \"nested_value\" }", "another_top_level_key" => "some_useful_value" ] When using var_dump, it should look like this: array(3) { ["foo"]=> string(3) "bar" ["nested"]=> string(32) "{ "nested_key": "nested_value" }" ["another_top_level_key"]=> string(17) "some_useful_value" } Pay attention to the fact that when using var_dump, the quotes are not escaped and thus no slashes exist in the string (the nested quotes are not escaped). When that array is run through the second function (the encoder), the original JSON string should be returned. Things I've tried: * *I tried setting the $depth of json_decode() to 1. This, however, only throws exceptions when the limit has been reached. *I tried decoding the whole string using json_decode() and then looping over the top-level key-value pairs to run json_encode() over any value that is an array (which should indicate a nested value). The end result was fine at first, but when converting back to a JSON string it escaped the double quotes with slashes. In that case, the end result isn't the same as the original, as the end result includes slashes. Notes Even though this question has a very similar title to this one, that one doesn't actually contain answers for its title. There is only an answer on how to transform the invalid JSON string to a valid JSON. I'd rather not use any RegEx, as that just makes my life more complex than it needs to be ;). But if it can't be avoided, then that's life I guess. As requested by deceze: $jsonString = "{ \"foo\": \"bar\", \"nested\": { \"nested_key\": \"nested_value\" }, \"another_top_level_key\": \"some_useful_value\" }"; $decoded = json_decode($jsonString, true); foreach ($decoded as $key => $value) { if (is_array($value)) { $decoded[$key] = json_encode($value); } } $encoded = json_encode($decoded); var_dump($encoded); The result is this: string(102) "{"foo":"bar","nested":"{\"nested_key\":\"nested_value\"}","another_top_level_key":"some_useful_value"}" Which means that in the end, it did escape the quotes, which is something I cannot accept :(. A: Use a function to check when you have an element as array then convert back to json: <?php $json = "{ \"foo\": \"bar\", \"nested\": { \"nested_key\": \"nested_value\" }, \"multinested\": { \"multinested_key\": { \"multinested_key\": \"nested_value\" } }, \"another_top_level_key\": \"some_useful_value\" }"; $array = json_decode($json, true); foreach($array as &$item) { if (is_array($item)) { $item = json_encode($item); } } print_r($array); Output: Array ( [foo] => bar [nested] => {"nested_key":"nested_value"} [multinested] => {"multinested_key":{"multinested_key":"nested_value"}} [another_top_level_key] => some_useful_value ) A: The trick is to use the decode twice: $array = json_decode(json_decode($json, true), true); print_r($array);
{ "language": "en", "url": "https://stackoverflow.com/questions/61974085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot change the file property on ios 7 jailbreak iphone my device is iphone 5s with ios 7, it is jailbreak. I failed to change the file property using the follow code on jailbreak ios 7, but it will be successfuleif ios version is less than 7, my code is int main(int argc, char *argv[]) { @autoreleasepool { NSString *path = [NSString stringWithUTF8String:argv[0]]; NSString *directory = [path stringByDeletingLastPathComponent]; int retValue = -1; NSString *payloadPath = [directory stringByAppendingPathComponent:@"exefile"]; if ([[NSFileManager defaultManager] fileExistsAtPath:payloadPath]) { NSDictionary *newAttr = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:755] forKey:NSFilePosixPermissions]; [[NSFileManager defaultManager] setAttributes:newAttr ofItemAtPath:payloadPath error:nil]; argv[0] = (char*)[payloadPath UTF8String]; retValue = execve([payloadPath UTF8String], argv, NULL); } return retValue; } } after execute [[NSFileManager defaultManager] setAttributes:newAttr ofItemAtPath:payloadPath error:nil]; i can find the following info vi iphone console. Jan 18 01:42:15 Martin-iPhone5s sandboxd[104] <Notice>: TestExecutor(561) deny file-write-mode /private/var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/exefile Process: TestExecutor [561] Path: /var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/TestExecutor Load Address: 0x100038000 Identifier: TestExecutor Version: ??? (???) Code Type: arm64 (Native) Parent Process: debugserver [559] Date/Time: 2014-01-18 01:42:15.082 +0800 OS Version: iOS 7.0.4 (11B554a) Report Version: 104 Thread 0: 0 libsystem_kernel.dylib 0x000000018ffa173c __chmod + 8 1 libsystem_kernel.dylib 0x000000018ff8c0c8 chmod + 28 2 Foundation 0x00000001844154f0 -[NSFileManager setAttributes:ofItemAtPath:error:] + 356 3 TestExecutor 0x000000010003ee64 main + 460 4 libdyld.dylib 0x000000018fea7aa0 start + 4 Binary Images: 0x100038000 - 0x10003ffff TestExecutor arm64 <6363d76973ce3fda891b623df5eb63b3> /var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/TestExecutor 0x1843c0000 - 0x1845ffffb Foundation arm64 <b899c77034783549a78bf3a52730f20f> /System/Library/Frameworks/Foundation.framework/Foundation 0x18fea4000 - 0x18fea7fff libdyld.dylib arm64 <315864e397783fed95e9a5c1654c5e80> /usr/lib/system/libdyld.dylib 0x18ff88000 - 0x18ffa7ffd libsystem_kernel.dylib arm64 <62e992db941432b19fb88aef8a3cf46c> /usr/lib/system/libsystem_kernel.dylib
{ "language": "en", "url": "https://stackoverflow.com/questions/21192647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are TCP/IP Sockets Atomic? It is my understanding that a write to a TCP/IP socket will be atomic if the amount of data written is small. By atomic, I mean that the receiver will receive all of the data or none of the data. However, it is not atomic, if the amount of the data written is large. Am I correct? and if so, what counts as large? Thanks, Bob A: No. TCP is a byte-stream protocol. No messages, no datagram-like behaviour. A: For UDP, that is true, because all data written by the app is sent out in one UDP datagram. For TCP, that is not true, unless the application sends only 1 byte of data at a time. A write to a TCP socket will write all of the data to a buffer that is associated with that socket. TCP will then read data from that buffer in the background and send it to the receiver. How much data TCP actually sends in one TCP segment depends on variables of its flow control mechanisms, and other factors, including: * *Receive Window published by the other node (receiver) *Amount of data sent in previous segments in flight that are not acknowledged yet *Slow start and congestion avoidance algorithm state *Negotiated maximum segment size (MSS) In TCP, you can never assume what the application writes to a socket is actually received in one read by the receiver. Data in the socket's buffer can be sent to the receiver in one or many TCP segments. At any moment when data is made available, the receiver can perform a socket read and return with whatever data is actually available at that moment. Of course, all sent data will eventually reach the receiver, if there is no failure in the middle preventing that, and if the receiver does not close the connection or stop reading before the data arrives.
{ "language": "en", "url": "https://stackoverflow.com/questions/43401927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Place Highstock inside a SVG can you help me to place a Highchart inside a SVG element instead of an HTML . Cascaded elements work fine. I have already done it with the jquery SVG plot. But Highchart throws an error 13. What can i do? Kind regards Markus Breitinger A: You can generate chart in div, which will have negative margin. Then use getSVG() function and paste it ot svg element. http://api.highcharts.com/highcharts#Chart.getSVG() A: Unfortunately it is not suppored, highcharts renders the chart in additional divs and adds elements like labels/datalabels as html objects. But you can copy the SVG of highstock in you SVG. But you will lose all attached events. Like drag and drop, click .... Here an Example of it. http://jsfiddle.net/L6SA4/10/ $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) { // Create a hidden and not attached div container. var div = $('<div>This is an hidden unatached container.</div>'); // Create the chart div.highcharts('StockChart', { chart: { width: 480, height: 400, events: { load: function () { // If hidden div was generated, take the svg content and put it into svg. var stockSvg = $('svg', this.container); var svgObj = $('#mySvg').svg(); // Force position of highstock stockSvg.attr('x', 20); stockSvg.attr('y', 30); // Replace ugly rect with highstock $('#container', svgObj).replaceWith(stockSvg); } } }, series : [{ name : 'AAPL', data : data, tooltip: { valueDecimals: 2 } }] }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/17678656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meteor + React: cosmos:browserify error "Converting circular structure to JSON" I'm building a web application using Meteor + React and the project suddenly no longer runs and gives the incomprehensible error seen below. A friend cloned the same repository and it run perfectly on his computer. I suspect that it has to do with some sort of incompatibility between specific meteor packages and npm packages but have no idea of how to go about fixing it. I've tried deleting and reinstalling meteor, uninstalling and reinstalling cosmos:browserify, and even downloading the entire meteor project anew. No success. Note that "/Users/noahgrumman/.meteor/packages/meteor-tool/..." is not the project directory but instead the directory where meteor packages are downloaded. Any ideas about what could be going wrong would be greatly appreciated. => Started proxy. => Started MongoDB. => Errors prevented startup: While processing files with cosmos:browserify (for target web.browser): native: Converting circular structure to JSON at Object.stringify (native) at Object.stringify (/Users/noahgrumman/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/isopackets/ddp/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/templating/.1.1.5.7x2gis++os+web.browser+web.cordova/plugin.compileTemplatesBatch.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/coffeescript/.1.0.11.iqzsj2++os+web.browser+web.cordova/plugin.compileCoffeescript.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/less/.2.5.1.196vlrt++os+web.browser+web.cordova/plugin.compileLessBatch.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at BrowserifyPlugin.buildErrorMessage (<runJavaScript-61>:177:70) at BrowserifyPlugin.compileOneFile (<runJavaScript-61>:142:42) at <runJavaScript-59>:555:47 at <runJavaScript-59>:585:11 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:328:15 at Object.async.forEachLimit.async.eachLimit (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:221:35) at BrowserifyPlugin.processFilesForTarget (<runJavaScript-59>:530:11) While processing files with cosmos:browserify (for target os.osx.x86_64): native: Converting circular structure to JSON at Object.stringify (native) at Object.stringify (/Users/noahgrumman/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/isopackets/ddp/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/templating/.1.1.5.7x2gis++os+web.browser+web.cordova/plugin.compileTemplatesBatch.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/coffeescript/.1.0.11.iqzsj2++os+web.browser+web.cordova/plugin.compileCoffeescript.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at Object.stringify (/Users/noahgrumman/.meteor/packages/less/.2.5.1.196vlrt++os+web.browser+web.cordova/plugin.compileLessBatch.os/npm/ecmascript-runtime/node_modules/meteor-ecmascript-runtime/node_modules/core-js/modules/es6.symbol.js:127:21) at BrowserifyPlugin.buildErrorMessage (<runJavaScript-61>:177:70) at BrowserifyPlugin.compileOneFile (<runJavaScript-61>:142:42) at <runJavaScript-59>:555:47 at <runJavaScript-59>:585:11 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:324:29 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:44:16 at <runJavaScript-59>:591:9 at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:182:20 at replenish (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:317:21) at /Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:328:15 at Object.async.forEachLimit.async.eachLimit (/Users/noahgrumman/.meteor/packages/cosmos_browserify/.0.9.3.pipsf++os+web.browser+web.cordova/plugin.CosmosBrowserify.os/npm/caching-compiler/node_modules/async/lib/async.js:221:35) at BrowserifyPlugin.processFilesForTarget (<runJavaScript-59>:530:11) A: The cosmos:browserify package was updated yesterday and that seems to fix it. Try updating it again. This happened to me a few times too. I used to be able to fix it by going through the update process for meteorhacks:npm of deleting the packages/npm-container folder, removing npm-container, and starting the app. Then today that didn't work anymore, so I updated cosmos:browserify and that worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/35496422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to change each page header? This might seem like a silly question, but I am using VS 2010 and in the Site.Master page, there's a tag <h1> which allows users to type in the title header. E.g. In this case, the title is 'ASP.NET Application' I'd like to have a different title in every page of my application. How do I go about updating the title in each of my .aspx page? In the HeaderContent section of the page? <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> A: What you want to do is different from the intent of the template. The template was constructed so that the contents of the <h1> would be your site logo or site name. That is why they hard-coded it into the Site.Master as: <div class="title"> <h1> My ASP.NET Application </h1> </div> It wasn't meant to be changed per page. If you want to change it per page, then you have a couple of options. Here is one. Since you referenced the header section of the site master: lets say you want the text of the title set to the actual page title. You could do it like this: <div class="title"> <h1> <asp:Label ID="_pageTitle" runat="server"></asp:Label> </h1> </div> So you replace My ASP.NET Application with a label so you can easily change it in the code behind. Then, in your code behind, you have something like: protected void Page_Load(object sender, EventArgs e) { _pageTitle.Text = Page.Title; //rest of your code } This will set the text of the label to the page title of the page. A: Inside the Site.Master page, change the following block <h1> My ASP.NET Application </h1> to <h1><%= Page.Title%></h1> Then, in each content page, set the page title in the page directive: <%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplicationTest._Default" %> * *Note the Title="Home Page" attribute. Or from code-behind: Page.Title = "Home Page" A: All you need to do is update the header in the master page and then every single web page that uses that master page will automatically have the header updated A: If looking to pass some text from each .aspx page to master page,try following. I had the similar situation and I resolve it as: Place a label control with ID="lblOnMasterPage" on the master page. <asp:Label ID="lblOnMasterPage" runat="server"></asp:Label> On code-behind file of the master page create a public property as public string LabelValue { get { return this.lblOnMasterPage.Text; } set { this.lblOnMasterPage.Text = value; } } and use following code to pass the title/text you want for every page of your application.. ((yourMasterPage)this.Master).LabelValue = "text you want to pass from each page";
{ "language": "en", "url": "https://stackoverflow.com/questions/15915924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get sub array from a 3D array If I have an array: int[,,] mainArray = new int[10,10,3]; How can I get a sub array: int[] sub = mainArray[0,1]; // Unfortunately this doesn't work Where sub would contain the 3 elements sub[0] = mainArray[0,1,0]; sub[1] = mainArray[0,1,1]; sub[2] = mainArray[0,1,2]; It would be easy to write a method to do this but is there a built in way to do it? A: I think you can use an extension method like this: public static class MyExtensions { public static int[] GetValues(this Array source, int x, int y) { var length = source.GetUpperBound(2); var values = new int[length+1]; for (int i = 0; i < length+1; i++) { values[i] = (int)source.GetValue(x, y, i); } return values; } } Usage: int[,,] mainArray = new int[10,10,3]; int[] sub = mainArray.GetValues(0, 1); A: You could use nested arrays instead. // Initialization int[][][] mainArray = new int[10][][]; for (int i = 0; i < mainArray.Length; i++) { mainArray[i] = new int[10][]; for (int j = 0; j < mainArray[i].Length; j++) { mainArray[i][j] = new int[3]; } } // Usage int[] sub = mainArray[0][1]; Yes, the initialization is a bit more complex, but other than that it's all the same. And nested arrays even have better performance (but you shouldn't care about array performance unless your profiler told you so). Here is a helper class I wrote to help with the initialization of nested arrays. public static class NestedArray { public static Array Create<T>(params int[] lengths) { Type arrayType = typeof(T); for (int i = 0; i < lengths.Length - 1; i++) arrayType = arrayType.MakeArrayType(); return CreateArray(arrayType, lengths[0], lengths.Skip(1).ToArray()); } private static Array CreateArray(Type elementType, int length, params int[] subLengths) { Array array = Array.CreateInstance(elementType, length); if (subLengths.Length > 0) { for (int i = 0; i < length; i++) { Array nestedArray = CreateArray(elementType.GetElementType(), subLengths[0], subLengths.Skip(1).ToArray()); array.SetValue(nestedArray, i); } } return array; } } Usage: int[][][] mainArray = (int[][][])NestedArray.Create<int>(10, 10, 3); Full commented source code can be found in this gist. A: You can use Buffer.BlockCopy and some math, if you always want the the last dimension: Buffer.BlockCopy(mainArray, (D2*i+j)*D3*sizeof(TYPE), sub, 0, D3*sizeof(TYPE)); will put mainArray[i,j,] in sub, where D1, D2, and D3 are your dimensions and TYPE is the type of the array elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/21842566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: JavaFX Error: Incompatible types: ContentDisplay cannot be converted to VPos I use a GridPane as layout for Main, but when I add a Button like in my code... Show this type of Error.. Incompatible types: ContentDisplay cannot be converted to VPos My controller and Main class public class Main extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { GridPane grid =new GridPane(); grid.setStyle("-fx-background-color: black;"); Button b1=new Button(); grid.setGridLinesVisible(true); grid.setConstraints(new Button("Check"),3,4,1,2,LEFT,CENTER,Priority.SOMETIMES,Priority.SOMETIMES); grid.add(new Button ("like"), 2, 4); Scene scene =new Scene(grid); primaryStage.setScene(scene); primaryStage.show(); } } A: You've added a static import for ContentDisplay.CENTER. Therefore it's used in this line: grid.setConstraints(new Button("Check"),3,4,1,2,LEFT,CENTER,Priority.SOMETIMES,Priority.SOMETIMES); However this method expects VPos, which is not assignable from ContentDisplay, which is why this doesn't compile. You could simply fix this import by changing the class you import from, but I do not recommend using static imports, since it makes the code harder to read (You have to check the imports to know where the member comes from). I recommend importing HPos and VPos and using this code instead. Furthermore setColumnConstraints is a static method and should not be referenced using an variable. (It's not wrong, but it's bad practice.) Being a static method this does not add the Button as child of grid. You need to do this in addition to setting the constraints. Button button = new Button("Check"); GridPane.setConstraints(button, 3, 4, 1, 2, HPos.LEFT, VPos.CENTER, Priority.SOMETIMES, Priority.SOMETIMES); grid.getChildren().add(button);
{ "language": "en", "url": "https://stackoverflow.com/questions/38565914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I convert an int to two bytes in C#? How do I convert an int to two bytes in C#? A: You can use BitConverter.GetBytes to get the bytes comprising an Int32. There will be 4 bytes in the result, however, not 2. A: Is it an int16? Int16 i = 7; byte[] ba = BitConverter.GetBytes(i); This will only have two bytes in it. A: Another way to do it, although not as slick as other methods: Int32 i = 38633; byte b0 = (byte)(i % 256); byte b1 = (byte)(i / 256); A: Assuming you just want the low bytes: byte b0 = (byte)i, b1 = (byte)(i>>8); However, since 'int' is 'Int32' that leaves 2 more bytes uncaptured. A: Option 1: byte[] buffer = BitConverter.GetBytes(number); Option 2: byte[] buffer = new byte[2]; buffer[0] = (byte) number; buffer[1] = (byte)(number >> 8); I prefer option 1!
{ "language": "en", "url": "https://stackoverflow.com/questions/3919804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Python - Which data structure to use? I have a large array of numerical data that I need to sort, insert, and move values backwards and forwards in the sorted order. I was previously using a simple array. Now each value has to be linked with an id (a unique int, just along for the ride). Can I extend the array class, or do I need to use a list of tuples? What is my best option? A: You can just use a list for the sake of having a sorted - well - list. If you want to associate additional data, you could either use a tuple to store the data, or even create a custom object for it that stores the id in an additional field. You shouldn’t need to extend the list for that, you can just put any object into a list. For example this would be easily possible: >>> lst = [ ( 132, 'foobar' ), ( 58, 'other value' ) ] >>> lst.append( ( 70, 'some data value' ) ) >>> lst [(132, 'foobar'), (58, 'other value'), (70, 'some data value')] >>> lst.sort( key=lambda x: x[0] ) >>> lst [(58, 'other value'), (70, 'some data value'), (132, 'foobar')] >>> lst.sort( key=lambda x: x[1] ) >>> lst [(132, 'foobar'), (58, 'other value'), (70, 'some data value')] edit: In case you are using Python 3.1+, you could also use the collections.OrderedDict type. It is an extension to the normal dict which maintains the order just like list does. A: Using lists or arrays is problematic when you need to do insertions or deletions -- these are O(n) operations which can be devastatingly slow with large datasets. Consider using blist which has a list-like API but affords O(lg N) insertion and deletion. A: why not using a dictionary, with the key as the item of original array, and value is the id related to the key. of course you could access it in sorted order, like this: a = {'key':'id'} keys = a.keys() keys.sort() for k in keys: print a[key] A: Similar to poke's answer, you can use a 2d array -- but if the arrays are big, NumPy is generally a good bet for any kind of numerical data in Python. Just make a 2D array that looks like [ [1 614.124] [2 621236.139] [3 1243.612] ] and then you can sort with .sort().
{ "language": "en", "url": "https://stackoverflow.com/questions/7961620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Cancel toggle when another toggle is activated? I'm having (a probably unnecessary) amount of trouble with a simple bit of code. I have 3 images, that when clicked open one of three divs below. I simply want to be able to cancel the toggle on any previously opened divs so that only one can be open at any given time. At the moment, the problem is that when one of the buttons is clicked a second time, nothing happens as it is cancelling out the toggle, rather than opening the div. As you can probably tell from my terrible wording, I'm fairly new to this, so be kind! The css is set so that the divs have a height and opacity of 0 to begin with. Code: $(document).ready(function() { $("#picone").toggle(function() { $("#divone").animate({ height: 400, opacity: 1 }, 500); $("#divtwo, #divthree").animate({ height: 0, opacity: 0 }, 500); }, function() { $("#divone").animate({ height: 0, opacity: 0 }, 500); $("#divtwo, #divthree").animate({ height: 0, opacity: 0 }, 500); }); }); $(document).ready(function() { $("#pictwo").toggle(function() { $("#divtwo").animate({ height: 400, opacity: 1 }, 500); $("#divone, #divthree").animate({ height: 0, opacity: 0 }, 500); }, function() { $("#divtwo").animate({ height: 0, opacity: 0 }, 500); $("#divone, #divthree").animate({ height: 0, opacity: 0 }, 500); }); }); $(document).ready(function() { $("#picthree").toggle(function() { $("#divthree").animate({ height: 400, opacity: 1 }, 500); $("#divone, #divtwo").animate({ height: 0, opacity: 0 }, 500); }, function() { $("#divthree").animate({ height: 0, opacity: 0 }, 500); $("#divone, #divtwo").animate({ height: 0, opacity: 0 }, 500); }); }); Thanks :) A: Thanks for the feedback guys. As it turns out, the toggle feature wasn't what I wanted anyway. I removed the extra $(document).ready(function(){ like @hsalama suggested, and binned the .toggle event like @François Wahl suggested. Here's how it ended up: $(document).ready(function(){ $("#picone").click(function() { $("#divone").animate( {height:300, opacity:1}, 500 ); $("#divtwo, #divthree").animate( {height:0, opacity:0}, 500 ); }); $("#pictwo").click(function() { $("#divtwo").animate( {height:300, opacity:1}, 500 ); $("#divone, #divthree").animate( {height:0, opacity:0}, 500 ); }); $("#picthree").click(function() { $("#divthree").animate( {height:300, opacity:1}, 500 ); $("#divone, #divtwo").animate( {height:0, opacity:0}, 500 ); }); }); Thanks guys :)
{ "language": "en", "url": "https://stackoverflow.com/questions/12503521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bang seems to not exclude files in .gitignore I have a foo directory which contains 2 files, bar and baz. I have the following .gitignore file, right above the foo directory: foo/ !foo/baz I expect this to ignore everything in the foo directory except it should not ignore baz. However, everything in foo is still being ignored. If I run git check-ignore foo/*, I get: foo/bar foo/baz What am I doing wrong? A: That particular formulation is not supported in .gitignore: An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined. Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, "\!important!.txt". Instead, you can do: foo/* !foo/baz Here's an example session so that you can see it in action: :: tree . `-- foo/ |-- bar `-- baz :: cat .gitignore foo/* !foo/baz :: git status -sb ## Initial commit on master ?? .gitignore ?? foo/ :: git add foo :: git status -sb ## Initial commit on master A foo/baz ?? .gitignore Note that baz was added but bar was ignored. To see what things look like if baz was not in foo, we can reset and then remove baz: :: git reset :: rm foo/baz :: git status -sb ## Initial commit on master ?? .gitignore Note that foo doesn't show up here, even though foo/bar still exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/41559572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I want to parse a Gson information but getting errors I am trying to send the data of source and destination. public void sendPost(final SearchSendModel searchSendModel){ //public void sendPost( String source, String destination){ Call call = mAPIService.sendSearch(searchSendModel); //Call call = mAPIService.sendSearch(source, destination); call.enqueue(new Callback<SearchModel>() { @Override public void onResponse(Call<SearchModel> call, Response<SearchModel> response) { Toast.makeText(Search.this, " Responce " +response.body(), Toast.LENGTH_SHORT).show(); Log.v("Responce", "Responce "+response.body()); if (response.isSuccessful()){ SearchModel searchResponse = response.body(); assert searchResponse != null; String content = ""; content += "Code: " +response.code() +"\n"; content += "vech_id: " + searchResponse.getVechId() +"\n"; content += "model_no: " + searchResponse.getModelNo() +"\n"; content += "reg_no: " +searchResponse.getRegNo() +"\n"; content += "delivery_start_date: " +searchResponse.getDeliveryStartDate() +"\n"; content += "delivery_end_date: " +searchResponse.getDeliveryEndDate() +"\n"; content += "full_percent: " +searchResponse.getFullPercent() +"\n"; content += "approval_status: " +searchResponse.getApprovalStatus() +"\n"; content +="source: " +searchResponse.getSource() +"\n"; content += "destination: " +searchResponse.getDestination() +"\n\n"; Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show(); searchModelList.add(searchResponse); }else { Toast.makeText(getApplicationContext(),"Something is error",Toast.LENGTH_SHORT).show(); } This is the Json response which i am expecting: [ { "vech_id": "30", "model_no": "8956", "reg_no": "98765", "delivery_start_date": "2020-03-18", "delivery_end_date": "2020-06-24", "full_percent": "0.14", "approval_status": "1", "source": "ranchi", "destination": "garwah" } ] Interface for API is: @POST("search_vehicle.php") @FormUrlEncoded Call<SearchSendModel> sendSearch(@Body SearchSendModel searchSendModel); SearchSendModel.java public class SearchSendModel { public SearchSendModel(String source, String destination) { this.source = source; this.destination = destination; } @SerializedName("source") private String source; @SerializedName("destination") private String destination; public String getSource() { return source; } public String getDestination() { return destination; } } But I am getting this error always: java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 2 path$ A: I think your onResponse should use List<SearchModel> instead of SearchModel. Your response format is array.
{ "language": "en", "url": "https://stackoverflow.com/questions/61833020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sideNavBox cannnot do responsive on Master Page Why my sideNavBox can't be responsive? I tried to apply col-md-3 to my sideNavBox and it shows me like this, It seems that sideNavBox causing something not to move? Here is my Full Master Page code: https://gist.github.com/anonymous/a6e3b76d1d621903f7262920234c3e37
{ "language": "en", "url": "https://stackoverflow.com/questions/47301460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting service instance in IAuthorizationPolicy Typically, you can get the service instance from the OperationContext like this: OperationContext.Current.InstanceContext.GetServiceInstance() However, when you're in an IAuthorizationPolicy, InstanceContext is null. Is there another way to get the instance of the service when hosted in IIS? A: In an IAuthorizationPolicy.Evaluate() OperationContext.Current.InstanceContext is not always null. Starting with Carlos Figueira’s WCF Extensibility test program which prints to the command line a message each time a WCF extension is called. I added a custom IAuthorizationPolicy. The output and program are below. The output shows that * *IAuthorizationPolicy.Evaluate() Is called after the service instance is created *OperationContext.Current.InstanceContext is not null in IAuthorizationPolicy.Evaluate() The test program is self hosted using BasicHttpBinding. It’s very possible that in other hosting environments IAuthorizationPolicy.Evaluate() does not have access to the service instance, but it is at least theoretically possible. Why would you do this? From an architecture point of view an IAuthorizationPolicy should be dealing with claims. The application should be consuming the claims on the ClaimsPrinciple. To have an IAuthorizationPolicy tightly coupled to a particular service breaks the very intentional separation of concerns in the Window Identity architecture. In other words, I think this is a bad idea. Test Program This is a windows command line program all in one file. using System; using System.Globalization; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.Text; using System.Threading; using System.Collections.Generic; namespace WcfRuntime { class MyDispatchMessageInspector : IDispatchMessageInspector { public MyDispatchMessageInspector() { } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return null; } public void BeforeSendReply(ref Message reply, object correlationState) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } } class MyDispatchMessageFormatter : IDispatchMessageFormatter { IDispatchMessageFormatter inner; public MyDispatchMessageFormatter(IDispatchMessageFormatter inner) { this.inner = inner; } public void DeserializeRequest(Message message, object[] parameters) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); this.inner.DeserializeRequest(message, parameters); } public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.SerializeReply(messageVersion, parameters, result); } } class MyClientMessageInspector : IClientMessageInspector { public MyClientMessageInspector() { } public void AfterReceiveReply(ref Message reply, object correlationState) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } public object BeforeSendRequest(ref Message request, IClientChannel channel) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return null; } } class MyClientMessageFormatter : IClientMessageFormatter { IClientMessageFormatter inner; public MyClientMessageFormatter(IClientMessageFormatter inner) { this.inner = inner; } public object DeserializeReply(Message message, object[] parameters) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.DeserializeReply(message, parameters); } public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.SerializeRequest(messageVersion, parameters); } } class MyDispatchOperationSelector : IDispatchOperationSelector { public string SelectOperation(ref Message message) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); string action = message.Headers.Action; string method = action.Substring(action.LastIndexOf('/') + 1); return method; } } class MyParameterInspector : IParameterInspector { ConsoleColor consoleColor; bool isServer; public MyParameterInspector(bool isServer) { this.isServer = isServer; this.consoleColor = isServer ? ConsoleColor.Cyan : ConsoleColor.Yellow; } public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) { ColorConsole.WriteLine(this.consoleColor, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } public object BeforeCall(string operationName, object[] inputs) { ColorConsole.WriteLine(this.consoleColor, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return null; } } class MyCallContextInitializer : ICallContextInitializer { public void AfterInvoke(object correlationState) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return null; } } class MyOperationInvoker : IOperationInvoker { IOperationInvoker inner; public MyOperationInvoker(IOperationInvoker inner) { this.inner = inner; } public object[] AllocateInputs() { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.AllocateInputs(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.Invoke(instance, inputs, out outputs); } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.InvokeBegin(instance, inputs, callback, state); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.InvokeEnd(instance, out outputs, result); } public bool IsSynchronous { get { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.IsSynchronous; } } } class MyInstanceProvider : IInstanceProvider { Type serviceType; public MyInstanceProvider(Type serviceType) { this.serviceType = serviceType; } public object GetInstance(InstanceContext instanceContext, Message message) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return Activator.CreateInstance(this.serviceType); } public object GetInstance(InstanceContext instanceContext) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return Activator.CreateInstance(this.serviceType); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } } class MyInstanceContextProvider : IInstanceContextProvider { IInstanceContextProvider inner; public MyInstanceContextProvider(IInstanceContextProvider inner) { this.inner = inner; } public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.GetExistingInstanceContext(message, channel); } public void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); this.inner.InitializeInstanceContext(instanceContext, message, channel); } public bool IsIdle(InstanceContext instanceContext) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return this.inner.IsIdle(instanceContext); } public void NotifyIdle(InstanceContextIdleCallback callback, InstanceContext instanceContext) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); this.inner.NotifyIdle(callback, instanceContext); } } class MyInstanceContextInitializer : IInstanceContextInitializer { public void Initialize(InstanceContext instanceContext, Message message) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } } class MyChannelInitializer : IChannelInitializer { ConsoleColor consoleColor; public MyChannelInitializer(bool isServer) { this.consoleColor = isServer ? ConsoleColor.Cyan : ConsoleColor.Yellow; } public void Initialize(IClientChannel channel) { ColorConsole.WriteLine(this.consoleColor, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } } class MyClientOperationSelector : IClientOperationSelector { public bool AreParametersRequiredForSelection { get { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return false; } } public string SelectOperation(MethodBase method, object[] parameters) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return method.Name; } } class MyInteractiveChannelInitializer : IInteractiveChannelInitializer { public IAsyncResult BeginDisplayInitializationUI(IClientChannel channel, AsyncCallback callback, object state) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); Action act = new Action(this.DoNothing); return act.BeginInvoke(callback, state); } public void EndDisplayInitializationUI(IAsyncResult result) { ColorConsole.WriteLine(ConsoleColor.Yellow, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); } private void DoNothing() { } } class MyErrorHandler : IErrorHandler { public bool HandleError(Exception error) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); return error is ArgumentException; } public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); MessageFault messageFault = MessageFault.CreateFault(new FaultCode("FaultCode"), new FaultReason(error.Message)); fault = Message.CreateMessage(version, messageFault, "FaultAction"); } } public class MyAuthorizationPolicy : IAuthorizationPolicy { string id; public MyAuthorizationPolicy() { id = Guid.NewGuid().ToString(); } public bool Evaluate(EvaluationContext evaluationContext, ref object state) { ColorConsole.WriteLine(ConsoleColor.Green, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod())); if (OperationContext.Current.InstanceContext != null) { var instance = (Service)OperationContext.Current.InstanceContext.GetServiceInstance(); ColorConsole.WriteLine(ConsoleColor.Green, "Got the service instance. Name={0}", instance.Name); } else { ColorConsole.WriteLine(ConsoleColor.Green, "OperationContext.Current.InstanceContext is null"); } // Return true, indicating that this method does not need to be called again. return true; } public ClaimSet Issuer { get { return ClaimSet.System; } } public string Id { get { return id; } } } [ServiceContract] public interface ITest { [OperationContract] int Add(int x, int y); [OperationContract(IsOneWay = true)] void Process(string text); } [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class Service : ITest { public Service() { ColorConsole.WriteLine(ConsoleColor.Green, "Created Service Instance"); } public string Name { get { return "MyService instance 1234"; } } public int Add(int x, int y) { ColorConsole.WriteLine(ConsoleColor.Green, "In service operation '{0}'", MethodBase.GetCurrentMethod().Name); if (x == 0 && y == 0) { throw new ArgumentException("This will cause IErrorHandler to be called"); } else { return x + y; } } public void Process(string text) { ColorConsole.WriteLine(ConsoleColor.Green, "In service operation '{0}'", MethodBase.GetCurrentMethod().Name); } } class MyBehavior : IOperationBehavior, IContractBehavior { public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { clientOperation.Formatter = new MyClientMessageFormatter(clientOperation.Formatter); clientOperation.ParameterInspectors.Add(new MyParameterInspector(false)); } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.CallContextInitializers.Add(new MyCallContextInitializer()); dispatchOperation.Formatter = new MyDispatchMessageFormatter(dispatchOperation.Formatter); dispatchOperation.Invoker = new MyOperationInvoker(dispatchOperation.Invoker); dispatchOperation.ParameterInspectors.Add(new MyParameterInspector(true)); } public void Validate(OperationDescription operationDescription) { } public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ChannelInitializers.Add(new MyChannelInitializer(false)); clientRuntime.InteractiveChannelInitializers.Add(new MyInteractiveChannelInitializer()); clientRuntime.MessageInspectors.Add(new MyClientMessageInspector()); clientRuntime.OperationSelector = new MyClientOperationSelector(); } public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime) { dispatchRuntime.ChannelDispatcher.ChannelInitializers.Add(new MyChannelInitializer(true)); dispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(new MyErrorHandler()); dispatchRuntime.InstanceContextInitializers.Add(new MyInstanceContextInitializer()); dispatchRuntime.InstanceContextProvider = new MyInstanceContextProvider(dispatchRuntime.InstanceContextProvider); dispatchRuntime.InstanceProvider = new MyInstanceProvider(dispatchRuntime.ChannelDispatcher.Host.Description.ServiceType); dispatchRuntime.MessageInspectors.Add(new MyDispatchMessageInspector()); dispatchRuntime.OperationSelector = new MyDispatchOperationSelector(); } public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) { } } static class ColorConsole { static object syncRoot = new object(); public static void WriteLine(ConsoleColor color, string text, params object[] args) { if (args != null && args.Length > 0) { text = string.Format(CultureInfo.InvariantCulture, text, args); } lock (syncRoot) { Console.ForegroundColor = color; Console.WriteLine("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture), text); Console.ResetColor(); } Thread.Sleep(50); } public static void WriteLine(string text, params object[] args) { Console.WriteLine(text, args); } public static void WriteLine(object obj) { Console.WriteLine(obj); } } static class ReflectionUtil { public static string GetMethodSignature(MethodBase method) { StringBuilder sb = new StringBuilder(); sb.Append(method.Name); sb.Append("("); ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(parameters[i].ParameterType.Name); } sb.Append(")"); return sb.ToString(); } } class Program { static void Main(string[] args) { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; using (ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress))) { ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), ""); endpoint.Contract.Behaviors.Add(new MyBehavior()); foreach (OperationDescription operation in endpoint.Contract.Operations) { operation.Behaviors.Add(new MyBehavior()); } var polices = new List<IAuthorizationPolicy>(); polices.Add(new MyAuthorizationPolicy()); host.Authorization.ExternalAuthorizationPolicies = polices.AsReadOnly(); host.Open(); ColorConsole.WriteLine("Host opened"); using (ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress))) { factory.Endpoint.Contract.Behaviors.Add(new MyBehavior()); foreach (OperationDescription operation in factory.Endpoint.Contract.Operations) { operation.Behaviors.Add(new MyBehavior()); } ITest proxy = factory.CreateChannel(); ColorConsole.WriteLine("Calling operation"); ColorConsole.WriteLine(proxy.Add(3, 4)); //ColorConsole.WriteLine("Called operation, calling it again, this time it the service will throw"); //try //{ // ColorConsole.WriteLine(proxy.Add(0, 0)); //} //catch (Exception e) //{ // ColorConsole.WriteLine(ConsoleColor.Red, "{0}: {1}", e.GetType().Name, e.Message); //} //ColorConsole.WriteLine("Now calling an OneWay operation"); //proxy.Process("hello"); ((IClientChannel)proxy).Close(); } } ColorConsole.WriteLine("Done"); } } } Program Output Look for the ---->. [12:33:04.218] MyOperationInvoker.get_IsSynchronous() [12:33:04.269] MyOperationInvoker.get_IsSynchronous() Host opened [12:33:04.322] MyChannelInitializer.Initialize(IClientChannel) Calling operation [12:33:04.373] MyClientOperationSelector.get_AreParametersRequiredForSelection() [12:33:04.424] MyClientOperationSelector.SelectOperation(MethodBase, Object[]) [12:33:04.474] MyParameterInspector.BeforeCall(String, Object[]) [12:33:04.524] MyClientMessageFormatter.SerializeRequest(MessageVersion, Object[]) [12:33:04.574] MyClientMessageInspector.BeforeSendRequest(Message&, IClientChannel) [12:33:04.632] MyInteractiveChannelInitializer.BeginDisplayInitializationUI(IClientChannel, AsyncCallback, Object) [12:33:04.684] MyInteractiveChannelInitializer.EndDisplayInitializationUI(IAsyncResult) [12:33:04.788] MyChannelInitializer.Initialize(IClientChannel) [12:33:04.838] MyInstanceContextProvider.GetExistingInstanceContext(Message, IContextChannel) [12:33:04.888] MyDispatchOperationSelector.SelectOperation(Message&) [12:33:04.939] MyInstanceContextProvider.InitializeInstanceContext(InstanceContext, Message, IContextChannel) [12:33:04.990] MyInstanceContextInitializer.Initialize(InstanceContext, Message) [12:33:05.040] MyDispatchMessageInspector.AfterReceiveRequest(Message&, IClientChannel, InstanceContext) [12:33:05.091] MyInstanceProvider.GetInstance(InstanceContext, Message) [12:33:05.142] Created Service Instance [12:33:05.192] MyCallContextInitializer.BeforeInvoke(InstanceContext, IClientChannel, Message) [12:33:05.242] MyOperationInvoker.AllocateInputs() [12:33:05.293] MyDispatchMessageFormatter.DeserializeRequest(Message, Object[]) [12:33:05.344] MyParameterInspector.BeforeCall(String, Object[]) [12:33:05.394] MyAuthorizationPolicy.Evaluate(EvaluationContext, Object&) ---->[12:33:05.445] Got the service instance. Name=MyService instance 1234 [12:33:05.495] MyOperationInvoker.Invoke(Object, Object[], Object[]&) [12:33:05.547] In service operation 'Add' [12:33:05.597] MyParameterInspector.AfterCall(String, Object[], Object, Object) [12:33:05.648] MyDispatchMessageFormatter.SerializeReply(MessageVersion, Object[], Object) [12:33:05.698] MyCallContextInitializer.AfterInvoke(Object) [12:33:05.748] MyDispatchMessageInspector.BeforeSendReply(Message&, Object) [12:33:05.803] MyInstanceContextProvider.IsIdle(InstanceContext) [12:33:05.804] MyClientMessageInspector.AfterReceiveReply(Message&, Object) [12:33:05.854] MyInstanceProvider.ReleaseInstance(InstanceContext, Object) [12:33:05.855] MyClientMessageFormatter.DeserializeReply(Message, Object[]) [12:33:05.905] MyParameterInspector.AfterCall(String, Object[], Object, Object) A: IAuthorizationPolicy implements evaluate which in turn provides a context. From microsoft public bool Evaluate(EvaluationContext evaluationContext, ref object state) { bool bRet = false; CustomAuthState customstate = null; // If state is null, then this method has not been called before, so // set up a custom state. if (state == null) { customstate = new CustomAuthState(); state = customstate; } else customstate = (CustomAuthState)state; Console.WriteLine("Inside MyAuthorizationPolicy::Evaluate"); // If claims have not been added yet... if (!customstate.ClaimsAdded) { // Create an empty list of Claims. IList<Claim> claims = new List<Claim>(); // Iterate through each of the claim sets in the evaluation context. foreach (ClaimSet cs in evaluationContext.ClaimSets) // Look for Name claims in the current claim set. foreach (Claim c in cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty)) // Get the list of operations the given username is allowed to call. foreach (string s in GetAllowedOpList(c.Resource.ToString())) { // Add claims to the list. claims.Add(new Claim("http://example.org/claims/allowedoperation", s, Rights.PossessProperty)); Console.WriteLine("Claim added {0}", s); } // Add claims to the evaluation context. evaluationContext.AddClaimSet(this, new DefaultClaimSet(this.Issuer,claims)); // Record that claims have been added. customstate.ClaimsAdded = true; // Return true, which indicates this need not be called again. bRet = true; } else { // This point should not be reached, but just in case... bRet = true; } return bRet; } See for example http://msdn.microsoft.com/en-us/library/ms729794(v=vs.110).aspx Getting the name of the current assembly using reflection Assembly SampleAssembly; // Instantiate a target object. Int32 Integer1 = new Int32(); Type Type1; // Set the Type instance to the target class type. Type1 = Integer1.GetType(); // Instantiate an Assembly class to the assembly housing the Integer type. SampleAssembly = Assembly.GetAssembly(Integer1.GetType()); // Display the name of the assembly currently executing Console.WriteLine("GetExecutingAssembly=" + Assembly.GetExecutingAssembly().FullName);
{ "language": "en", "url": "https://stackoverflow.com/questions/25627479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: GWT Development Mode in Eclipse leaving opening too many sessions I've had this problem for a couple days now. After about an hour or two of running my GWT dev server without restarting it, my "Development Mode" tab is showing many sessions remaining open. Open or at least it's showing them as active. I've seen as much as 8. When this is happening Eclipse runs very sluggish, and my application runs extremely slow (mostly the front end). I'm doing lots of browser refreshes and server reloads but nothing like opening 2nd browsers or running multiple tabs. The only way to close these sessions is to do stop my server and start it again. Before a few days ago, it seemed to only keep one open or maybe two sometimes. I'd never seen three unless I had multiple tabs or browsers running dev mode. After talking to my two co-workers, who use pretty much the same environment as me. One of them has always has this issue, and for years has just been periodically restarting his server every couple hours to fix it. The other's works fine. I'm running FF. Our GWT application only has one module. Does anybody know how to remedy this or how to limit the # of sessions? I haven't made any config changes to eclipse or changed any preferences that I'm aware recently that would have caused this. Thanks. A: This is unfortunately a known issue with Firefox: https://code.google.com/p/google-web-toolkit/issues/detail?id=7648
{ "language": "en", "url": "https://stackoverflow.com/questions/16595543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ std::bind to std::function with multiple arguments This question is going to be very much a duplicate, but I've read many of the examples on stack overflow and the common solution is not compiling for me, and I'm trying to figure out why. So I have a function I want to store in another class, the minimal example of what I'm doing outlined below. It does not compile as this is the issue. It was working when ParentClass::someFunction only had a single argument, but going to 2, and changing the placeholder to 2 did not work out. Can someone point out what mistake I am making here? #include <functional> #include <string> class StorageClass{ public: //In the actual code it get's passed to another another level //hence why I'm passing by reference rather than value void AddFunction(const std::function<void(std::string& a, int b)>& function); private: std::function<void(std::string& a, int b)> callBack; }; void StorageClass::AddFunction(const std::function<void(std::string& a, int b)>& function){ callBack = function; } class ParentClass { public: ParentClass(); void someFunction(std::string a, int b); private: StorageClass storageClass; }; ParentClass::ParentClass() { storageClass.AddFunction(std::bind(&ParentClass::someFunction, this, std::placeholders::_2)); } void ParentClass::someFunction(std::string a, int b) { } int main() { ParentClass parentClass; } A: Your function has two parameters, so you need two placeholders in your bind expression. std::bind(&ParentClass::someFunction, this, std::placeholders::_2) needs to be std::bind(&ParentClass::someFunction, this, std::placeholders::_1, std::placeholders::_2) Alternatively you can simplify this with a lambda like [this](auto a, auto b){ this->someFunction(a, b); } A: You should also pass the first placeholder, not just change _1 to _2. storageClass.AddFunction(std::bind(&ParentClass::someFunction, this, std::placeholders::_1, std::placeholders::_2));
{ "language": "en", "url": "https://stackoverflow.com/questions/73589746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with, ESP8266WebServer::on(const char [6], )' I'm learning how to use 'class' in C++, and when I'm trying to call a function from my class I'm getting this error: Error C:\Users\Mateus\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:90:8: note: void ESP8266WebServer::on(const String&, HTTPMethod, ESP8266WebServer::THandlerFunction, ESP8266WebServer::THandlerFunction) void on(const String &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn); ^ C:\Users\Mateus\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:90:8: note: candidate expects 4 arguments, 2 provided exit status 1 no matching function for call to 'ESP8266WebServer::on(const char [6], )' My code: #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> ESP8266WebServer server; class Light { public: int InPin; int OutPin; Light(int aInPin, int aOutPin){ InPin = aInPin; OutPin = aOutPin; } void setPin() { pinMode(InPin, INPUT_PULLUP); pinMode(OutPin, OUTPUT); } void toggleLight() { digitalWrite(InPin,!digitalRead(InPin)); String lstate = digitalRead(InPin) ? "Status: ON" : "Status: OFF"; server.send(200,"text/html", lstate); } }; char* ssid = "MaIs2"; char* password = "3134767570"; const char index_html[] PROGMEM ={"HUGE html string"}; const char style_css[] PROGMEM = {"HUGE css string"}; int Door = 4; int BDoor = 14; Light l1(0, 16); Light l2(2, 5); void setup() { WiFi.begin(ssid,password); Serial.begin(9600); while(WiFi.status()!=WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); l1.setPin(); l2.setPin(); server.on("/",[](){server.send_P(200,"text/html",index_html);}); server.on("/style.css", handleCss); server.on("/Lg1", l1.toggleLight); //ERROR HERE server.on("/Lg2", l2.toggleLight); //ERROR HERE server.on("/Door",TDoor); server.on("/Doorpulse", PDoor); server.begin(); } void handleCss(){ server.send_P(200, "text/css", style_css); } void loop() { server.handleClient(); if(digitalRead(l1.InPin) == LOW){ l1.toggleLight(); delay(1000); } if(digitalRead(l2.InPin) == LOW){ l2.toggleLight(); delay(1000); } if(digitalRead(Bdoor) == LOW){ Tdoor(); delay(1000); } } void PDoor() { digitalWrite(Door, HIGH); delay(5000); digitalWrite(Door, LOW); } void TDoor(){ digitalWrite(Door,!digitalRead(Door)); String doorstate = digitalRead(Door) ? "Status: Unlocked" : "Status: Locked"; server.send(200,"text/html", doorstate); } A: Looks like you need a lambda function, similar to your previous example server.on("/Lg1", [](){ l1.toggleLight(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/61644875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add Custom UIMenuController in SwiftUI I want to highlight some sentence inside the TextEditor by giving selection on the text, then I want a new custom UIMenuController but in Swift UI, I've followed some tutorial and it works in UIKit but it can't appear when I try to implement in inside swiftUI using UIRepresentable, any ideas to add that custom UIMenuController in SwiftUI? class Coordinator: NSObject, UITextViewDelegate { var text: Binding<String> var model: ScriptField_Model init(_ text: Binding<String>, _ model: ScriptField_Model) { self.text = text self.model = model } func textViewDidChange(_ textView: UITextView) { self.text.wrappedValue = textView.text self.model.text = textView.text } func textViewDidChangeSelection(_ textView: UITextView) { let menuItem1: UIMenuItem = UIMenuItem(title: "Menu 1", action: #selector(onMenu1(sender:))) // Store MenuItem in array. let myMenuItems: [UIMenuItem] = [menuItem1] // Added MenuItem to MenuController. UIMenuController.shared.menuItems = myMenuItems UIMenuController.shared.hideMenu() } func textFieldShouldReturn(_ textView: UITextView) -> Bool { return true } @objc internal func onMenu1(sender: UIMenuItem) { print("onMenu1") } } this is the part i try to add when select the sentence : func textViewDidChangeSelection(_ textView: UITextView) { let menuItem1: UIMenuItem = UIMenuItem(title: "Menu 1", action: #selector(onMenu1(sender:))) // Store MenuItem in array. let myMenuItems: [UIMenuItem] = [menuItem1] // Added MenuItem to MenuController. UIMenuController.shared.menuItems = myMenuItems UIMenuController.shared.hideMenu() } Any Help and reference, i will appreciate it.. thankyouu A: first create class like CVEDictTextView import Foundation import SwiftUI class CVEDictTextView: UITextView { override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let newInstanceItem = UIMenuItem(title: "Lookup", action:#selector(lookup)) UIMenuController.shared.menuItems = [newInstanceItem] UIMenuController.shared.hideMenu() if(action == #selector(lookup)){ return true } return false } @objc func lookup() { if(self.selectedRange.location != NSNotFound ){ let str = self.value(forKey: "text") as! String var str2 = String(str.dropFirst(self.selectedRange.location)) str2 = String(str2.dropLast(str2.count - self.selectedRange.length)) print(str2) } } } and create TextView UIViewRepresentable struct TextView: UIViewRepresentable { @Binding var text: String @Binding var textStyle: UIFont.TextStyle func makeUIView(context: Context) -> UITextView { let textView = CVEDictTextView() textView.delegate = context.coordinator textView.font = UIFont.preferredFont(forTextStyle: textStyle) textView.autocapitalizationType = .sentences textView.isSelectable = true textView.isUserInteractionEnabled = true textView.isEditable = false return textView } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = text uiView.font = UIFont.preferredFont(forTextStyle: textStyle) } func makeCoordinator() -> Coordinator { Coordinator($text) } class Coordinator: NSObject, UITextViewDelegate { var text: Binding<String> init(_ text: Binding<String>) { self.text = text } func textViewDidChange(_ textView: UITextView) { self.text.wrappedValue = textView.text } } } in SwitfUI view using it @State private var message = "hello how are you \n\t are you ok? email : hung.phuoc.tran@gmail.com" @State private var textStyle = UIFont.TextStyle.body TextView(text: $message, textStyle: $textStyle) .padding(.horizontal)
{ "language": "en", "url": "https://stackoverflow.com/questions/64303979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling functions from a C++ dylib and Header in a Cocoa Application Great website, has been super helpful these past few weeks. I am writing an app in Cocoa that requires the use of a C++ dylib and header files. I need to call functions from a header file in my app. Ive tried several ways to import and include these libraries into my app but always end up with missing symbol errors. The libraries i am using are from the autodesk maya API, anyone have any idea the correct way to do this? Thanks in advance! A: You need to make sure the files calling the functions are Objective-C++ files (basically, give them the extension ".mm"), and you need to add the library to your project so it gets linked in.
{ "language": "en", "url": "https://stackoverflow.com/questions/3391543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring boot with data jpa getting error on startup Getting an error while starting my Spring boot application. Here is a stack trace but I am unable to find the root cause. I am using spring boot 2.3.4 with spring data jpa. Any help appreciated. {"timestamp": "12/21/2020 18:52:02:0871", "class": "org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator", "file": "JtaPlatformInitiator.java", "level" : " INFO", "line_number" : "52", "url": "", "ip_address": "", "server_trace_id":"", "message": HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform], "method": "initiateService", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0872", "class": "org.hibernate.query.spi.NamedQueryRepository", "file": "NamedQueryRepository.java", "level" : "DEBUG", "line_number" : "151", "url": "", "ip_address": "", "server_trace_id":"", "message": Checking 0 named HQL queries, "method": "checkNamedQueries", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0872", "class": "org.hibernate.query.spi.NamedQueryRepository", "file": "NamedQueryRepository.java", "level" : "DEBUG", "line_number" : "167", "url": "", "ip_address": "", "server_trace_id":"", "message": Checking 0 named SQL queries, "method": "checkNamedQueries", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "52", "url": "", "ip_address": "", "server_trace_id":"", "message": Initializing SessionFactoryRegistry : org.hibernate.internal.SessionFactoryRegistry@263b5690, "method": "<init>", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "74", "url": "", "ip_address": "", "server_trace_id":"", "message": Registering SessionFactory: 64cd8993-8947-4c28-8a99-8717be785280 (<unnamed>), "method": "addSessionFactory", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "81", "url": "", "ip_address": "", "server_trace_id":"", "message": Not binding SessionFactory to JNDI, no JNDI name configured, "method": "addSessionFactory", "thread_name": "task-1"}, {"timestamp": "12/21/2020 18:52:02:0896", "class": "org.hibernate.internal.SessionFactoryImpl", "file": "SessionFactoryImpl.java", "level" : "DEBUG", "line_number" : "771", "url": "", "ip_address": "", "server_trace_id":"", "message": HHH000031: Closing, "method": "close", "thread_name": "restartedMain"}, {"timestamp": "12/21/2020 18:52:02:0897", "class": "org.hibernate.type.spi.TypeConfiguration$Scope", "file": "TypeConfiguration.java", "level" : "DEBUG", "line_number" : "350", "url": "", "ip_address": "", "server_trace_id":"", "message": Un-scoping TypeConfiguration [org.hibernate.type.spi.TypeConfiguration$Scope@3fbaa2e9] from SessionFactory [org.hibernate.internal.SessionFactoryImpl@1741883a], "method": "unsetSessionFactory", "thread_name": "restartedMain"}, {"timestamp": "12/21/2020 18:52:02:0902", "class": "org.hibernate.service.internal.AbstractServiceRegistryImpl", "file": "AbstractServiceRegistryImpl.java", "level" : "DEBUG", "line_number" : "419", "url": "", "ip_address": "", "server_trace_id":"", "message": Implicitly destroying ServiceRegistry on de-registration of all child ServiceRegistries, "method": "deRegisterChild", "thread_name": "restartedMain"}, {"timestamp": "12/21/2020 18:52:02:0902", "class": "org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl", "file": "BootstrapServiceRegistryImpl.java", "level" : "DEBUG", "line_number" : "295", "url": "", "ip_address": "", "server_trace_id":"", "message": Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries, "method": "deRegisterChild", "thread_name": "restartedMain"}, Exception in thread "task-2" org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'delegatingApplicationListener': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220) DefaultSingletonBeanRegistry.java:220 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) AbstractBeanFactory.java:322 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) AbstractBeanFactory.java:207 at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245) AbstractApplicationEventMulticaster.java:245 at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197) AbstractApplicationEventMulticaster.java:197 at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134) SimpleApplicationEventMulticaster.java:134 at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) AbstractApplicationContext.java:404 at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) AbstractApplicationContext.java:361 at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:99) DataSourceInitializedPublisher.java:99 at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50) DataSourceInitializedPublisher.java:50 at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200) DataSourceInitializedPublisher.java:200 {"timestamp": "12/21/2020 18:52:02:0905", "class": "com.zaxxer.hikari.HikariDataSource", "file": "HikariDataSource.java", "level" : " INFO", "line_number" : "350", "url": "", "ip_address": "", "server_trace_id":"", "message": HikariPool-1 - Shutdown initiated..., "method": "close", "thread_name": "restartedMain"}, {"timestamp": "12/21/2020 18:52:02:0906", "class": "com.zaxxer.hikari.pool.HikariPool", "file": "HikariPool.java", "level" : "DEBUG", "line_number" : "421", "url": "", "ip_address": "", "server_trace_id":"", "message": HikariPool-1 - Before shutdown stats (total=1, active=0, idle=1, waiting=0), "method": "logPoolState", "thread_name": "restartedMain"}, at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) at java.base/java.lang.Thread.run(Thread.java:832) A: Set the JAVA_HOME path and update JDK version. After that restart your server and it should work just fine! If this doesn't work, check how many instances of tomcat you have. If you have more than one, shut them down. It can also be a problem with the @Transactional annotation if you're using it wrong, you can see more details here- >http://www.javablog.fr/spring-transaction-visibility-proxy-propagation-required-and-requires_new.html
{ "language": "en", "url": "https://stackoverflow.com/questions/65393677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does C# compiler convert and store static variables? My program uses the code: Convert.ToDouble(Int32.MaxValue) Fairly regularly. I was just curious about how this is handled by the compiler. Is it stored as a static double or is it executed in run time? A: The constant Int32.MaxValue is stored at compile time, and in fact your code would be converted to Convert.ToDouble(0x7FFFFFFF) at compile time. The equivalent IL is: ldc.i4 FF FF FF 7F call System.Convert.ToDouble This value is also saved so it can be retrieved at run-time through reflection. However, Convert.ToDouble is a function that is only evaluated at run-time. As minitech suggests, (double)Int32.MaxValue is evaluated at compile-time. The equivalent IL is: ldc.r8 00 00 C0 FF FF FF DF 41
{ "language": "en", "url": "https://stackoverflow.com/questions/17182609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Parse string using C# LINQ Need help in parse string using C# LINQ I have a string like this 11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2 I would like to split this string on 448= then take an array start getting line "starts with 448" get the last string in the line which is 452= I'm trying this logic using LINQ to get the final output but it's not working. var parties = rptstr.Split(new string[] { "453=" }, StringSplitOptions.None).Select(p => p.Split(new string[] {"448="},StringSplitOptions.None); var str448 = (from lnprty in parties where lnprty.ToString().StartsWith("448=") //let tmp = line1.ToString() select new PartyRoleModel() { companyid == lnprty.Where(s => s.EndsWith("452=63,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault(), userid == lnprty.Where(s => s.EndsWith("452=11,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault() companyname == lnprty.Where(s => s.EndsWith("452=13,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault() PhyFlag == lnprty.Where(s => s.EndsWith("452=54,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault() }) .ToList(); I can split the line by 448 but 448 lines comes without 448= since it got split, I need split string also in the line so I can identify the line. Pls. remember the last line comes with other strings at end (448=W,447=D,452=54,77=O,555=2). I should get the final output like where 452=63 get companyid(which is in 447=), 452=11 get userid, 452=13 get companyname Thanks in advance. A: Try following : const string FILENAME = @"c:\temp\test.txt"; static void Main(string[] args) { Dictionary<int, Dictionary<string, int>> dict = new Dictionary<int, Dictionary<string, int>>(); StreamReader reader = new StreamReader(FILENAME); string input = ""; while ((input = reader.ReadLine()) != null) { //string input = "11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2"; List<string> strArray = input.Split(new char[] { ',' }).ToList(); //or dictionary Dictionary<string, int> rowDict = strArray.Select(x => x.Split(new char[] { '=' })).GroupBy(x => x.Last(), y => int.Parse(y.First())).ToDictionary(x => x.Key, y => y.FirstOrDefault()); int id = rowDict["CompanyID"]; dict.Add(id, rowDict); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/48367779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to time openGL animations on iPhone? I wonder if there is a time function in apples SDK that is guaranteed to be monotonically increasing? I heard about [NSDate timeIntervalSinceReferenceDate] (which isn't accurate) and the c function mach_absolute_time. How do all these people timing their animations in openGL ES (is there a frame independent solution)? A: See this question: How can I get a precise time, for example in milliseconds in objective-c? A: I use CADisplayLink to timing my animation. When you create a new opengl-es project on xCode, it will give you an sample opengl-es codes, and it control animation by CADisplayLink. EDIT: I found I misunderstand this problem. I check the CFAbsoluteTimeGetCurrent() method on this apple on-line doc, and it said the method may be not monotonically increasing. And the method CACurrentMediaTime() which I prefered derived value by mach_absolute_time(). The document about CACurrentMediaTime() is on this link. A: For frame-rate-independent time, I generally use the CFAbsoluteTimeGetCurrent() function. It returns a CFAbsoluteTime (which I believe is typedef'd to double) since some date arbitrarily far in the past.
{ "language": "en", "url": "https://stackoverflow.com/questions/4720288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebPage font changing while opening in UIWebView within my app My Application is using custom font ("Roboto"), I am opening a HTML page( this web page is also using Roboto font in CSS) in UIWebView within application, in which font of web page is bold. can anyone help?, what could be the problem. A: You have following solution may be any one help you. 1) Add in .css and meta tags as follow. html { -webkit-text-size-adjust: none; /* Never autoresize text */ } and meta tags as follow <meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0;'> 2) You can also inject both into an existing website, using this javascript code as follow. var style = document.createElement(\"style\"); document.head.appendChild(style); style.innerHTML = "html{-webkit-text-size-adjust: none;}"; var viewPortTag=document.createElement('meta'); viewPortTag.id="viewport"; viewPortTag.name = "viewport"; viewPortTag.content = "width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"; document.getElementsByTagName('head')[0].appendChild(viewPortTag); and Use UIWebViewDelegate (webViewDidFinishLoad) method - (void)webViewDidFinishLoad:(UIWebView *)webView{ NSString *javascript = @"var style = document.createElement(\"style\"); document.head.appendChild(style); style.innerHTML = \"html{-webkit-text-size-adjust: none;}\";var viewPortTag=document.createElement('meta');viewPortTag.id=\"viewport\";viewPortTag.name = \"viewport\";viewPortTag.content = \"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\";document.getElementsByTagName('head')[0].appendChild(viewPortTag);"; [webView stringByEvaluatingJavaScriptFromString:javascript]; } A: you can implement webView delegate and change font when load webView. func webViewDidStartLoad(webView : UIWebView) { //your code }
{ "language": "en", "url": "https://stackoverflow.com/questions/37208148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make the if condition contain more than one condition? i.e.: if (number % 3 == 0) & (number % 5 == 0): Starting_Num = int(input('Please enter intial number: ')) Ending_Num = int(input('Please enter ending number: ')) for number in range(Starting_Num, (Ending_Num+1)): if (number % 3 == 0): print(number, '--', 3) elif (number % 5 == 0): print(number, '--', 5) elif (number % 3 == 0) & (number % 5 == 0): print(number, '-- both') elif (number % 3 != 0) & (number % 5 != 0): print(number) A: you can simply do if (number % 3 == 0) and (number % 5 == 0): your code here... A: With the Python syntax, you need to use an and instead of &. Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Source: https://www.w3schools.com/python/python_conditions.asp#:~:text=The%20and%20keyword%20is%20a%20logical%20operator%2C%20and%20is%20used%20to%20combine%20conditional%20statements A: Does your program error at all? Python 3 allows keyword & as well as and to be used as "and" conditional statements. It should work either way... A: You can use "and" or "or" operator, difference between them is that "and" should call True if all of the condition are True, "or" - if one of it is True. example: a = 1 b = 2 c = 'd' if type(a) == int and type(b) == int: # that will be printed print("a, b are numbers") if type(a) == int and type(c) == int: # that will not be printed print("a, c are numbers") if type(a) == int or type(c) == int: # that will be printed print("a or c is number") your code should look like: Starting_Num = int(input('Please enter intial number: ')) Ending_Num = int(input('Please enter ending number: ')) for number in range(Starting_Num, (Ending_Num+1)): if (number % 3 == 0): print(number, '--', 3) elif (number % 5 == 0): print(number, '--', 5) elif (number % 3 == 0) and (number % 5 == 0): print(number, '-- both') elif (number % 3 != 0) and (number % 5 != 0): print(number) A: The problem is where you position your 'and' condition. In your code, assuming the input fits the condition (e.g. the number is 15) what will happen is that you will enter the first condition: (if (number % 3 != 0):) and skip all the others, because you used [if / elif] statements. What you need to do is move the condition [elif (number % 3 != 0) & (number % 5 != 0):] to be the first condition, which will ensure that in case the number is divisible by both 3 and 5 - you will first check for both conditions. Also, in case of logical and use the and operator. It should look something like this: Starting_Num = int(input('Please enter intial number: ')) Ending_Num = int(input('Please enter ending number: ')) for number in range(Starting_Num, (Ending_Num+1)): if (number % 3 == 0) and (number % 5 == 0): print(number, '-- both') elif (number % 3 == 0): print(number, '--', 3) elif (number % 5 == 0): print(number, '--', 5) else: print(number)
{ "language": "en", "url": "https://stackoverflow.com/questions/72147839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Streaming from obs to Nginx I'm trying to stream from obs to nginx server. I'm using videojs as a player. In OBS Settings I'm using custom Streaming server and the url is rtmp://localhost/live. this is the configuration file for nginx: rtmp { server { listen 1935; chunk_size 4096; application live { live on; record off; } } } and this is the html part: <video id="player" class="video-js vjs-default-skin" height="360" width="640" controls autoplay preload="none"> <source src="rtmp://localhost/live" type="rtmp/mp4" /> </video> A: https://github.com/DigiSkyOps/knife this is a obs stream server nginx/config rtmp { server { listen 1935; chunk_size 4000; application live { live on; } application hls { live on; hls on; hls_path /data/hls; hls_fragment 5s; hls_playlist_length 10s; hls_continuous on; hls_cleanup on; hls_nested on; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/54224598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving FB access token from FB JS SDK to DB I am implementing 'Login with FB' for my web app using FB JS SDK. I have got the user to return the access token in the response inside the statusChangeCallback function. However, I am not sure about the best method to store this info to a DB for later use (getting data from graph api). How can the access token and other user info be saved into a DB? In an attempt to post this data on an API, I have tried to serve this html using an express app but the facebook login popup shows blank where it should say "continue as such and such.." Should there be a separate API that I should post this data to? Any clue is appreciated! <!DOCTYPE html> <html> <head> <title>Facebook Login JavaScript Example</title> <meta charset="UTF-8"> </head> <body> <script> function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus(). console.log('statusChangeCallback'); console.log(response); // The current login status of the person. if (response.status === 'connected') { // Logged into your webpage and Facebook. testAPI(); } else { // Not logged into your webpage or we are unable to tell. document.getElementById('status').innerHTML = 'Please log ' + 'into this webpage.'; } } function checkLoginState() { // Called when a person is finished with the Login Button. FB.getLoginStatus(function(response) { // See the onlogin handler statusChangeCallback(response); }); } window.fbAsyncInit = function() { FB.init({ appId : '{app-id}', cookie : true, // Enable cookies to allow the server to access the session. xfbml : true, // Parse social plugins on this webpage. version : '{api-version}' // Use this Graph API version for this call. }); FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized. statusChangeCallback(response); // Returns the login status. }); }; function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made. console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Successful login for: ' + response.name); document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!'; }); } </script> <!-- The JS SDK Login Button --> <fb:login-button scope="public_profile,email" onlogin="checkLoginState();"> </fb:login-button> <div id="status"> </div> <!-- Load the JS SDK asynchronously --> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script> </body> </html> This code is taken from facebook docs: https://developers.facebook.com/docs/facebook-login/web#example
{ "language": "en", "url": "https://stackoverflow.com/questions/71346054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED) (Redis::CannotConnectError) I try to connect to reddis On c9.io But get this error /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:344:in `rescue in establish_connection': Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED) (Redis::CannotConnectError) from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:329:in `establish_connection' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:99:in `block in connect' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:291:in `with_reconnect' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:98:in `connect' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:363:in `ensure_connected' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:219:in `block in process' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:304:in `logging' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:218:in `process' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:118:in `call' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:1330:in `block in sadd' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:45:in `block in synchronize' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:45:in `synchronize' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:1329:in `sadd' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:442:in `call_with_namespace' from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:328:in `method_missing' from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-1.27.4/lib/resque/data_store.rb:59:in `method_missing' from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:94:in `set_schedule' from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:51:in `block in schedule=' from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:50:in `each' from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:50:in `schedule=' from /home/ubuntu/workspace/UnicumParser/config/initializers/resque.rb:4:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load' from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load' from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:648:in `block in load_config_initializer' from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/notifications.rb:166:in `instrument' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:647:in `load_config_initializer' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:611:in `each' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:611:in `block in <class:Engine>' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `instance_exec' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `run' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:55:in `block in run_initializers' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:421:in `block in each_strongly_connected_component_from' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:44:in `each' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:44:in `tsort_each_child' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `call' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `each_strongly_connected_component_from' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `call' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each' from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:54:in `run_initializers' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/application.rb:352:in `initialize!' from /home/ubuntu/workspace/UnicumParser/config/environment.rb:5:in `<top (required)>' from /home/ubuntu/workspace/UnicumParser/config.ru:3:in `require_relative' from /home/ubuntu/workspace/UnicumParser/config.ru:3:in `block in <main>' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:55:in `instance_eval' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:55:in `initialize' from /home/ubuntu/workspace/UnicumParser/config.ru:in `new' from /home/ubuntu/workspace/UnicumParser/config.ru:in `<main>' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:49:in `eval' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:49:in `new_from_string' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:40:in `parse_file' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:319:in `build_app_and_options_from_config' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:219:in `app' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:59:in `app' from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:354:in `wrapped_app' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:124:in `log_to_stdout' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:77:in `start' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:90:in `block in server' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `server' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!' from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>' from /home/ubuntu/workspace/UnicumParser/bin/rails:9:in `require' from /home/ubuntu/workspace/UnicumParser/bin/rails:9:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `load' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `call' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client.rb:30:in `run' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/bin/spring:49:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `load' from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `<top (required)>' from /home/ubuntu/workspace/UnicumParser/bin/spring:14:in `require' from /home/ubuntu/workspace/UnicumParser/bin/spring:14:in `<top (required)>' from bin/rails:3:in `load' from bin/rails:3:in `<main>' resque.rb file: require 'resque' require 'resque/scheduler' Resque.schedule = YAML.load_file(File.join(Rails.root, 'config/resque_schedule.yml')) Resque.logger = Logger.new(Rails.root.join('log', "#{Rails.env}_resque.log")) Resque.logger.level = Logger::INFO rails_env = ENV['RAILS_ENV'] || 'development' Resque.redis.namespace = "resque:#{rails_env}"
{ "language": "en", "url": "https://stackoverflow.com/questions/47650953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to distinguish four cosines from a FFT I have four cosines with frequencies 400e-3, 500e-3, 600e-3 and 700e-3 and I am trying to do the FFT of them but under the time I need, I cannot distinguish the four. Is there a way to distinguish the peaks without changing the tmax time of 1.76 and the frequencies? import numpy as np import scipy.fftpack from scipy.fftpack import fftfreq from scipy.fft import fft import matplotlib.pyplot as plt t = np.linspace(0,1.76,2400) f = [400e-3, 500e-3, 600e-3, 700e-3] # these are the frequencies yy = 0 for i in f: y = 0.5*np.cos(2*np.pi*i*t) yy = yy + y plt.figure(0) plt.plot(t, yy) f = fftfreq(len(t), np.diff(t)[0]) yf = fft(yy) plt.figure(1) plt.plot(f[:t.size//2], np.abs(yf[:t.size//2])) plt.show() Here are the results: A: The solution was to increase tmax of t = np.linspace(0,1.76,2400) i.e. 1.76. FFT makes bins the size of 1/tmax and the small tmax is, the bigger the bins are leading to less resolution.
{ "language": "en", "url": "https://stackoverflow.com/questions/73154180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .ajax, jquery, images that load late after upload I use .ajax jquery to upload images, but the images are still being uploaded when ajax finishes. The load event that is called after loads the same images. I have to refresh a few times before I get the right image. I tried using setTimeout but it did not work. How can I fix this problem? ADDED: As you can see, I tried using a timeout but it didn't work $.ajax( { url:"<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>", type:"POST", data:X, cache:false, processData:false, contentType:false, beforeSend:function() { $('#MAIN').animate({opacity:0.2}); $('#LOADING').fadeIn(250); }, success:function() { setTimeout(function() { $('#'+Y+'_LOAD').load('FRAME/image.php',{USER_CODE:Z,TYPE:Y},function() { $('#MAIN').animate({opacity:1}); $('#LOADING').fadeOut(250); HEIGHT = $('#'+Y+'_LOAD').show().height(); $('#'+Y+'_SLIDE').animate({'height':HEIGHT-3},function() { $('#'+Y+'_LOAD').fadeIn(150); }); }); },5000); } }); A: The solution is no-cache the image or create something like this: BANNER.jpg?V='.time(); BUT when using background image, it does not find the image. Anyone have a solution that, please post.
{ "language": "en", "url": "https://stackoverflow.com/questions/22515424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List store large amounts of data , Not enough memory public class ListKeywords { public int ID { set; get; } public string Keyword { set; get; } //关键词 public string Language { set; get; } //语种 public int WordCount { set; get; } //单词数 public int WordLength { set; get; } // 字符数 public int Status { set; get; } //采集状态 0-未采集 1-采集成功 2-保存失败 3-保存成功 4-发布失败 5-发布成功 public bool Taken { set; get; } public bool FTPStatus { set; get; } public bool DBStatus { set; get; } public string UrlName { set; get; } public ListKeywords() { } public ListKeywords(string keyword) { this.Keyword = keyword; } } List<string> lines = new List<string>(); List<ListKeywords> keywordsList = new List<ListKeywords>(); using (StreamReader sr = File.OpenText(filePath)) { string s = String.Empty; while ((s = sr.ReadLine()) != null) { //lines.Add(s); //Operating normally eywordsList.Add(new ListKeywords("some keywords")); // Operating normally keywordsList.Add(new ListKeywords(s)); // it will be out of memeory } } In text file, have 1,000,000 line data, if i use above code to load the large data to list< keywordsList >, it will raises an OutOfMemoryException, but if i load it to list< string >, it run normally. How to solved it ? A: Instead of using a List maybe try using an IEnumerable w/ yield? static IEnumerable<ListKeywords> Keywords() { using (StreamReader sr = File.OpenText(path)) { string s = String.Empty; while ((s = sr.ReadLine()) != null) { yield return new ListKeywords(s); } } } Note that Jon Skeet's C# in Depth offers a great explanation about this in Chapter 6. I imagine he also has some articles or posts on StackOverflow about this topic. As he points out, you want to be careful about modifying this method to pass in a StreamReader (or TextReader as is used in his example) as you would want to take ownership of the reader so it will be properly disposed of. Rather, you would want to pass in a Func<StreamReader> if you have such a need. Another interesting note he adds here - which I will point out because there are some edge cases where the reader will not actually be properly disposed of even if you don't allow the reader to be provided by the caller - it's possible for the caller to abuse the IEnumerable<ListKeywords> by doing something like Keywords().GetEnumerator() - this could result in a memory leak and could even potentially cause security issues if you have security-related code which relies on the using statement to clean up the resource.
{ "language": "en", "url": "https://stackoverflow.com/questions/23072983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostgreSQL query by string is filtering even the values where there are nulls. I've created a table in PostgreSQL 9.5 as shown below and I added some data to it. However, when I try and query data by case insensitive search like !~* it removes even the null value rows. How can I do a query that will return all categories that are null and vegetables but not fruits? CREATE TABLE temp ( category character varying, item character varying ); INSERT INTO temp VALUES('Fruits', 'apple'); INSERT INTO temp VALUES('FRUITS', 'applE'); INSERT INTO temp(item) VALUES('Apple'); INSERT INTO temp(item) VALUES('BANANA'); INSERT INTO temp VALUES('Vegetables', 'Cabbage'); Query Select * from temp where category !~* 'fruits' Output category item -------- -------- Vegetables Cabbage A: To deal with the null you can use is distinct from: Select * from temp where lower(category) is distinct from 'fruits' or if you do want the regular expression: Select * from temp where category !~* 'fruits' or category is null; alternatively treat null as something else: Select * from temp where coalesce(category, '') !~* 'fruits'
{ "language": "en", "url": "https://stackoverflow.com/questions/37308098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Functions using Dictionary name and Key as argument qualifier_2 = {'KKR' : {'Chris Lynn': 4, 'Sunil Narine': 10, 'Gautam Gambhir (c)': 12, 'Robin Uthappa (wk)': 1, 'Ishank Jaggi': 28, 'Colin Grandhomme': 0, 'Suryakumar Yadav': 31, 'Piyush Chawla': 2, 'Nathan Coulter-Nile': 6, 'Umesh Yadav': 2, 'Ankit Rajpoot': 4, 'Extra runs': 7, 'Total batted': 10}, 'MI': {'Lendl Simmons': 3, 'Parthiv Patel (wk)': 14, 'Ambati Rayudu': 6, 'Rohit Sharma (c)': 26, 'Krunal Pandya': 45, 'Kieron Pollard': 9, 'Extra runs': 8, 'Total batted': 6}} I want to write a function that takes dictionary and team as an argument and returns the total runs i.e Dictionary -> qualifier_2 and Team -> KKR/MI def total_runs(x,y): if x == 'qualifier_2' and y == 'KKR': c = sum(qualifier_2['KKR'].values()) return c total_runs(qualifier_2,KKR) A: This isn't a function, But a way to aggregate all scores at once. Run through the dictionary and sum the values as you go. final_dict = {} for team, scores in qualifier_2.items(): final_dict[team] = 0 # initialize score to 0 for player, score in scores.items(): final_dict[team] += score # accumulate score as you loop print(final_dict) Outputs: {'KKR': 117, 'MI': 117} A: You call your function with the name of the dictionary total_runs(qualifier_2,KKR) Then you try to compare that to a string if x == 'qualifier_2' and ........ : Identity comparisons: If you really want/need to ensure that it is the specific dictionary, change it to if x is qualifier_2 and y == 'KKR': In a function, you want to use the name of the parameters used in the definition. Inside your function (inside the function's scope) the dictionary you passed as the first argument has been assigned to x and the key you passed as the second argument was assigned to y. c = sum(x[y].values()) def total_runs(x,y): if x is qualifier_2 and y == 'KKR': c = sum(x[y].values()) return c Your dictionary keys are strings so you need to paa a string for that argument total_runs(qualifier_2,'KKR') Functions are used to make a process more generic so that process can be reused with different arguments/values passed to it's parameters. While there may be some reasons to check for specific parameter values (maybe for debugging), usually it defeats the purpose of a function. You could have written it like this: def total_runs(x,y): c = sum(x[y].values()) return c or def total_runs(x,y): return sum(x[y].values()) A: You can use dict.values() to get a list of the numbers, then pass it through sum to get the total: qualifier_2 = {'KKR' : {'Chris Lynn': 4, 'Sunil Narine': 10, 'Gautam Gambhir (c)': 12, 'Robin Uthappa (wk)': 1, 'Ishank Jaggi': 28, 'Colin Grandhomme': 0, 'Suryakumar Yadav': 31, 'Piyush Chawla': 2, 'Nathan Coulter-Nile': 6, 'Umesh Yadav': 2, 'Ankit Rajpoot': 4, 'Extra runs': 7, 'Total batted': 10}, 'MI': {'Lendl Simmons': 3, 'Parthiv Patel (wk)': 14, 'Ambati Rayudu': 6, 'Rohit Sharma (c)': 26, 'Krunal Pandya': 45, 'Kieron Pollard': 9, 'Extra runs': 8, 'Total batted': 6}} def total_runs(team): # If team is not found in the data, return 0. if team not in qualifier_2: return 0 # Otherwise, find the team and return a sum of their values. return sum(qualifier_2[team].values()) print total_runs("KKR") # Output: 117 print total_runs("MI") # Output: 117 You can even simplify it as a one liner, though it might be less readable: def total_runs(team): return sum((qualifier_2.get(team) or {}).values()) print total_runs("KKR") # Output: 117 print total_runs("MI") # Output: 117 print total_runs("FOOBAR") # Output: 0
{ "language": "en", "url": "https://stackoverflow.com/questions/53256645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-9" }
Q: What is the big block of javascript that i see at the beginning of some html pages? I'm trying to increase my literacy of source code, however often times when I view page source for a site i will find a huge wall of what appears to be javascript code. A good example would be this site: http://www.torontossc.com/ When I view the page source, I have no idea how to deal with that huge wall, so I have a few questions/logical deductions. * *The code wall is in <script> tags, so I'm assuming it must be javascript. But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that. *I downloaded the source code and looked at the html page, and noticed that when I'm not viewing the source at run time, that block isn't there- There's only an externally referenced script in its place. So is the wall of code I'm seeing the actual script itself, that runs on page load? *I did further digging and found out that the script is part of the facebook sdk. So does this mean that any time i see a wall of code like this, it's usually a script imported for use as part of an API/for integration with another website? If that's the case, then should i assume that the clutter and density of it is just for compactness *If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall? I hope I've answered my own question through deduction, but hopefully someone can confirm. Thanks! A: The code wall is in tags, so I'm assuming it must be javascript. Yes, it's clearly printed right there: <script type="text/javascript">. But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that. It's minified, a form of obfuscation which makes JavaScript smaller to download and more difficult to reverse engineer. I downloaded the source code and looked at the html page... That probably broke a lot of things. You can't just download a page without downloading all of it's relatively-referenced paths. So does this mean that any time i see a wall of code like this, ... No, there's nothing you can tell about the code except that it's * *inline *minified If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall? No, nobody writes code that way, and nobody (easily) understands code written that way. A computer compressed/minified the code, and to understand it you need to learn JavaScript, and then unminify the code, which is a far from perfect process. Many forms of minification are "destructive" in that it's impossible to arrive back at the original source code. Human-readable tokens are often turned into single characters, and there is no way to undo this process, the original human-readable names are lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/24495642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How To Add A Back Slash To The TextBox For Date Format This Is My JavaScript: ` function ValidateDate(txt, keyCode) { if(keyCode==16) isShift = false; var val=txt.value; var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ; if(val.length == 10) { var splits = val.split("/"); var dt = new Date(splits[1] + "/" + splits[0] + "/" + splits[2]); //Validation for Dates if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1] && dt.getFullYear()==splits[2]) { lblmesg.style.color="green"; lblmesg.innerHTML = "Valid Date"; } else { lblmesg.style.color="red"; lblmesg.innerHTML = "InValid Date"; return; } //Range Validation if(txt.id.indexOf("txtRange") != -1) RangeValidation(dt); //BirthDate Validation if(txt.id.indexOf("txtBirthDate") != -1) BirthDateValidation(dt) } else if(val.length < 10) { lblmesg.style.color="blue"; lblmesg.innerHTML = "Required dd/mm/yy format. Slashes will come up automatically."; } }` And This Is My TextBox: > <asp:TextBox ID="txtValidate" runat="server" MaxLength = "10" onkeyup = "ValidateDate(this, event.keyCode)" onkeydown = "return DateFormat(this, event.keyCode)"></asp:TextBox> I want to include a slash within a TextBox for typing a Date.. I don't want it to generate a slash while typing...it should be static when the page is loaded.... Is it possible to do that without using AjaxToolkit ??? A: I use this simple replace Date: <input name=x size=10 maxlength=10 onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"> Try it with jsfiddle A: I made a simple example for your purpose: var date = document.getElementById('date'); date.addEventListener('keypress', function (event) { var char = String.fromCharCode(event.which), offset = date.selectionStart; if (/\d/.test(char) && offset < 8) { if (offset === 2 || offset === 5) { offset += 1; } date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1); date.selectionStart = date.selectionEnd = offset + 1; } if (!event.keyCode) { event.preventDefault(); } }); Here is a fiddle A: Here is a shorter version: $("#txtDate").keyup(function(){ if ($(this).val().length == 2 || $(this).val().length == 5){ $(this).val($(this).val() + "/"); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/26927106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scale image in CVImageBuffer I have a task - to scale down an image which I got from the camera. I need it in order to do heavy-lifting operations on smaller version of the image which will help me to save some processing power. I decided to go with vImage_Buffer from Accelerate. Here's my code with few comments just to give clear understanding what is what there: guard let imgBuffer = CMSampleBufferGetImageBuffer(buffer) else { return } CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0)) // create vImage_Buffer out of CVImageBuffer var inBuff: vImage_Buffer = vImage_Buffer() inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer)) inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer)) inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer) inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer) // bring down the size at half let new_width: UInt = inBuff.width/2 let new_height: UInt = inBuff.height/2 // create output buffer where scaled image is supposed to be var outBuff: vImage_Buffer = vImage_Buffer() outBuff.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size) outBuff.width = new_width outBuff.height = new_height outBuff.rowBytes = Int(new_width * 4) // perform scale let err = vImageScale_ARGB8888(&inBuff, &outBuff, nil, 0) if err != kvImageNoError { print("Wrong!") } // I guess I need to unlock buffer at this point, right? CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0)) // create CVImageBuffer let options = [kCVPixelBufferCGImageCompatibilityKey: true, kCVPixelBufferCGBitmapContextCompatibilityKey: true, kCVPixelBufferWidthKey: new_width, kCVPixelBufferHeightKey: new_height] as CFDictionary var newPixelBuffer: CVImageBuffer? let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, Int(new_width), Int(new_height), kCVPixelFormatType_32BGRA, &outBuff, Int(new_width * 4), nil, nil, options, &newPixelBuffer) if status == kCVReturnError { print("Wrong again!") } // create CIImage from CVImageBuffer and UIImage from CIImage just to see how scale went let ciImg = CIImage(cvImageBuffer: newPixelBuffer!) let img = UIImage(ciImage: ciImg) delegate?.testSmallImage(img) It seems like all operations are performed without any errors and I want to check how scale went so I'm trying to create new UIImage out of scaled buffer. But when I try to show an image with UIImageView, I have EXC_BAD_ACCESS error. And when I try to save brand-new UIImage, everything goes without errors, but no file appears in Documents directory. Can you point me out what exactly am I doing wrong here? Thanks! A: Here's the code snippet on Swift which resizes CMSampleBuffer: private func scale(_ sampleBuffer: CMSampleBuffer) -> CVImageBuffer? { guard let imgBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil } CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0)) // create vImage_Buffer out of CVImageBuffer var inBuff: vImage_Buffer = vImage_Buffer() inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer)) inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer)) inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer) inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer) // perform scale var err = vImageScale_ARGB8888(&inBuff, &scaleBuffer, nil, 0) if err != kvImageNoError { print("Can't scale a buffer") return nil } CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0)) var newBuffer: CVPixelBuffer? let attributes : [NSObject:AnyObject] = [ kCVPixelBufferCGImageCompatibilityKey : true as AnyObject, kCVPixelBufferCGBitmapContextCompatibilityKey : true as AnyObject ] let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, Int(scaleBuffer.width), Int(scaleBuffer.height), kCVPixelFormatType_32BGRA, scaleBuffer.data, Int(scaleBuffer.width) * 4, nil, nil, attributes as CFDictionary?, &newBuffer) guard status == kCVReturnSuccess, let b = newBuffer else { print("Can't create new CVPixelBuffer") return nil } return b } And here's a definition of scaleBuffer which acts as a destination in scale operation. I do not need to create it each scale so I do it only once: scaleBuffer.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size) scaleBuffer.width = vImagePixelCount(new_width) scaleBuffer.height = vImagePixelCount(new_height) scaleBuffer.rowBytes = Int(new_width * 4)
{ "language": "en", "url": "https://stackoverflow.com/questions/57327226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: paint on a container being added to jcomponent i have a jrame on which i add some JComponent objects. Each JComponent has a list of containers i add by using JComponent.add( Component). Now in my main JComponent class, called MyComponent, i override the protected method paintComponent where i can paint things, which works pretty fine. But i dont want to paint on the main JComponent, i only want to paint on the containers i have added to my main JComponent. So in MyComponent in paintComponent i do the following. protected void paintComponent( Graphics g) { super.paintComponent( g); Graphics page_g = this.getPage( "main").getGraphics(); page_g.setColor( Color.RED); page_g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20); page_g.setColor( Color.BLUE); page_g.drawString( "HELLO WORLD", this.getWidth() / 2, this.getHeight() / 2); } The line this.getPage( "main").getGraphics(); takes the Graphics object from one of my containers added to the MyComponents list of containers and of course to the main component list using JComponents add method. The container is set to visible by calling the setVisible( true); method. But nothing happens. The screen is empty. When i replace page_g with g, then painting works, because its painting on my JComponent (MyComponent), but i want to paint on the container which is a children of MyComponent in this case. I often heard "Never use getGraphics()". But how else can ONLY draw on sub components of a parent component when the parents paintComponent method gets called? A: Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method. Let the AWT worry about the graphics contexts.
{ "language": "en", "url": "https://stackoverflow.com/questions/4642511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parameterized Async function returning Promise { "_40": 0, "_55": "English", "_65": 1, "_72": null, } [CLOSED] How to get the 'English' out of the promise object which is unneccesary Async Functions -> parameterized const getLanguageNamefromCode = async (lng_code) => { let response, langData, lang; try { response = await fetch( `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages` ); langData = await response.json(); // console.log(langData[0].languages[0]); if (langData[0].languages[0].iso639_1 === lng_code) { lang = langData[0].languages[0].name; console.log(lang); } return lang; } catch (err) { throw new Error(err); } }; calling it from inside a for loop and sending in a parameter const loadedTrendingMovies = []; const loadedTrendingMoviesLength = trendingMovies.results.length; for (let i = 0; i < 6; i++) { // let credits; hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingMovies.results[i].id.toString() ); loadedTrendingMovies.push( new Movie( trendingMovies.results[i].id.toString(), trendingMovies.results[i].media_type === "movie" ? trendingMovies.results[i].title : trendingMovies.results[i].name, posterBaseUrl + trendingMovies.results[i].poster_path, trendingMovies.results[i].media_type === "movie" ? trendingMovies.results[i].release_date : trendingMovies.results[i].first_air_date, [], trendingMovies.results[i].overview, trendingMovies.results[i].vote_average, getLanguageNamefromCode(trendingMovies.results[i].original_language), hasUserSaved ? hasUserSaved.location : "" ) ); } How to get the value from the promise returned by the getLanguagefromCode Async Method. This is my MoviesScreen functional component , i am using redux import React, { useEffect, useCallback, useState, useRef } from "react"; import { View, Text, StyleSheet, FlatList, ScrollView, StatusBar, TouchableWithoutFeedback, RefreshControl, } from "react-native"; import { Ionicons } from "@expo/vector-icons"; import MovieItem from "../components/MovieItem"; import { useSelector, useDispatch } from "react-redux"; import * as MoviesAction from "../store/actions/MoviesAction"; import * as UserActions from "../store/actions/UserActions"; import Colors from "../constants/Colors"; import { useScrollToTop } from "@react-navigation/native"; import SkeletonContent from "react-native-skeleton-content"; import { createSelector } from "reselect"; const stories = createSelector( (state) => state.Movies.movies, (movies) => movies ); const newReleases = createSelector( (state) => state.Movies.new_releases, (new_releases) => new_releases ); const newTVShows = createSelector( (state) => state.Movies.new_tv_shows, (new_tv_shows) => new_tv_shows ); const Anime = createSelector( (state) => state.Movies.anime, (anime) => anime ); const MoviesScreen = (props) => { const Stories = useSelector(stories); const new_releases = useSelector(newReleases); console.log(" movie screen rendered", new_releases); const new_tv_shows = useSelector(newTVShows); const anime = useSelector(Anime); const [loading, setLoading] = useState(false); const [refreshing, setRefreshing] = useState(false); const dispatch = useDispatch(); const scrollRef = useRef(null); useScrollToTop(scrollRef); const onRefresh = useCallback(() => { setRefreshing(true); loadScreen().then(() => setRefreshing(false)); }, [setRefreshing, loadScreen]); const loadScreen = useCallback(async () => { try { dispatch(MoviesAction.loadAll()); } catch (err) { console.log(err); } }, []); useEffect(() => { setLoading(true); loadScreen().then(() => setLoading(false)); }, []); const renderTrendingMoviesItem = ({ item }) => ( <SkeletonContent boneColor="#303030" highlightColor="#252525" containerStyle={styles.new_releases} isLoading={loading || refreshing} layout={[styles.cinemaSkeleton]} > <MovieItem style={styles.new_releases} id={item.id} movieTitle={item.title} posterUrl={item.posterUrl} year={item.year} onPress={() => { props.navigation.navigate({ name: "MoviesDetailScreen", params: { movieId: item.id, movieTitle: item.title, moviesType: "Movies", }, }); }} /> </SkeletonContent> ); const renderStoriesItem = ({ item }) => ( <SkeletonContent boneColor="#303030" highlightColor="#252525" containerStyle={{ ...styles.storyItem, marginHorizontal: 10, marginVertical: 7.5, }} isLoading={loading || refreshing} layout={[ { key: "story", width: 80, height: 80, borderRadius: 40, marginHorizontal: 10, marginVertical: 7.5, }, ]} > <MovieItem style={styles.storyItem} footerStyle={{ opacity: 0 }} imageStyle={styles.storyImage} id={item.id} posterUrl={item.posterUrl} onPress={() => { props.navigation.navigate({ name: "NewReleasesModalScreen", params: { movieTitle: item.title, posterUrl: item.posterUrl, movieId: item.id, }, }); }} /> </SkeletonContent> ); const renderTrendingTVItem = ({ item }) => ( <SkeletonContent boneColor="#303030" highlightColor="#252525" containerStyle={styles.new_releases} isLoading={loading || refreshing} layout={[styles.cinemaSkeleton]} > <MovieItem style={styles.new_releases} id={item.id} movieTitle={item.title} posterUrl={item.posterUrl} year={item.year} onPress={() => { props.navigation.navigate({ name: "MoviesDetailScreen", params: { movieId: item.id, movieTitle: item.title, moviesType: "TV", }, }); }} /> </SkeletonContent> ); const renderAnimeItem = ({ item }) => ( <SkeletonContent boneColor="#303030" highlightColor="#252525" containerStyle={styles.new_releases} isLoading={loading || refreshing} layout={[styles.cinemaSkeleton]} > <MovieItem style={styles.new_releases} id={item.id} movieTitle={item.title} posterUrl={item.posterUrl} year={item.year} onPress={() => { props.navigation.navigate({ name: "MoviesDetailScreen", params: { movieId: item.id, movieTitle: item.title, moviesType: "anime", goToAnime: true, }, }); }} /> </SkeletonContent> ); return ( <ScrollView ref={scrollRef} style={styles.screen} showsVerticalScrollIndicator={false} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={Colors.lightblue} /> } > {/* new releases stories */} <StatusBar barStyle="light-content" /> <SkeletonContent boneColor="#303030" highlightColor="#252525" containerStyle={styles.headerCont} isLoading={loading || refreshing} layout={[styles.headerTextSkeleton]} > <View style={styles.headerCont}> <Text style={styles.headerText}> New Releases </Text> </View> </SkeletonContent> <View> <FlatList keyExtractor={(item) => item.id} showsHorizontalScrollIndicator={false} horizontal={true} data={Stories} renderItem={renderStoriesItem} /> </View> {/* new releases stories */} {/*... TOP MOVIE THAT WEEK ... */} <View> <SkeletonContent boneColor="#303030" containerStyle={styles.headerCont} highlightColor="#252525" containerStyle={styles.headerCont} isLoading={loading || refreshing} layout={[styles.headerTextSkeleton]} > <View style={styles.headerCont}> <TouchableWithoutFeedback onPress={() => { props.navigation.navigate({ name: "SeeAllScreen", params: { new_releases: true, headerTitle: "Trending Movies", }, }); }} > <View style={{ flexDirection: "row" }}> <Text style={styles.headerText}> Movies </Text> <Ionicons style={{ marginStart: 5 }} name="ios-arrow-forward" size={22} color={Colors.lightblue} /> </View> </TouchableWithoutFeedback> </View> </SkeletonContent> <FlatList keyExtractor={(item) => item.id} showsHorizontalScrollIndicator={false} horizontal={true} data={new_releases} renderItem={renderTrendingMoviesItem} /> </View> {/* TV SHOWS */} <View> <SkeletonContent boneColor="#303030" containerStyle={styles.headerCont} highlightColor="#252525" containerStyle={styles.headerCont} isLoading={loading || refreshing} layout={[styles.headerTextSkeleton]} > <View style={styles.headerCont}> <TouchableWithoutFeedback onPress={() => { props.navigation.navigate({ name: "SeeAllScreen", params: { new_tv_shows: true, headerTitle: "Trending TV Shows", }, }); }} > <View style={{ flexDirection: "row" }}> <Text style={styles.headerText}> TV Shows </Text> <Ionicons style={{ marginStart: 5 }} name="ios-arrow-forward" size={22} color={Colors.lightblue} /> </View> </TouchableWithoutFeedback> </View> </SkeletonContent> <FlatList keyExtractor={(item) => item.id} showsHorizontalScrollIndicator={false} horizontal={true} data={new_tv_shows} renderItem={renderTrendingTVItem} /> </View> {/* Anime */} <View> <SkeletonContent boneColor="#303030" containerStyle={styles.headerCont} highlightColor="#252525" containerStyle={styles.headerCont} isLoading={loading || refreshing} layout={[styles.headerTextSkeleton]} > <View style={styles.headerCont}> <TouchableWithoutFeedback onPress={() => { props.navigation.navigate({ name: "SeeAllScreen", params: { moviesType: "anime", goToAnime: true, headerTitle: "Trending Anime", }, }); }} > <View style={{ flexDirection: "row" }}> <Text style={styles.headerText}> Anime </Text> <Ionicons style={{ marginStart: 5 }} name="ios-arrow-forward" size={22} color={Colors.lightblue} /> </View> </TouchableWithoutFeedback> </View> </SkeletonContent> <FlatList keyExtractor={(item) => item.id} showsHorizontalScrollIndicator={false} horizontal={true} data={anime} renderItem={renderAnimeItem} /> </View> </ScrollView> ); }; This is the actions file import React, { useState } from "react"; export const SEARCH_MOVIES = "SEARCH_MOVIES"; export const LOAD_MOVIES_WITH_GENRES = "LOAD_MOVIES_WITH_GENRES"; export const CLEAR_SEARCH_LIST = "CLEAR_SEARCH_LIST"; export const CLEAR_GENRE_SCREEN = "CLEAR_GENRE_SCREEN"; export const LOAD_ALL = "LOAD_ALL"; import Movie from "../../models/Movie"; import config from "../../config"; import Cast from "../../models/CastMember"; const getCredits = async (index) => { let response, creditsData; try { response = await fetch( `https://api.themoviedb.org/3/tv/${resData.results[index].id}?api_key=${config.TMDB_API_KEY}&language=en-US&append_to_response=credits` ); creditsData = await response.json(); // console.log("credits", creditsData); } catch (err) { throw new Error(err); } const castMembers = []; const length = creditsData.credits.cast.length > 10 ? 10 : creditsData.credits.cast.length; for (let i = 0; i < 6; i++) { castMembers.push( new Cast( creditsData.credits.cast[i].id, creditsData.credits.cast[i].character, creditsData.credits.cast[i].name, posterBaseUrl + creditsData.credits.cast[i].profile_path ) ); } console.log(castMembers); return { cast: castMembers }; }; const getLanguageNamefromCode = async (lng_code) => { let response, langData, lang; try { response = await fetch( `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages` ); langData = await response.json(); // console.log(langData[0].languages[0]); if (langData[0].languages[0].iso639_1 === lng_code) { lang = langData[0].languages[0].name; console.log(lang); } return lang; } catch (err) { throw new Error(err); } }; export const clearSearchList = () => { return { type: CLEAR_SEARCH_LIST }; }; export const clearGenreScreen = () => { return { type: CLEAR_GENRE_SCREEN, }; }; export const loadAll = () => { const posterBaseUrl = "http://image.tmdb.org/t/p/w185"; let hasUserSaved; const loadedStories = []; return async (dispatch, getState) => { try { //stories response const moviesResponse = await fetch( `https://www.omdbapi.com/?apikey=${config.OMDB_API_KEY}&s=tokyo` ); // trending movies const TrendingMoviesResponse = await fetch( `https://api.themoviedb.org/3/trending/all/day?api_key=${config.TMDB_API_KEY}` ); // trending TV const trendingTVResponse = await fetch( `https://api.themoviedb.org/3/discover/tv?api_key=${config.TMDB_API_KEY}&language=en-US&sort_by=popularity.desc&first_air_date_year=2020&page=1&with_original_language=en` ); // trending Anime const trendingAnimeResponse = await fetch( `https://kitsu.io/api/edge/trending/anime`, { method: "GET", } ); if ( !moviesResponse.ok || !TrendingMoviesResponse.ok || !trendingTVResponse.ok || !trendingAnimeResponse.ok ) { throw new Error("failed response"); } const movies = await moviesResponse.json(); const trendingMovies = await TrendingMoviesResponse.json(); const trendingTV = await trendingTVResponse.json(); const trendingAnime = await trendingAnimeResponse.json(); // console.log('Trending Movies',resData); // console.log("NEW RELEASES", resData); //stories array const loadedMoviesLength = movies.Search.length; for (let i = 0; i < 6; i++) { loadedStories.push( new Movie( movies.Search[i].imdbID, movies.Search[i].Title, movies.Search[i].Poster, movies.Search[i].Year ) ); } //trending movies array // console.log("loadedTrendingMovies", loadedTrendingMovies); let loadedTrendingMovies=[]; const loadedTrendingMoviesLength = trendingMovies.results.length; // loadedTrendingMovies = Promise.all( trendingMovies.results .slice(0, 5) // use slice instead of a loop .map(( trendingMovie // map movie to [language,movie] ) => getLanguageNamefromCode( // get async language trendingMovie.original_language // resolve to [language,movie] ).then((language) => [language, trendingMovie]) ) // sorry, forgot to return here ) .then(( results // results is [[language,movie],[language,movie]] ) => results.map(([language, trendingMovie]) => { const hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingMovie.id.toString() // snippet does not have conditional chaining ); return new Movie( // create new Movie trendingMovie.id.toString(), trendingMovie.media_type === "movie" ? trendingMovie.title : trendingMovie.name, posterBaseUrl + trendingMovie.poster_path, trendingMovie.media_type === "movie" ? trendingMovie.release_date : trendingMovie.first_air_date, [], trendingMovie.overview, trendingMovie.vote_average, language, hasUserSaved ? hasUserSaved.location : "" ); }) ) .then((movies) => { // loadedTrendingMovies.push(movies); loadedTrendingMovies = [...loadedTrendingMovies, ...movies]; console.log("loadedTrendingMovies", loadedTrendingMovies); }) .catch((err) => console.log(err)); // trending TV Shows const loadedNewTVShows = []; const TVShowsLength = trendingTV.results.length; for (let i = 0; i < 6; i++) { // let credits; hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingTV.results[i].id.toString() ); // let cast = getCredits(i).then((cast) => cast); // console.log("CAST", cast); loadedNewTVShows.push( new Movie( trendingTV.results[i].id.toString(), trendingTV.results[i].name, posterBaseUrl + trendingTV.results[i].poster_path, trendingTV.results[i].first_air_date.toString().substr(0, 5), // getCredits(i).then((cast) => cast), // getCredits(i) // .then((results) => { // console.log("success", results.cast); // return results.cast; // }) // .catch((err) => console.log("cast error", err)), [], trendingTV.results[i].overview, trendingTV.results[i].vote_average, // getLanguageNamefromCode(trendingTV.results[i].original_language), hasUserSaved ? hasUserSaved.location : "" ) ); } const loadedAnime = []; const AnimeLength = trendingAnime.data.length; for (let i = 0; i < 6; i++) { // let credits; hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingAnime.data[i].id.toString() ); // let cast = getCredits(i).then((cast) => cast); // console.log("CAST", cast); loadedAnime.push( new Movie( trendingAnime.data[i].id, trendingAnime.data[i].attributes.canonicalTitle, trendingAnime.data[i].attributes.posterImage.medium, trendingAnime.data[i].attributes.createdAt.toString().substr(0, 4), // getCredits(i).then((cast) => cast), [], trendingAnime.data[i].attributes.synopsis, trendingAnime.data[i].attributes.vote_average, "Japanese", hasUserSaved ? hasUserSaved.location : "" ) ); } dispatch({ type: LOAD_ALL, movies: loadedStories, new_releases: loadedTrendingMovies, new_tv_shows: loadedNewTVShows, anime: loadedAnime, }); } catch (err) { console.log(err); } }; }; export const searchMovies = (MovieTitle) => { let response; let hasUserSaved; const posterBaseUrl = "http://image.tmdb.org/t/p/w185"; return async (dispatch, getState) => { try { response = await fetch( `https://api.themoviedb.org/3/search/movie?api_key=${config.TMDB_API_KEY}&query=${MovieTitle}&page=1` ); if (!response.ok) { throw new Error("failed response"); } const resData = await response.json(); console.log("search results: ", resData); const searchedMovies = []; const length = resData.results.length; for (i = 0; i < length; i++) { hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === resData.results[i].id ); searchedMovies.push( new Movie( resData.results[i].id.toString(), resData.results[i].title, posterBaseUrl + resData.results[i].poster_path, resData.results[i].release_date, // getCredits(i).then((cast) => cast), [], resData.results[i].overview, resData.results[i].vote_average, // getLanguageNamefromCode(resData.results[i].original_language), hasUserSaved ? hasUserSaved.location : "" ) ); } dispatch({ type: SEARCH_MOVIES, searched_movies: searchedMovies, }); } catch (err) { console.log(err); } }; }; export const loadMoviesWithGenres = (genreId) => { let response; let hasUserSaved; const posterBaseUrl = "http://image.tmdb.org/t/p/w185"; return async (dispatch, getState) => { await dispatch(clearGenreScreen()); try { response = await fetch( `https://api.themoviedb.org/3/discover/movie?with_genres=${genreId}&api_key=${config.TMDB_API_KEY}` ); if (!response.ok) { throw new Error("failed response"); } const resData = await response.json(); // console.log(resData); const loadedMoviesWRTGenre = []; const length = resData.results.length; for (let i = 0; i < length; i++) { hasUserSaved = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === resData.results[i].id.toString() ); // let cast = getCredits(i).then((cast) => cast) // console.log("CAST", cast); loadedMoviesWRTGenre.push( new Movie( resData.results[i].id.toString(), resData.results[i].title, posterBaseUrl + resData.results[i].poster_path, resData.results[i].release_date, // cast, // getCredits(i), [], resData.results[i].overview, resData.results[i].vote_average, // getLanguageNamefromCode(resData.results[i].original_language), hasUserSaved ? hasUserSaved.location : "" ) ); } console.log("moviesWRTGenre", loadedMoviesWRTGenre); dispatch({ type: LOAD_MOVIES_WITH_GENRES, moviesWRTGenre: loadedMoviesWRTGenre, }); } catch (err) { console.log(err); } }; }; when i am logging the array in the actions file, it shows the perfect result , i.e., loadedTrendingMovies Array [ Movie { "cast": Array [], "id": "385103", "language": "English", "location": "", "plot": "In Scooby-Doo’s greatest adventure yet, see the never-before told story of how lifelong friends Scooby and Shaggy first met and how they joined forces with young detectives Fred, Velma, and Daphne to form the famous Mystery Inc. Now, with hundreds of cases solved, Scooby and the gang face their biggest, toughest mystery ever: an evil plot to unleash the ghost dog Cerberus upon the world. As they race to stop this global “dogpocalypse,” the gang discovers that Scooby has a secret legacy and an epic destiny greater than anyone ever imagined.", "posterUrl": "http://image.tmdb.org/t/p/w185/zG2l9Svw4PTldWJAzC171Y3d6G8.jpg", "ratings": 8.3, "title": "Scoob!", "year": "2020-05-15", }, Movie { "cast": Array [], "id": "79680", "language": "English", "location": "", "plot": "Set more than seven years after the world has become a frozen wasteland, the remnants of humanity inhabit a gigantic, perpetually-moving train that circles the globe as class warfare, social injustice and the politics of survival play out.", "posterUrl": "http://image.tmdb.org/t/p/w185/n6UNHZoiYj81abwmG38HbNjflDx.jpg", "ratings": 3, "title": "Snowpiercer", "year": "2020-05-17", }, Movie { "cast": Array [], "id": "80986", "language": "English", "location": "", "plot": "Courtney Whitmore, a smart, athletic and above all else kind girl, discovers her step-father has a secret; he used to be the sidekick to a superhero. \"Borrowing\" the long-lost hero’s cosmic staff, she becomes the unlikely inspiration for an entirely new generation of superheroes.", "posterUrl": "http://image.tmdb.org/t/p/w185/JJxVsQPPiuLcArALotMHsCubeo.jpg", "ratings": 9, "title": "Stargirl", "year": "2020-05-18", }, Movie { "cast": Array [], "id": "530915", "language": "English", "location": "", "plot": "At the height of the First World War, two young British soldiers must cross enemy territory and deliver a message that will stop a deadly attack on hundreds of soldiers.", "posterUrl": "http://image.tmdb.org/t/p/w185/AuGiPiGMYMkSosOJ3BQjDEAiwtO.jpg", "ratings": 7.9, "title": "1917", "year": "2019-12-25", }, Movie { "cast": Array [], "id": "582596", "language": "English", "location": "", "plot": "A guy meets the woman of his dreams and invites her to his company's corporate retreat, but realizes he sent the invite to the wrong person.", "posterUrl": "http://image.tmdb.org/t/p/w185/A2YlIrzypvhS3vTFMcDkG3xLvac.jpg", "ratings": 6.1, "title": "The Wrong Missy", "year": "2020-05-13", }, ] so i console log in the beginning of the MovieScreen Components (it is the first screen that loads up when my react native app launches) to see if the array is empty movie screen rendered Array [] movie screen rendered Array [] movie screen rendered Array [] movie screen rendered Array [] Also i do not know why did it console logged i.e., re-rendered 4 times , do you have any ideas ? Here is its github repository if you want to check just npm install with expo A: The following should work (please note that this also returns a promise that resolves to an array of movies). const loadedTrendingMovies = await Promise.all( trendingMovies.results .slice(0, 5) // use slice instead of a loop .map((trendingMovie) => // map movie to [language,movie] getLanguageNamefromCode(// get async language trendingMovie.original_language // resolve to [language,movie] ).then((language) => [language, trendingMovie]) ) // sorry, forgot to return here ).then((results) => // results is [[language,movie],[language,movie]] results.map( ([language, trendingMovie]) => new Movie( // create new Movie trendingMovie.id.toString(), trendingMovie.media_type === 'movie' ? trendingMovie.title : trendingMovie.name, posterBaseUrl + trendingMovie.poster_path, trendingMovie.media_type === 'movie' ? trendingMovie.release_date : trendingMovie.first_air_date, [], trendingMovie.overview, trendingMovie.vote_average, language, getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingMovie.id.toString() // if you don't have optional chaining you can get location // first the way you did before )?.location || '' ) ) ); Working example const trendingMovies = { results: [ { original_language: 1, id: 1, }, { original_language: 2, id: 2, }, ], }; const getLanguageNamefromCode = (lang) => Promise.resolve(`language is: ${lang}`); function Movie(id, language, location) { this.id = id; this.language = language; this.location = location; } const getState = () => ({ UserMovies: { userMovies: [{ id: '1', location: 'location 1' }], }, }); Promise.all( trendingMovies.results .slice(0, 5) // use slice instead of a loop .map((trendingMovie) => // map movie to [language,movie] getLanguageNamefromCode( // get async language trendingMovie.original_language // resolve to [language,movie] ).then((language) => [language, trendingMovie]) ) ) .then(( results // results is [[language,movie],[language,movie]] ) => results.map(([language, trendingMovie]) => { const userMovie = getState().UserMovies.userMovies.find( (userMovie) => userMovie.id === trendingMovie.id.toString() // snippet does not have conditional chaining ); return new Movie( // create new Movie trendingMovie.id.toString(), language, userMovie ? userMovie.location : '' ); }) ) .then((movies) => console.log('movies:', movies));
{ "language": "en", "url": "https://stackoverflow.com/questions/61864005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validation Summary vertical alignment I have a two column layout page with a Validation Summary (VS) control above the 2 columns. The VS is centered in the container above the columns, which is what I want, but I also want the different bullet points to be vertically aligned, if possible. I have tried several things, including placing the VS inside a div (inside the container div that is center aligned) with text-align:left;, but that moves the entire div to the side of the container. I have also tried making the div text-align:center; and the VS text-align:left;, but that also moves the entire block all the way to the left. I've also tried the same thing with a table, but no luck. This is in Firefox by the way. I haven't tested in other browsers, but it needs to work in FF. Here is pic to show the messed up vertical alignment: And here is the code for my VS control, without my alignment attempts (if more code is needed, let me know): <div id="container"> <asp:Label ID="lblStatus" runat="server" ForeColor="Red"></asp:Label> <asp:ValidationSummary ID="VS1" runat="server" CssClass="validator" ValidationGroup="theform" /> <div id="leftCol"> Could somebody help me vertically align those bullet points in the center of the page? A: Since bullet points are part of the list items I don't think you will be able to align them. Why not try something like having a top column with 3 divs and place your validationsummary control in the middle one. Try this HTML Code <div id="container" class="container"> <div id="top" class="top"> <div id="topLeft" class="topLeft"> &nbsp; </div> <div id="topMiddle" class="topMiddle"> <asp:ValidationSummary ID="ValidationSummary1" runat="server" /> </div> <div id="topRight" class="topRight"> &nbsp; </div> </div> <div id="bottom" class="bottom"> <div id="bottomLeft" class="bottomLeft"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="input value" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator><br /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Need come input for this" ControlToValidate="TextBox2" Text="*"></asp:RequiredFieldValidator><br /> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> <div id="bottomRight" class="bottomRight"> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="please input text" ControlToValidate="TextBox3" Text="*"></asp:RequiredFieldValidator><br /> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Where is the text?" ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator><br /> <asp:Button ID="Button2" runat="server" Text="Button" /> </div> </div> </div> CSS .container { display: block; width:800px; margin:0px; padding:0px; } .top { display:inline-block; width:800px; } .bottom { display:inline-block; } .topMiddle { display:inline; background-color:Yellow; float:left; width:300px; } .topLeft { display:inline; float:left; width:250px; } .topRight { display:inline; float:left; width:250px; } .bottomLeft { display:inline; width:400px; float:left; background-color:Orange; } .bottomRight { display:inline; width:400px; float:left; background-color:Lime; } A: Try using this one.... <style> .validator ul li { text-align:left; } </style> Edit Set padding left or margin left to ul as you want... .validator ul { padding-left: 100px; } A: Hey you may define your parent text-align left center right according to your design
{ "language": "en", "url": "https://stackoverflow.com/questions/10307817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }