text
stringlengths
15
59.8k
meta
dict
Q: Start Web Service in Solution without Web Reference When I work with a web service in Visual Studio and I'm using a web reference, the WCF web service project is automatically started as soon as I start the client application. Interestingly, this does not change when I remove the web reference. Is there a setting in Visual Studio to get this behaviour, without actually referencing the service? (I'm working with a WebChannelFactory.) A: In the solution's properties, under Common Properties, Startup Project, you can choose Multiple startup projects and select Start as the action for both the service and the consumer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7041773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent drawings to a UIView context from dissappearing? I'd like to create a simple fingerpainting feature in my app. Problem is any drawings I do to my UIView subclass view instance are erased after each drawRect call... How do you go about preserving your context drawings in your UIViews? A: You have to add your drawings to your model and make sure your model is rendered, as appropriate, when the view is invalidated. You do not want to be drawing on the view directly without a model around to re-render it when necessary. Jacob
{ "language": "en", "url": "https://stackoverflow.com/questions/1291869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostgresSQL AND Operator I have a query like the following. SELECT * FROM table WHERE A AND B Where A and B are conditions (B is slower than A). Does anybody know if A and B will be evaluated all the time or if B is only evaluated if A evaluates to 'true'? Many thanks Patrick A: The behaviour, which you desribe is called "Short circuit evaluation". There are already many entries regarding this topic on stackOverflow, e.g. here. But in short: You do not know! See PostgreSQL documentation here. It says: The order of evaluation of subexpressions is not defined. In particular, the inputs of an operator or function are not necessarily evaluated left-to-right or in any other fixed order. Furthermore, if the result of an expression can be determined by evaluating only some parts of it, then other subexpressions might not be evaluated at all. If you continue reading the documentation then you see that it stays consistently vague like this. So summary: In general SQL is declarative, meaning that you can tell the database-framework what you want, but not how you want it to be computed. The system can make freely choices in that regard.
{ "language": "en", "url": "https://stackoverflow.com/questions/73323579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what can be used as an alternative to data.exists Below i am trying to get the value that matches the number input by the user. In the line where there is data.exists, I am getting an error message "The getter 'exists' isn't defined for the type 'DataSnapshot'. (Documentation) Try importing the library that defines 'exists', correcting the name to the name of an existing getter, or defining a getter or field named 'exists" What is the best solution to it or is there any alternative except of using data.exists ? var data = await FirebaseDatabase.instance .reference() .child('Subscribers') .orderByChild('number') .equalTo(numberPhone) .once(); if (!data.exists) { await showDialog( context: context, builder: (_) => AlertDialog( title: Text( 'Sorry!', style: TextStyle(color: Colors.red), ), content: Text( "This Number is already Excite ", style: TextStyle(color: Colors.indigo[900]), ), actions: [ // ignore: deprecated_member_use FlatButton( child: Text('Try Again'), onPressed: () { Navigator.of(context).pop(); }), // ignore: deprecated_member_use ])); return; } Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (c) => OTPController( phoneNumber: _controller.text, codeDigit: dialCodeDigits))); },
{ "language": "en", "url": "https://stackoverflow.com/questions/69556462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get row with className How can you get the first row in a table with a specific className? var rows = $('tr', tbl); A: var rows = $('tr.classname:first', tbl); or var rows = $('tr.classname', tbl).first(); Docs here: http://api.jquery.com/category/selectors/ A: var firstRow = $('tr.classname:first', tbl) A: You can use the :first selector along with the class selector, Try this: var rows = $('tr.someclass:first', tbl); A: var row = $("tr.className:first", tbl); should do the trick. A: If you keep the proprietary :first selector out of it, you'll have a valid querySelectorAll selector. var rows = tbl.find('tr.someClass').slice( 0, 1 ); or var rows = tbl.find('tr.someClass').eq( 0 ); Also, using the context parameter $( selector, context ) is just a slower way of using the find()[docs] method. A: You can even use eq method of jquery if you want to loop through a list of elements. var rows = $('tr.classname'); rows.eq(0);//first row rows.eq(1);//second row
{ "language": "en", "url": "https://stackoverflow.com/questions/6428375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to secure Spring boot management actuator endpoints I am trying to secure the Spring Boot actuactor endpoints. I have working security on my /api REST interface, but trying to add security on the built-in endpoints does not seem to work. I have set up grouping of the endpoints in my application.properties: management.context-path=/management I have this in my Java Config @Override protected void configure( HttpSecurity http ) throws Exception { http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ); http.authorizeRequests() .antMatchers( "/api/**" ).hasRole( "READONLY" ) .antMatchers( "/management/**" ).hasRole( "ADMIN" ); SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityConfigurer = new XAuthTokenConfigurer( userDetailsServiceBean() ); http.apply( securityConfigurer ); } When I use my browser to go to anything below /api, I get a 403 back as expected. When going to /management/info for example, I see the JSON being returned where I would also expect a 403. I also tried adding this to my application.properties file: management.security.role=ADMIN But that did not help either. The DEBUG output shows: 2014-05-02 10:15:30 DEBUG [localhost-startStop-1] ExpressionBasedFilterInvocationSecurityMetadataSource - Adding web access control expression 'hasRole('ROLE_READONLY')', for Ant [pattern='/api/**'] 2014-05-02 10:15:30 DEBUG [localhost-startStop-1] ExpressionBasedFilterInvocationSecurityMetadataSource - Adding web access control expression 'hasRole('ROLE_ADMIN')', for Ant [pattern='/management/**'] And then why I try the HTTP GET: 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] AntPathRequestMatcher - Checking match of request : '/management/info'; against '/css/**' 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] AntPathRequestMatcher - Checking match of request : '/management/info'; against '/js/**' 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] AntPathRequestMatcher - Checking match of request : '/management/info'; against '/images/**' 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] AntPathRequestMatcher - Checking match of request : '/management/info'; against '/**/favicon.ico' 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] AntPathRequestMatcher - Checking match of request : '/management/info'; against '/management/info' 2014-05-02 10:16:39 DEBUG [http-nio-8443-exec-4] FilterChainProxy - /management/info has an empty filter list A: The log that tells the story is: "/management/info has an empty filter list" because it is explicitly marked as ignored (/info is always supposed to be available). Try one of the other actuator endpoints and see if those behave as you expect. If you really need to secure the info endpoint you can set endpoints.info.sensitive=true (I think).
{ "language": "en", "url": "https://stackoverflow.com/questions/23423550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: TypeORM migration with nx-Monorepo Issue I tried this a lot but now I think I need some help. I have a nx-monorepo with angular-frontend and nestjs backend. Now I added a Postgres-SQL database with TypeORM. Everything is working fine, connection to Database is running, api-calls coming in, etc. But I can't add the generate migration script. I added a run-command for my backend-project: "generate-migration": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "ts-node ../../node_modules/.bin/typeorm migration:generate -n", "cwd": "apps/api" } } I can run the command by "npm run api:generate-migration" but it results with this error: Error during migration generation: /apps/api/src/model/base.entity.ts:1 import { __decorate, __metadata } from "tslib"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at wrapSafe (node:internal/modules/cjs/loader:1024:16) at Module._compile (node:internal/modules/cjs/loader:1072:27) at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1056:23) at Module._extensions..js (node:internal/modules/cjs/loader:1137:10) at Object.require.extensions. [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1059:12) at Module.load (node:internal/modules/cjs/loader:973:32) at Function.Module._load (node:internal/modules/cjs/loader:813:14) at Module.require (node:internal/modules/cjs/loader:997:19) at require (node:internal/modules/cjs/helpers:92:18) at /Users/IsabelleGlasmacher/Documents/Programme/save_easytonomy/src/util/DirectoryExportedClassesLoader.ts:41:22 ERROR: Something went wrong in @nrwl/run-commands - Command failed: ts-node ../../node_modules/.bin/typeorm migration:generate -n ormConfig.json: { ... "type": "postgres", "migrationsTableName": "migration", "migrations": ["src/migration/*.ts"], "cli": { "migrationsDir": "src/migration" }, "ssl": false } Does anybody know something about that and could help me? Please :) A: I am able to make a backend service using NX@13, NestJS@8 and TypeORM@0.2, In project.json of game-api , I added some commands like this "generate-migration": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "ts-node --project tsconfig.app.json ../../node_modules/.bin/typeorm migration:generate --pretty -f .env.local", "cwd": "apps/game-api" } }, Code repository: https://github.com/coinconket/conketkemon A: Adding "module": "CommonJS" to compilerOptions in tsconfig.app.json of the related nx app fixed the issue for me. A: Hope this is helpful for some people. For the latest nx@^14 , @nestjs/*@^9 and typeorm@~0.3: in your project.json. Note that "apps/<app-name>" can be applied to "libs/<lib-name>" as well "typeorm": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "ts-node --project tsconfig.json <path-to-node_modules>/typeorm/cli", "cwd": "apps/<app-name>" } }, "mig-gen": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "nx run <app-name>:typeorm migration:generate <path-to-migration>/{args.name} -d <path-to-typeorm-config>/typeorm.config.ts", "cwd": "apps/<app-name>" } }, In your typeorm.config.ts import { DataSource, DataSourceOptions } from 'typeorm'; import { config } from 'dotenv'; import { join } from 'path'; config({ path: '<path-to-env>/.env' }); const { DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_PORT, DB_NAME } = process.env; export default new DataSource({ type: DB_TYPE, host: DB_HOST, port: Number(DB_PORT), username: DB_USER, password: DB_PASS, database: DB_NAME, entities: [join(__dirname, '<path-to-entities>/*.entity.{ts,js}')], migrations: [join(__dirname, '<path-to-migration>/*{.ts,.js}')], synchronize: false, } as DataSourceOptions); in your <path-to-app>/tsconfig.json make sure inside compilerOptions{...}, property "emitDecoratorMetadata": true is set. Properties module,types and target may need to be set as well. See your <root-workspace>/tsconfig.base.json and documentation https://www.typescriptlang.org/tsconfig for reference Finally in your terminal, you can run the command like this to generate your migration file nx run <app-name>:mig-gen --name=whatever-makes-you-happy
{ "language": "en", "url": "https://stackoverflow.com/questions/66302398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can http://localhost:8080/tunnel-web/jsonws be opened on default installation? I have error 404 if open http://localhost:8080/tunnel-web/jsonws on default Liferay installtion. Aren't there any services registered by default? UPDATE My Liferay version is 6.0.6 (Bunyan / Build 6006 / February 17, 2011) A: As of Liferay 6.1 RC, the path has changed to /api/jsonws (from tunnel-web/jsonws). Most (if not all) public services should be registered by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/8665573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I ignore TS1192 when using @types/cleave.js in my angular project? I am using cleave.js (^1.5.2) in an Angular 6 application along with the @types/cleave.js package (^1.4.0) and an odd thing is happening. If I run ng build to build the application it fails with the following errors: ERROR in src/app/app.component.ts(4,8): error TS1192: Module '"C:/Users/evcomes/Angular2/hellogular/node_modules/@types/cleave.js/index"' has no default export. src/app/app.component.ts(5,8): error TS1192: Module '"C:/Users/evcomes/Angular2/hellogular/node_modules/@types/cleave.js/options/index"' has no default export. I see that that is true in the source for @types/cleave.js, but it's just a type library, why would I need a default export? And the really weird part is if I then modify (insignificantly) a file and then save, the automatic rebuild picks that up (still shows the error, but continues), will happily serve the angular app in development, and the cleave.js functionality that I was using even works in my browser. So is this not a real error? How can I turn it off? Any of the tutorials or guides I have seen for using the DefinitelyTyped libraries just say that npm installing them should be sufficient to use them without any other modifications, so most of the issues I find when searching for this are people trying to make their own TypeScript bindings for JS libraries or their own modules in general. In package.json: ... "@types/cleave.js": "^1.4.0", "cleave.js": "^1.5.2" ... In my tsconfig.json: ... "esModuleInterop": true, "typeRoots": [ "node_modules/@types" ] ... In my app.component.ts: ... import Cleave from 'cleave.js'; import CleaveOptions from 'cleave.js/options' ... A: Most js libs that get TS types use either ...* as.... Or require allowSyntheticDefaultImports: true in your tsconfig for default exports to work correctly. import * as CleaveOptions from 'cleave.js/options' // AND import Cleave from 'cleave.js' //tsconfig.json ... { allowSyntheticDefaultImports: true } ...
{ "language": "en", "url": "https://stackoverflow.com/questions/57066151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I figure out which file / gem is monkey patching a method? There is a Gem in my dependency list that is Monkey Patching to_json on String. How can I figure where this monkey patching is happening? A: Use source_location. Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native) $ cat monkey.rb class String def reverse "" end end p String.instance_method(:reverse).source_location $ ruby monkey.rb ["monkey.rb", 2] A: puts String.instance_method(:to_json).source_location
{ "language": "en", "url": "https://stackoverflow.com/questions/13895725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change Connection String After Creating Setup File in C#.NET I am creating a C# windows form applications, the working can be summarized as users fills some form and data is saved in Access database. Now the problem I am facing is that I have to deliver this as a setup file to someone. What I am thinking is that the code once installed on other computers and executed will give errors because of the connection string of Access db, as it will not match with that computer. I know that if a distribute projects I can put connection string in app.config and every user can change it according to his/her machine. But as I am giving a setup file how to solve this problem. A: Suppose you deploy your app.config with this connectionstring "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\yourFile.accdb;" In a WinForms application the |DataDirectory| shortcut represent your application working folder, but you can change at runtime where it points to using this code. // appdomain setup information AppDomain currentDomain = AppDomain.CurrentDomain; //Create or update a value pair for the appdomain currentDomain.SetData("DataDirectory", "Your user choosen path"); It eliminates the need to hard-code the full path which, has you have discovered, leads to several problems to resolve during install. Of course your setup should deliver your database in your user choosen path. A: You can build ConnectionString at run-time by SqlConnectionStringBuilder // Create a new SqlConnectionStringBuilder and // initialize it with a few name/value pairs. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString()); // The input connection string used the // Server key, but the new connection string uses // the well-known Data Source key instead. Console.WriteLine(builder.ConnectionString); // Pass the SqlConnectionStringBuilder an existing // connection string, and you can retrieve and // modify any of the elements. builder.ConnectionString = "server=(local);user id=ab;" + "password= a!Pass113;initial catalog=AdventureWorks"; // Now that the connection string has been parsed, // you can work with individual items. Console.WriteLine(builder.Password); builder.Password = "new@1Password"; builder.AsynchronousProcessing = true; // You can refer to connection keys using strings, // as well. When you use this technique (the default // Item property in Visual Basic, or the indexer in C#), // you can specify any synonym for the connection string key // name. builder["Server"] = "."; builder["Connect Timeout"] = 1000; builder["Trusted_Connection"] = true; Console.WriteLine(builder.ConnectionString); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); Edit: you can use this : Finding SQL Servers on the Network A: I have met this problem before. I solve it in such a way. (1)in your app.config file, put a placeholder in the connection string. the connection string will contains the file path of the access db file. replace the path with a special string. <connectionStrings> <!-- original connection string , change it to the below line --> <!-- <add name="test" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=d:\test\test.mdb "/> --> <add name="test" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=##path##\test.mdb "/> </connectionStrings> (2)when your application start, use Directory.GetCurrentDirectory to get app path. before create a connection, replace the ##path## with the actual path on client computer. static void test() { string s = ConfigurationManager.ConnectionStrings["test"].ConnectionString; s.Replace("##path##", Directory.GetCurrentDirectory()); OleDbConnection conn = new OleDbConnection(s); } A: In case of deploying the application, along with SQLLocalDB, the user (machine\user) should be added in your database to have access.
{ "language": "en", "url": "https://stackoverflow.com/questions/11028468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to center UILabel text top and bottom spaces I have a UILabel in a stackview in a content view that is in a tableview cell. Everything is working correctly and the cell is resizing but i cannot center the text in the UILabel. I always have strange spaces in the bottom of the text. Check out screen shot. Yellow: content view Green: stackview Blue: label Additional info: No static height for cells. The yellow view has top bottom and trailing and leading constraints plus horizontal and vertical aligned to super view same thing the stack view. The only thing that has constant height which I activate and deactivate through code is the button. So it hides and shows according to the cell. Stackview is fill proportionally. The UILabel is sizeToFit Also tried: detailLbl.textAlignment = .center detailLbl.lineBreakMode = .byWordWrapping //also tried byClipping detailLbl.baselineAdjustment = .alignCenters The text inside i parse as HTML "<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>" Second screenshot "<h6 lang=\"en\" style=\"color=#cd1719 !important; font-weight: normal !important\"><font color=\"#cd1719\" weight=\"normal\"><i>The alleluia is said or sung.</i></font></h6>" This is an NSAttributedString extension I use for parsing HTML extension NSAttributedString { convenience init(htmlString html: String, font: UIFont? = nil, useDocumentFontSize: Bool = true) throws { let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] let data = html.data(using: .utf8, allowLossyConversion: true) guard (data != nil), let fontFamily = font?.familyName, let attr = try? NSMutableAttributedString(data: data!, options: options, documentAttributes: nil) else { try self.init(data: data ?? Data(html.utf8), options: options, documentAttributes: nil) return } let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize let range = NSRange(location: 0, length: attr.length) attr.enumerateAttribute(.font, in: range, options: .longestEffectiveRangeNotRequired) { attrib, range, _ in if let htmlFont = attrib as? UIFont { let traits = htmlFont.fontDescriptor.symbolicTraits var descrip = htmlFont.fontDescriptor.withFamily(fontFamily) if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitBold.rawValue) != 0 { descrip = descrip.withSymbolicTraits(.traitBold)! } if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitItalic.rawValue) != 0 { descrip = descrip.withSymbolicTraits(.traitItalic)! } attr.addAttribute(.font, value: UIFont(descriptor: descrip, size: fontSize ?? htmlFont.pointSize), range: range) } } self.init(attributedString: attr) } } And this is how I use it in the code if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: CGFloat(Constants.defualtContentDescriptionFontSize)), useDocumentFontSize: false) { cell.detailLbl.attributedText = attributedString } A: Part of the problem is that you are using formatted html text, which includes the "extra space." For example, your first html text line includes <p> </p> tags. This code creates two green-background labels, each the same width, each with no height constraint: class ViewController: UIViewController, UIScrollViewDelegate { override func viewDidLoad() { super.viewDidLoad() let firstLabel = UILabel() firstLabel.backgroundColor = .green firstLabel.numberOfLines = 0 firstLabel.translatesAutoresizingMaskIntoConstraints = false let secondLabel = UILabel() secondLabel.backgroundColor = .green secondLabel.numberOfLines = 0 secondLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstLabel) view.addSubview(secondLabel) let g = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ // first label 40-pts from top, 20-pts on each side firstLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0), firstLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0), firstLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0), // second label 40-pts from bottom of first label, 20-pts on each side secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 40.0), secondLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0), secondLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0), ]) var htmlTxt = "<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>" if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: 24.0), useDocumentFontSize: false) { firstLabel.attributedText = attributedString //cell.detailLbl.attributedText = attributedString } htmlTxt = "<font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b>" if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: 24.0), useDocumentFontSize: false) { secondLabel.attributedText = attributedString //cell.detailLbl.attributedText = attributedString } } } The output: The difference between the two? For the second label, I removed the <p> </p> tags before processing the html with your extension. Your second html text defines it as h6 ... here's the output with that string: Again, the difference between the two is that I removed the h6 tag before processing the html. You'll probably need to modify your extension to remove the paragraph tags, or set a paragraph style that would ignore them.
{ "language": "en", "url": "https://stackoverflow.com/questions/64427880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sending "/" in Meteor http param This Meteor server code attempts to use the HTTP package to send a POST request with the params object containing date value as below orderDate: '03/06/2016' let params = {}; const d = new Date(); params.action = 'submit'; let day = d.getDate(); day = day < 9 ? '0' + day : day; let month = d.getMonth() + 1; month = month < 9 ? '0' + month : month; params.orderDate = day + "/" + month + "/" + d.getFullYear(); HTTP.call('POST','someurl',{headers: {headerObj}, params: {paramsObj}}; How can this "/" be encoded before sending to the remote server as it is responding with content-length: 0? Thanks A: In another technology, I found it easier to have your date sent as ISO format (YYYY-MM-DD), unless you specifically need to have day, month and year received as parameters A: Fixed by changed params.orderDate = day + "/" + month + "/" + d.getFullYear(); to: params.orderDate = moment().format('MM/DD/YYYY'); Since the HTTP docs applies application/x-www-form-urlencoded to the request params, and the two above expressions console.log(d) the same value, that leaves me guessing that the javascript compiler does not treat the output of both expressions the same, maybe in their data types. If this is the case, how can this issue be best handled when it comes to sending other non alphanumeric characters collected from the client via jQuery..serializeArray() and ends up in the HTTP POST request params to a remote server?
{ "language": "en", "url": "https://stackoverflow.com/questions/37608357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elastic Search nested multimatch query So my problem is basically the same as described here, however it still remains unanswered on the group. My mapping: { "abstract": { "properties": { "summary": { "type": "string" } } }, "authors": { "type": "nested", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" } } } } And I would like to perform a full-text search on both of these fields, probably unequally weighted. The query that comes to my mind, but unfortunately doesn't work, would be this: { "query": { "bool": { "should": [{ "multi_match": { "query": "higgs boson", "fields": ["abstract.summary^5", "author.last_name^2"] } }] } } } I don't get any results from the authors field, because of its nested mapping. I also can't get rid of the nested property - I use it for aggregations. Any elegant idea how to solve it? A: The only solution that I managed to work out, which is not handy nor elegant but somehow works is such query: "query": { "bool": { "should": [ { "nested": { "path": "authors", "query": { "multi_match": { "query": "higgs", "fields": ["last_name^2"] } } } }, { "multi_match": { "query": "higgs", "fields": ["abstract.summary^5"] } } ] } } I'm also not sure if the boosting will work as expected, providing it's set in different queries. Any suggestions appreciated. A: Changing your mapping to the following one which uses include_in_root: true will allow you to use the query you original wrote: { "abstract": { "properties": { "summary": { "type": "string" } } }, "authors": { "type": "nested", "include_in_root": true, "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" } } } } You may want to index inner objects both as nested fields and as flattened object fields. This can be achieved by setting include_in_parent to true. - Link Note: include_in_root may be deprecated in future versions of elasticsearch in favor of copy_to.
{ "language": "en", "url": "https://stackoverflow.com/questions/31829654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Is It Worthwhile To Have a Table That Only References Columns From Parent Table I currently have a database for trading cards and the main table is AllCards. This table has twenty columns and has over millions of rows, but my question regards towards the column boolean type isSold in AllCards. Whenever a user loads our site, a query like “select someColumns from AllCards where isSold = False” is done to show all the available cards. However, I was wondering if it would be better to have a separate table labelled historic and current to not query millions of rows. My backend code will place cards that are not sold yet to Current and once sold, delete that row in Current and move that row to Historic. Table Historic Uid INT, HCardID INT, FOREIGN KEY Uid REFERENCES User(id), FOREIGN KEY HCardID REFERENCES AllCards(cardID) Table Current Uid INT, CCardID INT, FOREIGN KEY Uid REFERENCES User(id), FOREIGN KEY CCardID REFERENCES AllCards(cardID) As shown above, Historic contains IDs to AllCards that have been sold and Current contains IDs to AllCards that have not been sold yet. Thus, when a user loads our site, I can just do a join query on table Current and iterate table AllCards where CardID = CCardID, instead of having to query through all rows of table All Events and check if it was sold or not. Is this a valid approach for performance and organization, or should I just forget about it, and only have an AllCards table and use the columns isSold? On the same topic, I also have implemented a table Week, a table with all the cards bought this week from a user. For this table I also do the approach of Table Week Uid INT, WCardID INT, FOREIGN KEY Uid REFERENCES User(id), FOREIGN KEY WCardID REFERENCES AllCards(cardID) This way, I do not have to query millions of rows to find cards that the user has bought this week and instead can do a join from Table Week and AllCards where cardID = WCardID and Uid = Uid. Does this help performance and organization and is this approach even worthwhile? Or should I just do go through rows in AllCards and do a query to get the same data for cards bough this week by the user? A: The week table should not exist. Instead, have a datetime in AllCards and index it. It is probably slower to go back and forth between Current and AllCards than to simply scan the entire AllCards. Ditto for History. Anyway, both are equivalent to having a pair of indexes on the big table. I assume there is some column that distinguishes a "current" entity from a "history" entry in AllCards? If the same "card" shows up again each time it is traded, then you might need a table of Cards (with 'card'-related columns) and a table of Trades (with trade related columns. Trades would probably have UId and CCardId columns and the TradeDate, but Cards would not. TradeDate would definitely be indexed, so you can get the week's trades efficiently.
{ "language": "en", "url": "https://stackoverflow.com/questions/74494741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Linux SGX enclave with OpenSSL I saw on the Intel website here that there is an OpenSSL library available for SGX but only on Windows. Does anyone know if there is also such an extension for Linux SGX SDK? A: Linux SGX SSL Crypto Lib has now been open sourced and it's available here: https://github.com/01org/intel-sgx-ssl A: I found an alternative solution to OpenSSL namely mbedtls here. It is available for Linux and Windows and the compiled libraries only need to be linked against the application and enclave. A: TaLoS is a TLS library that allows existing applications (with an OpenSSL/LibreSSL interface) to securely terminate their TLS connection inside an Intel SGX enclave. The code is available on GitHub. There also is a technical report containing details about the architecture and performance results.
{ "language": "en", "url": "https://stackoverflow.com/questions/41685134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to parallelize a function which is column bound? I have a function, which does some operations on each DataFrame column and extracts a shorter series from it (in the original code there is some time consuming calculations going on) Then it adds it to a dictionary before it goes on with the next columns. In the end it creates a dataframe from the dictionary and manipulates its index. How can I parallelize the loop in which each column is manipulated? This is a less complicated reproducable sample of the code. import pandas as pd raw_df = pd.DataFrame({"A":[ 1.1 ]*100000, "B":[ 2.2 ]*100000, "C":[ 3.3 ]*100000}) def preprocess_columns(raw_df, ): df = {} width = 137 for name in raw_df.columns: ''' Note: the operations in this loop do not have a deep sense and are just for illustration of the function preprocess_columns. In the original code there are ~ 50 lines of list comprehensions etc. ''' # 3. do some column operations. (actually theres more than just this operation) seriesF = raw_df[[name]].dropna() afterDropping_indices = seriesF.index.copy(deep=True) list_ = list(raw_df[name])[width:] df[name]=pd.Series(list_.copy(), index=afterDropping_indices[width:]) # create df from dict and reindex df=pd.concat(df,axis=1) df=df.reindex(df.index[::-1]) return df raw_df = preprocess_columns(raw_df ) A: Maybe you can use this: https://github.com/xieqihui/pandas-multiprocess pip install pandas-multiprocess from pandas_multiprocess import multi_process args = {'width': 137} result = multi_process(func=func, data=df, num_process=8, **args)
{ "language": "en", "url": "https://stackoverflow.com/questions/63877964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Typescript force generic type to be an object I am trying to create a generic function with generic types that must be of a particular object type, not just any object. Specifically, I am trying to create a wrapper around the AWS Lambda handler function with well defined types for the request and response headers bodies. Here is the best solution I have been able to find so far: import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; export type AsyncHandler = (event: APIGatewayProxyEvent, context: Context) => Promise<APIGatewayProxyResult>; interface EmptyInterface { _?: string; } export type RequestQueryParameters = EmptyInterface; export type RequestHeaders = EmptyInterface; export type RequestBody = EmptyInterface; export interface Request<Q extends RequestQueryParameters, H extends RequestHeaders, B extends RequestBody> { queryParameters: Q; headers: H; body?: B; } export type ResponseHeaders = EmptyInterface; export type ResponseBody = EmptyInterface; export interface Response<H extends ResponseHeaders, B extends ResponseBody> { statusCode: number; headers?: H; body: B; } export function createHandler<Q, H, B, RH, RB>(main: (request: Request<Q, H, B>) => Promise<Response<RH, RB>>): AsyncHandler { return async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => { const response = await main({ queryParameters: (event.queryStringParameters as unknown) as Q, headers: (event.headers as unknown) as H, body: event.body ? (JSON.parse(event.body) as B) : undefined, }); return { statusCode: response.statusCode, headers: response.headers as Record<string, string> | undefined, body: JSON.stringify(response.body), }; }; } And here would be an example usage: interface TestRequestQueryParameters extends RequestQueryParameters { a: string; } interface TestRequestHeaders extends RequestHeaders { b: string; } interface TestRequestBody extends RequestBody { c: string; d?: string; e: number; } interface TestResponseHeaders extends ResponseHeaders { f: string; } interface TestResponseBody extends ResponseBody { g: string; h?: string; i: number; } const main = async ( request: Request<TestRequestQueryParameters, TestRequestHeaders, TestRequestBody>, ): Promise<Response<TestResponseHeaders, TestResponseBody>> => { console.log(request.queryParameters.a); console.log(request.headers.b); console.log(request.body.c); console.log(request.body.d); console.log(request.body.e); return { statusCode: 200, headers: { f: 'test', }, body: { g: 'test', h: 'test', i: 100, }, }; }; export const handler = createHandler(main); The problems with this approach are: * *I can't enforce that the query parameters and headers are strings. *All of the methods have a dangling _ prop. Any suggestions on how to improve this? Is there an existing library for wrapping AWS Lambda handlers? Edit: With the help of @jcalz, I have improved the code by using Q extends Record<keyof Q, string | undefined>. But there are still two things I would like to improve: * *The type definition for createHandler has become very verbose. Is there a way to simplify it? *I can't have optional fields (e.g. b?: string) in the input/output interfaces. I can get around this by doing b: string | undefined. But is there a way I can do b?: string? Here is the updated example code: https://tsplay.dev/WkvlDm A: For types where you want to allow anything whatsoever as long as it is an object and not a primitive, you can use the object type. This should be the case for your B-like type parameters, whose values you have (in your tsplay link at the bottom) only constrained to any | undefined (which is just any, by the way). For types where you want to make sure that the values are constrained to string or undefined, and you want to support optional properties, I'd create a type alias like this: type OptStrDict<T> = { [K in keyof T]?: string } You will use it to recursively constrain your type parameters like T extends OptStrDict<T>. So your Request interface becomes, for example: export interface Request< Q extends OptStrDict<Q>, H extends OptStrDict<H>, B extends object > { queryParameters: Q; headers: H; body?: B; } I will dispense with writing out the full version of your code with these changes, but you can verify that this works via the Playground link below. Note that re-use of the OptStrDict type alias will reduce verbosity of your code, especially if you shorten it to OSD or something. If you think that createHandler()'s type signature is still too wordy after this, I'm not sure how best to proceed; pragmatically speaking, having five constrained generic type parameters is going to take up some space no matter what you do. ‍♂️ Playground link to code
{ "language": "en", "url": "https://stackoverflow.com/questions/66956479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Single instance app with message passing via cmd line? I have a C# app that is launched via command line. Usually data is pass through the command line such as add (app -a string). I would like only ONE instance of the app to be opened and if more strings are added via command line i would like the single instance to know about it and update itself. I can either put the data into the database properly and msg the running instance or msg and pass the data to the running instance and let it put it in the db and update itself. How would i do this in C# .NET? (3.5) A: The first instance of the application should create a named pipe, subsequent instances of the application would fail to create the same named pipe and should instead attempt to open the named pipe for use. Once opened, the string (or really any data) can be transferred to the already running instance of the app. The named pipe can then be closed and the app could exit. Alternatively, you could use .NET Remoting and register a well-known type that other instances of the application could activate, with behavior similar to what is described above. Ultimately, a quick search on "IPC" or "Inter-Process Communication" may open up other alternatives. But I believe the named pipe approach is the cleanest and would be the easiest to implement/extend. For "first-run" detection you can also create a named mutex, in case you opt for an IPC mechanism that doesn't exhibit a failure condition on multiple-runs (for example, using a database as a middle-man for data share). No two processed can "Create" a mutex with the same name, this is the same constraint as with Named pipes, as these names are managed by the Kernel (and thus span process, session, desktop and window station boundaries.)
{ "language": "en", "url": "https://stackoverflow.com/questions/1685005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS Help Please! CSS nested elements deactivating links I’m having a problem with my links becoming deactive within some nested elements. I followed some instruction on creating rounded corner boxes via a tutorial by Andy Budd. Anyway, it all works great except when I wrap link tags around a few pieces of copy. I’m a bit of a beginner still so maybe this is a simple fix but I’ve spent over a days worth of time now trying to figure it out on my own and can’t seem to get it. Just to clear this up, the links work everywhere on the page outside of the “box” element I’ll list below and I’ve double and triple checked that the link within the “box” element is written correctly and it is. The CSS even finds the link and styles it correctly, however, the mouse function seems to be disabled. Does this all make sense? Below is the CSS, any help would be greatly appreciated… This is the code that creates the box and it works correctly… .box { width:831px; background:url(../imgs/box-spacer.gif) repeat-y; } .box h1 { background:url(../imgs/box-top.gif) no-repeat left top; padding-top:40px; font-weight: normal; } .box .last { background:url(../imgs/box-bottom.gif) no-repeat left bottom; padding-bottom:60px; } .box h1, .box p { padding-left:60px; padding-right:60px; } And this is the code I used to test that the page is seeing it as a link… .box h1 a:link { color:#00CCFF; } .box h1 a:hover { color: #FF0066; } It changes the color correctly but the hover doesn’t work and if you click, it doesn’t link you anywhere. Again, the link is written correctly on the page. Can anyone help please? I appreciate it. Also, the website is up at http://www.fiddlergroup.com/zygote if it helps. The particular page I was using for testing is the “what’s in a name” page. As you’ll see, all the code and pages and what not is all very simple, just can’t seem to figure out how to fix this one odd issue. A: The problem is with z-index: -100 on your #holder element. Click events are ending on the body element and not making it down through to the link. Remove the negative z-index and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/1773132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A clean way for an action to fire multiple asynchronous actions with createAsyncThunk We're delaying the rendering of our React-Redux web app until several asynchronous app initialization tasks in the Redux store have been completed. Here's the code that sets up the store and then fires off the initialization action: export const setupStoreAsync = () => { return new Promise((resolve, reject) => { const store = setupStore() store .dispatch(fetchAppInitialization()) .then(unwrapResult) .then(_ => resolve(store)) .catch(e => reject(e.message)) }) } The promise rejection is very important since it's used to render an error message for the user in case the app cannot be properly set up. This code is very nice to read and works wonderfully. The issue is with the action creator: export const fetchAppInitialization = createAsyncThunk( 'app/initialization', (_, thunkApi) => new Promise((resolve, reject) => Promise.all([thunkApi.dispatch(fetchVersionInfo())]).then(results => { results.map(result => result.action.error && reject(result.error)) }) ) ) This code works beautifully. If any of these actions fail, the promise is rejected and the user sees an error message. But it's ugly - It's not as pretty as our normal action creators: export const fetchVersionInfo = createAction('system/versionInfo', _ => ({ payload: { request: { url: `/system/versionInfo` }, }, })) We will at some point fire more than one fetch request in fetchAppInitialization, so the Promise.all function is definitely required. We'd love to be able to use Redux-Toolkit's createAction syntax to fire multiple promisified actions in order to shorten this action creator, but I have no idea if that's even possible. Note: I'm using redux-requests to handle my axios requests. Is createAsyncThunk even required? A: Since I wasn't using the fetchAppInitialization action for anything but this single use case, I've simply removed it and moved the logic straight into the setupStoreAsync function. This is a bit more compact. It's not optimal, since the results.map logic is still included, but at least we don't use createAsyncThunk any more. export const setupStoreAsync = () => { return new Promise((resolve, reject) => { const store = setupStore() new Promise((resolve, reject) => Promise.all([store.dispatch(fetchVersionInfo())]).then(results => { results.map(result => result.action.error && reject(result.error)) resolve() }) ) .then(_ => resolve(store)) .catch(e => reject(e.message)) }) } Update: I was able to make the code even prettier by using async/await. export const setupStoreAsync = async () => { const store = setupStore() const results = await Promise.all([store.dispatch(fetchVersionInfo())]) results.forEach(result => { if (result.action.error) throw result.error }) return store }
{ "language": "en", "url": "https://stackoverflow.com/questions/63595307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to edit /etc/hosts file to open angularjs springboot project in specific website address I have an angularJS application with springboot and it runs on 8090 port number with "index.htm" file. Like below ; 192.168.1.25:8090/index.htm I just googled about the changing port and I did the change with 80 port number so I can open the web page with 192.168.1.25/index.htm But, in google there are plenty of angular result and they tell me to change those settings with in angular.json file. I created a temporary angular project and did those with successfully. But, I could not figure out about the angularjs part. I checked the project and I could not find any file like angular.json. After that checking the springboot, I found this part of where I can open the web page with the above second URL address ; 192.168.1.25/index.htm The code of Spring Boot part is below (There is where I can change the port number) : Those ones did the trick by the way. config.getMemberAttributeConfig().setStringAttribute(ServerService.MANAGEMENT_URL_PREFIX, ":80/index.htm"); config.getMemberAttributeConfig().setStringAttribute(ServerService.MANAGEMENT_URL_PREFIX, ":80"); After those steps, I can easily serve my angularjs app on 80 port and start to thinking about editing the /etc/hosts file on the server machine as : 192.168.1.25/index.htm xyz.com I did reboot when I finished the editing part and I tried again to write xyz.com on firefox browser it does not go to my application. I am still looking on the google and still could not find any solutions about this problem. Any help will be really appreciated. A: Format for hosts file is #<ip> <hostname that resolve to the ip> 192.168.1.25 xyz.com # or a list of names 192.168.1.25 xyz.com myapp.xyz.com You do not put any port numbers or path parts in it. This will obviously only work if you edit the hosts file on all the computers you are indending to access the site from and not necessarily on the host running the application itself. That being said, you should probably read on supported Spring Boot properties because starting an application server on a specific port should be as easy as adding application.properties file in java resources with the following line: server.port=80
{ "language": "en", "url": "https://stackoverflow.com/questions/69588913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pfSense Traffic Shaping - distribute bandwidth evenly I am trying to distribute traffic evenly per IP on the network. I have seen an implementation of this using monowall with a simple check-box for distributing bandwidth evenly, but since monowall is discontinued I am resorting to pfSense or Opnsense. With pfSense it doesn't seem to be working properly and there is a latency when applying firewall rules to do the job. Also Opnsense is very similar to pfSense since it is a fork of it so I don't see a working solution. Does anyone know how this can be done using pfSense or Opnsense? A: You can use the Firewall > Traffic Shaper > Wizards option to do this. I don't recommend dedicating even bandwidth to each user since they don't use the connection at the same time constantly wherein if a user is idle then you are wasting bandwidth at their idle time. Managing priorities on protocols and applications while penalizing abusers is enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/48920524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can android animation change view's size is it possible that change the image size by animation? what I want to achieve is I have an imageView,and I want to use an animation to resize it.make it bigger ,like I set it 200dip in xml file,after the animation it become 500dip.is that possible?what methods should I use exactly?any help and guideness will be highly appeciate.thank you:D. or can realize this effect. EDIT: I think I need to make it more clear,I have a screen 800dip.and two view ,first is 200dip,another is 600dip.so the second size is calculate by screen size - first size,and I wonder if I change the first imageView size to 600dip by animation,and of course the second imageView become 200 automatic,could that happen? A: Your animation changes view hierarchi params so you should apply new layout params (lp) to ImageView. Create custom animation which will apply new lp to ImageView setting different width/height on every frame. So your image view will increase it's size and move other views. There are a lot examples how to implement this. Take a look at this one. @Override protected void applyTransformation(float interpolatedTime, Transformation t) { android.view.ViewGroup.LayoutParams lp = mContent.getLayoutParams(); lp.height = (int) (mStartHeight + mDeltaHeight * interpolatedTime); mContent.setLayoutParams(lp); }
{ "language": "en", "url": "https://stackoverflow.com/questions/14454710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ImageMagick 7.0.7-34 installation gives "undefined reference to `PNGSetExifProfile'" I'm trying to install ImageMagick 7.0.7-34 on a ubuntu 16.04, I'm using wget to download the latest version (7.0.7-34) from here http://www.imagemagick.org/download/ImageMagick.tar.gz, then after extracting the tar, I'm running the following inside the extracted folder: sudo ./configure --with-pango sudo make which gives the following error: make all-am make[1]: Entering directory '/usr/local/sources/ImageMagick-7.0.7-34' CCLD utilities/magick MagickCore/.libs/libMagickCore-7.Q16HDRI.so: undefined reference to `PNGSetExifProfile' collect2: error: ld returned 1 exit status Makefile:7042: recipe for target 'utilities/magick' failed make[1]: *** [utilities/magick] Error 1 make[1]: Leaving directory '/usr/local/sources/ImageMagick-7.0.7-34' Makefile:5178: recipe for target 'all' failed make: *** [all] Error 2 I've searched but found nothing concerning this error!, anyone knows how to fix this? --Update-- A similar issue was opened on ImageMagick's github repo, just an hour ago A: This was a mistake we made when adding support for the PNG eXIf chunk. This will be resolved in ImageMagick 7.0.7-35. If you upgrade your libpng library you can also fix the build. You will need a version of libpng that has PNG_READ_eXIf_SUPPORTED defined. p.s. Next time it will be better to create an issue here: https://github.com/ImageMagick/ImageMagick/issues. You will get a much faster response.
{ "language": "en", "url": "https://stackoverflow.com/questions/50449289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: selecting multiple dates in a calendar i need to add checkboxes to every cell in the calendar so that the user can select multiple dates and the dates get stored in the database for later retrieval. basically i am developing a calendar as a signup sheet for day shift and night shift. so i need 2 checkboxes per calendar date in the calendar. is it possible. i am using Visual studio and c sharp A: Is your question whether or not this is possible? Then the answer is "Yes!" -- What else would you like to know? Are there any details to your question? Specific areas you would like to concentrate on? Areas that are causing you problems? Or are you simply looking for a full solution?
{ "language": "en", "url": "https://stackoverflow.com/questions/1976529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple action contexts in Zend I am new to Zend and am working on a project that requires three contexts for a particular action. There is the standard context that will normally be used, an AJAX context for AJAX calls, and finally a print-friendly context. The goal is for each of these to have their own view, so the view files used would be something like: /action_name.phtml /action_name.ajax.phtml /action_name.print.phtml I read http://framework.zend.com/manual/en/zend.controller.actionhelpers.html and came up with: public function init() { // add any necessary context switching here $contextSwitch = $this->_helper->getHelper('AjaxContext'); $contextSwitch->addActionContext('history', 'html') ->initContext(); //need to add another context for the print view $this->_helper->getHelper('contextSwitch')->addActionContext('history','print')->initContext(); } The first two lines I am convinced works, but I am not sure if I am going about the print context the right way, since in the examples the second parameter is normally a file type, like JSON, XML, HTML, etc. Am I going about things the right way or is there something else I should be doing? A: It's everything in the documentation. If you want custom contexts, you have to add them first: $this->_helper ->getHelper('contextSwitch') ->addContext('print', array( // context options go here )) ->addActionContext('history', 'print') // more addActionContext()s goes here ->initContext(); A: What you might do instead of using a context for the print view is just have a parameter in the URL like /print/1. Then in the controller action, check to see if that parameter is true, and if it is, render the "print" view script instead of the regular view script.
{ "language": "en", "url": "https://stackoverflow.com/questions/6220310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to select a single input value among multiple inputs? I have a number of inputs with an select button for each to allow the user to select a coupon code. This is what I have, which has the desired result: <!-- code 1 --> <input id="code1" type="text" value="codeval1" disabled /> <button id="btn1">Select</button> <br> <!-- code 2 --> <input id="code2" type="text" value="codeval2" disabled /> <button id="btn2">Select</button> <input id="text" value="" type="text"></input> <button id="clear" >clear selection</button> And the script: $("#clear").on("click", function() { var text = $('#text'); text.val(""); }); $('#btn1').on('click', function(){ var text = $('#text'); var code = $('#code1'); text.val(code.val()); }); $('#btn2').on('click', function(){ var text = $('#text'); var code = $('#code2'); text.val(code.val()); }); Is there an easier way of doing this without having to re-write the function for every input/button ID? A: You can do everything with a single (anonymous) function, as demonstrated below: $("body").on("click","button",function() { with ($(this)) $('#text').val(hasClass('sel')? prev('input').val():'') }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- code 1 --> <input id="code1" type="text" value="codeval1" disabled /> <button class="sel">Select</button> <br> <!-- code 2 --> <input id="code2" type="text" value="codeval2" disabled /> <button class="sel">Select</button> <input id="text" value="" type="text"></input> <button class="clear" >clear selection</button> I simply test, whether the class sel exists for the clicked button ($(this)) and then copy the value of the previous input field to the target. Otherwise I place an empty string into the target. My event binding is done on the <body> of your page so potentially all buttons will have this functionality. In a real example you would restrict the scope to a container (<div> or <form>) in which all buttons will have this functionality. A: Simple solution $('.sel').on('click', function(){ var value= $(this).prev('input').val(); $('#text').val(value); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- code 1 --> <input id="code1" type="text" value="codeval1" disabled /> <button class="sel">Select</button> <br> <!-- code 2 --> <input id="code2" type="text" value="codeval2" disabled /> <button class="sel">Select</button> <input id="text" value="" type="text"></input> <button class="clear" >clear selection</button>
{ "language": "en", "url": "https://stackoverflow.com/questions/57705684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep max checkpoints with some criteria? I'm trying to keep only a number of checkpoints in TensorFlow during training because of the disk limit. CheckpointManager has a max_to_keep argument, but by default, it keeps the newest checkpoints. Is there a way to keep a limited number of checkpoints according to some criteria, say the validation loss, easily in TensorFlow? Surely I can write the code myself, but it would be good to make the use of CheckpointManager, and just in case there's anything written already that I've neglected. P.S. I noticed the ModelCheckpoint but my model is not of type tf.keras.models.Model so, unfortunately, cannot make use of that feature. A: ModelCheckpoint is a Callback subclass. You can modify the source code to adapt it to your use case. In particular, you can focus on the constructor and the _save_model method. This can be used as a starting point to write your own code.
{ "language": "en", "url": "https://stackoverflow.com/questions/72296749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recoding numeric variables classified as vectors I am having trouble recoding a four point variable that I want to use for an index. When I try using the recode command I get the error message that the command cannot be applied to the class the variable cases belong to. Is there a package to get around this or a way to change the column's class? df$v1 <- recode(df$v1, '1'=4, '2'=3, '3'=2, '4'=1) df <- mutate(df, v1_recode = recode(v1, "1" = 4, "2" = 3, "3" = 2, "4"=1)) Error in UseMethod("recode") : no applicable method for 'recode' applied to an object of class "c('haven_labelled', 'vctrs_vctr', 'double')" A: An alternative way to achieve that would be this: df <- mutate(df, v1_recode =case_when(v1 == "1" ~ 4, v1 == "2" ~ 3, v1 == "3" ~ 2, v1 == "4" ~ 1, TRUE ~ v1))
{ "language": "en", "url": "https://stackoverflow.com/questions/72296887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Variable return as nil I'm confused by this error. I'm writing a lua script for mocp to display info in conky. When I play music files in "/media/Stuff/old-music" everything works fine but I get an error when I play music files in "/home/tony/Music". None of the directories are hard coded in my script. The error says a variable is returned as nil. I check and the music file has the required info. Why am I getting this error? error.. Conky: llua_do_call: function conky_main execution failed: /home/tony/.conky/lua-test/albumart.lua:68: attempt to concatenate global 'album' (a nil value) code... .... totaltime,totaltimesecs,song,artist,album,albumart=newsong(update_num) .... function newsong() local f = io.popen("mocp -Q %album") album= f:read("*a") f:close() album=string.gsub(album,"[\n]","") local f = io.popen("mocp -Q %artist") artist= f:read("*a") f:close() artist=string.gsub(artist,"[\n]","") local f = io.popen("mocp -Q %song") song= f:read("*a") f:close() song=string.gsub(song,"[\n]","") local f = io.popen("mocp -Q %tt") totaltime= f:read("*a") f:close() totaltime=string.gsub(totaltime,"[\n]","") local f = io.popen("mocp -Q %ts") totaltimesecs= f:read("*a") f:close() totaltime=string.gsub(totaltime,"[\n]","") return totaltime,totaltimesecs,song,artist,album,albumart A: The code you have written seems unrelated to the actual error code. The error code specifically describes this problem: .../albumart.lua:68: attempt to concatenate global 'album' (a nil value) This means that you are trying to concatenate the album variable using the concatenate operator .., and it's value happens to be nil. The code you have written suggests that this should not be the case (even though you may want to try make all the variables in the function local). Please take a look at line 68 in your file to find the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/9142318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse inserts a new line in android xml files I have an Android xml file which contains something like: <!-- foto with border --> <LinearLayout android:id="@+id/ll_border_black" android:padding="1dp" > When I remove the blank line between the comment and the LinearLayout and then I do code formatting by Strg + Shift + F or Strg + I the empty line gets inserted again. I tried to fix this by Settings -> XML -> XML Files -> Editor by new settings like "Split multiple attributes each on a new line". I had no success. A: By default, XML files in Android project will use a custom XML formatter intended for XML files (so it for example has different policies for whether attributes appear on separate lines and blank lines between elements depending on which type of resource file you're editing -- values, layouts, manifests, etc.) You can edit these preferences under Preferences > Android > Editors. If you want to use the default XML editor instead (which uses the settings path pointed to by others in this thread) you can also go to that preference page and turn off the custom formatter. A: If you're using android xml editor check: Window > Preferences > Android > Editors > Always remove empty lines between elements A: set enable Window -> Preference -> XML Files ->Editor ->Clear all blank lines And than use code formatting A: The Android layout editor has its own formatter. Perhaps it has its own preference page?
{ "language": "en", "url": "https://stackoverflow.com/questions/9890333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding a Core Data entity's property values I have a Core Data entity with four boolean non-optional properties, defaulted to NO. A class gets the entity object when the class is initialized, so this is not a result of an NSFetchResquest, and one of these four properties will be set to YES. The class needs to know which property is YES. Of course, I can use nested IF/Else statements (or ternaries) to find out which property is YES, but I'm wondering if there is a better (meaning more cocoa-ish) way to look at the entity and say 'is there a boolean value YES in your properties?'. also, i can remodel to have the booleans have no value as default, and only look for the boolean that has YES, but that seems the same question. A: Well there are several different possibilities. Using four different boolean properties is a clean solution. You then have to use the if ... elsif statements to find out what happened. A more C way of doing that would be to define bitmasks which can be OR'ed together and stored as an NSUInteger. If this would semantically makes sense you could group them together in an enum, but that is the C way. You could also define a custom subclass of NSManagedObject and write some convenience methods to check these options. Depends a bit on what they are good for. A: You could use reflection (e.g., class_copyPropertyList and class_getProperty) to check what properties the class has, and examine their values, but that's a pretty heavy-handed approach when you already know which four properties are relevant. I wouldn't suggest this approach, and I wouldn't call it more Cocoa-ish, just more abstracted. If you're looking at specific combinations of states, I think GorillaPatch's suggestion is right: You would turn those four booleans into a single 4-bit integer and compare it against bit masks representing the various combinations you're interested in.
{ "language": "en", "url": "https://stackoverflow.com/questions/5017906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print 20 random numbers? I am looking to print 20 random numbers. Is it possible to do this with a for loop; and if it is, how can I do it? Here is my current code: int[] randomNum = new int[20]; Random RandomNumber = new Random(); for (int i = 0; i < 20; i++) { randomNum[i] = RandomNumber.Next(1, 80); } foreach (int j in randomNum) { Console.WriteLine("First Number:{0}", j); Thread.Sleep(200); } A: Just loop the number generation until it generated a new number: int[] randomNum = new int[20]; Random RandomNumber = new Random(); for (int i = 0; i < 20; i++) { int number; do { number = RandomNumber.Next(1, 80); } while(randomNum.Contains(number)); randomNum[i] = number; } foreach (int j in randomNum) { Console.WriteLine("First Number:{0}", j); Thread.Sleep(200); } A: According to your last comment, I would say: for (int i = 0; i < 20; i++) { int num; do { num = RandomNumber.Next(1, 80); } while (randomNum.Contains(num)); randomNum[i] = num; } A: Why you used array for this? If you want to print random numbers, you can write this. Random RandomNumber = new Random(); for (int i = 0; i < 20; i++) { int randomNum = RandomNumber.Next(1, 80); Console.WriteLine("Number:{0}", randomNum); Thread.Sleep(200); } A: you don't need in randomNum. Just do it so: for (int i = 0; i < 20; i++) { Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80)); } If you wanna avoid dublication, do so: List<int> intList = new List(); for (int i = 0; i < 20; i++) { int r = RandomNumber.Next(1, 80); foreach(int s in intList) if(s!=r){ intList.Add(s); Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80)); }else i--; }
{ "language": "en", "url": "https://stackoverflow.com/questions/29061947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to determine if login failed due to not accepted cookies in grails In my grails application using shiro, I'm using cookies to store the session data including authorization. When a user tries to log in without accepting cookies, the login works, but then (as expected) the session is lost again and the user is logged out. I don't want to change this behavior in general, I just want to display a notification to the user that his Browser needs to accept cookies. So is there a way to tell that this user has been the one who TRIED to log in after the session data is lost, so that I can display a respective message? I think running a test whether cookies are accepted on every page is a bit too much, therefore I'm heading towards the solution at login only. A: You could use the grails session to store the current state of the user. Then, on login, check the grails session and determine whether to show your message or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/4316849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assigning Data from SQL Server 2000 Database to Strings I am new to C#. My Database table with two columns, A column and B column. Column A has unique static values and column b has random values, so I am running a query to get all these data but now want to store each row of data to strings that are already defined that matches column A. So In others words, my strings will look like the following once done String first (same name as in A column) = B column; (Row 1 value) string second (same name as in A column) = B column; (Row 2 value) string third (same name as in A column) = B column; (Row 3 value) I was also thinking of using XML as an alternative, so exporting data to XML and the reading from XML and still converting them to strings so I can use them in my application, but was not able to find solution A: Try this string connStr = "Enter Your connection String Here"; string SQL = "Enter Your SELECT Here"; SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr); DataTable ds = new DataSet(); adapter.Fill(ds); ds.WriteXml("FileName", XmlWriteMode.WriteSchema);
{ "language": "en", "url": "https://stackoverflow.com/questions/31244705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Web page timeout and refresh is not working I have a web page template on django. In this template i have two controls. I am waiting the page to be forwarded to another page after a certain time passed. One is meta : <meta http-equiv="refresh" content="900;{% url 'list-attendance' %}"/> and second one is script : <script> window.setTimeout(function(){ window.location.href = "{% url 'list-attendance' %}"; },610000); </script> If i open one page on browser it works. And redirects to list-attendance url. But if i open same page in two tabs on same browser, one of the pages redirect other one stucks and does not redirect.
{ "language": "en", "url": "https://stackoverflow.com/questions/53812192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a DDP request monitoring tool for Chrome or Firefox? I am working on Meteor projects, which provide real-time updates by DDP (Distributed Data Protocol). I wish to monitor those requests within the browser. Is there any tool to allow monitoring DDP requests? A: As DDP is based on WebSockets, you can actually monitor the transmitted data of those requests within the Chrome DevTools. To do so just switch the Network tab and then choose websocket from the list and click the Frames tab: A: There is a Chrome extension that adds monitoring of Meteor DDP traffic to the Dev Tools: https://chrome.google.com/webstore/detail/ddp-monitor/ippapidnnboiophakmmhkdlchoccbgje Source code: https://github.com/thebakeryio/meteor-ddp-monitor A: Meteor Toys has a DDP monitor that logs to the console - which lets you view DDP data in any browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/29427446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Click on tablecell show UIDatePicker I have a tableview controller and one of the cell is "date" and when i click i wanna show a datepicker and update the values. When i click on limit date i get Now here is the code: -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if ( indexPath.section == 0 ) { if ( indexPath.row == 3 ) { UITableViewCell *targetCell = [tableView cellForRowAtIndexPath:indexPath]; self.pickerView.date = [self.dateFormatter dateFromString:targetCell.detailTextLabel.text]; // check if our date picker is already on screen if (self.pickerView.superview == nil) { [self.view.window addSubview: self.pickerView]; // size up the picker view to our screen and compute the start/end frame origin for our slide up animation // // compute the start frame CGRect screenRect = [[UIScreen mainScreen] applicationFrame]; CGSize pickerSize = [self.pickerView sizeThatFits:CGSizeZero]; CGRect startRect = CGRectMake(0.0, screenRect.origin.y + screenRect.size.height, pickerSize.width, pickerSize.height); self.pickerView.frame = startRect; // compute the end frame CGRect pickerRect = CGRectMake(0.0, screenRect.origin.y + screenRect.size.height - pickerSize.height, pickerSize.width, pickerSize.height); // start the slide up animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // we need to perform some post operations after the animation is complete [UIView setAnimationDelegate:self]; self.pickerView.frame = pickerRect; // shrink the table vertical size to make room for the date picker CGRect newFrame = self.tableView.frame; newFrame.size.height -= self.pickerView.frame.size.height; self.tableView.frame = newFrame; [UIView commitAnimations]; // add the "Done" button to the nav bar self.navigationItem.rightBarButtonItem = self.doneButton; } } } } - (IBAction)dateChanged:(id)sender { [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]].detailTextLabel.text = [self.dateFormatter stringFromDate:[sender date]]; } - (void)slideDownDidStop { [self.pickerView removeFromSuperview]; } - (IBAction)doneAction:(id)sender { CGRect screenRect = [[UIScreen mainScreen] applicationFrame]; CGRect endFrame = self.pickerView.frame; endFrame.origin.y = screenRect.origin.y + screenRect.size.height; // start the slide down animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // we need to perform some post operations after the animation is complete [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(slideDownDidStop)]; self.pickerView.frame = endFrame; [UIView commitAnimations]; // grow the table back again in vertical size to make room for the date picker CGRect newFrame = self.tableView.frame; newFrame.size.height += self.pickerView.frame.size.height; self.tableView.frame = newFrame; // remove the "Done" button in the nav bar self.navigationItem.rightBarButtonItem = nil; // deselect the current table row NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; self.navigationItem.rightBarButtonItem = self.nextButton; } I have three questions: First: what is that black bar on top of datepicker and how do i remove it? Second: what can i do for closing the datepicker when the user clicks outside the datepicker? Third: How can i move the tableview scroll so that the field "limit date" can be visible when datepicker opens? Sorry for the big screenshots. A: What about presenting your date picker modally in UIActionSheet? In the example above that black bar (which is probably a sizing issue) is replaced with a convenient toolbar in which you can place buttons like "save" and "cancel", and I believe that if you use a UIActionSheet and click outside of it it's automatically dismissed (I'm not sure about this), but if' it's not you can use it's dismiss method to hide it. About the table view, you can use [myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:someRow inSection:someSection] atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; to set the offset of the table scroll at a particular cell you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/12391129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Exception creation stateless session bean I'm trying to create an JaveEE project using EJB upon glassfish. I have an Exception when trying to run it. There is a entity bean: User.java @Entity public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; EJB session: package com.supinfo.courses.EJB; import com.supinfo.courses.EJB.local.UserFacadeLocal; import com.supinfo.courses.entities.User; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; @Stateless public class UserFacade extends AbstractFacade<User> implements UserFacadeLocal { @PersistenceContext(unitName = "4JVA-Courses-ejbPU") private EntityManager em; public UserFacade(EntityManager em, Class<User> entityClass) { super(entityClass); this.em = em; } @Override protected EntityManager getEntityManager() { return em; } public UserFacade() { super(User.class); } @Override public User findByCredentials(String email, String password) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> from = cq.from(User.class); cq.where(cb.equal(from.get("email"), email)); cq.where(cb.equal(from.get("password"), hashPassword(password))); TypedQuery<User> query = getEntityManager().createQuery(cq); List<User> resultList = query.getResultList(); // return first user that match or null return (resultList.isEmpty()) ? null : resultList.get(0); } @Override public void create(User entity) { // encrypt password (sha1) entity.setPassword(hashPassword(entity.getPassword())); super.create(entity); } public String hashPassword(String password) { String sha1 = ""; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(password.getBytes("UTF-8")); byte[] byteHash = crypt.digest(); try (Formatter formatter = new Formatter()) { for (byte b : byteHash) formatter.format("%02x", b); sha1 = formatter.toString(); } } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new Error("Unable to hash password"); } return sha1; } } And a service for using it: @Stateless public class UserService { @EJB public UserFacade userFacade; public User registerUser(User user) { userFacade.create(user); return user; } public User loginUser(String email, String password) { User foundUser = userFacade.findByCredentials(email, password); return foundUser; } public boolean isValidEmailAddress(String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; } } And finally the related servlet: @WebServlet(name = "LoginServlet", urlPatterns = {"/login"}) public class LoginServlet extends AbstractServlet { @EJB UserService userService; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String error = null; // Parse login informations String email = request.getParameter("email"); String password = request.getParameter("password"); User user = null; if (email == null || password == null) { error = "Missing field"; } else if(!userService.isValidEmailAddress(email)) { error = "Invalid email address"; } else if(password.length() < 7) { error = "Password too short"; } else { user = userService.loginUser(email, password); if (user == null) { error = "Bad Credentials"; } } if (error != null) { //redirect with error data to jsp request.setAttribute("error", error); render("login", request, response); } else { request.getSession().setAttribute("user", user); forward("/courses/list", request, response); } } } The stacktrace indicate: Avertissement: Context path from ServletContext: /4JVA-Courses-war differs from path from bundle: 4JVA-Courses-war Grave: EJB5070: Exception creating stateless session bean : [UserService] Avertissement: EJB5184:A system exception occurred during an invocation on EJB UserService, method: public boolean com.supinfo.courses.services.UserService.isValidEmailAddress(java.lang.String) Avertissement: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435) at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2516) at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1906) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88) at com.sun.proxy.$Proxy447.isValidEmailAddress(Unknown Source) at com.supinfo.courses.services.__EJB31_Generated__UserService__Intf____Bean__.isValidEmailAddress(Unknown Source) at com.supinfo.courses.servlets.authentication.LoginServlet.doPost(LoginServlet.java:60) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) ... 40 more Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700) at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246) at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430) ... 44 more Caused by: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514) at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97) at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698) ... 46 more Caused by: java.lang.IllegalStateException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:145) at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46) at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:64) at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:91) at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257) at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1683) at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475) ... 48 more Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:717) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:484) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170) at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:138) ... 54 more Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438) at javax.naming.InitialContext.lookup(InitialContext.java:411) at javax.naming.InitialContext.lookup(InitialContext.java:411) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:613) ... 57 more Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]] at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:188) at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1143) at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:745) at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715) at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471) ... 61 more Caused by: javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438) at javax.naming.InitialContext.lookup(InitialContext.java:411) at javax.naming.InitialContext.lookup(InitialContext.java:411) at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:183) ... 66 more Caused by: javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237) at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204) at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66) at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478) ... 70 more Avertissement: StandardWrapperValve[LoginServlet]: Servlet.service() for servlet LoginServlet threw exception javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435) at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2516) at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1906) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88) at com.sun.proxy.$Proxy447.isValidEmailAddress(Unknown Source) at com.supinfo.courses.services.__EJB31_Generated__UserService__Intf____Bean__.isValidEmailAddress(Unknown Source) at com.supinfo.courses.servlets.authentication.LoginServlet.doPost(LoginServlet.java:60) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) ... 42 more Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700) at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246) at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430) ... 44 more Caused by: javax.ejb.CreateException: Could not create stateless EJB at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514) at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97) at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698) ... 46 more Caused by: java.lang.IllegalStateException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:145) at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46) at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:64) at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:91) at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257) at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1683) at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475) ... 48 more Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:717) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:484) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170) at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:138) ... 54 more Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438) at javax.naming.InitialContext.lookup(InitialContext.java:411) at javax.naming.InitialContext.lookup(InitialContext.java:411) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:613) ... 57 more Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]] at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:188) at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1143) at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:745) at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715) at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471) ... 61 more Caused by: javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438) at javax.naming.InitialContext.lookup(InitialContext.java:411) at javax.naming.InitialContext.lookup(InitialContext.java:411) at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:183) ... 66 more Caused by: javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237) at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204) at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66) at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478) ... 70 more A: Problem solved, also i didn't totally understood the logic. From EJB Spec 3.1 - 4.9.2.1: Session Bean Superclasses A session bean class is permitted to have superclasses that are themselves session bean >classes. However, there are no special rules that apply to the processing of annotations or the deployment descriptor for this case. For the purposes of processing a particular session bean class, all superclass processing is identical regardless of whether the superclasses are themselves session bean classes. In this regard, the use of session bean classes as superclasses merely represents a convenient use of implementation inheritance, but does not have component inheritance semantics. For example, the client views exposed by a particular session bean are not inherited by a subclass that also happens to define a session bean. @Stateless public class A implements Foo { ... } @Stateless public class B extends A implements Bar { ... } Assuming Foo and Bar are local business interfaces and there is no associated deployment descriptor, session bean A exposes local business interface Foo and session bean B exposes local business interface Bar, but not Foo. Session bean B would need to explicitly include Foo in its set of exposed views for that interface to apply. For example: @Stateless public class A implements Foo { ... } @Stateless public class B extends A implements Foo, Bar { ... } I my case, refractoring project and removing Interfaces worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/22213108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Combo Core Data Fetch I have two types of entities: Subjects and Correspondents. They're both related to each other via a to-many relationship. I want to have a single fetchRequest that I can pass to a NSFetchedResultsController which will have it return: * *All of the subjects which have more than one correspondent. *All of the correspondents which have subjects that only they are apart of. After trying a variety of things, I decided that it's not possible to make a single fetch that returns both Subjects and Correspondents, so I turned to StackOverflow and found someone else suggesting that you have a single entity which does nothing more than have relationships with the two entities you'd like to return. So I created a third type of entity, which I called Folders, which each have an optional to-one relationship with a Subject and a Correspondent. It also has two attributes, hasCorrespondent and hasSubject, which are booleans keeping track of whether Subject or Correspondent are set. So I wrote this predicate which returns the Folder entities: (hasCorrespondent == 1 AND ANY correspondent.subjects.correspondents.@count == 1) OR (hasSubject == 1 AND subject.correspondents.@count >= 1) The issue with this is I'm getting an error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported function expression count:(correspondent.subjects.correspondents) So, any suggestions as to what I'm doing incorrectly? How can I accomplish what I'd like? Are there any additional details I should share? UPDATE With Martin's suggestion, I changed the offending portion to this: SUBQUERY(correspondent.subjects, $s, $s.correspondents.@count == 1).@count > 0 But that generated a new error: Keypath containing KVC aggregate where there shouldn't be one; failed to handle $s.correspondents.@count After googling around, I found suggestions to add a check that the collection being enumerated over had at least one object, but modifying the offending line to this didn't change my error messages (so as far as I can tell it did nothing): correspondent.subjects.@count > 0 AND SUBQUERY(correspondent.subjects, $s, $s.correspondents.@count == 1).@count > 0 A: This work around has been less than ideal, but it seems to get the job done: 1 - I added an attribute to subject called count. 2 - I set (part of) my expression to ANY correspondent.subjects.count == 1 Note that no SUBQUERY() was necessary for this workaround. 3 - Everytime I modify a subject's correspondents set, I run subject.count = @(subject.correspondents.count); I'm still hoping for a better solution and will be happy to mark any (working) better solution as correct. A: I had a similar problem. I created an additional field countSubentity. And when add/remove subentity change this field. And predicate looks: [NSPredicate predicateWithFormat:@"SUBQUERY(subcategories, $s, $s.countSubentity > 0).@count > 0"];
{ "language": "en", "url": "https://stackoverflow.com/questions/17519591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I got this error "Operand should contain 1 column(s)" where am i wrong? I searched over other questions on the site. Other solutions that i found does'nt solve my problem. Any idea? INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES ( (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685) ) i am using mysql with php. A: you have to remove the () from values , or it will be considered as one entry . try that: INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685) A: Remove () near values INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685);
{ "language": "tr", "url": "https://stackoverflow.com/questions/23673735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: what does this error >/dev/null 2>/dev/null) mean I have this error in logs file CRON[3304]: (root) CMD ( /usr/bin/php /home/app/foxorders/scripts/restart_apache.php >/dev/null 2>/dev/null) Whats mean please ? A: This is not a error. It's just information about cron job which execute command: /usr/bin/php /home/app/foxorders/scripts/restart_apache.php and redirect STDOUT and STDERR to NULL device
{ "language": "en", "url": "https://stackoverflow.com/questions/69402363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ruby/Webdriver: Ending a test gracefully and closing the browser if element not found This is what I'm currently using : which works... but I would like it to end the test immediately and close the browser if the element is not found. If the element is found I'd like for it to continue on with the rest of the test. begin assert element_present?(:xpath, "//*[text() = 'Narrative Support Primary Signs & Symptoms gar']") @driver.find_element(:xpath, "//*[text() = 'Narrative Support Primary Signs & Symptoms gar']").click rescue Exception => e puts e.message puts "Filter Not Found In List" end A: The API mentions Driver#quit as something to "quit the browser". It seems that adding @driver.quit to your rescue would do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/29497540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic OnClick in IE, Safari, Firefox I have the following bit of code. I'm trying to dynamically add drop-down options to a second drop-down based on the selection in a first drop-down. Both are generated through an Ajax call to a script that pulls the data from a database. Here is the relevant code. function setSub(doc) { // Setup some variables var sNode = document.getElementById('4'); // GRAB THE ELEMENT HERE var rmiData = doc.getElementById('rmiData').innerHTML; var aItems = rmiData.split("|"); var aVals; // Set some background sNode.style.background = "#fff"; // Loop through adding options to the drop down for (var x = 0; x < (aItems.length -1); x ++) { aVals = aItems[x].split("="); // ADD OPTIONS DYNAMICALLY TO SECOND DROP-DOWN HERE sNode.options[x+1] = new Option(aVals[1],aVals[0],false,false); // PROBLEM HERE: ADD ONCLICK TO THE OPTION WE JUST CREATED sNode.options[x+1].onclick = function() { fixDayList(); }; //sNode.options[x+1].onclick = new Function("fixDayList();"); //sNode.options[x+1].setAttribute("onclick", "fixDayList();"); // END PROBLEM LINES } // Set the length sNode.length = x+1; // Select the first item in the list sNode[0].selected = true; } If you notice the section after the "// PROBLEM HERE" line, I've tried to add the onclick event in three different ways. All 3 work correctly in Firefox. None of the 3 work in IE6 or Safari (Not sure on IE8). Any suggestions for this? The rest of the code is using some old-schoolish JavaScript that I copied from an existing piece of legacy code that works and I'm just trying to add onclick to my version (preferably without re-writing a lot of code). Any thoughts on why the onclick events don't fire from Safari and IE? I do have access to jQuery in my code. So, if jQuery fixes this internally and I can figure out the proper selector to use, that would work. But, I'm not sure how to select this, exactly. I tried: $('#4').options[x+1].click( function() { fixDayList(); } ); But that selector is bad and I'm not sure exactly how to select the right one (I'm green in the ways of jQuery). A: Use something like this: if(window.addEventListener){ sNode.options[x+1].addEventListener('click', fixDayList, false); } else if (window.attachEvent){ sNode.options[x+1].attachEvent('onclick', fixDayList); } else { sNode.options[x+1].onclick = fixDayList; } Update: In Safari, unless the option elements are visible and not displayed as a dropdown list, they will never trigger a click event. But, if you add size=10 or whatever to your select element, Safari will then trigger click events on the option elements. Your best bet will be to listen for the change event on the select element instead of trying to use click on the options.
{ "language": "en", "url": "https://stackoverflow.com/questions/2240573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort using statement of C# code in vim? Recently I edit C# code in vim. And the build system has StyleCop enabled so that all using statement should be in alphabetical order. So, I tried to select below lines of code in visual mode, then type ":sort". using System.Security.Permissions; using System.Runtime.Serialization; using System.Security; using System.ServiceModel; The result is: using System.Runtime.Serialization; using System.Security.Permissions; using System.Security; using System.ServiceModel; It doesn't pass StyleCop checking because "System.Security" is not ahead of "System.Security.Permissions". The ASCII value of ";" is larger than ASCII value of ".". The preferred result is: using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.ServiceModel; How to achieve it? A: :h :sort is your friend: :[range]sort r /[^;]*/ If along the way you wish to remove duplicates, add the uniq flag: :[range]sort ur /[^;]*/ (This won't do any good if you have different comments after the ';' though) A: :1,4s/;$// :sort :1,4s/$/;/ (where 1,4 are lines with using statements) A: Not using CodeRush or ReSharper is stealing from your employer <ducks for downvotes> (Yes, I know that requires VS (and AFAIK VS10 has this OOTB)) A: On my linux box with a local other than C (tested fr_FR, fr_FR.UTF-8, en_US, en_GB), the sort command sorts as you expect. You could very well pipe to the sort command : :1,4!sort If you are on windows, I suppose you can install unix tools (like SFU) that could do the job since vim's sort command doesn't seem to handle locale.
{ "language": "en", "url": "https://stackoverflow.com/questions/1872884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Conversion Failed error in sql I have a problem in my code and I figure it out: SELECT pono, convert(varchar,podate,103) as podate, Convert(varchar,validity,103) as validity, OriginalPOno, Sitename, Vendorname FROM dbo.tbl_POR_PO_MAIN WHERE originalpono not in (select originalpono from tbl_Despatch_POR_PO_Main) AND pono not in (select pono from tbl_Despatch_POR_PO_Main) AND status=15 AND (DATEDIFF(day,getdate(),validity)<=1) ORDER BY sitename, validity, originalpono This gives me a following error: Conversion failed when converting datetime from character string. How do I solve this problem? A: Please check data in column podate and validity. Any of this column is having string value. That is the reason why you are getting this error. A: Try to use MSSQL server ISDATE() function it returns 0 if a string isn't date and 1 if it is date and can be converted. Try to run following select and check incorrect strings: select 'incorrect podate', podate from dbo.tbl_POR_PO_MAIN where ISDATE(podate)=0 union all select 'incorrect validity', validity from dbo.tbl_POR_PO_MAIN where ISDATE(validity)=0 A: Found this thread: SQL Server expects dates in the format mm/dd/yyyy so you will need to convert your date into this format before submitting. The problem with this error is that if the day value of a date is <=12, it will automagically be converted to mm/dd/yyyy giving you the false impression that your code is working. it's not until the day hits 13> that the problem raises it's ugly head. Sounds like this could be the issue,maby you should take a looka the podate structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/11789598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Base64 Decoding of UTF 8 character and printing it I have UTF8 character which are encoded in Base64. I am decoding it and trying to print it.But its only priting its hex value but not the UTF-8 String. Things I tried 1: I have verified the Character is online decoder which tell me that the string I get is of right format: https://www.base64decode.org/ 2: System.getProperty("file.encoding") is also UTF8 def main(args: Array[String]): Unit = { println("Hello, world!") val sd = Base64.getDecoder.decode("7IiY7KeE7IiY7KeE7IiY7KeE7IiY7KeE7IiY7KeE7IiY7KeE7IiY7KeE7IiY7KeE7IiY") println(System.getProperty("file.encoding")) println(sd.toString()) val sb = new StringBuffer var i:Int=0 while(i<sd.length){ sb.append("%02X".format(sd(i) & 0xff)) i=i+1 } println(sb) } What am I missing in this one ? Actruall string required is as below: 수진수진수진수진수진수진수진수진수 A: Why not simply using new String(sd, "UTF-8"), which will return your characters. Worked on my machine, result: 수진수진수진수진수진수진수진수진수 A: The X in "%02X".format(sd(i) & 0xff) specifies upper case hexadecimal. Try %s to get the UTF-8 string.
{ "language": "en", "url": "https://stackoverflow.com/questions/36245073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what is the format of DMPfinder in minfi package in r I have processed data, containing 4 columns (chromosome, start, end, beta value ) for each sample. and 2 groups (patient and normal). I want to find differentially methylated positions between these 2 groups using DMPfinder in minfi Package. but I don't know how should I create an input data for these codes(from package toturial): M <- getM(mset, type = "beta", betaThreshold = 0.001) dmp <- dmpFinder(M, pheno=pd$Sample_Group, type="categorical")
{ "language": "en", "url": "https://stackoverflow.com/questions/72414649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass List* to EnumWindows' lParam in C# I'm trying to write a function which iterates over top level windows and puts them into a list if they fulfil a set of criteria. At the moment I can get this to work by adding the windows into a static List<IntPtr> instances variable, but I would like to instead pass a pointer to a list in the EnumWindowsProc's lParam in order to avoid this static variable. I think I have to use fixed to fix the list's position in memory, but I am unsure how to do this. I tried this to pass the list to my callback function: unsafe { fixed (void* dp = &instances) { WinApi.EnumWindows(new WinApi.EnumWindowsProc(FindPPWindows), dp); } } but I get Cannot take the address of, get the size of, or declare a pointer to a managed type ('System.Collections.GenericList<IntPtr>') I'm newish to c# so I don't really know how to do this - or even if it's possible, I've read that marshalling a managed type containing references is impossible but I only need to fix it in memory and create a pointer to it, then cast the pointer back and use it. How can I make this work, if at all? A: You could call the EnumWindows function with an lambda expression. Then the EnumWindowsProc Callback would be inline and you can access to local variables: List<IntPtr> list = new List<IntPtr>(); WinApi.EnumWindows((hWnd, lParam) => { //check conditions list.Add(hWnd); return true; }, IntPtr.Zero); You could capsulate this inline call in an extra function, e.g.: List<IntPtr> GetMatchingHWnds() { List<IntPtr> list = new List<IntPtr>(); WinApi.EnumWindows((hWnd, lParam) => { //check conditions list.Add(hWnd); return true; }, IntPtr.Zero); return list; }
{ "language": "en", "url": "https://stackoverflow.com/questions/13973452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What driver are you expected to provide for Reflections.collect() to work from a Groovy script? I have the following snippet of scratch code import com.google.appengine.api.datastore.Entity import org.reflections.Reflections Reflections r = Reflections.collect() Set<Class<?>> entities = r.getTypesAnnotatedWith(Entity.class) print entities that throws the following exception: org.xml.sax.SAXException: Can't create default XMLReader; is system property org.xml.sax.driver set? at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source) at org.dom4j.io.SAXHelper.createXMLReader(SAXHelper.java:83) Googling for org.xml.sax.SAXException: Can't create default XMLReader; is system property org.xml.sax.driver set? brings up questions, mostly about Android with link only answers or code based answers that do not actually address the issue of providing the correct system property value. The same code works as Java code from the same IDE project. So what do I have to supply to get this to work as a Groovy script? A: I have this script in the src/test/groovy in my Maven project so I added. <dependency> <groupId>org.apache.servicemix.bundles</groupId> <artifactId>org.apache.servicemix.bundles.crimson</artifactId> <version>1.1.3_2</version> <scope>test</scope> </dependency> to my pom.xml And I added -Dorg.xml.sax.driver=org.apache.crimson.parser.XMLReaderImpl to the VM Options: in the Run/Debug Configuration for the script. This makes it work, but I would still like to know what I can used without having to add a dependency to get things in the test scope to run since things in the main scope work without this dependency.
{ "language": "en", "url": "https://stackoverflow.com/questions/34888476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Footer W/ Gradient - Not Sticky What my designer wants and what I'm trying to code is a footer that begins at the bottom of dynamic content (actually, they want the footer to start beneath the content area up about 20px - but that's something else). The thing is, they have a gradient that they want down there that expands as the browser window does. Due to the gradient I can't just cheat and declare the window color as black and if I set the size of the footer to the height of the gradient, I end up with the scroll bar. I feel I must be missing something incredibly obvious, but I've been staring at it so long I just am seeing cross-eyed. <body> <div id = "page"> <div id = "header"> </div> <div id = "content"> I am ze content area (for now) </div> </div> <div id = "footer"> I AM THA FOOTAH<br/> So much cooler than the header these days </div> </body> body { background-color: grey; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; margin: 0px; padding: 0px; } div { display: block; } #page { background-color: white; margin: 0px auto; padding: 0px; } #header { background: url("http://kjunek.com/images/header_background.png") repeat-x; color: yellow; height: 240px; } #content { background-color: white; } #footer { background: #030a19 url("http://kjunek.com/images/footer_background.png") repeat-x 50% 0%; height: 626px; overflow: hidden; color: white; } Kind of like http://roughtech.com/t/oppsticky.html from Doing the opposite of CSS Sticky Footer only I want the red to continue down to the bottom of a window with a gradient that fades to black. Thanks! A: Deleted my last answer - it does not work either. In standards compliant modes the only content that can not be scrolled to is content inside a parent which is hidden. And except for bugs it is not shown. What I was looking at was a IE bug. Sorry no can do in CSS as it stands today. If you need to do a calc today you would need to use jquery to get the heights of the elements then calculate the height needed for the footer; And, use CSS gradients http://robertnyman.com/2010/02/15/css-gradients-for-all-web-browsers-without-using-images/ so you can go from your shade of navy to your shade of black. I would discourage this approach as when you start to consider all of the possible resolution situations the calculation it will become rather complex and I assume they may want to redesign the heights depending on different resolutions.
{ "language": "en", "url": "https://stackoverflow.com/questions/4559047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search a file recursively for string I am using some vbscript to search for string inside a directory. Now I need my script to search for multiple instance of string in each file and return line number or some other identifiable information. My current vbscript is :- Sub ProcessFolder(FolderPath) On Error Resume Next Set fldr = fso.GetFolder(FolderPath) Set Fls = fldr.files For Each thing in Fls Set contents = thing.OpenAsTextStream If err.number = 0 then Test = Instr(contents.readall, searchterm) If Isnull(test) = false then If Test > 0 then ObjOutFile.WriteLine thing.path demo.innerHtml = demo.innerHtml & thing.path & "<br>" Else err.clear End If Next Set fldrs = fldr.subfolders For Each thing in fldrs ProcessFolder thing.path Next End Sub I need to iterate through lines of each file to get line numbers containing string. A: Reads each line and searches each line. Also remembers the previous search and directory. Two issues that you can fix. * *It will now hits the 5 million statement timeout message esp if going through exe files. *It won't find Unicode text. This is the third time I've written the program. <HTML> <HEAD><TITLE>Simple Validation</TITLE> <SCRIPT LANGUAGE="VBScript"> Dim Dirname Dim Searchterm Dim FSO Dim objOutFile Sub Browse On Error Resume Next Set bffShell = CreateObject("Shell.Application") Set bff = bffShell.BrowseForFolder(0, "Select the My Documents folder", 9) If Err.number<>0 Then MsgBox "Error Setting up Browse for Folder" Else A = bff.ParentFolder.ParseName(bff.Title).Path If err.number=424 then err.clear tb2.value = A End If End Sub Sub Search On Error Resume Next Set WshShell = CreateObject("WScript.Shell") WshShell.RegWrite "HKCU\Software\StackOverflow\VBS\Searchterm", tb1.value WshShell.RegWrite "HKCU\Software\StackOverflow\VBS\Directory", tb2.value Set fso = CreateObject("Scripting.FileSystemObject") Set objOutFile = fso.CreateTextFile("results.txt",True) Dirname = tb2.value Searchterm = tb1.value ProcessFolder DirName End Sub Sub ProcessFolder(FolderPath) On Error Resume Next Set fldr = fso.GetFolder(FolderPath) Set Fls = fldr.files For Each thing in Fls Set contents = thing.OpenAsTextStream If err.number = 0 then Linenum = 0 Do Until contents.AtEndOfStream line = contents.readline Linenum = Linenum + 1 Test = Instr(line, searchterm) If Isnull(test) = false then If Test > 0 then ObjOutFile.WriteLine LineNum & " " & thing.path Loop Else err.clear End If Next Set fldrs = fldr.subfolders For Each thing in fldrs ProcessFolder thing.path Next End Sub Sub Init On Error Resume Next Set WshShell = CreateObject("WScript.Shell") tb1.value = WshShell.RegRead("HKCU\Software\StackOverflow\VBS\Searchterm") tb2.value = WshShell.RegRead("HKCU\Software\StackOverflow\VBS\Directory") End Sub </script> </head> <body Onload=Init> <p><INPUT Name=tb1 TYPE=Text Value="Search"> <p><INPUT Name=tb2 TYPE=Text Value="Folder"> <INPUT NAME="Browse" TYPE="BUTTON" VALUE="Browse" OnClick=Browse> <p><INPUT NAME="Search" TYPE="BUTTON" VALUE="Search" OnClick=Search> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/35596791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Config File without Environment Variable I don't have permission to create the Environment variable and I want to pass my Config file path and Name using variable. A: Can you use one of the other configuration methods (SQL Server or XML)? Since you have file access, using XML seems appropriate. See the section for "Types of Configurations": http://msdn.microsoft.com/en-us/library/cc895212.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/13750539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to perform data analysis using python I just want to do these 3 steps: * *identify the missing data *impute the missing values in the data using k-means or k-nearest-neighbor imputation. *return the imputed data and compare it with the complete data to measure the accuracy and reliability of your results Kindly suggest how to do it. A: Your question isn't formulated very well, but here's some things that might work for your application. * *pandas.isnan *pandas.interpolate *mse = lambda y1, y2: (y2 - y1)**2 A: so you have data set in csv format or other. you can first load the data using the pandas library and fill the missing values. Build the model : mse = lambda y1, y2: (y2 - y1)**2 Test with sample data set on this model.
{ "language": "en", "url": "https://stackoverflow.com/questions/62768418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Firebase setting user data on registration I want to create an new user in my firebase. This is the code I´m using: function createUser(email, password, username) { ref.createUser({ email: email, password: password }, function(error) { if (error === null) { $activityIndicator.stopAnimating(); $scope.padding_error = null; $scope.error = null; logUserIn(email, password); } else { $activityIndicator.stopAnimating(); console.log(error.code); switch (error.code) { case "INVALID_EMAIL": $scope.padding_error = "10"; $scope.error = "Falsche E-Mail Adresse oder falsches Passwort"; $scope.$apply(); case "INVALID_PASSWORD": $scope.padding_error = "10"; $scope.error = "Falsche E-Mail Adresse oder falsches Passwort"; $scope.$apply(); case "EMAIL_TAKEN": $scope.padding_error = "10"; $scope.error = "Diese E-Mail Adresse ist schon registriert"; $scope.$apply(); } } }); } I want to store the username in addition to email and password somewhere in my firebase. How is this possible instantly after user registration? A: If the registration is succesful you can simply push the email and password variables to firebase. See code below. function createUser(email, password, username) { ref.createUser({ email: email, password: password }, function(error) { if (error === null) { ... Registration successful $activityIndicator.stopAnimating(); $scope.padding_error = null; $scope.error = null; ##NEWCODE HERE## emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email") passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password") emailRef.set(email) passRef.set(password) logUserIn(email, password); } else { ... Something went wrong at registration } } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/26606091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I redirect in JSF 2.0 I want to redirect from a link in a JSF page, how can I do it? In HTML I can use <a> tag for this. But in JSF I use <h:outputLink> or <h:commandLink> as they can be conditionally rendered. I want redirect link to other page in same application or to an external URL. How can I do it with JSF? How can I use action in <h:commandLink> for this? A: Assuming that you'd like to redirect to some.xhtml which is placed in web root folder: * *You can just continue using plain HTML. <a href="#{request.contextPath}/some.xhtml">go to some page</a> For conditional rendering, just wrap it in an <ui:fragment>. *Or use <h:link> with implicit navigation. <h:link outcome="/some" value="go to some page" /> Note: no need to prepend context path nor to include FacesServlet mapping. *Or use <h:commandLink> with ?faces-redirect=true. <h:commandLink action="/some?faces-redirect=true" value="go to some page" /> Note: no need to prepend context path nor to include FacesServlet mapping. *Or use <h:outputLink>, but you need to specify context path. <h:outputLink value="#{request.contextPath}/some.xhtml" value="go to some page" /> Redirecting to an external URL is already answered in this duplicate: Redirect to external URL in JSF. See also: * *How to navigate in JSF? How to make URL reflect current page (and not previous one) *When should I use h:outputLink instead of h:commandLink? *JSF implicit vs. explicit navigation
{ "language": "en", "url": "https://stackoverflow.com/questions/3947959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is it possible to set product version at build time in a Basic MSI project? I have an InstallScript project that I'm looking at manually recreating as a Basic MSI project. For the InstallScript project, we obtain the product version at build time through the following mechanism: * *Ant does all the compiling, testing, etc. and during this process obtains a build version number. *Ant calls IsCmdBld.exe, passing the build version as an environment variable. *Installshield has an "Environment"-type path variable configured, which picks up the build version. *This path variable is specified in the General Information -> Product Version field. Unfortunately, it looks like the Basic MSI project does not allow path variables in the Product Version field. Does this mean the product version has to always be manually modified before each build with a Basic MSI project? Or is there a different way to pass the version to InstallShield? A: You can use the following command for Basic MSI and InstallScript MSI: ISCmdBld.exe -y "1.0.5" A: Another way: IsCmdBld.exe -z "ProductVersion=1.0.0002"
{ "language": "en", "url": "https://stackoverflow.com/questions/7585522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unavailable to Export Data with Current Layout - Power BI Report Server it is not yet available to export table with current layout from powerbi report server, because I had seen that it was supposed to be there in the release of Jannuary 2023 however it seems to me that it is not available yet. Is there any possibility of doing it any other way ?
{ "language": "en", "url": "https://stackoverflow.com/questions/75583225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if opened window has been closed I have a main window, which is the application start up window. In that window, there is a Repeater control binded to a SQL Database, and a button to open a new window. The new window has a method that inserts data into the SQL Database that the first windows' Repeater control reads from. The repeater has a RepeaterRefresh() method that forces it to rebind to the SQL Database, revealing anything added. How would I be able to bind the Close() event of the second window to the RepeaterRefresh() method, so the data is automatically shown on the repeater. I have read this, this and this, but I still feel that my question doesn't relate. A: Why not simply add a handler to the Closing or Closed event: private void ShowChildWindow() { Window childWindow = new ChildWindow(); childWindow.Closed += ChildWindowClosed; childWindow.Show(); } private void ChildWindowClosed(object sender, EventArgs e) { ((Window)sender).Closed -= ChildWindowClosed; RepeaterRefresh(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/12106657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Angular 2 materials, autocomplete with remote data I'm using Angular 4 with Materials 2. I have successfully created some autocomplete fields using an array of data. Here my controller: sectorCtrl; allSectors filteredSectors: any; constructor() { this.sectorCtrl = new FormControl(); this.filteredSectors = this.sectorCtrl.valueChanges .startWith(null) .map(name => this.filterValues(name)); } filterValues(val: string) { return val ? this.allSectors.filter(s => new RegExp(`^${val}`, 'gi').test(s.label)) : this.allSectors; } And my template: <md-input-container> <input mdInput placeholder="Sectors" [mdAutocomplete]="auto" [formControl]="sectorsCtrl"> </md-input-container> <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn"> <md-option *ngFor="let value of filteredSectors | async" [value]="value" > {{ value.label }} </md-option> </md-autocomplete> How can I adapt the code in order to use a remote API? A: You will have to get the remote data via service and assign the data to a variable, in your example it will be assigned to allSectors. Then it's usual business, running the filter on allSectors, if allSectors is an array of objects, than you have to specify on which property you want to run the filter. In my demo, I am doing it for sector.name. You can use displayWith to control what value to show in input field. HTML: <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn"> <md-option *ngFor="let sector of filteredSectors | async" [value]="sector"> {{ sector.name }} </md-option> </md-autocomplete> TS: export class AutocompleteOverviewExample implements OnInit{ stateCtrl: FormControl; filteredSectors: any; allSectors; constructor(private dataService: DataService) { this.stateCtrl = new FormControl(); } ngOnInit(){ this.dataService.fetchData() .subscribe( (data) => { this.allSectors = data.customers; this.filteredSectors = this.stateCtrl.valueChanges .startWith(null) .map(val => val ? this.filter(val) : this.allSectors.slice()); } ); } filter(name) { return this.allSectors.filter(sector => new RegExp(`^${name}`, 'gi').test(sector.name)); } displayFn(sector) { return sector ? sector.name : sector; } } Here's the Plunker.
{ "language": "en", "url": "https://stackoverflow.com/questions/44308283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where is a reference to regex header on MSDN? I can include this file directly now without tr1 in VS 2010 but can't find description of this file anywhere on MSDN. Where is a reference to regex header on MSDN? A: The regex description on MSDN: http://msdn.microsoft.com/en-us/library/bb982382.aspx Basically, you create "basic_regex" objects, then call the "regex_match" or "regex_replace" functions A: You shouldn't need any specific headers beyond <regex> to include the tr1 functionality. To get start using Regular Expressions in tr1 I suggest reading: http://www.johndcook.com/cpp_regex.html
{ "language": "en", "url": "https://stackoverflow.com/questions/3292683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Angular 2 animations pass an Input I need a way to configure my animations dynamically. For example, I want my consumer to be able to pass as Input of the numbers of the animate declaration or any CSS property. animations: [ trigger('heroState', [ state('inactive', style({ backgroundColor: '#eee', transform: this.transform })), state('active', style({ backgroundColor: '#cfd8dc', transform: this.transform })), transition('inactive => active', animate(this.animateInActive), transition('active => inactive', animate('100ms ease-out')) ]) ] class Cmp { @Input() transform = 'scale(1)'; @Input() animateInActive = '200ms ease-out'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/41810838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Label detection mouse click c++ I'm trying to build a simple API in c++. It detects which button of my mouse I click on my window and it shows a MessageBox saying which button was clicked. I also managed to show in a messageBox when I release the button of my mouse. But I can't use both at the same time. It is possible, instead using messageBox, inserting text of which button was clicked in a label, and change it depending of which button was pressed/released? I use a switch with differents cases for each button pressed/released. Tell me if you have something for me, would be appreciated. Can show my code if you want ! A: I managed to find a solution. First declareda label. #define ID_LABEL 1 static HWND myLabel; Then created it. case WM_CREATE: myLabel = CreateWindow(TEXT("BUTTON"),TEXT("hello"), WS_VISIBLE|WS_CHILD,50,50,150,25, hwnd,(HMENU) ID_LABEL,NULL,NULL); break; And then for each button pressed/released, I edit the text. Example for when i press the left button of my mouse. case WM_LBUTTONDOWN: myLabel = CreateWindow(TEXT("BUTTON"),TEXT("left button pressed"), WS_VISIBLE|WS_CHILD,50,50,150,25, hwnd,(HMENU) ID_LABEL,NULL,NULL); break; And it's working. Is anyway a better way to do it ?
{ "language": "en", "url": "https://stackoverflow.com/questions/52428250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: WebRTC Get stats metrics for refreshing keyframes I am currently using webrtc to receive an h264 stream over udp(rtp). I am encoding this stream and sending it, using gstreamer. The way I am encoding it right now, is with an infinite GOP size, to allow for lowest bitrate. However with an infinite GOP size, packet loss etc requires me to send keyframes. I am wondering if there are better metrics for figuring out when to send a keyframe, and why we need to send keyframes in this situation at all. For example, what is happening to the stream that requires a keyframe. Also what is the best metric that can be used to determine that it is a good time to send keyframes. I've heard packet loss isn't good enough, since not all packet loss requires a keyframe refresh, and sometimes there is a delay between packet loss and the frame being received. A: Could you run avdec_h264 and then when you hit errors send a PLI? You could parse the H264 bitstream yourself and perform an action on certain conditions. * *Did I get a corrupted I-Frame *After n corrupted P/B Frames I am going to go do some reading myself. I wonder how hard it would be to determine the amount of broken macroblocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/66307974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to redirect IE to Edge like youtube, twitter, stackoverflow without permission When you navigate to youtube, twitter, StackOverflow in IE11. you can find your browser opened Microsoft Edge without permission. I wanna know how to do that, and apply my own web site. enter image description here that is the permission that I said.
{ "language": "en", "url": "https://stackoverflow.com/questions/63913850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reset variable using shell I use the shell script to reset variable. #!/bin/sh reset_var() { while [ "$#" -gt "0" ] do echo "\$1 is $1" unset $1 done } i=50 j= 40 reset_var i j but this it does not work! the purpose is to reset i and j variable to 0 is there any way to reset many variables ! A: In your situation, you do not need a reset_var function, simply do: i=50 j=40 unset i j That is said, a possible reset_var function would be: reset_var() { while [ "${#}" -ge 1 ] ; do unset "${1}" shift done } A: You have an infinite loop when passing some arguments. Your reset function should look something like this: reset_var() { for arg do unset ${arg} done }
{ "language": "en", "url": "https://stackoverflow.com/questions/53592271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java : Array items null and int values I have an array with type Object. Then I assign it's values to null. But later I want to assign int values on null cells. Is that possible? In these lines: Queue[y]=new Int; Queue[y]=num; I am trying create an object Int type, in the null cell. But I get this error: error: '(' or '[' expected Queue[y]=new Int; private Object Queue[]; public PriorityQueue(int capacity){ this.capacity=capacity; Queue= new Object [capacity]; for(int i=0;i<=Queue.length;i++) { Queue[i]=null; } } public boolean insert(int num){ if (y<capacity){ Queue[y]=new Int; Queue[y]=num; y++; return true; } else{ y++; return false; } } A: (I don't know what class you mean by Int - perhaps you mean java.lang.Integer, but perhaps you mean some custom class. It's not totally relevant to the answer, however) You always need a parameter list when you invoke a constructor, even if it is empty: new Int() Or, if you mean to create an array, you need to specify the number of elements: new Int[10] However, you don't need the first assignment: Queue[y]=new Int(); Queue[y]=num; The second line overwrites the value in the first line, so it's actually just creating an object and then immediately discarding it. You could simply write: Queue[y]=num; Note that this isn't actually assigning an int to an Object array element: due to autoboxing, the compiler automatically converts this to: Queue[y]=Integer.valueOf(num); so an instance of Integer is being added to the array. However, this conversion isn't something that you need to do yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/36486669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Passing ViewModel from View to Controller Ok, here is my problem. I am trying to pass a view model of mine, which has multiple list in it, to my view. Then in my view i need to edit the different list. Then on my post i need to save the edits. Although, when i pass my viewmodel back to my post, it is empty! Can somebody explain what i am doing wrong? Controller public ActionResult ManageNewsArticles() { NewsViewModel newsViewModel = new NewsViewModel(); newsViewModel.ListBreakingNews = db.NewsArticles.Where(n => n.PageSetupID == 1).ToList<NewsArticle>(); newsViewModel.ListMainArticle = db.NewsArticles.Where(n => n.PageSetupID == 2).ToList<NewsArticle>(); newsViewModel.ListSubNews1 = db.NewsArticles.Where(n => n.PageSetupID == 3).ToList<NewsArticle>(); newsViewModel.ListSubNews2 = db.NewsArticles.Where(n => n.PageSetupID == 4).ToList<NewsArticle>(); newsViewModel.ListSubNews3 = db.NewsArticles.Where(n => n.PageSetupID == 5).ToList<NewsArticle>(); return View(newsViewModel); } [HttpPost] public ActionResult ManageNewsArticles(NewsViewModel newsViewModel) { if (ModelState.IsValid) { db.SaveChanges(); return RedirectToAction("Admin"); } return View(newsViewModel); } here is my View <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TrueNews.ViewModels.NewsViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Manage News Articles </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Manage News Articles</h2> <% Html.EnableClientValidation(); %> <% using (Html.BeginForm(Model)) {%> <%: Html.ValidationSummary(true) %> <fieldset> <%: Html.EditorForModel(Model) %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to Admin Controls", "Admin") %> </div> </asp:Content> NewsViewModel public class NewsViewModel { public List<NewsArticle> ListBreakingNews { get; set; } public List<NewsArticle> ListMainArticle { get; set; } public List<NewsArticle> ListSubNews1 { get; set; } public List<NewsArticle> ListSubNews2 { get; set; } public List<NewsArticle> ListSubNews3 { get; set; } } // End of Class A: First of all, I assume that you use linq2sql or something similar. In order to update an object in your database, that object has to be fetched through a DataContext. Inside your method "ManageNewsArticles" you're calling db.SaveChanges(); but since there is no objects loaded through db no rows will get updated. A solution to this is to fetch all news you want to update, and then use the Controller.UpdateModel method to update your actual instances, and then call db.SaveChanges(); to persist your changes. A: Try using the UpdateModel(NewsViewModel); db.SaveChanges(); return RedirectToAction("Admin"); A: I've never tried using EditorFor on lists of complex objects. I'm guessing that MVC is unable to encode your NewsArticle objects in such a way that they can be reassembled into a NewsViewModel object. Have you tried using something like Firebug to see what the actual POST looks like? What are the query parameter keys and values? You may be able to simply take an IEnumerable<NewsArticle>, and then re-parse that out using the same logic you use in the ManageNewsArticles method. Give that a shot, and let us know what you find out.
{ "language": "en", "url": "https://stackoverflow.com/questions/4413679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Security - How to prevent XSS filename injection in Dropzone.js? I am doing some security tests with my dropzone.js extension, I find out that it's possible with a Linux system to rename a legit filename and execute it with special characters like : "><svg onload=alert(1)>.jpg or "><img src=x onerror=prompt(document.domain)>.png This script injections are inoffensive, but some other could do great damage. we can find more examples on owasp.org To protect my filename I'm able to rename it via PHP with this : public static function FileTitleSafe($string) { $str = $string; // Trim white spaces at beginning and end of title $str = trim($str); // Remove any duplicate whitespace, and XSS protect $str = preg_replace('/([\s\s]|\<|\>\=|\#|\"|\?|\%|\!|\*|\:|\.)+/', ' ', $str); // Trim dashes at beginning and end of alias $str = trim($str, '-'); return $str; } But it doesn't prevent the creation of filename in the thumbnail description... How can I prevent the upload of unauthorized filename via a Dropzone Script by blocking non-legit characters or by renaming the filename before it appears in the thumbnail description?
{ "language": "en", "url": "https://stackoverflow.com/questions/39858211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python XML - incrementally writing XML without duplicating namespaces I am wondering if there is a way to have a concise namespace declaration of my XML when I am writing it in an incremental manner using lxml. Currently, I get duplicated namespaces with the way I generate my XML. See below, where the tags data and oneEntry duplicate the namespaces: <?xml version='1.0' encoding='utf-8'?> <data xmlns="nsURI1" xmlns:second="nsURI2"> <oneEntry xmlns:second="nsURI2" xmlns="nsURI1"> <subEntry1/> <second:subEntry2/> </oneEntry> </data> This can be generated from a script like this (inspired by http://lxml.de/api.html#incremental-xml-generation) from lxml import etree from io import BytesIO class XmlWriter(object): ROOT_TAG = 'data' ENCODING = 'utf-8' NSMAP = { None: 'nsURI1', 'second': 'nsURI2' } def write(self): f = BytesIO() w = self.writer(f) # Creates the writer next(w) # Start writing (go to first yield) element = etree.Element('oneEntry', nsmap=self.NSMAP) etree.SubElement(element, '{nsURI1}subEntry1') etree.SubElement(element, '{nsURI2}subEntry2') w.send(element) w.close() # Closing stream closes root tag print(f.getvalue().decode('utf-8')) @classmethod def writer(cls, out_stream): with etree.xmlfile(out_stream, encoding=cls.ENCODING) as xf: xf.write_declaration() with xf.element(cls.ROOT_TAG, nsmap=cls.NSMAP): while True: el = yield xf.write(el) xf.flush() XmlWriter().write() The part computing one entry is actually a loop generating multiple thousands of entries, therefore my need for a stream. Now, I understand why this is happening. The root tag in my stream writer is not known by the part computing the entry element. So, during the incremental writing, the namespaces are duplicated on each entry. This will increase (when my file is not compressed) the size of my output. Any idea how I could still write incrementally my XML, without having to change the structure of it and still use lxml preferably? Thanks a lot!
{ "language": "en", "url": "https://stackoverflow.com/questions/50326271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apach Flink CEP "At Least" Condition I am trying to create a CEP pattern that matches "at least" occurrence. Modifying the example code: middle.oneOrMore().where(new IterativeCondition<SubEvent>() { @Override public boolean filter(SubEvent value, Context<SubEvent> ctx) throws Exception { if (!value.getName().startsWith("foo")) { return false; } double sum = value.getPrice(); for (Event event : ctx.getEventsForPattern("middle")) { sum += event.getPrice(); } return Double.compare(sum, 5.0) < 0; } }); into middle.oneOrMore().where(new IterativeCondition<SubEvent>() { @Override public boolean filter(SubEvent value, Context<SubEvent> ctx) throws Exception { if (!value.getName().startsWith("foo")) { return false; } long count = 0; for (Event event : ctx.getEventsForPattern("start")) { count = count + 1; } return count >= MIN_COUNT; } }); does not solve my problem because the condition will keep failing and never be able to contribute to count. I found in https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/libs/cep.html that there are // expecting 4 occurrences start.times(4); // expecting 0 or 4 occurrences start.times(4).optional(); // expecting 1 or more occurrences start.oneOrMore(); // expecting 0 or more occurrences start.oneOrMore().optional(); Is there anything like start.atLeast(5) exist? A: Check this link for the solution. It checks for the pattern to occur 5 times. You can modify it in times(number_of_times) [https://stackoverflow.com/questions/45033109/flink-complex-event-processing/45048866] A: You can use .times(5) followed by the same pattern but with the quantifier .oneOrMore().optional(). The times requires exactly 5 and the zeroOrMore will give you the "atLeast...".
{ "language": "en", "url": "https://stackoverflow.com/questions/44813368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MetaWhere to Squeel migration In MetaWhere I combined conditions to sql variable using loops, if else statements. sql = {} email_starts_with = "vany%" sql["growth"] = 0..200 sql = sql & (:rating > 50) sql = sql & (:email =~ email_starts_with) ..... ..... User.where(sql).to_sql => "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"growth\" BETWEEN 0 AND 200 AND \"users\".\"rating\" > 50 AND \"users\".\"email\" ILIKE 'vany%'" user = User.where(sql).first => #<User id: 1, .................................. > How can I do the same using Squeel? Thanks for any help) A: check out the "squeel" method, new in 0.9.0. It was added to support exactly this sort of thing. It just gives you an easy way to write a block of Squeel DSL without actually attaching it to a "where", "join", etc. You also might want to consider encapsulating this logic in a sifter for your model. class User < ActiveRecord::Base sifter :my_sifter do |growth_range, min_rating, email_start| growth.in(growth_range) & rating.gt(min_rating) & email.matches("#{email_start}%") end end User.where{sift :my_sifter, 0..200, 50, 'vany'} A: I resolved my problem using Arel. I think (I just changed MetaWhere code to Arel) that it is just the same as MetaWhere. t = User.arel_table email_starts_with = "vany%" sql = t[:rating].gt(50) sql = t[:growth].in(0..200) sql = sql.and(t[:email].matches(email_starts_with)) User.where(sql).to_sql => "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"growth\" BETWEEN 0 AND 200 AND \"users\".\"email\" ILIKE 'vany%')" Thanks everybody for help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7302417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How navigator read atomic javascript? I found something who disturbed me. How can a navigator can interpret this kind of code : [][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+ as javascript ?? Here is a fiddle : http://jsfiddle.net/6Cr4H/ Does every languages have an atomic form like this ??
{ "language": "en", "url": "https://stackoverflow.com/questions/18844858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap Dropdown Keeps Collapsing on Mobile Site: http://pegasusbus.com/ebrochure My menu works great, but when i click on the dropdown for "packages" in the nav, the dropdown closes before i can select an option. This only happen on mobile. Can anyone please tell me whats going on here please? A: Inside your freelancer.js file you're targeting all the a tags inside the navbar (which includes the navbar-toggle) to collapse the mobile menu when clicking any link. Currently you have this: // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); You can prevent this by using jQuery :not() Selector // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function() { $('.navbar-toggle:visible').click(); }); ** As a Sidenote you should consider running your site through a Validation process if you have not all ready: See validator.nu as an example. Working Example: // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function() { $('.navbar-toggle:visible').click(); }); body { position: relative; } section { padding: 50px; height: 500px; } section:nth-child(3) { background-color: lightgreen; } section:nth-child(4) { background-color: lightblue; } section:nth-child(5) { background-color: darkblue; } section:nth-child(6) { background-color: lightcoral; } section:nth-child(7) { background-color: darkmagenta; } section:nth-child(8) { background-color: lightskyblue; } section:nth-child(9) { background-color: lightgoldenrodyellow; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <nav class="navbar navbar-default navbar-fixed-top" id="tophead"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="#">Pegasus eBrochure</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#">Home</a> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" role="button">Packages<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#deals">Vacation Deals</a> </li> <li><a href="#sports">Sports</a> </li> <li><a href="#shopping">Shopping</a> </li> <li><a href="#holiday">Holiday</a> </li> <li><a href="#circuit">Circuits</a> </li> </ul> </li> <li><a href="#about">About</a> </li> <li><a href="#contact">Contact</a> </li> <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a> </li> <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a> </li> </ul> </div> </div> </nav> <section id="deals"> <h1>Vacation Deals</h1> </section> <section id="sports"> <h1>Sports</h1> </section> <section id="shopping"> <h1>Shopping</h1> </section> <section id="holiday"> <h1>Holiday</h1> </section> <section id="circuit"> <h1>Circuits</h1> </section> <section id="about"> <h1>About</h1> </section> <section id="contact"> <h1>Contact</h1> </section> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> A: I saw your website in the below line href="#" is missing just add that it will fix your problem <a class="dropdown-toggle" data-toggle="dropdown" role="button">Packages<span class="caret"></span></a>
{ "language": "en", "url": "https://stackoverflow.com/questions/38132741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating ByteArray in Kotlin Is there a better/shorter way in creating byte array from constant hex than the version below? byteArrayOf(0xA1.toByte(), 0x2E.toByte(), 0x38.toByte(), 0xD4.toByte(), 0x89.toByte(), 0xC3.toByte()) I tried to put 0xA1 without .toByte() but I receive syntax error complaint saying integer literal does not conform to the expected type Byte. Putting integer is fine but I prefer in hex form since my source is in hex string. Any hints would be greatly appreciated. Thanks! A: I just do: val bytes = listOf(0xa1, 0x2e, 0x38, 0xd4, 0x89, 0xc3) .map { it.toByte() } .toByteArray() A: as an option you can create simple function fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() } and use it val arr = byteArrayOfInts(0xA1, 0x2E, 0x38, 0xD4, 0x89, 0xC3) A: If all your bytes were less than or equal to 0x7F, you could put them directly: byteArrayOf(0x2E, 0x38) If you need to use bytes greater than 0x7F, you can use unsigned literals to make a UByteArray and then convert it back into a ByteArray: ubyteArrayOf(0xA1U, 0x2EU, 0x38U, 0xD4U, 0x89U, 0xC3U).toByteArray() I think it's a lot better than appending .toByte() at every element, and there's no need to define a custom function as well. However, Kotlin's unsigned types are an experimental feature, so you may have some trouble with warnings. A: The issue is that bytes in Kotlin are signed, which means they can only represent values in the [-128, 127] range. You can test this by creating a ByteArray like this: val limits = byteArrayOf(-0x81, -0x80, -0x79, 0x00, 0x79, 0x80) Only the first and last values will produce an error, because they are out of the valid range by 1. This is the same behaviour as in Java, and the solution will probably be to use a larger number type if your values don't fit in a Byte (or offset them by 128, etc). Side note: if you print the contents of the array you've created with toInt calls, you'll see that your values larger than 127 have flipped over to negative numbers: val bytes = byteArrayOf(0xA1.toByte(), 0x2E.toByte(), 0x38.toByte(), 0xD4.toByte(), 0x89.toByte(), 0xC3.toByte()) println(bytes.joinToString()) // -95, 46, 56, -44, -119, -61
{ "language": "en", "url": "https://stackoverflow.com/questions/51403881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: how I can use back-reference in boost::regex I am tring to use back-reference in boost version 1.44 but this don't work for me. this is my code: boost::regex_constants::syntax_option_type flags = boost::regex::extended; std::string regx="(aaa)bb\1"; std::cout << "Expression: \"" << regx << "\"\n"; std::string str ="aaabbaaa"; boost::regex e(regx,flags); if(boost::regex_match(text, what, e))//, boost::match_extra)) { std::cout<<"found"; } else { std::cout<<"not found"; } and this is my ouput: Expression: "(aaa)bbb☺" ** not found ** Press any key to continue . . . what I am missing? when I try std::string regx="(aaa)bb\\1" program crashed in boost::regex e(regx,flags); mybe I miss some flag? A: "(aaa)bb\\1". You need to escape the backslash. A: Both C++ and the regex use \ as an escape character. When you use it in your string C++ is interpreting it as octal character constant 1. You'll need to double escape the 1: std::string regx="(aaa)bb\\1"; A: In addition to needing to escape your backslash: Boost::regex sets the extended-syntax specific no_bk_refs flag by default. If you want to use back-references with extended syntax you'll have to unset it yourself: flags = boost::regex::extended & ~boost::regex::no_bk_refs; A: I fix this problem by chaning this row boost::regex_constants::syntax_option_type flags = boost::regex::extended; to boost::regex_constants::syntax_option_type flags = boost::regex::bk_vbar; and ofcourse use \\ and this work for me. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/6455232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it a good idea to run Apache on Windows server 2012? I run AmazonWebService with: Windows Server 2012 + IIS + Python3 website and want to add django. I tried to find some tutorial how to do it, but unfortunately, found nothing. Is it a good idea to install Apache on Windows Server 2012 and then try to deploy django on it? How difficult is it? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/32213605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to synchronize clock with Spotify servers? I'm trying to create cool visualization to music using the Spotify Web API(https://developer.spotify.com/documentation/web-api/reference/). What I'm trying, is to first fetch what the user is playing, what's their progress and then I fetch the track analysis as well. Fetching the currently played song is possible on this endpoint: https://developer.spotify.com/documentation/web-api/reference/player/get-the-users-currently-playing-track/ The important stuff for me from the response is basically this: { "id": H7sbas7Gda98sh...., //ID of the song "timestamp": 1490252122574, //unix timestamp when the data is fetched "progress_ms": 42567 //The progress of the track in milliseconds } Obviously some time elapses between the request and the time I parse the response in my application. So the plan is that I synchronize the music this way: const auto current_time = get_current_unix_timestamp(); const auto difference = current_time - timestamp; //the timestamp that is in the response const offset = progress_ms + difference; //the progress_ms that is in the response The theory is cool but it seems like the clock between the servers and on my system is not synchronized because I usually get values like -1638 for difference which is obviously not good because that would mean that I parsed the data sooner than it was fetched. So my question is that what options do I have to synchronize my clock to Spotify servers? If it's not possible what options do I have to be able to synchronize the music properly? I couldn't find anything in Spotify documentation, although it should be possible because there are already some existing applications that do the same what I'm trying to do(e.g.: https://www.kaleidosync.com/) A: It seems that synchronization is not currently practical, because while the docs say that the "timestamp" field signifies when the API gave you the data, it actually does not do what it says because of some issue on their side: https://github.com/spotify/web-api/issues/1073 Instead the timestamp seems to change only when there is a new song starting, pause, or seek. This means that as it is, we cannot know when the API response was generated.
{ "language": "en", "url": "https://stackoverflow.com/questions/59029450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP echo of javascript for a new window script worked before and now doesn't - what've I missed? I have fiddled for ages with escaping special characters and not, and doing this and that. I've exhausted the best part of a couple of hours and I need a fresh pair of eyes! What am I doing wrong? Updated. echo <<<EOT <script type="text/javascript"> $( document ).ready( function () { var w = window.open("{$address} result", "#", "width=800,height=600"); var d = w.document.open(); d.write("<!DOCTYPE html> <html> <head> <title>{$address} result</title> <link rel="stylesheet" href="css/base.css" type="text/css" /> </head> <body> <code> Request method: {$request_method} {$address}?{$qry_cfg}&amp;{$man_qry} $result </code> </body> </html>"); d.close(); }); </script> EOT; I'm getting an Uncaught SyntaxError: Unexpected token ILLEGAL on line 15 which is where the d.write begins. This answer may help me but I'm having no luck thus far. OUPUT: <script type="text/javascript"> $( document ).ready( function () { var w = window.open("https://api.classmarker.com/v1/groups/recent_results.json result", "#", "width=800,height=600"); var d = w.document.open(); d.write("<!DOCTYPE html> <html> <head> <title>https://api.classmarker.com/v1/groups/recent_results.json result</title> <link rel="stylesheet" href="css/base.css" type="text/css" /> </head> <body> <code> Request method: 0 https://api.classmarker.com/v1/groups/recent_results.json?api_key=d4tsE7SvEgzAKlJPFrlvAz3oe9uFQnxy&amp;signature=4495a14efc483aa5ee2f6d4cd480f968&amp;timestamp=1335783600&amp;finishedAfterTimestamp=1335783600&amp;= {"status":"error","request_path":"v1\/groups\/recent_results","server_timestamp":1415026084,"finished_after_timestamp_used":1413809284,"error":{"error_code":"timeStampOutOfRange","error_message":"Access denied. Timestamp issue. Recalculate the digital signature with each call. (There is a 5-minute window of time variance allowed.) Use seconds since the UNIX Epoch, not milliseconds. Make sure your server calling our service is in sync with an atomic clock."}} </code> </body> </html>"); d.close(); }); </script> A: Syntax errors, due to incorrect escaping. From your generated JS: d.write(" ^---start of string <!DOCTYPE html> <html> <head> <title>https://api.classmarker.com/v1/groups/recent_results.json result</title> <link rel="style[...snip...] ^---end of string A trivial look at your browser's debug console would have told you this. Running around for 2+ hours, as you say you did, means you didn't look at the ONE thing that would immediately have told you about the problem. Since you need your backslashes to get from PHP -> JS, you need to DOUBLE escape at the PHP level: d.write(\" <!DOCTYPE html> <html> <head> <title>{$address} result</title> <link rel=\\"sty ^^---note the doubled backslash. A: Not sure if it is the problem, but you escape your newline character \\n A: Problem solved by using the following (verbose I know) code: echo "\n<script type='text/javascript'> $(document).ready( function () { var w = window.open('{$address} result', '#', 'width=800,height=600'); var d = w.document.open(); d.write('<html>\ <head>\ <title>{$address} result</title>\ <link rel=\"stylesheet\" href=\"css/base.css\" type=\"text/css\" />\ </head>\ <body class=\"result\">\ <code>Request method: {$request_method}\\n{$address}\\n?{$qry_cfg}&amp;{$man_qry}\\n", htmlentities($result), "</code>\ </body>\ </html>'); d.close(); }); </script>\n"; Not escaping the newlines may have been the crux of the problem. Funny because I knew this about JS and managed to overlook it here as it was working before in a different format.
{ "language": "en", "url": "https://stackoverflow.com/questions/26716000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Insertion sort in Python I am trying to write the insertion sort algorithm ( without the help of the solution in the book) and so far came up with this algorithm, when I matched it with the solution, it looks different. This is the code I wrote: def insertSor(n): key = 0 while key < len(n): for j in range(len(n)-1): if n[j] > n[j+1]: n[j], n[j+1] = n[j+1], n[j] key = key+1 return n print(insertSor([2, 1, 0, 8, 9, 5])) Is this code still valid as an insertion sort? Algo in the book: for j = 2 to A.length key = A[j] i=j-1 while i > 0 and A[i]>key A[i+1]=A[i] i = i - 1 A[i+1]=key A: Looks like a bubble sort to me
{ "language": "en", "url": "https://stackoverflow.com/questions/68930017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Class wise classification in keras on tensorflow I am getting the following error, I am trying to get class-wise accuracy on training data. I have installed the latest TensorFlow and Keras, could anyone please help with the error? Thanks Error: **raise ValueError('Found two metrics with the same name: {}'.format( ValueError: Found two metrics with the same name: acc1** Code: resnet_model.summary() from keras import backend as K #interesting_class_id = 0 # Choose the class of interest def single_class_accuracy(interesting_class_id): def acc1(y_true, y_pred): class_id_true = K.argmax(y_true) class_id_preds = K.argmax(y_pred) accuracy_mask = K.cast(K.equal(class_id_preds, interesting_class_id), 'int32') class_acc_tensor = K.cast(K.equal(class_id_true, class_id_preds), 'int32') * accuracy_mask class_acc = K.cast(K.sum(class_acc_tensor), 'float32') / K.cast(K.maximum(K.sum(accuracy_mask), 1), 'float32') return class_acc return acc1 def single_class_recall(interesting_class_id): def recall(y_true, y_pred): class_id_true = K.argmax(y_true, axis=-1) class_id_pred = K.argmax(y_pred, axis=-1) recall_mask = K.cast(K.equal(class_id_true, interesting_class_id), 'int32') class_recall_tensor = K.cast(K.equal(class_id_true, class_id_pred), 'int32') * recall_mask class_recall = K.cast(K.sum(class_recall_tensor), 'float32') / K.cast(K.maximum(K.sum(recall_mask), 1), 'float32') return class_recall return recall def single_class_precision(interesting_class_id): def prec(y_true, y_pred): class_id_true = K.argmax(y_true, axis=-1) class_id_pred = K.argmax(y_pred, axis=-1) precision_mask = K.cast(K.equal(class_id_pred, interesting_class_id), 'int32') class_prec_tensor = K.cast(K.equal(class_id_true, class_id_pred), 'int32') * precision_mask class_prec = K.cast(K.sum(class_prec_tensor), 'float32') / K.cast(K.maximum(K.sum(precision_mask), 1), 'float32') return class_prec return prec resnet_model.compile(optimizer=Adam(lr=0.01),loss='binary_crossentropy',metrics=[ 'accuracy', single_class_accuracy(0), single_class_accuracy(1), single_class_recall(0), single_class_recall(1), single_class_precision(0), single_class_precision(1) ]) resnet_model.save('my_model') history = resnet_model.fit(train_ds, validation_data=val_ds, epochs=20) A: You can't add multiple metrics in metrics argument, changing only the parameter with which you call the metric. During the fit of your model, it will detect that you have multiple metrics with same name. The name is automatically set as the name of the inner metric function: acc1, recall and prec in your case. So when it goes through your metrics, it will find single_class_accuracy(0) and will call it acc1, then will find single_class_accuracy(1) and will try to call it acc1 too, which leads to the error. What you can do is set different names to your metric functions, like so: def single_class_accuracy(interesting_class_id): def acc1(y_true, y_pred): class_id_true = K.argmax(y_true) class_id_preds = K.argmax(y_pred) accuracy_mask = K.cast(K.equal(class_id_preds, interesting_class_id), 'int32') class_acc_tensor = K.cast(K.equal(class_id_true, class_id_preds), 'int32') * accuracy_mask class_acc = K.cast(K.sum(class_acc_tensor), 'float32') / K.cast(K.maximum(K.sum(accuracy_mask), 1), 'float32') return class_acc # setting a name according to your additional parameter acc1.__name__ = 'acc_1_{}'.format(interesting_class_id) return acc1
{ "language": "en", "url": "https://stackoverflow.com/questions/73627748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open password protected pdf using itext I am using iText library to read PDF files. It's working fine for all the pdf files, except for password protected ones. I used some way by using the overloading constructor of PdfReader class PdfReader reader = new PdfReader("locked pdf file","password".getBytes()); But it is showing show error like : Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1OctetString Is there any other to read password protected pdf file? or should I include bouncy castle into my project library? A: try { PdfReader pdfReader = new PdfReader(String.valueOf(file)); pdfReader.isEncrypted(); } catch(IOException) { e.printStackTrace(); } A: Starting from iText 2.0.0 you need the BouncyCastle jars. You need to download it from its site. More info can be found from here: java.lang.NoClassDefFoundError
{ "language": "en", "url": "https://stackoverflow.com/questions/10878721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Number of elements done from a to-do list I'm trying to put on the screen that items from a list that I have done. I came up with this function: function countDone() { let numberOfDone = 0 for (let i = 0; i < todoList.length; i++) { if (todoList[i].isDone === true) { numberOfDone = numberOfDone + 1 } return numberOfDone } } function printCountDone() { let f = countDone() document.querySelector('#todo-done').innerHTML = f } I don't know if the function is wrong or if I'm just calling it at the wrong place. I saw some similar posts here, but I couldn't understand (I'm a newbie, sorry in advance) Here is the codepen link: https://codepen.io/lodesousa/pen/jOLOeLr A: @Chris G has already covered this in their comments, but I wanted to explore what's happening with you in greater depth. Here's the code you have, in plain English: function countDone: create variable "numberOfDone" and set to 0 iterate over all todos. for each todo: if the todo is done: increase variable "numberOfDone" by 1 return variable numberOfDone end iteration end function Spot the error? Check out the indentation. Spoiler: The function isn't returning anything. You're returning numberOfDone every iteration of the for loop rather than right at the end of the function like you want. Returning a value at the wrong point in a function is an incredibly common programming error – I'd bet every programmer has faced this at one point. That's something that you should think about going forward: checking if a function returns anything is an excellent starting place when debugging functions. Anyway, cheers, and welcome to Stack Overflow! Congrats on your first question!
{ "language": "en", "url": "https://stackoverflow.com/questions/69548078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run a Google Apps Script using Javascript I have a command in cURL that allows me to run a Google Apps Script: curl -X POST \ -H 'Authorization: Bearer ### access token ###' \ -H "Content-Type: application/json" \ -d '{"function": "##function name##", "parameters": ["##MainDocID##", ["##Doc1ID##","##Doc2ID##","##Doc3ID##"]], devMode: false}' \ "https://script.googleapis.com/v1/scripts/### script ID ###:run" This script calls a function that is responsible for creating a folder in Google Drive and copying into the folder an edited and modified sheet file with certain values. The script works perfectly if I run it from the terminal. I'm creating a web application and I want to include this script in a button that when clicked triggers the Apps Script function. To do this I want to convert this cURL command to javascript. I have used this converter (REQBIN) and got this code but no matter how many times I run it, it does not work correctly. Converted javascript code: var url = "https://script.googleapis.com/v1/scripts/### script ID ###:run"; var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Authorization", "Bearer ### access token ###"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { console.log(xhr.status); console.log(xhr.responseText); }}; var data = '{"function": "##function name##", "parameters": ["##MainDocID##", ["##Doc1ID##","##Doc2ID##","##Doc3ID##"]], devMode: false}'; xhr.send(data); After creating the button and adding the javascript code, I have tested if it works but it doesn't because I check in Google Drive and the folder has not been created and the file I edit has not been copied. I have not been able to find out the exact error. From the web browser (client side) I get the response code '200' and in Google Cloud (logging operations), I get nothing but the only sure thing is that the function has not been executed. Why is it not working?. Is the javascript code correct?. Could anyone help me, please?. Thank you very much, Wardiam
{ "language": "en", "url": "https://stackoverflow.com/questions/69144139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to expose a property in MBean description The following managed operation exists in the project: @ManagedOperation(description = "Some description") @ManagedOperationParameters({ @ManagedOperationParameter(name = "key", description = "Some description"), }) public void foo(String key) { // some logic } Also there is a property which can be used in Spring context by surrounding it with dollar sign and square brackets: "${some.property.key}" Is it possible to use the value of aforementioned property key in the managed operation annotation description? Something like: @ManagedOperationParameter(name = "key", description = "Some description, please note that the key is ${some.property.key}") A: Not out-of-the-box, but it's pretty easy to customize... public class CustomAttributeSource extends AnnotationJmxAttributeSource implements EmbeddedValueResolverAware { private StringValueResolver embeddedValueResolver; @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.embeddedValueResolver = resolver; } @Override public ManagedAttribute getManagedAttribute(Method method) throws InvalidMetadataException { ManagedAttribute managedAttribute = super.getManagedAttribute(method); if (this.embeddedValueResolver != null) { managedAttribute .setDescription(this.embeddedValueResolver.resolveStringValue(managedAttribute.getDescription())); } return managedAttribute; } @Override public ManagedOperation getManagedOperation(Method method) throws InvalidMetadataException { ManagedOperation managedOperation = super.getManagedOperation(method); if (this.embeddedValueResolver != null) { managedOperation .setDescription(this.embeddedValueResolver.resolveStringValue(managedOperation.getDescription())); } return managedOperation; } } Then... <bean class="org.springframework.jmx.export.annotation.AnnotationMBeanExporter"> <property name="assembler"> <bean class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"> <property name="attributeSource"> <bean class="foo.CustomAttributeSource" /> </property> </bean> </property> </bean>
{ "language": "en", "url": "https://stackoverflow.com/questions/34785000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: google date parsing I'm having trouble parsing event dates pulled from a Google calendar feed. Here's the relevant code snippet that I'm working with: jQuery(function(){ jQuery.getJSON("https://www.google.com/calendar/feeds/(my feed URL...)", function(data){ function lpad(str, pad_string, length) { var str = new String(str); while (str.length < length) str = pad_string + str; return str; }; jQuery.each(data.feed.entry, function(i, item){ if(i == 0) { jQuery("#events li").first().hide(); }; var event_url = jQuery.trim(item.content.$t); var event_header = item.title.$t; if(event_url.length > 0) { event_title = "<a href='" + event_url + "'>" + event_header + "</a>"; }; // Format the date string var d = item.gd$when[0].startTime + ' - ' + item.gd$when[0].endTime; var d_string = d; // Render the event jQuery("#events li").last().before( "<li><strong>" + event_title + "</strong><br/>Date: " + d_string + "</a></li>" ); }); }); }); Everything works -- except I'm trying parse the date. The date displays as: Date: 2012-10-11T10:00:00.000-05:00 - 2012-10-11T12:00:00.000-05:00 I know I need to create a new date object: d=new Date(item.gd$when[0].startTime); But then I try to debug: alert('Month: ' + d.getMonth()); I receive: Month: NaN I'm obviously missing something -- but I'm not sure what. A: try like this: item.gd$when[0].startTime = item.gd$when[0].startTime.replace('Date: ', ''); item.gd$when[0].startTime = item.gd$when[0].startTime.split(' - '); var firstDate = item.gd$when[0].startTime[0]; var secondDate = item.gd$when[0].startTime[1]; var _firstDate = new Date(firstDate); var _secondDate = new Date(secondDate); alert(_firstDate.getMonth()); alert(_secondDate.getMonth());
{ "language": "en", "url": "https://stackoverflow.com/questions/12841361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extending compose UI - Missing Tokens I try to extend the compose UI to add attachments from an outside server, I try first to use the newUpdateDraftActionResponseBuilder() function but it's just to add content to the draft body. So now, I try to get the draft itself in the way to make a simple draft.update() but when I try to get the info of the last draft, I have this error: "Missing access token for authorization. Request: MailboxService.GetMessage". Here is my code, and the error is on the second line: var draft = GmailApp.getDrafts()[0]; var attachmentList = draft.getMessage().getAttachments(); Have you an idea to get this token? A: I think I found the solution, this error seems to come from a conflict between several scopes. After removing unnecessary scopes, it is working! "oauthScopes": [ "https://www.googleapis.com/auth/gmail.addons.execute", "https://mail.google.com/", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/gmail.addons.current.action.compose", "https://www.googleapis.com/auth/script.locale" ]
{ "language": "en", "url": "https://stackoverflow.com/questions/53080728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Maven Android integration error I am beginner in Maven. Please consider this. I want to use Maven for my Android project. For that I have done steps as per: * *http://rgladwell.github.com/m2e-android/ and *http://code.google.com/a/eclipselabs.org/p/m2eclipse-android-integration/wiki/GettingStarted I have Eclipse Helios, Android SDK, ADT-plugin rev 20 installed. Also I installed maven to eclipse plugin. I am using Windows 7 (32 bit). Here is the parent Pom.xml: <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3.1.1</version> <configuration> <sdk> <platform>15</platform> </sdk> <deleteConflictingFiles>true</deleteConflictingFiles> <undeployBeforeDeploy>true</undeployBeforeDeploy> </configuration> <extensions>true</extensions> </plugin> ... which installs Android Maven integration plugins. But with the child pom.xml I am getting errors. child pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>GROUPID</groupId> <artifactId>CHILDID</artifactId> <version>1.0</version> <packaging>apklib</packaging> <parent> <!-- getting error here ---> <groupId>GROUPID</groupId> <artifactId>ARTIID</artifactId> <version>1.0</version> <relativePath>..</relativePath> </parent> ...... ...... <plugins> <plugin> <artifactId>ID</artifactId> <version>1.1</version> <executions> <execution> <!-- getting error here ---> </execution> </plugin> </plugins> A: My pom.xml in a maven android project. It works fine: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>empresa</groupId> <version>1.0.0.BUILD-SNAPSHOT</version> <artifactId>maestro-empresas</artifactId> <packaging>apk</packaging> <name>maestro-empresas</name> <properties> <maven-android-plugin-version>3.0.0-alpha-13</maven-android-plugin-version> <maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version> <com.google.android-version>2.2.1</com.google.android-version> <org.springframework.android-version>1.0.0.BUILD-SNAPSHOT</org.springframework.android-version> <commons-httpclient-version>3.1</commons-httpclient-version> <org.codehaus.jackson-version>1.8.8</org.codehaus.jackson-version> <android-platform>8</android-platform> </properties> <pluginRepositories> <pluginRepository> <id>oss.sonatype.org-jayway-snapshots</id> <name>Jayway OpenSource SNAPSHOTs on Sonatype.org</name> <url>http://oss.sonatype.org/content/repositories/jayway-snapshots/</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <build> <sourceDirectory>src</sourceDirectory> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>${maven-android-plugin-version}</version> <configuration> <sdk> <!-- D:/SW/android-sdks/ --> <!-- <path>${android.home}</path> --> <platform>${android-platform}</platform> </sdk> <emulator> <avd>Android2.2</avd> </emulator> <deleteConflictingFiles>true</deleteConflictingFiles> <undeployBeforeDeploy>true</undeployBeforeDeploy> </configuration> <extensions>true</extensions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin-version}</version> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>${com.google.android-version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.android</groupId> <artifactId>spring-android-rest-template</artifactId> <version>${org.springframework.android-version}</version> </dependency> <dependency> <!-- Para json --> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${org.codehaus.jackson-version}</version> </dependency> </dependencies> <repositories> <repository> <id>org.springframework.maven.snapshot</id> <name>Spring Maven Snapshot Repository</name> <url>http://maven.springframework.org/snapshot</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>org.springframework.maven.milestone</id> <name>Spring Maven Milestone Repository</name> <url>http://maven.springframework.org/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>android-rome-feed-reader-repository</id> <name>Android ROME Feed Reader Repository</name> <url>https://android-rome-feed-reader.googlecode.com/svn/maven2/releases</url> </repository> </repositories> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/11262042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the dimensions of the scroll bars? Possible Duplicate: Javascript : Get the browser's scrollbar sizes I have an HTML table that contains lots of rows and columns. Therefore, it has vertical and horizontal scroll bars. How can I get the dimensions in pixels of these scroll bars in Javascript/jQuerys ? A: Ben Alman has a nice scrollbarWidth plugin that works nicely. var content = $('#content').css( 'width', 'auto' ), container = content.parent(); if ( content.height() > container.height() ) { content.width( content.width() - $.scrollbarWidth() ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/2722506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQUERY: Setting Active state on animated menu tabs I have image sprites that use JQuery to set the BG position on mouseover and mouseout events. When I set the active state BG position using JQUERY it works fine until I move my cursor away from the active 'tab' which then fires the mouseout event animation. What I want is the mouseClick event to stop the animation on the active tab but still allow the animation effect to work on the other tabs, and when another tab is clicked for the active state to be removed from the current tab to the new 'active' tab. JQuery $(function(){ /* This script changes main nav links hover state*/ $('.navigation a') .css( {backgroundPosition: "-1px -120px"} ) .mouseover(function(){ $(this).stop().animate({backgroundPosition:"(-1px -240px)"}, {duration:400}) }) .mouseout(function(){ $(this).stop().animate({backgroundPosition:"(-1px -120px)"}, {duration:400, complete:function (){ $(this).css({backgroundPosition: "-1px -120px"}) }}) }) }); $(document).ready(function(){ $("a").click(function(){ $(this).css({backgroundPosition: "-1px -235px"}); }); }); HTML <ul class="navigation"> <li><a href="#index" tabindex="10" title="Home" id="homeButton"></a></li> <li><a href="#about" tabindex="20" title="About us" id="aboutButton"></a></li> <li><a href="#facilities" tabindex="30" title="Our facilities and opening Times" id="facilitiesButton"></a></li> <li><a href="#advice" tabindex="40" title="Advice and useful links" c id="adviceButton"></a></li> <li><a href="#find" tabindex="50" title="How to find Us" id="findButton"></a></li> <li><a href="#contact" tabindex="60" title="Get in touch with us" id="contactButton"></a></li> </ul> You can see what I've got so far here Thanks in advance for any help A: $("ul li").click(function(){ $("ul li.active").removeClass('active'); $(this).stop().addClass('active'); })
{ "language": "en", "url": "https://stackoverflow.com/questions/2609482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple PHP program requires less time to execute i had applied for a job recently and the requirement was to complete a test and then interview 2 questions were given for test which was very simple and i did it successfully but still i was told that i have failed the test because the script took more than 18 seconds to complete execution. here is the program i dont understand what else i could do to make it fast. although i have failed the test but still wants to know else i could do? Program language is PHP and i had to do it using command line input here is the question: K Difference Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9] Input Format: 1st line contains N & K (integers). 2nd line contains N numbers of the set. All the N numbers are assured to be distinct. Output Format: One integer saying the no of pairs of numbers that have a diff K. Sample Input #00: 5 2 1 5 3 4 2 Sample Output #00:3 Sample Input #01: 10 1 363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 Sample Output #01: 0 Note: Java/C# code should be in a class named "Solution" Read input from STDIN and write output to STDOUT. and this is the solution $fr = fopen("php://stdin", "r"); $fw = fopen("php://stdout", "w"); fscanf($fr, "%d", $total_nums); fscanf($fr, "%d", $diff); $ary_nums = array(); for ($i = 0; $i < $total_nums; $i++) { fscanf($fr, "%d", $ary_nums[$i]); } $count = 0; sort($ary_nums); for ($i = $total_nums - 1; $i > 0; $i--) { for ($j = $i - 1; $j >= 0; $j--) { if ($ary_nums[$i] - $ary_nums[$j] == $diff) { $count++; $j = 0; } } } fprintf($fw, "%d", $count); A: Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only. Algorithm: * *Sort the array ary_nums. *for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise. sort($ary_nums); for ($i = $total_nums - 1; $i > 0; $i--) { $hi = $i-1; $low = 0; while($hi>=$low){ $mid = ($hi+$low)/2; if($ary_nums[$mid]==$ary_nums[$i]-$diff){ $count++; break; } if($ary_nums[$mid]<$ary_nums[$i]-$diff){ $low = $mid+1; } else{ $hi = $mid-1; } } } } A: I got the same question for my technical interview. I wonder if we are interviewing for the same company. :) Anyway, here is my answer I came up with (after the interview): // Insert code to get the input here $count = 0; sort ($arr); for ($i = 0, $max = $N - 1; $i < $max; $i++) { $lower_limit = $i + 1; $upper_limit = $max; while ($lower_limit <= $upper_limit) { $midpoint = ceil (($lower_limit + $upper_limit) / 2); $diff = $arr[$midpoint] - $arr[$i]; if ($diff == $K) { // Found it. Increment the count and break the inner loop. $count++; $lower_limit = $upper_limit + 1; } elseif ($diff < $K) { // Search to the right of midpoint $lower_limit = $midpoint + 1; } else { // Search to the left of midpoint $upper_limit = $midpoint - 1; } } } @Fallen: Your code failed for the following inputs: Enter the numbers N and K: 10 3 Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10 Result: 6 I think it has to do with your calculation of $mid (not accounting for odd number)
{ "language": "en", "url": "https://stackoverflow.com/questions/17849503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Reference children css in js I have a parent tag as #parallax-bg1 and I am able to reference them as whole in js. But how do I refer its children? As in #bg1-1 and #bg1-2 each? So that instead of changing the whole parent #parallax-bg1, I can set values to each of its childrens #bg1-1 and #bg1-2. main.css #parallax-bg1 { z-index: 1; position: fixed; /*left: 50%; /* align left edge with center of viewport */ top: 0; width: 2200px; margin-left: -270px; /* move left by half element's width */ } #bg1-1 { position: absolute; top: 48px; left: 270px; width: 1920px; height: 1080px; } #bg1-2 { position: absolute; top: 48px; left: 1990px; width: 1920px; height: 1080px; } js function Scroll(){ var scrolled = $(window).scrollTop(); $('#parallax-bg1').css('left',(0-(scrolled*.4))+'px'); //parent } A: Vanilla Javascript document.querySelector('#parallax-bg1 #bg1-1').style.left = `0-(${scrolled}*.4))px` Jquery $('#parallax-bg1 #bg1-1').css('left',(0-(scrolled*.4))+'px'); //parent
{ "language": "en", "url": "https://stackoverflow.com/questions/63227255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unknown key for a START_OBJECT in a multiple aggregations elasticsearch I'm trying to build a query allowing me to make multiple aggregations (on the same level, not sub aggregations) on a single query. Here's the request I'm sending : { "index": "index20", "type": "arret", "body": { "size": 0, "query": { "bool": { "must": [ { "multi_match": { "query": "anim fore", "analyzer": "query_analyzer", "type": "cross_fields", "fields": [ "doc_id" ], "operator": "and" } } ] } }, "aggs": { "anim_fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": { "pattern": "anim.*fore.*" } } }, "fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": { "pattern": "fore.*" } } } } } } However, I'm getting the following error when executing this query : Error: [parsing_exception] Unknown key for a START_OBJECT in [fore]., with { line=1 & col=1351 } I've been trying to change this query in many forms to make it works but I always end up with this error. It seems really strange to me as this query seems compatible with the format specified there : ES documentation. Maybe there is something specific about terms aggregations but I haven't been able to sort it out. A: The error is in your include settings, which should simply be strings "aggs": { "anim_fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": "anim.*fore.*" <--- here } }, "fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": "fore.*" <--- and here } } } A: You have trailing commas after doc_id and after closing array tag for must, your query should look like this "must": [ { "multi_match": { "query": "anim fore", "analyzer": "query_analyzer", "type": "cross_fields", "fields": [ "doc_id" // You have trailing comma here ], "operator": "and" } } ] // And here
{ "language": "en", "url": "https://stackoverflow.com/questions/43605374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WEB.API returning string property as json We have a fun situation where we are storing json as a string in SQL Server. We don't not care what is in this object its pretty much a passthrough property. Passthrough meaning we just save it for clients and return it as is. We never read it in C#. I'm storing it as a nvarchar in the database but I'm trying to figure out how i can automagically serialize that string into a json object to return to the client. I dont want to have to in javascript call fromJson. We are using Newtonsoft as our Json Serializer. Here is the highlevel setup: DTO: public class MyDto{ public dynamic SessionBag { get;set;} } Entity Framework Entity: public class My{ public string SessionBag { get;set;} } A client would post/put us: {"SessionBag":{"Name":"test"}} We would then save it in the db as a string: "{"Name":"test"}" How can I serialize this so when it returns from Web.API it looks like: { SessionBag:{ Name: "test" } } I'm currently messing around trying to get it to save using dynamic / object. But i can't figure how how to return it as a json object. I would love to figure out how to do this with just annotations. Here is how I convert it to a string to save: if (dto.SessionBag != null){ var serializer = JsonSerializer.Create(new JsonSerializerSettings(){ NullValueHandling = NullValueHandling.Ignore }); using (var writer = new StringWriter()){ serializer.Serialize(writer, dto.SessionBag); entity.SessionData = writer.ToString(); } } In case its helpful our WebApiControllers are pretty simple and just return an IHttpActionResult with the dto. All feedback is welcome. A: So I think i figured it out. In my dto: [JsonIgnore] public string SessionBagString { get; set; } public JObject SessionBag { get { if (!string.IsNullOrEmpty(SessionBagString)) { return JObject.Parse(SessionBagString); } return null; } set { if(value != null) { SessionBagString = value.ToString(); } } } In my repo code I now have: if (dto.SessionBag != null) { entity.SessionBagString = dto.SessionBagString; } That pretty much worked for me. Let me know if there is a better way to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/40022013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: New Core Data object doesn't show up in NSArrayController arrangedObjects When I insert a new object in a Core Data managed object context and shortly after that try to find this new object in the NSArrayController (which is connect with the managedObjectContext through binding), I can't find it. I do the creation and search in one method. My question now. How long does it take for a new inserted object to show up in the NSArrayControllers arrangedObject array? Update: Here is the code for inserting and fetching the new objects NSEntityDescription *entity = [[[self managedObjectModel] entitiesByName] objectForKey:@"EntityName"]; NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]]; ... [[self managedObjectContext] processPendingChanges]; [arrayController fetch:nil]; NSArray* objects = [arrayController arrangedObjects]; //the new object is not present in the array A: It's not a matter of "how long" but "at what point". There's enough of a distinction that it's important to study it. :-) Usually array controllers are automatically updated (re-fetch their contents in this case) on the next run-loop but technically "at some future run loop". If you want them to update immediately after inserting something, send your MOC a -processPendingChanges then ask the array controller to -fetch:. Among the first things you read in the Core Data documentation is that it's an advanced Cocoa topic whose prerequisite knowledge includes Key Value Binding and Key Value Observing. The missing bit of knowledge that led you to this question is found in understanding of KVC/KVO (and the Cocoa Bindings layer). A: Just found a fix for this. I use the setSelectedObjects: method of the NSArrayController to select the object. Don't know why I didn't used this method anyway!
{ "language": "en", "url": "https://stackoverflow.com/questions/4538704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: When implementing an interpreter, is it a good or bad to piggyback off the host language's garbage collector? Let's say you are implementing an interpreter for a GCed language in a language that is GCed. It seems to me you'd get garbage collection for free as long as you are reasonably careful about your design. Is this generally how it's done? Are there good reasons not to do this? A: Language and runtime are two different things. They are not really related IMHO. Therefore, if your existing runtime offers a GC already, there must be a good reason to extend the runtime with another GC. In the good old days when memory allocations in the OS were slow and expensive, apps brought their own heap managers which where more efficient in dealing with small chunks of data. That was one readon for adding another memory management to an existing runtime (or OS). But if you're talking Java, .NET or so - those should be good and efficient enough for most tasks at hand. However, you may want to create a proper interface/API for memory and object management tasks (and others), so that your language ("guest") runtime could be implemented on to of another host runtime later on. A: For an interpreter, there should be no problem with using the host GC, IMHO, particularly at first. As always they goal should be to get something working, then make it work right, then make it fast. This is particularly true for Domain Specific Languages (DSL) where the goal is a small language. For these, implementing a full GC would be overkill.
{ "language": "en", "url": "https://stackoverflow.com/questions/2179501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Json data's string name have "-" I use node.js. I try to get JSON data from one company's JSON URL but JSON data's few strings have "-". for example: "duo-fpp":{ "fdss" : 5, "fdsfsd" : 7 } this is my code: var sevenres = JSON.parse(body); console.log(sevenres.data.attributes.ModeStats.duo-fpp.assists); When I start my code, I get this error: fpp is not defined How can I get JSON data with "-" ?
{ "language": "en", "url": "https://stackoverflow.com/questions/51472276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Range of numbers in AngularJS not rendering with variable I can already render a list of numbers in angular using the following code in my controller $scope.range = function(n) { return new Array(n); }; and I use it like so <ul> <li class="ticked" ng-repeat="a in range(10) track by $index">{{$index + 1}}</li> </ul> and it draws 10 pretty <li>1</li> ... ... <li>10</li> as expected Now I when I am trying to use this code with a scope variable instead of ten i.e item.itemTickCount If I output {{item.itemTickCount}} I see 13 but when I try to render <ul> <li class="ticked" ng-repeat="a in range(item.itemTickCount) track by $index">{{$index + 1}}</li> </ul> I just get 1 <li></li> when it should be 13 What am I doing wrong. Note I have already tried range(itemTickCount) range({{item.itemTickCount}}) A: You are passing a string....cast it to number $scope.range = function(n) { return new Array(+n||0); }; DEMO
{ "language": "en", "url": "https://stackoverflow.com/questions/43837758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Share Image via android app using ACTION_SEND not working I have bee following this Android - Share on Facebook, Twitter, Mail, ecc But I am unable to share image using action_send intent in android.Please see my code and guide me where I am wrong. saveFileName = ""; Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/*"); Bitmap shareImage = null; shareImage = Bitmap.createBitmap(pc.getDrawingCache()); OutputStream OS = null; File f1 = new File(Environment.getExternalStorageDirectory() + "/Free Hand"); if (f1.isDirectory() == false) new File(Environment.getExternalStorageDirectory() + "/Free Hand").mkdir(); SimpleDateFormat filename = new SimpleDateFormat("yyyyMMddHmmss"); java.util.Date today1 = new java.util.Date(); saveFileName = filename.format(new java.sql.Timestamp(today1 .getTime())) + ".png"; if (saveFileName.length() == 0) saveFileName = "Free Hand"; file = new File(Environment.getExternalStorageDirectory() + "/Free Hand", saveFileName); try { outStream = new FileOutputStream(file); shareImage.compress(Bitmap.CompressFormat.PNG, 100, outStream); share.putExtra(android.content.Intent.ACTION_SEND, Uri.parse(Environment.getExternalStorageDirectory() + "/Free Hand/"+saveFileName+".png")); Toast.makeText( getApplicationContext(), "Saved in " + Environment.getExternalStorageDirectory() + "/Free Hand" + "\nFile: " + saveFileName + ".png", Toast.LENGTH_LONG).show(); Log.v("Before image", "Before image"); startActivity(Intent.createChooser(share, "Share Image")); Log.v("After image", "After image"); outStream.flush(); outStream.close(); saveFileName = ""; } catch (Exception e) { Toast.makeText(getApplicationContext(), "Exception : " + e.getMessage(), Toast.LENGTH_LONG) .show(); } save = false; The Logcat output I get is : 06-18 16:08:16.274: D/StatusBarPolicy(1378): [BRIGHTHY] 3. Show 3G indicator 06-18 16:08:17.791: W/ActivityManager(1378): Launch timeout has expired, giving up wake lock! 06-18 16:08:17.804: W/ActivityManager(1378): Activity idle timeout for HistoryRecord{454dabf8 com.facebook.katana/.ComposerActivity} 06-18 16:08:18.004: D/LGE_data(1463): LGE_Fast_Dormancy) new_state(2) i=(0) lastPDPstate=(2) 06-18 16:08:18.124: W/ResponseProcessCookies(15476): Invalid cookie header: "Set-Cookie: datr=HgbfT5h8NEIMcQRt7EurBx16; expires=Wed, 18-Jun-2014 10:42:38 GMT; path=/; domain=.facebook.com; httponly". Unable to parse expires attribute: Wed 06-18 16:08:18.644: D/ACRA(15476): #checkAndSendReports - finish 06-18 16:08:18.684: E/AndroidRuntime(15476): FATAL EXCEPTION: main 06-18 16:08:18.684: E/AndroidRuntime(15476): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.facebook.katana/com.facebook.katana.ComposerActivity}: java.lang.NullPointerException 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.os.Handler.dispatchMessage(Handler.java:99) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.os.Looper.loop(Looper.java:123) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread.main(ActivityThread.java:4627) 06-18 16:08:18.684: E/AndroidRuntime(15476): at java.lang.reflect.Method.invokeNative(Native Method) 06-18 16:08:18.684: E/AndroidRuntime(15476): at java.lang.reflect.Method.invoke(Method.java:521) 06-18 16:08:18.684: E/AndroidRuntime(15476): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 06-18 16:08:18.684: E/AndroidRuntime(15476): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 06-18 16:08:18.684: E/AndroidRuntime(15476): at dalvik.system.NativeStart.main(Native Method) 06-18 16:08:18.684: E/AndroidRuntime(15476): Caused by: java.lang.NullPointerException 06-18 16:08:18.684: E/AndroidRuntime(15476): at com.facebook.katana.activity.media.Storage.a(Storage.java:140) 06-18 16:08:18.684: E/AndroidRuntime(15476): at com.facebook.katana.ComposerActivity.a(ComposerActivity.java:742) 06-18 16:08:18.684: E/AndroidRuntime(15476): at com.facebook.orca.activity.FbFragmentActivity.onCreate(FbFragmentActivity.java:48) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 06-18 16:08:18.684: E/AndroidRuntime(15476): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 06-18 16:08:18.684: E/AndroidRuntime(15476): ... 11 more 06-18 16:08:18.714: W/ActivityManager(1378): Force finishing activity com.facebook.katana/.ComposerActivity 06-18 16:08:19.214: W/ActivityManager(1378): Activity pause timeout for HistoryRecord{454dabf8 com.facebook.katana/.ComposerActivity} 06-18 16:08:19.574: W/Flex(1378): getString FLEX_COUNTRY_CODE COM 06-18 16:08:19.574: W/Flex(1378): getString FLEX_OPERATOR_CODE OPEN 06-18 16:08:19.574: W/Flex(1378): getString FLEX_OPERATOR_CODE OPEN 06-18 16:08:19.574: W/Flex(1378): getString FLEX_COUNTRY_CODE COM 06-18 16:08:19.574: W/Flex(1378): getString FLEX_OPERATOR_CODE OPEN 06-18 16:08:19.574: D/StatusBarPolicy(1378): [BRIGHTHY] 0. mDataNetType: 8 06-18 16:08:19.574: D/StatusBarPolicy(1378): [BRIGHTHY] curNetwork=40420 curHPLMN=40420 I am testing it on real device via USB debugging. A: Simply use following code snippet : try { File myFile = new File("/mnt/sdcard/images/2.png"); MimeTypeMap mime = MimeTypeMap.getSingleton(); String ext=myFile.getName().substring(myFile.getName().lastIndexOf(".")+1); String type = mime.getMimeTypeFromExtension(ext); Intent sharingIntent = new Intent("android.intent.action.SEND"); sharingIntent.setType(type); sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile)); startActivity(Intent.createChooser(sharingIntent,"Share using")); } catch(Exception e){ Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/11081231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }